language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
JavaScript
UTF-8
2,204
2.96875
3
[]
no_license
let firstTime = localStorage.getItem("FirstTime") const music = document.getElementById("mcPozeDoRodo") const buttons = Array.from(document.getElementsByClassName("audioBtn")) let [backwards, forwards, play, stop, volDown, volUp] = buttons let audioBar = document.getElementsByClassName("musicBar")[0] let musicTimer = document.getElementsByClassName("audioTime")[0] let musicDuration let interval let currentTime = 0 function start() { musicDuration = music.duration play.addEventListener("click", playBtnClick) stop.addEventListener("click", stopBtnClick) backwards.addEventListener("click", musicBackwards) forwards.addEventListener("click", musicFowards) volUp.addEventListener("click", volumeUp) volDown.addEventListener("click", volumeDown) music.addEventListener("ended", playBtnClick) } function playBtnClick() { if(firstTime === null) { if(confirm("😬Essa música tem alguns palavões no inicio😬\nGostaria de pular eles?")) { music.currentTime = 26.49 musicPlayingActions() } firstTime = 'nop' localStorage.setItem("FirstTime", firstTime) } if(play.dataset.state == 0) { music.play() play.src = "assets/images/070-pause button.svg"; play.dataset.state = 1 interval = setInterval(musicPlayingActions, 500) } else { music.pause() play.src = "assets/images/072-play button.svg" play.dataset.state = 0 clearInterval(interval) } } function stopBtnClick() { if(play.dataset.state == 1) playBtnClick() music.currentTime = 0 musicTimeCounter() } function musicFowards() { music.currentTime += 10 musicPlayingActions() } function musicBackwards() { music.currentTime -= 10 musicPlayingActions() } const volumeDown = () => music.volume -= 0.1 const volumeUp = () => music.volume += 0.1 function musicPlayingActions() { currentTime = parseInt(music.currentTime) audioBar.value = (currentTime / musicDuration) * 100 musicTimer.innerText = `${('' + parseInt(currentTime / 60)).padStart(2, '0')}:${('' + currentTime % 60).padStart(2, '0')}` }
C++
UTF-8
6,944
3.640625
4
[]
no_license
#ifndef LIST342_H #define LIST342_H #include <iostream> #include <ostream> #include <string> #include <fstream> using namespace std; template <class ItemType> class List342 { // overloads "cout" operator friend ostream& operator<< (ostream& output, const List342<ItemType>& outputList) { Node* traversingNode = outputList.headPtr; if (outputList.isEmpty()) { output << "List is empty!" << endl; } else { while (traversingNode) // traversingNode != nullptr (same thing) { output << *traversingNode->data; traversingNode = traversingNode->next; } } return output; } public: // constructors List342(); List342(string fileName); List342(const List342& rhs); //copy constructor // destructor ~List342() { } // actions bool BuildList(string fileName); bool Insert(ItemType* obj); bool Remove(ItemType target, ItemType& result); bool Peek(ItemType target, ItemType& result) const; bool isEmpty() const; void DeleteList(); bool Merge(List342& list1); // overloaded operators List342 operator+(const List342& rhs) const; void operator+=(const List342& rhs); bool operator==(const List342& rhs) const; bool operator!=(const List342& rhs) const; void operator=(const List342& rhs); private: struct Node { /* Node() { data = nullptr; next = nullptr; }; ~Node() { delete next; };*/ ItemType* data = nullptr; Node* next = nullptr; }; Node* headPtr = nullptr; }; // constructor template <class ItemType> List342<ItemType>::List342() { headPtr = nullptr; } // constructor template <class ItemType> List342<ItemType>::List342(string fileName) { BuildList(fileName); } // copy constructor template<class ItemType> List342<ItemType>::List342(const List342<ItemType>& otherList) { this->headPtr = nullptr; *this = otherList; } // builds list from file of string template <class ItemType> bool List342<ItemType>::BuildList(string fileName) { ifstream inFile; inFile.open(fileName); if (inFile.is_open()) { while (!inFile.eof()) { ItemType* data = new ItemType(); inFile >> (*data); if (Insert(data) == false) { free(data); data = nullptr; } } inFile.close(); } else { cout << "File: " << fileName << " not found." << endl; } return true; } // inserts item in increasing order template <class ItemType> bool List342<ItemType>::Insert(ItemType* obj) { Node* temp = new Node(); Node* current; Node* previous; temp->data = obj; if (temp == nullptr) { delete temp; temp = nullptr; return false; } if (headPtr == nullptr) { headPtr = temp; return true; } else { if (*temp->data < *headPtr->data) { temp->next = headPtr; headPtr = temp; return true; } current = headPtr->next; previous = headPtr; while (current) { if (*temp->data < *current->data) { temp->next = current; previous->next = temp; return true; } else if (*temp->data == *current->data) { delete temp; temp = nullptr; return false; } previous = current; current = current->next; } if (previous) { previous->next = temp; return true; } delete temp; temp = nullptr; } delete temp; temp = nullptr; return false; } // Remove the target item from the list. // Return the item using a second parameter that is passed in by reference. template <class ItemType> bool List342<ItemType>::Remove(ItemType target, ItemType& result) { Node* current; Node* previous; if (!headPtr) { return false; } if (target == *headPtr->data) { result = target; current = headPtr; headPtr = headPtr->next; return true; } previous = headPtr; current = headPtr->next; while (current) { if (target == *current->data) { result = target; previous->next = current->next; return true; } previous = current; current = current->next; } return false; } // Same as remove except item is not removed from the list template <class ItemType> bool List342<ItemType>::Peek(ItemType target, ItemType& result) const { Node* current = headPtr; if (!current) { return true; } while (current) { if (target == *current->data) { result = *current->data; return true; } current = current->next; } return false; } // checks if list is empty template <class ItemType> bool List342<ItemType>::isEmpty() const { if (headPtr == nullptr) { return true; } else { return false; } } // Remove all items from the list template <class ItemType> void List342<ItemType>::DeleteList() { Node* current = headPtr; Node* next; while (current) { next = current->next; delete current; current = next; } current = nullptr; headPtr = nullptr; } // Takes a sorted list and merges into the calling sorted list template <class ItemType> bool List342<ItemType>::Merge(List342& list1) { Node* thisCurrent = headPtr; Node* otherCurrent = list1.headPtr; if (*this == list1) { return false; } else { while (thisCurrent && otherCurrent) { Insert(otherCurrent->data); thisCurrent = thisCurrent->next; otherCurrent = otherCurrent->next; } list1.DeleteList(); return true; } } // overloads + operator template <class ItemType> List342<ItemType> List342<ItemType>::operator+(const List342& rhs) const { List342<ItemType> list; Node* temp; while (temp) { list.Insert(temp->data); temp = temp->next; } temp = rhs.headPtr; while (temp) { list.Insert(temp->data); temp = temp->next; } temp = nullptr; return list; } // overloads += operator template <class ItemType> void List342<ItemType>::operator+=(const List342& rhs) { Node* current; if (!rhs.headPtr) { return; } current = rhs.headPtr; while (current) { Insert(current->data); current = current->next; } } // checks for equality between two lists (true/false) template <class ItemType> bool List342<ItemType>::operator==(const List342& rhs) const { Node* current = headPtr; Node* rhsCurrent = rhs.headPtr; while (current && rhsCurrent) { if (current->data != rhsCurrent->data) { return false; } current = current->next; rhsCurrent = rhsCurrent->next; } return true; } // checks for inequality between two lists (true/false) template <class ItemType> bool List342<ItemType>::operator!=(const List342& rhs) const { Node* current = headPtr; Node* rhsCurrent = rhs.headPtr; while (current && rhsCurrent) { if (current->data == rhsCurrent->data) { return false; } current = current->next; rhsCurrent = rhsCurrent->next; } return true; } // Makes a deep copy of all new memory template <class ItemType> void List342<ItemType>::operator=(const List342& rhs) { Node* rhsCurrent; Node* temp; if (this == &rhs) { return; } DeleteList(); rhsCurrent = rhs.headPtr; headPtr = rhsCurrent; temp = this->headPtr->next; rhsCurrent = rhsCurrent->next; while (rhsCurrent) { temp = rhsCurrent; rhsCurrent = rhsCurrent->next; } return; } // #endif // !LIST342_H
C++
UTF-8
938
2.96875
3
[]
no_license
#include <iostream> using namespace std; int n, m; int arr[100000]; int segtree[100000*4]; int makeseg(int ti, int start, int end){ if(start == end){ segtree[ti] = arr[start]; }else{ int mid = (start + end) / 2; segtree[ti] = makeseg(ti*2 + 1, start, mid) + makeseg(ti*2 + 2, mid+1, end); } return segtree[ti]; } int pfsum(int ti, int tl, int tr, int ps, int pe){ if(tl > pe || tr < ps) return 0; if(ps <= tl && tr <= pe) return segtree[ti]; else{ int mid = (tl + tr) / 2; return pfsum(ti*2 + 1, tl, mid, ps, pe) + pfsum(ti*2 + 2, mid+1, tr, ps, pe); } } int main(void){ cin.tie(nullptr); ios::sync_with_stdio(false); cin >> n >> m; for(int i=0; i<n; i++){ cin >> arr[i]; } makeseg(0, 0, n-1); while(m--){ int start, end; cin >> start >> end; cout << pfsum(0, 0, n-1, start-1, end-1) << '\n'; } }
C#
UTF-8
3,742
3.34375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CustomList { public class CustomList<T> { T[] array; public int capacity = 5; public int size; private int counter; public int Count { get { return counter; } } public T this[int index] { get { return array[index]; } set { array[index] = value; } } public CustomList() { array = new T[0]; } public void Add(T value) { T[] tempArray = new T[array.Length + 1]; counter++; for (int index = 0; index < array.Length; index++) { tempArray[index] = array[index]; } tempArray[tempArray.Length - 1] = value; array = tempArray; } public bool Remove(T value) { for (int i = 0; i < counter; i++) { if (array[i].Equals(value)) { int indexFirstInstance = i; for (int j = indexFirstInstance; j < counter-1; j++) { array[j] = array[j + 1]; } counter--; return true; } } return false; } public override string ToString() { string result = ""; foreach (T value in array) { result += value.ToString(); } return result; } public static CustomList<T> operator +(CustomList<T> listOne, CustomList<T> listTwo) { CustomList<T> combinedArray = new CustomList<T>(); for (int i = 0; i < listOne.Count; i++) { combinedArray.Add(listOne.array[i]); } for (int i = 0; i < listTwo.Count; i++) { combinedArray.Add(listTwo.array[i]); } return combinedArray; } public static CustomList<T> operator -(CustomList<T> listOne, CustomList<T> listTwo) { for (int i = 0; i < listOne.Count; i++) { for (int j = 0; j < listTwo.Count; j++) { if (listOne.array[i].Equals(listTwo.array[j])) { listOne.Remove(listTwo.array[j]); } } } return listOne; } public CustomList<T> ZipList(CustomList<T> listOne) { CustomList<T> ZipList = new CustomList<T>(); for (int i = 0; i < listOne.Count * 2; i++) { if (i % 2 == 0) { ZipList.Add(listOne[i / 2]); } else ZipList.Add(this[i / 2]); } return ZipList; } //public IEnumerator : GetEnumerator() //{ // //this is a reason to use var as the data type for the temporary variable // //in a foreach loop // yield return custom; // for (int i = 0; i < custom.Count(); i++) // { // yield return custom[i]; // } //} } }
Java
UTF-8
778
1.921875
2
[]
no_license
package org.ggyool.reservation.dao; public class ProductPriceSqls { public static final String SELECT_BY_PRODUCT_ID = "SELECT create_date AS createDate " + ", discount_rate AS discountRate " + ", modify_date AS modifyDate " + ", price " + ", price_type_name AS priceTypeName " + ", product_id AS productId " + ", id AS productPriceId " + "FROM product_price AS ppt " + "WHERE ppt.product_id = :productId"; public static final String SELECT_BY_ID = "SELECT create_date AS createDate " + ", discount_rate AS discountRate " + ", modify_date AS modifyDate " + ", price " + ", price_type_name AS priceTypeName " + ", product_id AS productId " + ", id AS productPriceId " + "FROM product_price AS ppt " + "WHERE ppt.id = :productPriceId"; }
Python
UTF-8
459
3.109375
3
[]
no_license
blockchain = [] def get_last_blockchain_value(): """Returns the last blockchain value""" return blockchain[-1] def add_value(value, last_transaction=[1]): blockchain.append([last_transaction, value]) def get_user_input(): return float(input('Enter Transaction amount: ')) add_value(get_user_input()) add_value(get_user_input(), get_last_blockchain_value()) add_value(get_user_input(), get_last_blockchain_value()) print(blockchain)
Java
MacCentralEurope
4,018
2.328125
2
[]
no_license
package com.turquaz.engine.ui.component; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.MenuItem; import com.cloudgarden.resource.SWTResourceManager; import com.turquaz.engine.bl.EngBLKeyEvents; import com.turquaz.engine.bl.EngBLLogger; import com.turquaz.engine.interfaces.SearchDialogInterface; import org.eclipse.swt.SWT; public class SearchDialogMenu extends org.eclipse.swt.widgets.Composite { { //Register as a resource user - SWTResourceManager will //handle the obtaining and disposing of resources SWTResourceManager.registerResourceUser(this); } private Menu menuActions; private MenuItem menuItem1; private Menu menu1; private ToolItem toolChoose; private ToolItem toolSearch; private ToolBar toolBar1; private MenuItem menuItemChoose; private MenuItem menuItemSearch; private SearchDialogInterface dialogInterface; public SearchDialogMenu(org.eclipse.swt.widgets.Composite parent, int style) { super(parent, style); initGUI(); } public SearchDialogMenu(org.eclipse.swt.widgets.Composite parent, int style, SearchDialogInterface dialogMenu) { super(parent, style); this.dialogInterface = dialogMenu; initGUI(); } private void initGUI() { try { { menuActions = new Menu(getShell(), SWT.BAR); getShell().setMenuBar(menuActions); { menuItem1 = new MenuItem(menuActions, SWT.CASCADE); menuItem1.setText("\u0130\u015flemler"); { menu1 = new Menu(menuItem1); menuItem1.setMenu(menu1); { menuItemSearch = new MenuItem(menu1, SWT.PUSH); TurqKeyEvent event=(TurqKeyEvent)EngBLKeyEvents.turqKeyEvents.get(EngBLKeyEvents.SEARCH); menuItemSearch.setAccelerator(event.stateMask | event.keyCode); menuItemSearch.setText("Ara\t"+EngBLKeyEvents.getStringValue(event)); menuItemSearch .addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent evt) { search(); } }); } { menuItemChoose = new MenuItem(menu1, SWT.PUSH); menuItemChoose.setText("Se\tENTER"); menuItemChoose.setAccelerator(SWT.CR); menuItemChoose .addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent evt) { choose(); } }); } } } } this.setLayout(new GridLayout()); this.setSize(505, 33); { GridData toolBar1LData = new GridData(); toolBar1LData.grabExcessHorizontalSpace = true; toolBar1LData.grabExcessVerticalSpace = true; toolBar1LData.verticalAlignment = GridData.FILL; toolBar1LData.horizontalAlignment = GridData.FILL; toolBar1 = new ToolBar(this, SWT.NONE); toolBar1.setLayoutData(toolBar1LData); { toolSearch = new ToolItem(toolBar1, SWT.NONE); toolSearch.setImage(SWTResourceManager.getImage("icons/search.gif")); toolSearch.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent evt) { search(); } }); } { toolChoose = new ToolItem(toolBar1, SWT.NONE); toolChoose.setImage(SWTResourceManager.getImage("icons/Ok16.gif")); toolChoose.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent evt) { choose(); } }); } } menuActions.setVisible(false); this.layout(); } catch (Exception e) { EngBLLogger.log(this.getClass(),e); } } public void choose() { if(dialogInterface != null) dialogInterface.choose(); } public void search() { if(dialogInterface != null) dialogInterface.search(); } }
Java
UTF-8
562
1.773438
2
[]
no_license
package com.qxf.mapper; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.baomidou.mybatisplus.plugins.pagination.Pagination; import com.qxf.pojo.OperateRecord; import org.apache.ibatis.annotations.Param; import java.util.List; public interface OperateRecordMapper extends BaseMapper<OperateRecord> { /** * 查询操作记录 */ List<OperateRecord> findOperateRecordByPage(Pagination page, @Param("searchKeyWord") String searchKeyWord); /** * 统计所有 请求 */ List<OperateRecord> findAllRequstCount(); }
JavaScript
UTF-8
693
2.765625
3
[]
no_license
const PubSub = require('../helpers/pub_sub.js'); const BeerView = require('./beer_view.js'); const BeersListView = function () { this.listElement = document.querySelector('#beer-list'); } BeersListView.prototype.bindEvents = function () { PubSub.subscribe('Beers:data-ready', (evt) => { this.clearList(); const data = evt.detail; this.createBeers(data); }) }; BeersListView.prototype.clearList = function () { this.listElement.innerHTML = ''; }; BeersListView.prototype.createBeers = function (allBeers) { allBeers.forEach((onebeer) => { const beerView = new BeerView(onebeer, this.listElement); beerView.render(); }); }; module.exports = BeersListView;
C#
UTF-8
859
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LatihanAsosiasi { class Program { static void Main(string[] args) { //membuat objek kartu Kartu kartu = new Kartu(); //membuat objek karyawan Karyawan karyawan = new Karyawan(); karyawan.Nama = "Manut"; karyawan.Status = false; //aktif //hubungan asosiasi if (karyawan.Login(kartu)) { Console.WriteLine("Data Karyawan Sangat Super Valid Sekali"); } else { Console.WriteLine("Maaf Data Karyawan Sangat Super Tidak Valid Sekali"); } Console.ReadKey(); } } }
JavaScript
UTF-8
3,366
2.71875
3
[]
no_license
const FoxyWebhook = require("../../src/foxy/FoxyWebhook.js"); const { after, before, describe, it } = require("mocha"); const chai = require("chai"); const crypto = require("crypto"); const sinon = require("sinon"); const {expect} = chai; let log; let logError; function silenceLog() { log = sinon.stub(console, 'log'); logError = sinon.stub(console, 'error'); } function restoreLog() { log.restore(); logError.restore(); } describe("Handles Foxy Webhook Requests", function() { let log; let logError; before(silenceLog); after(restoreLog); describe("Should retrieve items from a Webhook Request", function() { it("Should retrieve items when they are present.", function() { expect(FoxyWebhook.getItems({_embedded: {'fx:items': [{}, {}]}}).length).to.equal(2); }); it("Should return an empty list if fx:items is not available", function() { expect(FoxyWebhook.getItems({_embedded: {'items': [{}, {}]}}).length).to.equal(0); expect(FoxyWebhook.getItems({items: {'items': [{}, {}]}}).length).to.equal(0); }); }); }); describe("Builds Foxy Webhook Responses", function() { let log; let logError; before(silenceLog); after(restoreLog); it ("Should not accept error responses without details", function () { expect(() => FoxyWebhook.response("", 500)).to.throw(Error, /An error response needs to specify details/); expect(() => FoxyWebhook.response(null, 500)).to.throw(Error, /An error response needs to specify details/); expect(() => FoxyWebhook.response(undefined, 500)).to.throw(Error, /An error response needs to specify details/); }); }); describe("Verifies Foxy Webhook Signatures", function () { let log; let logError; before(silenceLog); after(restoreLog); it("Accepts the correct signature",function () { const foxySignature = crypto.createHmac('sha256', 'foo').update('bar').digest('hex'); expect(FoxyWebhook.validSignature('bar', foxySignature, 'foo')).to.be.true; }); it("Rejects incorrect signatures",function () { const cases = [0, 1, 2]; for (let c of cases) { const foxySignature = crypto.createHmac('sha256', 'foo').update('bar').digest('hex'); const values = ['bar', foxySignature, 'foo']; values[c] = 'wrong'; expect(FoxyWebhook.validSignature(...values)).to.be.false; values[c] = undefined; expect(FoxyWebhook.validSignature(...values)).to.be.false; } }); }); describe("Builds useful error messages", function() { let log; let logError; before(silenceLog); after(restoreLog); describe("Responds useful messages", function () { it("Informs the invalid items when the price is wrong.", async function () { const message = FoxyWebhook.messagePriceMismatch([ [{name: 'foo'}, {name: 'foo'}], [{name: 'bar'}, {name: 'bar'}], ]) expect(message).to.match(/foo/); expect(message).to.match(/bar/); }); it("Informs the items with insufficient inventory and the current available inventory.", async function () { const message = FoxyWebhook.messageInsufficientInventory([ [{name: 'foo', quantity:3}, {inventory: 2, name: 'foo'}], [{name: 'bar', quantity:3}, {inventory: 1, name: 'bar'}], ]) expect(message).to.match(/2 available/); expect(message).to.match(/1 available/); }); }); });
Python
UTF-8
15,399
2.578125
3
[ "MIT" ]
permissive
import torch import torch.nn as nn import torch.nn.functional as F def get_kl(m, v, m0, v0): # adapted from: https://github.com/bunkerj/mlmi4-vcl/blob/master/src/KL.py # numerical value for stability of log computation eps = 1e-8 constTerm = -0.5 * m.numel() logStdDiff = 0.5 * torch.sum(torch.log(eps+v0**2)-torch.log(eps+v**2)) muDiffTerm = 0.5 * torch.sum((v**2 + (m0-m)**2) / v0**2) return (constTerm + logStdDiff + muDiffTerm) / torch.numel(m) # def loss_fn_kd(scores, target_scores, T=2.): # """Compute knowledge-distillation (KD) loss given [scores] and [target_scores]. # Both [scores] and [target_scores] should be tensors, although [target_scores] should be repackaged. # 'Hyperparameter': temperature""" # #print("score", scores.shape) # #print("target", target_scores.shape) # log_scores_norm = F.log_softmax(scores / T, dim=1) # log_scores_norm = log_scores_norm[:,:target_scores.shape[1]] # log_scores_norm[:,:target_scores.shape[1],:,:] # targets_norm = F.softmax(target_scores / T, dim=1) # #targets_norm = targets_norm[:,:,:,:] # # Calculate distillation loss (see e.g., Li and Hoiem, 2017) # KD_loss_unnorm = -(targets_norm * log_scores_norm) # #print(KD_loss_unnorm.shape) # KD_loss_unnorm = KD_loss_unnorm.sum(dim=1) #--> sum over classes # #print(KD_loss_unnorm.shape) # KD_loss_unnorm = KD_loss_unnorm.mean() #--> average over batch # # normalize # KD_loss = KD_loss_unnorm * T**2 # return KD_loss def loss_fn_kd(scores, target_scores, T=2.): """Compute knowledge-distillation (KD) loss given [scores] and [target_scores]. Both [scores] and [target_scores] should be tensors, although [target_scores] should be repackaged. 'Hyperparameter': temperature""" #print("score", scores.shape) #print("target", target_scores.shape) device = scores.device log_scores_norm = F.log_softmax(scores / T, dim=1) targets_norm = F.softmax(target_scores / T, dim=1) # if [scores] and [target_scores] do not have equal size, append 0's to [targets_norm] n = scores.size(1) if n > target_scores.size(1): n_batch = scores.size(0) zeros_to_add = torch.zeros(n_batch, n-target_scores.size(1)) zeros_to_add = zeros_to_add.to(device) targets_norm = torch.cat([targets_norm.detach(), zeros_to_add], dim=1) # Calculate distillation loss (see e.g., Li and Hoiem, 2017) KD_loss_unnorm = -(targets_norm * log_scores_norm) #print(KD_loss_unnorm.shape) KD_loss_unnorm = KD_loss_unnorm.sum(dim=1) #--> sum over classes #print(KD_loss_unnorm.shape) KD_loss_unnorm = KD_loss_unnorm.mean() #--> average over batch # normalize KD_loss = KD_loss_unnorm * T**2 return KD_loss def loss_fn_kd_multihead(scores, target_scores, task_sizes, T=2.): """Compute knowledge-distillation (KD) loss given [scores] and [target_scores]. Both [scores] and [target_scores] should be tensors, although [target_scores] should be repackaged. 'Hyperparameter': temperature""" #print("score", scores.shape) #print("target", target_scores.shape) device = scores.device # caution! this works only if all tasks are same size and score is dividable (luckily this is provided by this framework) KD_losses = torch.zeros(scores.size(1) // task_sizes).to(device) for i in range(scores.size(1) // task_sizes): log_scores_norm = F.log_softmax(scores[:,i*task_sizes:(i+1)*task_sizes] / T, dim=1) targets_norm = F.softmax(target_scores[:,i*task_sizes:(i+1)*task_sizes] / T, dim=1) # Calculate distillation loss (see e.g., Li and Hoiem, 2017) KD_loss_unnorm = -(targets_norm * log_scores_norm) #print(KD_loss_unnorm.shape) KD_loss_unnorm = KD_loss_unnorm.sum(dim=1) #--> sum over classes #print(KD_loss_unnorm.shape) KD_loss_unnorm = KD_loss_unnorm.mean() #--> average over batch # normalize KD_loss = KD_loss_unnorm * T**2 KD_losses[i] = KD_loss KD_losses = KD_losses.sum() return KD_losses def loss_fn_kd_2d(scores, target_scores, T=2., weight=None): """Compute knowledge-distillation (KD) loss given [scores] and [target_scores]. Both [scores] and [target_scores] should be tensors, although [target_scores] should be repackaged. 'Hyperparameter': temperature""" device = scores.device log_scores_norm = F.log_softmax(scores / T, dim=1) #log_scores_norm = log_scores_norm[:,:target_scores.shape[1],:,:] targets_norm = F.softmax(target_scores / T, dim=1) #targets_norm = targets_norm[:,:,:,:] # if [scores] and [target_scores] do not have equal size, append 0's to [targets_norm] n = scores.size(1) if n>target_scores.size(1): n_batch = scores.size(0) zeros_to_add = torch.zeros(n_batch, n-target_scores.size(1), target_scores.size(2), target_scores.size(3)) zeros_to_add = zeros_to_add.to(device) #print("targets_norm", target_norm.size()) #print("zeros_add", zeros_to_add.size()) targets_norm = torch.cat([targets_norm.detach(), zeros_to_add], dim=1) # Calculate distillation loss (see e.g., Li and Hoiem, 2017) #print("targets_norm", targets_norm.shape) #weight = torch.ones(scores.size(1), scores.size(2), scores.size(3)) #weight[0,:,:] = 0.05 #weight = weight.float().to(device) #print("weight", weight.shape) KD_loss_unnorm = -(targets_norm * log_scores_norm) if not weight is None: KD_loss_unnorm = KD_loss_unnorm * (weight[:target_scores.size(1)].view(-1, 1, 1)) #print("kd_1", KD_loss_unnorm.shape) KD_loss_unnorm = KD_loss_unnorm.sum(dim=1) #--> sum over classes #print("kd_2", KD_loss_unnorm.shape) KD_loss_unnorm = KD_loss_unnorm.mean() #--> average over batch # normalize KD_loss = KD_loss_unnorm * T**2 return KD_loss def unified_loss_function(output_samples_classification, target, output_samples_recon, inp, mu, std, device, args, weight=None): """ Computes the unified model's joint loss function consisting of a term for reconstruction, a KL term between approximate posterior and prior and the loss for the generative classifier. The number of variational samples is one per default, as specified in the command line parser and typically is how VAE models and also our unified model is trained. We have added the option to flexibly work with an arbitrary amount of samples. Parameters: output_samples_classification (torch.Tensor): Mini-batch of var_sample many classification prediction values. target (torch.Tensor): Classification targets for each element in the mini-batch. output_samples_recon (torch.Tensor): Mini-batch of var_sample many reconstructions. inp (torch.Tensor): The input mini-batch (before noise), aka the reconstruction loss' target. mu (torch.Tensor): Encoder (recognition model's) mini-batch of mean vectors. std (torch.Tensor): Encoder (recognition model's) mini-batch of standard deviation vectors. device (str): Device for computation. args (dict): Command line parameters. Needs to contain autoregression (bool). Returns: float: normalized classification loss float: normalized reconstruction loss float: normalized KL divergence """ # for autoregressive models the decoder loss term corresponds to a classification based on 256 classes (for each # pixel value), i.e. a 256-way Softmax and thus a cross-entropy loss. # For regular decoders the loss is the reconstruction negative-log likelihood. if args.autoregression: recon_loss = nn.CrossEntropyLoss(reduction='sum') else: recon_loss = nn.BCEWithLogitsLoss(reduction='sum') if not weight is None: weight = torch.FloatTensor(weight[:output_samples_classification.size(2)]).to(device) class_loss = nn.CrossEntropyLoss(reduction='sum', weight=weight) else: class_loss = nn.CrossEntropyLoss(reduction='sum') # Place-holders for the final loss values over all latent space samples recon_losses = torch.zeros(output_samples_recon.size(0)).to(device) cl_losses = torch.zeros(output_samples_classification.size(0)).to(device) # numerical value for stability of log computation eps = 1e-8 # loop through each sample for each input and calculate the correspond loss. Normalize the losses. for i in range(output_samples_classification.size(0)): cl_losses[i] = class_loss(output_samples_classification[i], target) / torch.numel(target) recon_losses[i] = recon_loss(output_samples_recon[i], inp) / torch.numel(inp) # average the loss over all samples per input cl = torch.mean(cl_losses, dim=0) rl = torch.mean(recon_losses, dim=0) # Compute the KL divergence, normalized by latent dimensionality kld = -0.5 * torch.sum(1 + torch.log(eps + std ** 2) - (mu ** 2) - (std ** 2)) / torch.numel(mu) # DEBUG #mu0 = torch.zeros_like(mu) #print(mu0.shape) #std0 = torch.ones_like(std) #kld_test = get_kl(mu, std, mu0, std0) #print(kld.cpu().item(), kld_test.cpu().item()) return cl, rl, kld def unified_loss_function_multihead(output_samples_classification, target, output_samples_recon, inp, mu, std, device, args): """ Computes the unified model's joint loss function consisting of a term for reconstruction, a KL term between approximate posterior and prior and the loss for the generative classifier. The number of variational samples is one per default, as specified in the command line parser and typically is how VAE models and also our unified model is trained. We have added the option to flexibly work with an arbitrary amount of samples. Parameters: output_samples_classification (torch.Tensor): Mini-batch of var_sample many classification prediction values. target (torch.Tensor): Classification targets for each element in the mini-batch. output_samples_recon (torch.Tensor): Mini-batch of var_sample many reconstructions. inp (torch.Tensor): The input mini-batch (before noise), aka the reconstruction loss' target. mu (torch.Tensor): Encoder (recognition model's) mini-batch of mean vectors. std (torch.Tensor): Encoder (recognition model's) mini-batch of standard deviation vectors. device (str): Device for computation. args (dict): Command line parameters. Needs to contain autoregression (bool). Returns: float: normalized classification loss float: normalized reconstruction loss float: normalized KL divergence """ # for autoregressive models the decoder loss term corresponds to a classification based on 256 classes (for each # pixel value), i.e. a 256-way Softmax and thus a cross-entropy loss. # For regular decoders the loss is the reconstruction negative-log likelihood. if args.autoregression: recon_loss = nn.CrossEntropyLoss(reduction='sum') else: recon_loss = nn.BCEWithLogitsLoss(reduction='sum') class_loss = nn.CrossEntropyLoss(reduction='sum') # Place-holders for the final loss values over all latent space samples recon_losses = torch.zeros(output_samples_recon.size(0)).to(device) cl_losses = torch.zeros(output_samples_classification.size(0)).to(device) # numerical value for stability of log computation eps = 1e-8 # loop through each sample for each input and calculate the correspond loss. Normalize the losses. for i in range(output_samples_classification.size(0)): # calculate class loss only for current head (most recently added neurons) cl_losses[i] = class_loss(output_samples_classification[i], target) / torch.numel(target) recon_losses[i] = recon_loss(output_samples_recon[i], inp) / torch.numel(inp) # average the loss over all samples per input cl = torch.mean(cl_losses, dim=0) rl = torch.mean(recon_losses, dim=0) # Compute the KL divergence, normalized by latent dimensionality kld = -0.5 * torch.sum(1 + torch.log(eps + std ** 2) - (mu ** 2) - (std ** 2)) / torch.numel(mu) return cl, rl, kld def unified_loss_function_no_vae(output_samples_classification, target, output_samples_recon, inp, mu, std, device, args, weight=None): """ Computes the unified model's joint loss function consisting of a term for reconstruction, a KL term between approximate posterior and prior and the loss for the generative classifier. The number of variational samples is one per default, as specified in the command line parser and typically is how VAE models and also our unified model is trained. We have added the option to flexibly work with an arbitrary amount of samples. Parameters: output_samples_classification (torch.Tensor): Mini-batch of var_sample many classification prediction values. target (torch.Tensor): Classification targets for each element in the mini-batch. output_samples_recon (torch.Tensor): Mini-batch of var_sample many reconstructions. inp (torch.Tensor): The input mini-batch (before noise), aka the reconstruction loss' target. mu (torch.Tensor): Encoder (recognition model's) mini-batch of mean vectors. std (torch.Tensor): Encoder (recognition model's) mini-batch of standard deviation vectors. device (str): Device for computation. args (dict): Command line parameters. Needs to contain autoregression (bool). Returns: float: normalized classification loss float: normalized reconstruction loss float: normalized KL divergence """ # for autoregressive models the decoder loss term corresponds to a classification based on 256 classes (for each # pixel value), i.e. a 256-way Softmax and thus a cross-entropy loss. # For regular decoders the loss is the reconstruction negative-log likelihood. if weight is None: class_loss = nn.CrossEntropyLoss(reduction='sum') else: #weight = torch.ones(output_samples_classification.size(2)) #weight[0] = 0.02 #weight[1] = 0.0046 #weight[2] = 0.029 #weight[3] = 0.005 #weight[4] = 0.067 #weight[5] = 1 weight = torch.FloatTensor(weight[:output_samples_classification.size(2)]).to(device) #print("weight", weight) class_loss = nn.CrossEntropyLoss(reduction='sum', weight=weight) #class_loss = nn.CrossEntropyLoss(reduction='sum') # Place-holders for the final loss values over all latent space samples cl_losses = torch.zeros(output_samples_classification.size(0)).to(device) # numerical value for stability of log computation eps = 1e-8 # loop through each sample for each input and calculate the correspond loss. Normalize the losses. for i in range(output_samples_classification.size(0)): cl_losses[i] = class_loss(output_samples_classification[i], target) / torch.numel(target) # average the loss over all samples per input cl = torch.mean(cl_losses, dim=0) return cl, None, None
Markdown
UTF-8
1,007
2.78125
3
[ "MIT" ]
permissive
# JavaScript File 1. readFile(fileName, [encoding], [callback]) ------------ - 비동기식 I / O 로 파일을 읽어들인다. 2. readFileSync(fileName, [encoding]) ----------------- - 동기식 I / O 로 파일을 읽어들인다. 3. writeFile(fileName, data, encoding='utf8', [callback]) ------------ - 비동기식 I / O 로 파일을 쓴다. 4. writeFileSync(fileName, data, encoding='utf8') ------------- - 동기식 I / O 로 파일을 쓴다. #### 각각의 메서드의 차이는 Callback의 유무로 봐도 될 것 같다. ## File open, read, write, close 1. open(path, flags, [mode], [callback]) ---- - 파일 열기 2. read(fd, buffer, offset, length, position, [callback]) ---- - 지정한 부분의 파일을 읽는다. 3. write(fd, buffer, offset, length, position, [callback]) ---- - 파일의 지정한 부분에 데이터를 쓴다. 4. close(fd, [callback]) ---- - 파일을 닫아준다.
Ruby
UTF-8
3,478
3.46875
3
[]
no_license
require 'byebug' class Piece attr_accessor :position, :color, :board, :symbol, :off_sets def initialize(position, color, board) @board = board @position = position @color = color end def opponent_there? new_pos x, y = new_pos if board.in_bounds?(new_pos) && !board.grid[x][y].nil? return self.color != board.grid[x][y].color end false end def inspect symbol end def own_piece_there? new_pos x, y = new_pos unless board.grid[x][y].nil? return self.color == board.grid[x][y].color end false end def valid_moves player raise WrongPiece unless player.color == self.color piece_valid_moves = [] i, j = self.position moves.each do |next_i, next_j| old_board = board.dup old_board.grid[next_i][next_j], old_board.grid[i][j] = old_board.grid[i][j], old_board.grid[next_i][next_j] old_board.grid[i][j] = nil piece_valid_moves << [next_i,next_j] end piece_valid_moves end end class SlidingPiece < Piece def moves(n=8) all_moves = [] off_sets.each do |off_row, off_col| (1..n).each do |i| new_pos = [off_row * i + position[0], off_col * i + position[1]] if board.in_bounds?(new_pos) && !own_piece_there?(new_pos) && !opponent_there?(new_pos) all_moves << new_pos elsif opponent_there?(new_pos) #&& board.in_bounds?(new_pos) all_moves << new_pos break else break end end end all_moves end end class Bishop < SlidingPiece def initialize(position, color, board) super @symbol = "♗" @off_sets = [-1 ,1].product([ -1 ,1]) end end class Rook < SlidingPiece def initialize(position, color, board) super @symbol = "♖" @off_sets = [[0, -1], [1,0], [-1, 0], [0, 1]] end end class Queen < SlidingPiece def initialize(position, color, board) super @symbol = "♕" @off_sets = [-1, 0 ,1].product([ -1, 0 ,1]).reject {|offset| offset == [0,0]} end end class SteppingPiece < SlidingPiece def moves(n = 1) super end end class King < SteppingPiece def initialize(position, color, board) super @symbol = "♔" @off_sets = [-1, 0 ,1].product([ -1, 0 ,1]).reject {|offset| offset == [0,0]} end end class Knight < SteppingPiece def initialize(position, color, board) super @symbol = "♘" @off_sets = [[2, -1], [-2, 1], [-1, -2], [-1, 2], [ 1, -2], [ 1, 2], [-2, -1], [ 2, 1]] end end class Pawn < Piece attr_accessor :has_moved, :kill_moves, :piece_valid_moves def initialize(position, color, board) super @symbol = "♙" @has_moved = false @off_sets = color == :black ? [1, 0] : [-1, 0] @kill_moves = color == :black ? [[1, -1],[ 1, 1]] : [[-1, 1], [-1, -1]] end def moves off_sets all_moves = [] new_pos = [(position[0] + off_sets[0]), position[1]] all_moves << new_pos if board.grid[new_pos[0]][new_pos[1]].nil? all_moves if all_moves.include?(new_pos) && !has_moved new_pos = [(position[0] + 2 * off_sets[0]), position[1]] all_moves << new_pos if board.grid[new_pos[0]][new_pos[1]].nil? end kill_moves.each do |m_x, m_y| if opponent_there?([m_x + position[0], m_y + position[1]]) all_moves << [m_x + position[0], m_y + position[1]] end end all_moves end end
PHP
UTF-8
3,229
2.6875
3
[]
no_license
<?php namespace App\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\CompositionsProduitRepository") */ class CompositionsProduit { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="integer") */ private $quantiteComp; /** * * @ORM\Column(type="integer", nullable = true) */ private $idComposition;// auto /** * @ORM\ManyToMany(targetEntity="App\Entity\Produits") */ private $codeProduit; /** * @ORM\ManyToMany(targetEntity="App\Entity\Composants") */ private $idComposant; /** * CompositionsProduit constructor. * @param $quantiteComp * @param $idComposition * @param $codeProduit * @param $idComposant */ public function __construct( $quantiteComp)//, $idComposition { $this->quantiteComp = $quantiteComp; // $this->idComposition = $idComposition; $this->codeProduit = new ArrayCollection(); $this->idComposant = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getQuantiteComp(): ?int { return $this->quantiteComp; } public function setQuantiteComp(int $quantiteComp): self { $this->quantiteComp = $quantiteComp; return $this; } public function getIdComposition(): ?int { //changed to return id return $this->id; } public function setIdComposition(int $idComposition): self { $this->idComposition = $idComposition; return $this; } /** * @return Collection|Produits[] */ public function getCodeProduit(): Collection { return $this->codeProduit; } public function addCodeProduit(Produits $codeProduit): self { if (!$this->codeProduit->contains($codeProduit)) { $this->codeProduit[] = $codeProduit; } return $this; } public function removeCodeProduit(Produits $codeProduit): self { if ($this->codeProduit->contains($codeProduit)) { $this->codeProduit->removeElement($codeProduit); } return $this; } /** * @return Collection|Composants[] */ public function getIdComposant(): Collection { return $this->idComposant; } public function addIdComposant(Composants $idComposant): self { if (!$this->idComposant->contains($idComposant)) { $this->idComposant[] = $idComposant; } return $this; } public function removeIdComposant(Composants $idComposant): self { if ($this->idComposant->contains($idComposant)) { $this->idComposant->removeElement($idComposant); } return $this; } public function toArray() { return [ 'id' => $this->getId(), 'idComposition' => $this->getIdComposition(), 'quantiteComp ' => $this->getQuantiteComp() ]; } }
PHP
UTF-8
1,945
3.265625
3
[ "MIT" ]
permissive
<?php // 数据库连接-单例模式 namespace app\data; use PDO; use PDOException; class Connection { const ERROR_UNABLE = '<br>ERROR: 数据库连接失败!<br>'; private static $instance = NULL; private $conn; // const DEFAULT_CONFIG = '../config/testDB.php'; const DEFAULT_CONFIG = '../../app/config/testDB.php'; private function __construct($config) { $config = require_once($config); $opt = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ]; try { $this->conn = new PDO( $config['dsn'], $config['username'], $config['userpwd'], $opt ); $this->conn->query('SET NAMES '.$config['charset']); // echo 'connection succeeded!'; }catch(PDOException $e){ echo self::ERROR_UNABLE; error_log($e->getMessage()); return FALSE; } return $this; } /** * __clone() 防止克隆实例 * * @return void */ private function __clone() { return $this; } /** * Connection::getInstance() 获取连接数据库实例 * * @param String $config 数据库连接配置文件地址,默认为 '../../app/config/testDB.php' * @return void */ public static function getInstance($config = self::DEFAULT_CONFIG) { if( !self::$instance ) { self::$instance = new self($config); } return self::$instance; } /** * Connection->query() 封装查询的一些方法:query exec prepare * * @param string $sql 查询语句 * @return void */ public function query( $sql = '' ) { if( $sql && $sql !== '' ) { $stmt = $this->conn->query($sql); return $stmt; } return NULL; } }
C++
UTF-8
570
3.75
4
[]
no_license
#include <iostream> #include <deque> using namespace std; void print(deque<int> fl) { for (auto x : fl) cout << x << " "; cout << endl; } int main() { // basically stack/queue deque<int> d = {1, 3, 5}; d.push_back(2); d.push_front(4); // other available methods - insert(), size(), pop_front(), pop_back(), [c|r][begin|end]() & others like begin(), end(), front(), back(), etc // implemented internally using circular array, unlike in other languages which use dl-list, but this offers random access as well print(d); }
Markdown
UTF-8
645
3.046875
3
[]
no_license
# one-side-moveable-Rectangle-using-js use canvas html to make graphics drawing. This is a simple javascript code to draw a rectangle and to move it by keeping one side fixed. It contains two files animation.html and draw.js Open the animation.html to view. It contains a rectangle "abdc" with its breadth double than its length. There is a point p on a side say bd (initially at mid point), which can move up, down, right or left with condition that it always remain on the side i.e. point b,p,and d always remain in straight line. Side bd is rotated in both clockwise and anticlockwise direction about point p with keeping side ac fixed.
JavaScript
UTF-8
2,573
3.140625
3
[]
no_license
const background = document.querySelector('body') background.addEventListener( 'mousemove',(e)=>{ let clr = (e.clientX+e.clientY)/10 background.style.backgroundColor = `rgba(${e.clientX},${clr},${e.clientY},0.5)` }) let r=100, g=100, b=100, a=1 let color = `rgba(${r},${g},${b},${a})` //main circle for changing color const circleUp = document.querySelector('#head1') circleUp.style.borderColor = color const circleDown = document.querySelector('#head2') circleDown.style.borderColor = color //right inputs const first = document.querySelector('#now1') first.addEventListener('input',(e)=>{ let color = `rgba(${r},${g},${b},${a})` r = e.target.value if( r.length<=3 && 0<=r && r<=255 ){ circleUp.style.borderColor = color circleDown.style.borderColor = color } else{ alert('incorrect number') e.target.value = "" } }) const second = document.querySelector('#now2') second.addEventListener('input',(e)=>{ let color = `rgba(${r},${g},${b},${a})` g = e.target.value if( g.length<=3 && 0<=g && g<=255 ){ circleUp.style.borderColor = color circleDown.style.borderColor = color } else{ alert('incorrect number') e.target.value = "" } }) const third = document.querySelector('#now3') third.addEventListener('input',(e)=>{ let color = `rgba(${r},${g},${b},${a})` b = e.target.value if( b.length<=3 && 0<=b && b<=255 ){ circleUp.style.borderColor = color circleDown.style.borderColor = color } else{ alert('incorrect number') e.target.value = "" } }) const fourth = document.querySelector('#now4') fourth.addEventListener('input',(e)=>{ let color = `rgba(${r},${g},${b},${a})` a = e.target.value if( a.length<=1 && 0<=a && a<=1 ){ circleUp.style.borderColor = color circleDown.style.borderColor = color } else{ alert('incorrect number') e.target.value = "" } }) const button = document.querySelector('#color-set') button.addEventListener( 'click', (e)=>{ let color = `rgba(${r},${g},${b},${a})` first.value = Math.round(Math.random()*255) r = first.value second.value = Math.round(Math.random()*255) g = second.value third.value = Math.round(Math.random()*255) b = second.value fourth.value = Math.round(Math.random()*1) a = second.value circleUp.style.borderColor = color circleDown.style.borderColor = color })
Java
UTF-8
1,633
2.078125
2
[]
no_license
package com.appdevelopersumankr.suman_kumar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.AppCompatButton; import android.content.Intent; import android.os.Bundle; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.core.view.View; public class MainActivity extends AppCompatActivity { AppCompatButton login, register; FirebaseUser firebaseUser; @Override protected void onStart() { super.onStart(); firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); //check if user is null if (firebaseUser != null){ Intent intent = new Intent (MainActivity.this, Main_two.class); startActivity(intent); finish(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate ( savedInstanceState ); setContentView ( R.layout.activity_main ); login = findViewById(R.id.login); register = findViewById(R.id.register); login.setOnClickListener ( new android.view.View.OnClickListener () { @Override public void onClick(android.view.View v) { startActivity(new Intent(MainActivity.this, LoginActivity.class)); } } ); register.setOnClickListener ( new android.view.View.OnClickListener () { @Override public void onClick(android.view.View v) { startActivity(new Intent(MainActivity.this, RegisterActivity.class)); } } ); } }
JavaScript
UTF-8
2,056
3.4375
3
[ "MIT" ]
permissive
import { cities } from "./cities"; export var aRandomPlace = { city: undefined, day: function() { return getDayStatus() }, } //Gets a random city from an array const firstCity = (Math.floor(Math.random() * (cities.length))); var currentCity; //Saves a random place in a variable export function newRandomPlace() { if (aRandomPlace.city === undefined) { currentCity = firstCity; } else { if (currentCity + 1 >= cities.length) { currentCity = 0; } else { currentCity = currentCity + 1 } } aRandomPlace.city = cities[currentCity] return aRandomPlace; } function getDayPercentage(zero, hundred, x) { hundred = hundred - zero; x = x - zero; const h = hundred / 100; return Math.round((x / h) * 10) / 10; } function getDayStatus() { const sunc = SunCalc.getTimes(new Date(), aRandomPlace.city.lat, aRandomPlace.city.long); const now = moment().valueOf(); const millsecInDay = moment.duration(24, 'hours').asMilliseconds(); const sunrise = sunc.sunrise.getTime(); const sunset = sunc.sunset.getTime(); let isDay, circlePercentage; if (now > sunrise && now >= sunset) { circlePercentage = getDayPercentage(sunset, sunrise + millsecInDay, now) isDay = false } else if (sunset <= now && sunrise > now) { circlePercentage = getDayPercentage(sunset, sunrise, now); isDay = false } else if (sunrise >= now && sunset > now) { circlePercentage = getDayPercentage((sunset - millsecInDay), sunrise, now) isDay = false } else if (sunrise <= now && sunset > now) { circlePercentage = getDayPercentage(sunrise, sunset, now) isDay = true } (isDay) ? console.log(`We are at about ${circlePercentage}% of the day in ${aRandomPlace.city.name}`) : console.log(`We are at about ${circlePercentage}% of the night in ${aRandomPlace.city.name}`); return { isDay: isDay, percentage: circlePercentage, } }
Python
UTF-8
401
3.0625
3
[]
no_license
# Solution 1, simulation using dict class Solution: def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int: rs = collections.Counter() cs = collections.Counter() for i, j in indices: rs[i] += 1 cs[j] += 1 res = sum(1 for i in range(n) for j in range(m) if (rs[i] + cs[j]) % 2 == 1) return res
Java
UTF-8
2,272
2.328125
2
[]
no_license
package ppcg; import java.io.IOException; import java.util.Collection; import java.util.Hashtable; import PrologPlusCG.PPCGIO_CLI; import PrologPlusCG.cgspace.SpaceManager; import PrologPlusCG.gui.PrologPlusCGFrame; import PrologPlusCG.prolog.PPCGEnv; import PrologPlusCG.prolog.RuleVector; import PrologPlusCG.prolog.TypeHierarchy; public class CatOnMat { // Construct the application PPCGEnv env = null; PrologPlusCGFrame prologFrame = null; public CatOnMat() throws IOException { env = new PPCGEnv(); PPCGIO_CLI io = new PPCGIO_CLI(env); env.io = io; prologFrame = new PrologPlusCGFrame(env, false); } private void runCLI() throws InterruptedException { prologFrame.LoadFile("WizardOfOz.plgCG"); // SpaceManager.loadSpace("Planning.db4o", env); //System.out.println("Printing entire knowledge base"); // Collection<RuleVector> values = env.program.values(); // for(RuleVector rv: values) // { // System.out.println(rv.toString()); // } java.util.Vector<Hashtable<String, String> > vec = prologFrame.Resolve("[CITIZEN : x]<-MEMB-[COUNTRY : y].", true); if (vec != null) { for (int i = 0; i < vec.size(); ++i) { System.out.println(vec.get(i).toString()); } } else { System.out.println("No output."); } prologFrame.PurgeMemory(); } public static void main(String [] args) throws IOException { try { CatOnMat cli = new CatOnMat(); cli.runCLI(); } catch (Throwable e) { e.printStackTrace(); } } }
Python
UTF-8
234
3.078125
3
[]
no_license
def rotLeft(a, d): arr2=[] for i in range(len(a)): k = len(a)-d arr2.append(a[i-k]) return arr2 n = int(input()) d = int(input()) a = [] for i in range(n): a.append(int(input())) result = rotLeft(a, d) print(result)
Python
UTF-8
947
3.59375
4
[]
no_license
the_test = [[1,2,3],[4,5,6]] the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'bananna'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # lists aka arrays #(for key word in python) #(number could be anything just a temp variable #(in key word directing python to list) #(the_count list created above) #(colon at the end tells python the next line will be indented 4 spaces for block) #( function print "blah blah blah %d for numbers) #(%s string, %r represent or raw data) for cork in the_test: print "This is: %r" % cork for number in the_count: print "This is the count: %d" % number for fruit in fruits: print "Fruit type: %s" % fruit for i in change: print "I got %r" % i elements = [] for i in range(0, 6): print "adding %d to the list" % i elements.append(i) #(or range(6) 0 is implied #(if range(6) you don't use elements.append) #elements = range(6) for i in elements: print "Element was: %d" % i
Python
UTF-8
4,719
2.640625
3
[ "MIT" ]
permissive
import numpy as np import argparse from utils import data_utils from utils import ml_utils import pickle def shuffle_labels(labels): labelName_first = list(labels.keys())[0] numLabels = labels[labelName_first].shape[0] randIdxs = np.random.choice(numLabels, numLabels, replace=False) for key in labels.keys(): labels[key] = labels[key][randIdxs] return labels def classification(dataset_name, time_window, inp_len, num_shuffles): knn = 2 data = data_utils.get_dataset(dataset_name, time_window, inp_len) accs = [] encs = pickle.load(open("data/%s/encoding_%s_%s" % (dataset_name, time_window, inp_len), "rb")) """ labelsSelects = [ dict(), dict(), {"odor":[1,2,3],"isCorrect":[1]}, {"isInSeq":[1],"odor":[1,2,3],"isCorrect":[1]}, {"odor":[1,2,3],"isCorrect":[0]}, {"isInSeq":[1],"odor":[1,2,3],"isCorrect":[0]}, dict() ] accMeasures = ["isInSeq","odor","isInSeq","odor","isInSeq","odor","isCorrect"] """ labelsSelects = [ {"odor": [1, 2, 3], "isCorrect": [1]}, {"isInSeq": [1], "odor": [1, 2, 3], "isCorrect": [1]}, dict() ] accMeasures = ["isInSeq", "odor", "isCorrect"] for expNum in range(num_shuffles + 1): print("Run: (%i/%i)" % (expNum, num_shuffles)) acc = [] for encs_t, data_t in zip(encs, data): acc_t = dict() acc_t["startTime"] = min(encs_t["times"]) labelsTrain_t = data_t["labelsTrain"] labelsTest_t = data_t["labelsTest"] if expNum > 0: # Shuffle data labelsTrain_t = shuffle_labels(labelsTrain_t) labelsTest_t = shuffle_labels(labelsTest_t) # Make labels for labelsSelect, accMeasure in zip(labelsSelects, accMeasures): # Train model _, input_select_train, labels_select_train, name = data_utils.get_selected_data(labelsSelect, accMeasure, encs_t["inputTrain"], labelsTrain_t) if input_select_train.shape[0] == 0: print("No training examples for %s for accMeasure %s on trial %i, startTime %.3f, " "assigning NAN" % (dataset_name, accMeasure, expNum, acc_t["startTime"])) acc_t[name] = float('nan') continue predModel = ml_utils.knn_fn(input_select_train, labels_select_train, knn) # Test model _, input_select_test, labels_select_test, name = data_utils.get_selected_data(labelsSelect, accMeasure, encs_t["inputTest"], labelsTest_t) if input_select_train.shape[0] == 0: print("No testing examples for %s for accMeasure %s on trial %i, startTime %.3f, " "assigning NAN" % (dataset_name, accMeasure, expNum, acc_t["startTime"])) acc_t[name] = float('nan') continue labels_test_pred_t = predModel(input_select_test) acc_test = 100.0 * np.sum(labels_select_test == labels_test_pred_t) / float(input_select_test.shape[0]) acc_t[name] = acc_test acc.append(acc_t) accs.append(acc) pickle.dump(accs, open("data/%s/accs_%s_%s" % (dataset_name, time_window, inp_len), "wb")) return accs def main(): # Parse arguments parser = argparse.ArgumentParser() parser.add_argument('--timewindow', type=float, required=True, help="Time window of plots") parser.add_argument('--inpLen', type=int, required=True, help="Input length") parser.add_argument('--num_shuffles', type=int, default=0, help="Number of random shuffles") parser.add_argument('--datasets', type=str, required=True, help="Names of datasets separated by a comma") args = parser.parse_args() dataset_names = args.datasets.split(",") for dataset_name in dataset_names: print("DATASET: %s" % dataset_name) classification(dataset_name, args.timewindow, args.inpLen, args.num_shuffles) if __name__ == "__main__": main()
Java
UTF-8
1,706
2.9375
3
[]
no_license
package com.seven.ticket.enums; /** * @Description: TODO * @Author chendongdong * @Date 2019/11/8 9:56 * @Version V1.0 * "M":"一等座", * "0":"二等座", * "1":"硬座", * "N":"无座", * "2":"软座", * "3":"硬卧", * "4":"软卧", * "F":"动卧", * "6":"高等软卧", * "9":"商务座" **/ public enum SeatTypeEnum { BUSINESS_Z_TYPE("9", "商务座"), ONE_DZ_TYPE("M", "一等座"), SECOND_DZ_TYPE("0", "二等座"), HIG_SOFT_w_TYPE("6", "高级软卧"), MOVE_W_TYPE("F", "动卧"), SOFT_W_TYPE("4", "软卧"), HARD_W_TYPE("3", "硬卧"), SOFT_Z_TYPE("2", "软座"), HARD_Z_TYPE("1", "硬座"), NULL_Z_TYPE("N", "无座") ; private final String code; private final String name; SeatTypeEnum(final String code, final String name) { this.code = code; this.name = name; } public String getName() { return this.name; } public String getCode() { return this.code; } public static SeatTypeEnum nameOf(String code) { if (code == null) { return null; } for (SeatTypeEnum setEnum : values()) { if (setEnum.getCode().equals(code)) { return setEnum; } } return null; } public static SeatTypeEnum codeOf(String name) { if (name == null) { return null; } for (SeatTypeEnum setEnum : values()) { if (setEnum.getName().equals(name)) { return setEnum; } } return null; } }
Markdown
UTF-8
2,275
3.09375
3
[ "MIT" ]
permissive
# Ecosystem Algorithms ## What is Ecosystem Algorithms? Ecosystem Algorithms business layer on top of Ecosystem Notebooks, demonstrating how to effectively use and implement different business cases. ## Requirements * To use any of these algorithms [Ecosystem Notebooks](https://github.com/ecosystemai/ecosystem-notebooks) need to be installed. * Access to an Ecosystem API server. * Jupyter Notebook. * [Python3](https://www.python.org/downloads/): Was built using Python 3.6, but should work for most Python3 versions. ## Getting started To get going with Ecosystem Algorithms, start by installing Jupyter Notebook. **Note:** if Ecosystem Notebooks is already installed then all the required software will available. This can be done by running the configure_jupyter.sh shell script, in addition recommended styling options can be added by running the configure_jupyter_styling.sh shell script, but is not required. To install the relevant python code add the parent directory(ecosystem-notebooks) to the PYTHONPATH environment variable. Once Jupyter is installed run the command: ```bash jupyter notebook ``` in the directory containing the algorithm notebooks designated by the .ipynb extention. This will open up a default web browser to the Jupyter Notebook landing page from which you can open up the required notebook. ![Jupyter Landing Page](https://github.com/ecosystemai/ecosystem-algorithms/blob/master/docs/images/jupyter_landing_page.png "Jupyter Landing Page") ## How does Ecosystem Algorithms work The opened notebook is a live computing environment, allowing code to be edited and run in place. To navigate the notebook, use the table of contents on the left to easily find any section. Logging on is required before any of the api endpoints will function. Depending on the algorithm notebook this will either be a username, password and url endpoint combination or just an url endpoint. This will generate an authentication token that all api calls required to function. ![Login](https://github.com/ecosystemai/ecosystem-algorithms/blob/master/docs/images/login.png "Login") The Ecosystem Algorithms contains a host of business cases to play around with, whether running the code in place or copying it to be executed on an extranal site.
Python
UTF-8
816
3.125
3
[]
no_license
# coding=utf-8 # author: zengyuetian # count test case number via keyword "@reviewer" import os def count_keyword(file_name, word): count = 0 f = open(file_name) lines = f.readlines() for line in lines: if line.find(word) >= 0: count += 1 return count if __name__ == "__main__": python_file_num = 0 test_case_num = 0 for root, dirs, files in os.walk("../../testsuite"): for fi in files: if fi.find('.py') > -1: python_file_num += 1 # print fi full_path = os.path.join(root, fi) test_case_num += count_keyword(full_path, "@reviewer") print("\nTotal python file number is {0}.".format(python_file_num)) print("\nTotal test case number is {0}.".format(test_case_num))
Java
UTF-8
740
2.796875
3
[ "MIT" ]
permissive
package org.samuelsmal.tree; import org.samuelsmal.game.GPPlayer; /** * Created by samuel on 14/08/14. */ public class TournamentEntry implements Comparable<TournamentEntry> { private GPPlayer player; private int matchesWon; public TournamentEntry(GPPlayer player) { this.player = player; matchesWon = 0; } public void newMatchWon() { matchesWon++; } public int matchesWon() { return matchesWon; } public GPPlayer getPlayer() { return player; } @Override public int compareTo(TournamentEntry o) { return o.matchesWon - matchesWon; } @Override public String toString() { return player.getClass().getName(); } }
Java
UTF-8
485
2.03125
2
[]
no_license
package nc.onlinelibrary.mvc.dao; import nc.onlinelibrary.mvc.domain.Book; import nc.onlinelibrary.mvc.domain.Issue; import nc.onlinelibrary.mvc.domain.Users; import java.util.List; public interface UserDAO { void addUser(Users user); List listUsers(); void deleteUser(String username); Users getUser(String username); List<Issue> getUserIssue(String username); void addBookToList(Users users, Book book); List<Book> getUserReadList(String username); }
Java
UTF-8
2,105
2.1875
2
[ "MIT" ]
permissive
package com.cratorsoft.android.dialog; import android.app.Dialog; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.text.Editable; import android.text.Selection; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import com.afollestad.materialdialogs.MaterialDialog; import com.cratorsoft.android.chat.UserAdapter; import com.cratorsoft.android.frag.FragChatLog; import com.earthflare.android.ircradio.Globo; import com.earthflare.android.ircradio.R; import org.jibble.pircbot.User; public class DlgPromptUser extends DialogFragment implements AdapterView.OnItemClickListener{ public static DlgPromptUser newInstance() { DlgPromptUser frag = new DlgPromptUser(); return frag; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { String title = Globo.chatlogActChannelName; MaterialDialog mdlg = new MaterialDialog.Builder(this.getActivity()) .title(title) //.customView(R.layout.dlg_prompt_user) .adapter(new UserAdapter(this.getActivity()),null) .positiveText(this.getActivity().getString(R.string.button_ok)) .build(); /* ListView listview = (ListView)mdlg.getCustomView().findViewById(R.id.ListViewUsers); UserAdapter adapter = new UserAdapter(this.getActivity()); listview.setAdapter(adapter); listview.setOnItemClickListener(this); */ return mdlg; } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { UserAdapter adapter = (UserAdapter) arg0.getAdapter(); User user = (User)adapter.getItem(arg2); FragChatLog acl = (FragChatLog) this.getTargetFragment(); EditText et = (EditText)acl.getView().findViewById(R.id.textinput); et.setText("/msg " + user.getNick() + " "); //move carat to end of line Editable etext = et.getText(); int position = etext.length(); Selection.setSelection(etext, position); this.dismiss(); } }
Java
UTF-8
18,590
2.078125
2
[]
no_license
package com.tm.bltuth; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.tm.bltuth.application.MyApplication; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class MainActivity extends AppCompatActivity { //private TextView tvSEnd; // private TextView tvrcv; private static final int REQUEST_ENABLE_BT = 2; private static final int REQUEST_CONNECT_DEVICE = 1; //private EditText edtInput; private EditText editTextScreen; private Button btnOne; private Button btnTwo; private Button btnThree; private Button btnPlus; private Button btnFour; private Button btnFive; private Button btnSix; private Button btnMinus; private Button btnSeven; private Button btnEight; private Button btnNine; private Button btnMultiply; private Button btnClear; private Button btnZero; private Button btnEqual; private Button btnDevided; private float mValueOne=0, mValueTwo=0; boolean mAddition, mSubtruction, mMultiplication, mDevition; private String str=""; private Character op='q'; private int i, num, tempnum; private String operator=""; private boolean isSecond=false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.calculator_layout); // tvSEnd=(TextView)this.findViewById(R.id.tvSEnd); // edtInput=(EditText) this.findViewById(R.id.edtInput); // tvrcv=(TextView)this.findViewById(R.id.tvrcv); // tvrcv.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // rcv(); // } // }); // tvSEnd.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // if (!MyApplication.mBluetoothService.isBTopen()) { // Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // startActivityForResult(enableIntent, REQUEST_ENABLE_BT); // } // int state = MyApplication.mBluetoothService.getState(); // if (state != 3) { // Toast.makeText(MainActivity.this, "Please connect Bluetooth printer", Toast.LENGTH_LONG).show(); // Intent serverIntent = new Intent(MainActivity.this, DeviceListActivity.class); // startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); // } // else { // connect(); // } // } // }); //========================= editTextScreen=(EditText) findViewById(R.id.et_screen); btnOne=(Button)findViewById(R.id.btn_one); btnTwo=(Button)findViewById(R.id.btn_two); btnThree=(Button)findViewById(R.id.btn_three); btnPlus=(Button)findViewById(R.id.btn_plus); btnFour=(Button)findViewById(R.id.btn_four); btnFive=(Button)findViewById(R.id.btn_five); btnSix=(Button)findViewById(R.id.btn_six); btnMinus=(Button)findViewById(R.id.btn_minus); btnSeven=(Button)findViewById(R.id.btn_seven); btnEight=(Button)findViewById(R.id.btn_eight); btnNine=(Button)findViewById(R.id.btn_nine); btnMultiply=(Button)findViewById(R.id.btn_multiply); btnClear=(Button)findViewById(R.id.btn_clear); btnZero=(Button)findViewById(R.id.btn_zero); btnEqual=(Button)findViewById(R.id.btn_equal); btnDevided=(Button)findViewById(R.id.btn_devided); btnOne.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //insert(1); // editTextScreen.setText(editTextScreen.getText()+"1"); common("1"); } }); btnTwo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //insert(2); // editTextScreen.setText(editTextScreen.getText()+"2"); common("2"); } }); btnThree.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //insert(3); // editTextScreen.setText(editTextScreen.getText()+"3"); common("3"); } }); btnFour.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //insert(4); // editTextScreen.setText(editTextScreen.getText()+"4"); common("4"); } }); btnFive.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //insert(5); // editTextScreen.setText(editTextScreen.getText()+"5"); common("5"); } }); btnSix.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //insert(6); // editTextScreen.setText(editTextScreen.getText()+"6"); common("6"); } }); btnSeven.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //insert(7); // editTextScreen.setText(editTextScreen.getText()+"7"); common("7"); } }); btnEight.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //insert(8); // editTextScreen.setText(editTextScreen.getText()+"8"); common("8"); } }); btnNine.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //insert(9); // editTextScreen.setText(editTextScreen.getText()+"9"); common("9"); } }); btnZero.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //insert(0); // editTextScreen.setText(editTextScreen.getText()+"0"); common("0"); } }); btnPlus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { operate("+"); } }); btnMinus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { operate("-"); } }); btnMultiply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { operate("*"); } }); btnDevided.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { operate("/"); } }); btnEqual.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //calculate(); equal(); operator=""; mValueOne=0; str=""; verified(); } }); btnClear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { reset(); verified(); } }); //======= } public void common(String input){ if(operator=="" || mValueOne!=0){ editTextScreen.setText(""); } str=str+input; editTextScreen.setText(str); verified(); } boolean stopWorker; void beginListenForData() { final Handler handler = new Handler(); final byte delimiter = 10; //This is the ASCII code for a newline character //=========== // InputStream instream=null; // btInputstreem=instream; // try { // btInputstreem=MyApplication.btsocket.getInputStream(); // } catch (IOException e) { // e.printStackTrace(); // } // byte[] buffer = new byte[1024]; // int bytes; // // try { // bytes = btInputstreem.read(buffer); // final String strReceived = new String(buffer, 0, bytes); // final String msgReceived = String.valueOf(bytes) + // " bytes received:\n" // + strReceived; // // runOnUiThread(new Runnable(){ // // @Override // public void run() { // Toast.makeText(MainActivity.this, ""+strReceived, Toast.LENGTH_SHORT).show(); //// tvSEnd.setText(strReceived); // }}); // // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } stopWorker = false; // readBufferPosition = 0; // readBuffer = new byte[1024]; Thread workerThread = new Thread(new Runnable() { public void run() { while(!Thread.currentThread().isInterrupted() && !stopWorker) { InputStream instream=null; btInputstreem=instream; try { btInputstreem=MyApplication.btsocket.getInputStream(); } catch (IOException e) { e.printStackTrace(); } byte[] buffer = new byte[1024]; int bytes; try { bytes = btInputstreem.read(buffer); final String strReceived = new String(buffer, 0, bytes); final String msgReceived = String.valueOf(bytes) + " bytes received:\n" + strReceived; runOnUiThread(new Runnable(){ @Override public void run() { editTextScreen.setText(strReceived+""); Toast.makeText(MainActivity.this, ""+strReceived, Toast.LENGTH_SHORT).show(); // tvSEnd.setText(strReceived); }}); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); workerThread.start(); } public void equal(){ float result = 0; if(str!="") { mValueTwo = Float.parseFloat(str); if (operator == "+") { result = mValueOne + mValueTwo; //mAddition=false; } else if (operator == "-") { result = mValueOne - mValueTwo; //mSubtruction=false; } else if (operator == "*") { result = mValueOne * mValueTwo; //mMultiplication=false; } else if (operator == "/") { result = mValueOne / mValueTwo; //mDevition=false; } }else { result=mValueOne; } editTextScreen.setText(((int)result)+""); mValueOne=result; mValueTwo=0; } public void operate(String op){ if(editTextScreen==null || (editTextScreen.getText()+"")==""){ editTextScreen.setText(""); }else{ if(mValueOne==0) mValueOne=Float.parseFloat(editTextScreen.getText()+""); else { equal(); } operator=op; str=""; //editTextScreen.setText(null); } verified(); } public void reset(){ mValueOne=0; mValueTwo=0; operator=""; str=""; editTextScreen.setText("0"); } public void verified(){ if (!MyApplication.mBluetoothService.isBTopen()) { Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } int state = MyApplication.mBluetoothService.getState(); if (state != 3) { Toast.makeText(MainActivity.this, "Please connect Bluetooth printer", Toast.LENGTH_LONG).show(); Intent serverIntent = new Intent(MainActivity.this, DeviceListActivity.class); startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); } else { connect(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_ENABLE_BT) { if (resultCode == Activity.RESULT_OK) { ToastHelper.showToast(MainActivity.this, "Bluetooth open successful"); } else { ToastHelper.showToast(MainActivity.this, "Bluetooth open faild"); } } else if (requestCode == REQUEST_CONNECT_DEVICE) { if (resultCode == Activity.RESULT_OK) { String address = data.getExtras() .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS); String noDevices = "No paired device"; Log.w("address",address); Log.w("noDevices",noDevices); if (!noDevices.contains(address)) { BluetoothDevice mBluetoothDevice = MyApplication.mBluetoothService.getDevByMac(address); if (mBluetoothDevice != null) MyApplication.mBluetoothService.connect(mBluetoothDevice); // connect(); } else { ToastHelper.showToast(MainActivity.this, noDevices); } } else { ToastHelper.showToast(MainActivity.this, "Bluetooth Connection fail"); } } } public void rcv(){ InputStream instream=null; btInputstreem=instream; try { btInputstreem=MyApplication.btsocket.getInputStream(); } catch (IOException e) { e.printStackTrace(); } byte[] buffer = new byte[1024]; int bytes; try { bytes = btInputstreem.read(buffer); final String strReceived = new String(buffer, 0, bytes); final String msgReceived = String.valueOf(bytes) + " bytes received:\n" + strReceived; runOnUiThread(new Runnable(){ @Override public void run() { Toast.makeText(MainActivity.this, ""+strReceived, Toast.LENGTH_SHORT).show(); // tvSEnd.setText(strReceived); }}); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void printSingleText(String msg) { try { byte[] format = { 27, 33, 0 }; btoutputstream.write(format); btoutputstream.write(PrinterCommands.ESC_ALIGN_LEFT); btoutputstream.write(msg.getBytes(),0,msg.getBytes().length); } catch (IOException e) { Log.w("errorsending",e.toString()); e.printStackTrace(); } } public OutputStream btoutputstream; public InputStream btInputstreem; protected void connect() { OutputStream opstream = null; try { opstream = MyApplication.btsocket.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } btoutputstream = opstream; //print command try { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } btoutputstream = MyApplication.btsocket.getOutputStream(); byte[] printformat = { 0x1B, 0*21, FONT_TYPE }; btoutputstream.write(printformat); printSingleText(editTextScreen.getText().toString().trim()); btoutputstream.flush(); } catch (IOException e) { e.printStackTrace(); } beginListenForData(); } byte FONT_TYPE; private class ReceiveData extends Thread{ public void rcv(){ InputStream instream=null; btInputstreem=instream; try { btInputstreem=MyApplication.btsocket.getInputStream(); } catch (IOException e) { e.printStackTrace(); } byte[] buffer = new byte[1024]; int bytes; try { bytes = btInputstreem.read(buffer); final String strReceived = new String(buffer, 0, bytes); final String msgReceived = String.valueOf(bytes) + " bytes received:\n" + strReceived; runOnUiThread(new Runnable(){ @Override public void run() { Toast.makeText(MainActivity.this, ""+strReceived, Toast.LENGTH_SHORT).show(); // tvSEnd.setText(strReceived); editTextScreen.setText(strReceived); }}); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Java
UTF-8
1,412
2.09375
2
[]
no_license
package com.softeem.entity; import java.io.Serializable; /** * 报销单细节表(ExpenseReportDetail)实体类 * * @author makejava * @since 2021-01-24 15:24:52 */ public class ExpenseReportDetail implements Serializable { private static final long serialVersionUID = -17571713453405123L; /** * 报销单细节表id */ private Integer expensiveDetailId; /** * 报销单id */ private Integer expensiveId; private String item; /** * 费用明细 */ private Double amount; /** * 费用备注 */ private String comment; public Integer getExpensiveDetailId() { return expensiveDetailId; } public void setExpensiveDetailId(Integer expensiveDetailId) { this.expensiveDetailId = expensiveDetailId; } public Integer getExpensiveId() { return expensiveId; } public void setExpensiveId(Integer expensiveId) { this.expensiveId = expensiveId; } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } }
JavaScript
UTF-8
3,161
2.5625
3
[ "MIT" ]
permissive
'use strict'; module.exports = function() { var _this = this; if (!this.imagePosition) { this.imagePosition = { x: 0, y: 0, width: 0, height: 0 }; } if (this.image.blendingMode) { this.context.globalCompositeOperation = this.image.blendingMode; } if (this.imageNode) { setImagePosition(); return; } this.imageNode = new Image(); this.imageNode.onerror = function() { throw new Error('Granim: The image source is invalid.'); }; this.imageNode.onload = function() { _this.imgOriginalWidth = _this.imageNode.width; _this.imgOriginalHeight = _this.imageNode.height; setImagePosition(); _this.refreshColorsAndPos(); if (!_this.isPausedWhenNotInView || _this.isCanvasInWindowView) { _this.animation = requestAnimationFrame(_this.animateColors.bind(_this)); } _this.isImgLoaded = true; }; this.imageNode.src = this.image.source; function setImagePosition() { var i, currentAxis; for (i = 0; i < 2; i++) { currentAxis = !i ? 'x' : 'y'; setImageAxisPosition(currentAxis); } function setImageAxisPosition(axis) { var canvasWidthOrHeight = _this[axis + '1']; var imgOriginalWidthOrHeight = _this[axis === 'x' ? 'imgOriginalWidth' : 'imgOriginalHeight']; var imageAlignIndex = axis === 'x' ? _this.image.position[0] : _this.image.position[1]; var imageAxisPosition; switch(imageAlignIndex) { case 'center': imageAxisPosition = imgOriginalWidthOrHeight > canvasWidthOrHeight ? -(imgOriginalWidthOrHeight - canvasWidthOrHeight) / 2 : (canvasWidthOrHeight - imgOriginalWidthOrHeight) / 2; _this.imagePosition[axis] = imageAxisPosition; _this.imagePosition[axis === 'x' ? 'width' : 'height'] = imgOriginalWidthOrHeight; break; case 'top': _this.imagePosition['y'] = 0; _this.imagePosition['height'] = imgOriginalWidthOrHeight; break; case 'bottom': _this.imagePosition['y'] = canvasWidthOrHeight - imgOriginalWidthOrHeight; _this.imagePosition['height'] = imgOriginalWidthOrHeight; break; case 'right': _this.imagePosition['x'] = canvasWidthOrHeight - imgOriginalWidthOrHeight; _this.imagePosition['width'] = imgOriginalWidthOrHeight; break; case 'left': _this.imagePosition['x'] = 0; _this.imagePosition['width'] = imgOriginalWidthOrHeight; break; } if (_this.image.stretchMode) { imageAlignIndex = axis === 'x' ? _this.image.stretchMode[0] : _this.image.stretchMode[1]; switch(imageAlignIndex) { case 'none': break; case 'stretch': _this.imagePosition[axis] = 0; _this.imagePosition[axis === 'x' ? 'width' : 'height'] = canvasWidthOrHeight; break; case 'stretch-if-bigger': if (imgOriginalWidthOrHeight < canvasWidthOrHeight) break; _this.imagePosition[axis] = 0; _this.imagePosition[axis === 'x' ? 'width' : 'height'] = canvasWidthOrHeight; break; case 'stretch-if-smaller': if (imgOriginalWidthOrHeight > canvasWidthOrHeight) break; _this.imagePosition[axis] = 0; _this.imagePosition[axis === 'x' ? 'width' : 'height'] = canvasWidthOrHeight; break; } } } } };
Shell
UTF-8
864
3.203125
3
[]
no_license
# ###################################################################### FileMarker "script:build_db.sh START" # ###################################################################### BUILD_DB_SQL=${PIPE_DIR}/build_db_${v_team}.sql ECHO "Drop and recreate database for branch ${v_team} using ${BUILD_DB_SQL}" cat ${WORKSPACE}/build_db.template |sed -e "s/V_TEAM/${v_team}/g" -e "s/V_APPNAME/${MYAPP_NAME}/g" > ${BUILD_DB_SQL} cat ${BUILD_DB_SQL} HEADER2 "Execute ${BUILD_DB_SQL}" export PGPASSWORD=rao psql -h localhost -p 5432 -d rao -U rao -f ${BUILD_DB_SQL} r=$? if [ $r -eq 0 ]; then ECHO "Build DB successful for ${v_team}" else ERROR "Build DB failed for ${v_team}" fi # ###################################################################### FileMarker "script:build_db.sh END" # ######################################################################
Markdown
UTF-8
838
2.53125
3
[ "MIT" ]
permissive
# ブロックブラケットハンドラ(ブロックブラケットハンドラ) Block Bracket Handler はゲーム内のブロックにアクセスできます。 ゲームに登録されているブロックのみを取得できます そのため、Modの追加や削除は、Block Bracket HandlerでModのブロックを参照すると問題が発生する可能性があります。 ブロックは次のようにブロックブラケットハンドラで参照されます。 ```zenscript <block:modID:blockName> <block:minecraft:dirt> ``` If the block is found, this will return an [ICTBlockState](/Mods/ContentTweaker/Vanilla/Types/Block/ICTBlockState/) Object. Please refer to the [respective Wiki entry](/Mods/ContentTweaker/Vanilla/Types/Block/ICTBlockState/) for further information on what you can do with these.
Java
UTF-8
9,115
2.734375
3
[ "Unlicense" ]
permissive
package net.hetimatan.io.file; import java.io.File; import java.io.IOException; import net.hetimatan.io.filen.CashKyoroFile; import junit.framework.TestCase; public class TestForVirtualFile extends TestCase { public void log(String message) { // System.out.println("kiyo:"+"TestForViertualFile:"+message); } public void testHello() { log("testHello"); } public void testZeroByte() throws IOException { File testPath = new File(getFile(),"__001__.txt"); CashKyoroFile vf = null; try { testPath.delete(); testPath.createNewFile(); vf = new CashKyoroFile(testPath, 1024, 3); byte[] buffer = new byte[101]; for(int i=0;i<buffer.length;i++) { buffer[0] = 0; } int ret = vf.read(buffer); assertEquals(-1, ret); for(int i=0;i<buffer.length;i++) { assertEquals(0, buffer[0]); } } catch (Exception e) { e.printStackTrace(); assertTrue(false); } finally { if(vf != null) { vf.isCashMode(false); vf.close(); } } } public void testSync() throws IOException { File testPath = new File(getFile(),"__001__.txt"); CashKyoroFile vf = null; try { testPath.delete(); testPath.createNewFile(); byte[] add = {1, 2, 3, 4, 5}; vf = new CashKyoroFile(testPath, 1024, 5); byte[] read = new byte[6]; vf.addChunk(add, 0, 5); int ret = vf.read(read); assertEquals(1, read[0]); assertEquals(2, read[1]); assertEquals(3, read[2]); assertEquals(4, read[3]); assertEquals(5, read[4]); assertEquals(0, read[5]); assertEquals(5, ret); } finally { if(vf != null) { vf.isCashMode(false); vf.close(); } } } public void testUnsync() throws IOException { File testPath = new File(getFile(),"__001__.txt"); CashKyoroFile vf = null; try { testPath.delete(); testPath.createNewFile(); byte[] add = {1, 2, 3, 4, 5}; vf = new CashKyoroFile(testPath, 1024, 5); byte[] read = new byte[6]; vf.addChunk(add, 0, 5); vf.syncWrite(); vf.addChunk(add, 0, 1); int ret = vf.read(read); assertEquals(1, read[0]); assertEquals(2, read[1]); assertEquals(3, read[2]); assertEquals(4, read[3]); assertEquals(5, read[4]); assertEquals(1, read[5]); assertEquals(6, ret); } finally { if(vf != null) { vf.close(); } } } public void testSecound() { File testPath = new File(getFile(),"__001__.txt"); String testdata= "「この間はすまなかった。いつも間が悪くて君に会う機会がない。"+ "きょうは歌舞伎座の切符が二枚手に入ったから一緒に見に行か"+ "ないか。午後一時の開場だから十時頃の電車で銀座あたりへ来"+ "てくれるといい。君の知っているカフェーかレストランがあるだろう」"; CashKyoroFile vf = null; try { testPath.delete(); testPath.createNewFile(); vf = new CashKyoroFile(testPath, 1024, 5); byte[] buffer = new byte[1000]; for(int i=0;i<buffer.length;i++) { buffer[0] = 0; } int ret = vf.read(buffer); assertEquals(-1, ret); for(int i=0;i<buffer.length;i++) { assertEquals(0, buffer[0]); } byte[] buff = testdata.getBytes("utf8"); vf.addChunk(buff, 0, buff.length); { // first read ret = vf.read(buffer); String result = new String(buffer, 0 , ret); assertEquals(testdata, result); // second read { for(int i=0;i<buffer.length;i++) { buffer[0]=0; } ret = vf.read(buffer); assertEquals(-1, ret); } } { // sync for(int i=0;i<buffer.length;i++) { buffer[0]=0; } vf.syncWrite(); vf.seek(0); ret = vf.read(buffer); String result = new String(buffer, 0 , ret); assertEquals(testdata, result); } } catch (Exception e) { e.printStackTrace(); assertTrue(false); } finally { if(vf != null) { try { vf.close(); } catch (IOException e) { e.printStackTrace(); } } } } public void testThird() { File testPath = new File(getFile(),"__001__.txt"); String testdata= "" +"「ウップ。怪しい結論だね。恐ろしく無駄骨の折れる虚栄じゃないか」\r\n" +"「ええ。それがね。あの人は地道に行きたい行きたい。" +"みんなに信用されていたいいたいと、思い詰めているのがあの娘" +"ひと" +"の虚栄なんですからね。そのために虚構" +"うそ" +"を吐" +"つ" +"くんですよ」\r\n" +"「それが第一おかしいじゃないか。第一、そんなにまでしてこちらの信用を博する必要が何処に在るんだい。看護婦としての手腕はチャント認められているんだし、実家" +"うち" +"が裕福だろうが貧乏だろうが看護婦としての資格や信用には無関係だろう。それくらいの事がわからない馬鹿じゃ、姫草はないと思うんだが」\r\n" +"「ええ。そりゃあ解ってるわ。たとえドンナ女" +"ひと" +"だっても現在ウチの病院の大切なマスコットなんですから、疑ったり何かしちゃすまないと思うんですけど……ですけど毎月二日か三日頃になると印形" +"ハンコ" +"で捺" +"お" +"したように白鷹先生の話が出て来るじゃないの。おかしいわ……」\r\n" +"「そりゃあ庚戌会がその頃にあるからさ」\r\n"; CashKyoroFile vf = null; try { testPath.delete(); testPath.createNewFile(); vf = new CashKyoroFile(testPath, 1024, 3); byte[] buffer = new byte[1300]; for(int i=0;i<buffer.length;i++) { buffer[0] = 0; } int ret = vf.read(buffer); assertEquals(-1, ret); for(int i=0;i<buffer.length;i++) { assertEquals(0, buffer[0]); } byte[] testdataBuffer = testdata.getBytes("utf8"); vf.addChunk(testdataBuffer, 0, testdataBuffer.length); { // assertTrue(""+testdataBuffer.length +"<="+buffer.length,testdataBuffer.length <= buffer.length); // first read ret = vf.read(buffer); String result = new String(buffer, 0 , ret); assertEquals(testdata, result); // second read { for(int i=0;i<buffer.length;i++) { buffer[0]=0; } ret = vf.read(buffer); assertEquals(-1, ret); } } { // sync for(int i=0;i<buffer.length;i++) { buffer[0]=0; } vf.syncWrite(); vf.seek(0); ret = vf.read(buffer); String result = new String(buffer, 0 , ret); assertEquals(testdata, result); } } catch (Exception e) { e.printStackTrace(); assertTrue(false); } finally { if(vf != null) { try { vf.close(); } catch (IOException e) { e.printStackTrace(); } } } } public void testExtra1() { File testPath = new File(getFile(),"__001__.txt"); String[] testdata= { "●..1/:::/storage/sdcard0\r\n", " 2013/01/12 20:41:08:::/storage/sdcard0\r\n", " 8192byte:::/storage/sdcard0:::HR\r\n", "●keyword/:::/storage/sdcard0/.jota/keyword\r\n", " 2012/12/14 23:21:43:::/storage/sdcard0/.jota/keyword\r\n", " 4096byte:::/storage/sdcard0/.jota/keyword:::HR\r\n", "●..2/:::/storage/sdcard0\r\n", " 2013/01/12 20:41:08:::/storage/sdcard0\r\n", " 8192byte:::/storage/sdcard0:::HR\r\n" }; try { testPath.delete(); testPath.createNewFile(); CashKyoroFile vf = new CashKyoroFile(testPath, 1024, 5); byte[] buffer = new byte[1300]; for(int i=0;i<buffer.length;i++) { buffer[0] = 0; } int ret = vf.read(buffer); assertEquals(-1, ret); for(int i=0;i<buffer.length;i++) { assertEquals(0, buffer[0]); } for(String t : testdata) { byte[] testdataBuffer = t.getBytes("utf8"); vf.addChunk(testdataBuffer, 0, testdataBuffer.length); } StringBuilder expected = new StringBuilder(); for(String t : testdata) { expected.append(t); } { // // assertTrue(""+testdataBuffer.length +"<="+buffer.length,testdataBuffer.length <= buffer.length); // first read ret = vf.read(buffer); String result = new String(buffer, 0 , ret); assertEquals(expected.toString(), result); assertEquals("check:file pointer",ret, vf.getFilePointer()); assertEquals("check:length",ret, vf.length()); } { // sync for(int i=0;i<buffer.length;i++) { buffer[0]=0; } vf.syncWrite(); vf.seek(0); ret = vf.read(buffer); String result = new String(buffer, 0 , ret); assertEquals(expected.toString(), result); } vf.close(); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } } //*/ public File getFile() { return new File("."); } }
PHP
UTF-8
6,117
2.765625
3
[]
no_license
<?php /*//////////////////////////////////////////////////////////////////////////////////////////////////////////// @author Novi Sonko 2012 ////////////////////////////////////////////////////////////////////////////////////////////////////////*/ class print_handler extends website_object { private $shelf; private $pointer; public function config() { global $c, $m, $u; $this->has['form']= true; $this->has['submit']= true; $this->i_var['target_url']= $c->update_current_url("next_selected"); $this->i_var['form_name']= "print_handler"; $this->i_var['form_method']= "GET"; $this->shelf= array(); $memory_pointer= $m->print_handler_pointer; if ($_REQUEST['process_preview'] || ($_REQUEST['v'] == "process_preview")) { $this->is['process_preview']= true; } if (is_numeric($memory_pointer) && $_REQUEST['next_selected']) { $this->selected= $m->print_handler_selected; } elseif (is_array($_REQUEST['data_print_letter'])) { for ($i=0; $i < count($_REQUEST['data_print_letter']); $i++) { $list= explode("_", $_REQUEST['data_print_letter'][$i]); $this->selected[$i]= $this->require_id("numeric", $list[0]); } } //------------------------------ if ($u->dept_has_write_letter && $u->has_print_letter && ($_REQUEST['print_selected'] || $_REQUEST['print_all'])) { $this->is['printable']= true; $this->has['submit']= false; } else { $count= count($this->selected); if (($count > 1) && (!is_numeric($memory_pointer) || !$_REQUEST['next_selected'])) { $this->pointer= 0; } elseif (is_numeric($memory_pointer) && $_REQUEST['next_selected']) { $this->pointer= &$memory_pointer; $this->pointer= ($this->pointer == ($count-1)) ? 0 : ++$this->pointer; } if ($count > 1) { $this->has['many']= true; } } } private function initialize_object() { $obj= new letter_preview_handler(); $obj->initialize(); $obj->config(); $obj->set_has("submit", false); $obj->set_has("form", false); $obj->set_has("save", false); return $obj; } public function onsubmit() { } public function set_data() { global $q; if (!empty($this->selected)) { $list= &$this->selected; for ($i=0; $i < count($list); $i++) { if (is_numeric($list[$i])) { $q->set_filter("AND print_letter1.id_print_letter='".$list[$i]."'"); $q->sql_select("select_print_letter1", $numrows, $res, "all"); if ($numrows == 1) { $this->make_object(mysql_fetch_assoc($res)); } else { f1::echo_error("#data not found for letter with #id ".$list[$i].", in met#manage_list, cls#print_handler"); } } } } elseif ($_REQUEST['print_all']) { $q->sql_select("select_print_letter1", $numrows, $res, "all"); if ($numrows >= 1) { while ($data= mysql_fetch_assoc($res)) { $this->make_object($data); } } } } private function make_object(&$data) { $obj= $this->initialize_object(); $obj->set_id_letter($data['id_letter']); $obj->set_id_proj($data['id_proj']); $this->store_object($obj); } private function store_object(&$obj) { $_REQUEST['process_preview']= true; $obj->set_data(); $obj->start(); $this->shelf[]= $obj; } public function display_submit() { global $m, $u, $t; echo "<div class=\"submit_section\">"; if (!$this->has['many']) { buttons::back(true); } elseif ($this->has['many']) { echo <<<HTML <input type="submit" class="submit_button" name="print_letters" value="{$t->back}"/> <input type="submit" class="submit_button" name="next_selected" value="{$t->next}"/> HTML; } echo "</div>"; } public function display() { if (count($this->shelf)) { if ($this->is['printable']) { echo <<<HTML <script language="javascript" type="text/javascript"> //<!-- function print_page () { window.print(); } print_page(); //--> </script> HTML; for ($i=0; $i < count($this->shelf); $i++) { $this->shelf[$i]->display(); } } else { if ($this->has['form']) { $this->open_form($this->i_var['form_name'], $this->i_var['form_method'], $this->i_var['target_url']); } //-------- if ($this->has['submit']) { $this->display_submit(); } if ($this->has['many']) { $this->shelf[$this->pointer]->display(); } else { $this->shelf[0]->display(); } //------------------ if ($this->has['form']) { echo "</form>"; } } } //-------------------------- unset($this); } public function __destruct() { global $m; if ($this->has['many']) { $m->print_handler_selected= $this->selected; $m->print_handler_pointer= $this->pointer; } } }
C#
UTF-8
1,667
2.6875
3
[]
no_license
using System.Threading.Tasks; using System.Collections.Generic; using Newtonsoft.Json; using Dingus.Models; using Dingus.Helpers; namespace Dingus.Services { class CompanyServices { private NetServices _service; private JsonSerializerSettings _jsonSettings; public CompanyServices() { _service = new NetServices(); _jsonSettings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }; Task.Run(async () => AppSettings.Companies = await GetCompanies()); } public async Task<List<Company>> GetCompanies() { return await _service.GetDeserializedObject<List<Company>>($"{AppSettings.IexTradingHost}/{AppSettings.IexTradingVersion}/ref-data/symbols", _jsonSettings); } public async Task<List<CompanyChart>> GetCompanyChart(string symbol, int interval = 7) { return await _service.GetDeserializedObject<List<CompanyChart>>($"{AppSettings.IexTradingHost}/{AppSettings.IexTradingVersion}/stock/{symbol}/chart/1y?chartInterval={interval}", _jsonSettings); } public async Task<CompanyQuote> GetCompanyQuote(string symbol) { return await _service.GetDeserializedObject<CompanyQuote>($"{AppSettings.IexTradingHost}/{AppSettings.IexTradingVersion}/stock/{symbol}/quote", _jsonSettings); } public List<Company> GetCompanies(string keyword) { return AppSettings.Companies.FindAll((Company company) => company.Name.ToUpper().Contains(keyword.ToUpper()) || company.Symbol.ToUpper().Contains(keyword.ToUpper())); } } }
C
UTF-8
1,182
4.5625
5
[]
no_license
/** * Author: Dante Lawrence * Date: October 1, 2019 * * Thir program demonstrates pointers with functions. **/ #include <stdlib.h> #include <stdio.h> //pass by value int changeVals(int a, int b); //ignore the ugly function name //pass by reference int changeValsWithPointers(int *a, int *b); int main(int argc, char const *argv[]) { /* * The biggest thing you need to know is that pointers, allow us to pass by * reference to a function. This allows us to change a variable's value * globally, whereas with regular variables, we could not do this. This * allows us to change multiple variables with one function! */ int a = 5, b = 5; changeVals(a, b); printf("a = %d, b = %d. The values have not changed\n", a, b); changeValsWithPointers(&a, &b); //pass in the memory addresses of a and b printf("a = %d, b = %d. The values have changed!\n", a, b); return 0; } int changeVals(int a, int b) { a = 10; b = 10; return 0; } int changeValsWithPointers(int *a, int *b) { /* Dereference the pointers and place the value 10 into it. * Verbally, "Go to that spot in memory and place this value there." */ *a = 10; *b = 10; return 0; }
C++
UTF-8
515
3.328125
3
[]
no_license
#include<vector> #include<map> #include<string> #include<queue> #include<sstream> #include<stack> using namespace std; /* You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. */ int climbStairs(int n) { vector<int> results{ 1,2 }; for (size_t i{ 2 }; i < n; i++) { results.push_back(results[i - 1] + results[i - 2]); } return results[n - 1]; }
Java
UTF-8
4,126
2.265625
2
[]
no_license
package client; import java.io.Serializable; /** *An enum class to use database actions */ public class ActionsType implements Serializable { private static final long serialVersionUID = 3007036497465788417L; public enum ActionNumber { QUESIOTN_GET_ALL, QUESTION_GET_BY_CODE, QUESTION_UPDATE, QUESTION_GET_BY_OWNER, QUESTION_ADD, QUESTION_REMOVE, USER_LOGIN, USER_LOGOUT, TEST_CREATE, TEST_SET_QUESTIONS, TEST_UPDATE, TEST_UPDATE_COMMENTS_TEACHER, TEST_UPDATE_COMMENTS_STUDENT, TEST_DELETE, TEST_GET_ALL, TEST_GET_BY_ID, TEST_GET_ALL_TESTS_BY_STUDENT, START_TEST, STUDENT_TEST_CREATE, STUDENT_TEST_GET_ALL_TESTS_BY_STUDENT_ID, STUDENT_TEST_GET_ALL_TESTS_BY_TEACHER_ID, STUDENT_TEST_GET_ALL_TESTS_BY_COURSE_ID, STUDENT_TEST_UPDATE, STUDENT_GET_ALL_NAME, EXECUTED_TEST_ADD, EXECUTED_TEST_GET_ALL, EXECUTED_TEST_UPDATE, EXECUTED_TEST_CHECK_LOCK_TEST, UPLOAD_FILE, DOWNLOAD_FILE, COURSE_GET_ID_LIST, Subject_GET_ID_LIST, TEACHER_GET_ALL_NAME; } public static int getValue(ActionNumber action) { switch (action) { case QUESIOTN_GET_ALL: return 1; case QUESTION_GET_BY_CODE: return 2; case QUESTION_UPDATE: return 3; case QUESTION_GET_BY_OWNER: return 4; case QUESTION_ADD: return 5; case QUESTION_REMOVE: return 6; case USER_LOGIN: return 7; case USER_LOGOUT: return 8; case TEST_CREATE: return 100; case TEST_SET_QUESTIONS: return 103; case TEST_UPDATE: return 105; case TEST_UPDATE_COMMENTS_TEACHER: return 106; case TEST_UPDATE_COMMENTS_STUDENT: return 108; case TEST_DELETE: return 110; case TEST_GET_ALL: return 112; case TEST_GET_BY_ID: return 113; case STUDENT_TEST_CREATE: return 120; case STUDENT_TEST_GET_ALL_TESTS_BY_STUDENT_ID: return 121; case STUDENT_TEST_GET_ALL_TESTS_BY_TEACHER_ID: return 122; case STUDENT_TEST_GET_ALL_TESTS_BY_COURSE_ID: return 123; case STUDENT_TEST_UPDATE: return 124; case STUDENT_GET_ALL_NAME: return 125; case EXECUTED_TEST_ADD: return 1000; case EXECUTED_TEST_GET_ALL: return 1001; case EXECUTED_TEST_UPDATE: return 1002; case EXECUTED_TEST_CHECK_LOCK_TEST: return 1003; case UPLOAD_FILE: return 2000; case DOWNLOAD_FILE: return 2001; case COURSE_GET_ID_LIST: return 2002; case TEACHER_GET_ALL_NAME: return 2003; case Subject_GET_ID_LIST: return 2004; default: return 0; } } public static ActionNumber getAction(int number) { switch (number) { case 1: return ActionNumber.QUESIOTN_GET_ALL; case 2: return ActionNumber.QUESTION_GET_BY_CODE; case 3: return ActionNumber.QUESTION_UPDATE; case 4: return ActionNumber.QUESTION_GET_BY_OWNER; case 5: return ActionNumber.QUESTION_ADD; case 6: return ActionNumber.QUESTION_REMOVE; case 7: return ActionNumber.USER_LOGIN; case 8: return ActionNumber.USER_LOGOUT; case 100: return ActionNumber.TEST_CREATE; case 103: return ActionNumber.TEST_SET_QUESTIONS; case 105: return ActionNumber.TEST_UPDATE; case 106: return ActionNumber.TEST_UPDATE_COMMENTS_TEACHER; case 108: return ActionNumber.TEST_UPDATE_COMMENTS_STUDENT; case 110: return ActionNumber.TEST_DELETE; case 112: return ActionNumber.TEST_GET_ALL; case 113: return ActionNumber.TEST_GET_BY_ID; case 120: return ActionNumber.STUDENT_TEST_CREATE; case 121: return ActionNumber.STUDENT_TEST_GET_ALL_TESTS_BY_STUDENT_ID; case 122: return ActionNumber.STUDENT_TEST_GET_ALL_TESTS_BY_TEACHER_ID; case 123: return ActionNumber.STUDENT_TEST_GET_ALL_TESTS_BY_COURSE_ID; case 124: return ActionNumber.STUDENT_TEST_UPDATE; case 125: return ActionNumber.STUDENT_GET_ALL_NAME; case 1000: return ActionNumber.EXECUTED_TEST_ADD; case 1001: return ActionNumber.EXECUTED_TEST_GET_ALL; case 1002: return ActionNumber.EXECUTED_TEST_UPDATE; case 1003: return ActionNumber.EXECUTED_TEST_CHECK_LOCK_TEST; case 2000: return ActionNumber.UPLOAD_FILE; case 2001: return ActionNumber.DOWNLOAD_FILE; case 2002: return ActionNumber.COURSE_GET_ID_LIST; case 2003: return ActionNumber.TEACHER_GET_ALL_NAME; case 2004: return ActionNumber.Subject_GET_ID_LIST; } return null; } }
Shell
UTF-8
1,431
2.671875
3
[]
no_license
#!/bin/bash echo updating all dependend repositories cd ../plovr-main git-hg pull rm ../plovr/changes.txt cd ../closure-compiler git svn fetch echo "Closure Compiler" >> ../plovr/changes.txt echo "-----------------------------------------------------------------------------" >> ../plovr/changes.txt git log master..git-svn >> ../plovr/changes.txt git rebase git-svn echo "Closure Templates" >> ../plovr/changes.txt echo "-----------------------------------------------------------------------------" >> ../plovr/changes.txt cd ../closure-templates git svn fetch git log master..git-svn >> ../plovr/changes.txt git rebase git-svn echo "Closure Library" >> ../plovr/changes.txt echo "-----------------------------------------------------------------------------" >> ../plovr/changes.txt cd ../closure-library git svn fetch git log master..git-svn >> ../plovr/changes.txt git rebase git-svn echo Merging plovr upstream changes cd ../plovr git pull origin git merge master-hg echo updating closure versions cp -ra ../closure-compiler/* closure/closure-compiler cp -ra ../closure-library/* closure/closure-library cp -ra ../closure-templates/* closure/closure-templates echo Apply Plovr Patch to enable visibility patch -p 1 < patches/0001-Patching-the-closure-compiler-to-be-compatible-wit-plovr.patch git add closure git rm -r --cached closure/closure-compiler/build git rm -r --cached closure/closure-templates/build
Python
UTF-8
441
3.265625
3
[]
no_license
''' # 예제 입력 1 8 4 3 6 8 7 5 2 1 # 예제 입력 2 5 1 2 5 3 4 ''' from sys import stdin input = stdin.readline stack = [] num = int(input()) t = list(range(num, 0, -1)) answer = "" for _ in range(num): i = int(input()) while len(stack) == 0 or stack[-1] < i: stack.append(t.pop()) answer += '+\n' if stack[-1] == i: stack.pop() answer += '-\n' if len(stack) or len(t): print("NO") else: print(answer)
Java
UTF-8
976
1.6875
2
[]
no_license
package com.tsing.product.api.dict.bo.request; import java.io.Serializable; import java.time.LocalDateTime; import lombok.Data; /** * @author Tsing * @version 0.0.1 * @date 2021/8/5 6:29 上午 * @description: 产品字典修改信息 */ @Data public class ProductDictUpdateRequest implements Serializable { private static final long serialVersionUID = -1355367793029386621L; /** * 自增ID */ private Long id; /** * 分类编码 */ private String categoryCode; /** * 分类说明 */ private String categoryDesc; /** * 编码 */ private String dictCode; /** * 名称 */ private String dictDesc; /** * 排序编号 */ private Integer sortNo; /** * 数据类型 */ private String dataType; /** * 附加说明 */ private String remark; /** * 更新时间 */ private LocalDateTime updateTime; }
C++
UTF-8
1,396
3.734375
4
[]
no_license
#include<math.h> class Vector2D{ public: double x,y; Vector2D(double x,double y){this->x=x,this->y=y;}//initiallizes the vector Vector2D(){this->x=this->y=0;}//initializes the zero vector Vector2D polar(double r,double t){return {r*cos(t),r*sin(t)};}//creates a vector by polar form (radians) Vector2D operator+(Vector2D ot){return {this->x+ot.x,this->y+ot.y};}//adding two vectors Vector2D operator-(Vector2D ot){return {this->x-ot.x,this->y-ot.y};}//subtracting two vectors double dot(Vector2D ot){return this->x*ot.x+this->y*ot.y;}//returns the dot-product double cross(Vector2D ot){return this->x*ot.y-this->y*ot.x;}//returns the 2D version of cross product double mag(){return sqrt(this->x*this->x+this->y*this->y);}//returns the magnitude of the vector double dir(){return atan2(this->y,this->x);}//returns the direction the vector is pointing (radians) Vector2D norm(){double t=dir();return {cos(t),sin(t)};}//returns the norm of the vector Vector2D operator*(double c){return {this->x*c,this->y*c};}//multiplies the vector by a constant Vector2D operator/(double c){return {this->x/c,this->y/c};}//divides the vector by a constant double proj(Vector2D ot){return this->dot(ot)/ot.mag();}//returns the length of the projection of a vector onto another Vector2D perp(){return {-y,x};}//returns the vector rotated 90 degrees CCW };
C++
UTF-8
3,809
3.84375
4
[]
no_license
//Jeremiah Kalmus //P6 - STL #include <iostream> #include <iomanip> #include <list> #include <ctime> using namespace std; const int MAXSIZE = 10000; //Largest any randomly generated value can be. const int TOTALNUMS = 1000; //Total numbers to be entered into a new list. const int TEN = 10; const int ZERO = 0; const int TWO = 2; const int FIVE = 5; void print(list<int> pList); //Prints the contents in the list. //PRE: None //POST: None void removeMultOfFive(list<int>& pList); //Removes all multiples of 5 in the list //PRE: List must be created //POST: May make the list smaller by removing values. bool isPrime(int middle); //Checks to see if a value is prime. //PRE: List and removePrime function must be created. //POST: Determines if the value is prime void removePrime(list<int>& pList, bool& erased); //Removes a prime value in between two values of mixed parody. //PRE: List must be created. //POST: May make the list smaller by removing values. int main() { srand(time(0)); int val = 0; bool erased = false; list<int> pList; //Declaring an iterator list<int>::iterator front; cout << "Hello and welcome to the P6 program. " << endl << "This program will utilize the STL and store values into a list. " << endl << "It will then remove all multiples of 5, and then it will remove " << endl << "all prime numbers in between two numbers of mixed parody. " << endl << "The program will continue to remove prime numbers this way until " << endl << "there are no more changes to the list. " << endl << endl; for(int i = 0;i < TOTALNUMS;i++){ val = rand() % MAXSIZE; pList.push_back(val); } cout << "Printing values stores in the list" << endl; print(pList); cout << endl; removeMultOfFive(pList); cout << "Removing all multiples of 5" << endl; print(pList); cout << endl; removePrime(pList, erased); cout << "Removing primes between numbers of mixed parody" << endl; print(pList); while(erased == true){ cout << endl; removePrime(pList, erased); cout << "Removing primes between numbers of mixed parody" << endl; print(pList); } cout << endl << endl; cout << "Last two walks through the list are the same." << endl; cout << "Goodbye!" << endl; return 0; } void print(list<int> pList) { list<int>::iterator front = pList.begin(); int count = 0; while(front != pList.end()){ if(count == TEN){ cout << endl; count = ZERO; } cout << setw(6); cout << (*front) << " "; front++; count++; } cout << endl; } void removeMultOfFive(list<int>& pList) { list<int>::iterator val = pList.begin(); int count = 0; while(count != TOTALNUMS){ if((*val % FIVE) == ZERO){ pList.erase(val); val--; } else{ val++; count++; } } } bool isPrime(int middle) { int count = 2; bool prime = true; if(middle == TWO){ return true; } else{ while((prime == true) && (count < middle)){ if(((middle) % count) == ZERO){ prime = false; } count++; } return prime; } } void removePrime(list<int>& pList, bool& erased) { list<int>::iterator front = pList.begin(); list<int>::iterator middle = front; middle++; list<int>::iterator back = middle; back++; erased = false; while(back != pList.end()){ //Check to see if a prime is in between two numbers //of mixed parody if(((((*front % TWO) == 1) && ((*back % TWO) == 0)) || (((*back % TWO) == 1) && ((*front % TWO) == 0))) && (isPrime(*middle) == true)){ //Check to see if it is prime middle = pList.erase(middle); back++; erased = true; } else{ front++; middle++; back++; } } }
Markdown
UTF-8
7,246
3.046875
3
[]
no_license
This example, based on the awesome [Ecommerce-UX](https://dribbble.com/shots/2249964-Ecommerce-UX) design by [Levani Ambokadze](https://dribbble.com/Amboka), shows the use of `SwipeGesture` and `SwipeNavigate`, as well as how you can achieve 3D transformations using `Rotate` and `Viewport`. The icons are from Google's [Material Icons pack](https://design.google.com/icons/). # Swipe navigation Swiping left and right on both detail cards and the preview photos is done using a `PageControl`, which handles linear navigation between panels using swipes. The following is a simplification of the two `PageControl`s used in the app: ``` <Panel> <PageControl> <Each Count="3"> <Panel Margin="10,10,10,10"> <Panel Color="#F00"> <Translation Y="0.46" RelativeTo="ParentSize" ux:Name="pageTranslation" /> </Panel> <Panel Alignment="Top" Height="60%"> <!-- Preview images --> <PageControl> <Panel Color="#0FA" /> <Panel Color="#0AF" /> <Panel Color="#F0A" /> </PageControl> </Panel> </Panel> </Each> </PageControl> </Panel> ``` Note that the `PageControl` for navigating the preview images is a child of the `PageControl` which navigates the pages. In cases like this, the child `PageControl` will always get input, rather than the parent. Additionally, this snippet uses default transition animations instead of custom ones. In our example app, we set `Transition="None"` on the `PageControl`s to enable custom animations, and specified our own `EnteringAnimation` and `ExitingAnimation`. These will be discussed in further detail later in the article. # Swiping up to reveal more details This effect uses a `SwipingAnimation` hooked up to a `SwipeGesture` in order to translate the detail card upwards as the user swipes up. While a `PageControl` uses swipe gestures to navigate pages, `SwipeGesture` is a more general way of handling swipes. The `SwipeGesture` itself is a child of the first panel after our `Viewport` element (More on this later). This ensures the entire app can take swipe events through that `SwipeGesture`. This is because `SwipeGesture`s listen for swipes in the area of the screen their parent container populates. For the actual translation of the cards, we put a `SwipingAnimation` and `Translation` element in the cards, like this: ``` <SwipingAnimation Source="swipeGesture"> <Change pageTranslation.Y=".12" /> <Change moreDiv.Opacity="1" Easing="ExponentialOut" /> <Change infoPointPanel.Opacity="1" Easing="CubicIn" /> <Change ratingsGrid.Opacity="1" Easing="ExponentialIn" /> </SwipingAnimation> <Translation Y="0.46" RelativeTo="ParentSize" ux:Name="pageTranslation" /> ``` ## The unused SwipeGesture in the preview image container If you had a keen eye while looking over the example code, you might of noticed there is an unused `SwipeGesture` in the preview image container: ``` <Panel ux:Name="topPart" Alignment="Top" Height="60%"> <SwipeGesture Direction="Up"/> <!-- [...] --> </Panel> ``` This works as a mask, telling the `SwipeGesture` closer to the root node (`App`) to ignore swipes happening on that panel. This happens because `SwipeGesture` respects other `SwipeGesture`s deeper down on the node tree. This way, by putting an unused `SwipeGesture` on the top container, the parent `SwipeGesture` will ignore that area. # Rotating the detail cards in 3D Fuse supports 3D transformation out of the box. However, to pull this off, you need to wrap your UX in a `Viewport` element. This element handles perspective projection. We initialize the viewport like this: ``` <App> <Viewport Perspective="300" CullFace="Back"> <!-- Your app --> </Viewport> </App> ``` It is important to set `CullFace` to `Back` so any rotated elements aren't visible if they face away from the camera. The cards look rather ugly the last degrees before they are rotated out of the way, as there is a considerable amount of aliasing. To fix this, we fade out the cards as they leave the center of the screen using an exponential easing method. Lastly, the other elements that make up the cloth display have to be moved out of the way as the clothing card is swiped away. In our example, this is the preview image navigation panel, and the progress dots for said navigation panel. The following snippet shows the enter/exit animations in their entirety: ``` <EnteringAnimation> <Rotate Target="bottomPartOuter" DegreesY="70" Duration="1" /> <Change bottomPart.Opacity="0" Easing="ExponentialIn" Duration=".75" Delay=".0"/> <Change topScaling.Factor="0.5" Duration="1" /> <Change topPart.Opacity="0" Duration="1" Easing="ExponentialOut" /> <Change pageIndicatorPart.Opacity="0" Duration="1" Easing="ExponentialOut" /> </EnteringAnimation> <ExitingAnimation> <Rotate Target="bottomPartOuter" DegreesY="-70" Duration="1" /> <Change bottomPart.Opacity="0" Easing="ExponentialIn" Duration=".75" Delay=".0"/> <Change topScaling.Factor="0.5" Duration="1" /> <Change topPart.Opacity="0" Duration="1" Easing="ExponentialOut" /> <Change pageIndicatorPart.Opacity="0" Duration="1" Easing="ExponentialOut" /> </ExitingAnimation> ``` # Styling It is good practice when writing UX to define all custom UI elements as classes with semantic names. This results in the UX communicating well to a third party reader what different parts of the UX document does. The example has therefore almost all items that visually look like an UI element defined in classes. Additionally, due to the amount of classes used in this example, we put them in a separate UX file which we included. This reduces clutter in `MainView.ux`, something which is very useful when working with large projects. We pre-define all our theme colors. This helps make the UX more understandable, as it is easier to comprehend which visual element you are looking at the UX for: ``` <float4 ux:Global="FontColor" ux:Value="#556E7A" /> <float4 ux:Global="LighterFontColor" ux:Value="#556D79" /> <float4 ux:Global="InactiveColor" ux:Value="#ABB5BC" /> <float4 ux:Global="HintColor" ux:Value="#DEEBF4" /> <float4 ux:Global="CardBackground" ux:Value="#FFF" /> <float4 ux:Global="BackgroundColor" ux:Value="#f3f3f5" /> <float4 ux:Global="ColorSelRed" ux:Value="#F25254" /> <float4 ux:Global="ColorSelBlue" ux:Value="#6389AF" /> <float4 ux:Global="ColorSelGreen" ux:Value="#70C1B3" /> <float4 ux:Global="ColorSelYellow" ux:Value="#FFE664" /> ``` Further, we use classes to define both regularly used sets of properties, and more complicated custom UI elements. The following snippet shows how the circular `SizeButton` is defined. Notice how we utilize `ux:Property` to add our own property to our new class: ``` <Circle ux:Class="SizeButton" Width="40" Height="40" Margin="15"> <string ux:Property="Label" /> <Text Alignment="Center" Value="{ReadProperty Label}" Color="FontColor" /> <Stroke Width="2"> <SolidColor Color="InactiveColor" /> </Stroke> </Circle> ``` The following is an example of a more simple use of `ux:Class`, for often used properties. ``` <Image ux:Class="Icon" Margin="15" Color="FontColor" Height="40" /> ``` Last but not least, we include `Style.ux` in our main file using: ``` <ux:Include File="Style.ux" /> ``` That's about it!
JavaScript
UTF-8
1,484
2.515625
3
[ "MIT" ]
permissive
const html = require('choo/html'); const donateButtons = require('./donateButtons'); const donateBitcoin = require('./donateBitcoin'); const donateResults = require('./donateResults'); const providerButtons = require('./providerButtons'); const renderDonateButton = require('./renderDonateButton'); module.exports = donateView; function donateView(state, emit) { const { pending, success, error } = state.checkout; const donateProcessed = pending || (success || error); return html` <div> <h5 class="f4 mv0 color-neutral-80" > Choose an amount to donate </h5> ${donateButtons(state, emit)} <p></p> <h5 class="f4 mv0 color-neutral-80" > Choose how you would like to donate (tax-deductible) </h5> ${providerButtons(state, emit)} ${renderDonateButton(state, emit)} <p class="lh-copy f7 black-60 measure"> Donations are processed via Stripe (per transation: CC, 2.2% + $0.30; Bitcoin, 0.8% cap at $5). We receive donation in USD minus fees. </p> ${donateProcessed ? donateResults(state) : ''} <h5 class="f4 mb2 color-neutral-80" > Donate Anonymous Bitcoin (not tax-deductible) </h5> ${donateBitcoin()} <p class="lh-copy f7 black-60 measure"> Anonymous Bitcoin donations are not tax deducible. Bitcoins sent via Coinbase are sent directly to our wallet. </p> </div> `; }
C++
UTF-8
537
2.9375
3
[]
no_license
// // Created by Stephen Clyde on 2/15/17. // #ifndef WIDGETSORT_WIDGET_H #define WIDGETSORT_WIDGET_H #include <ostream> #include <string> class Widget { private: std::string m_name; int m_value; public: Widget(std::string name, int value); void print(std::ostream& out); static bool compareByName(Widget a, Widget b); static bool compareByValue(Widget a, Widget b); private: const std::string& getName() const { return m_name; } int getValue() const { return m_value; } }; #endif //WIDGETSORT_WIDGET_H
Markdown
UTF-8
3,743
3.015625
3
[]
no_license
--- date: 2020-08-16 title: Getting Started with Kubernetes Cronjob tags: - kubernetes --- Configurations === Important fields --- 1. `.spec.jobTemplate.spec.template.spec.restartPolicy`: How to handle when a container in a pod. Note that this doesn't mean a job restarts or not (it's commented on [this github issue](https://github.com/kubernetes/kubernetes/issues/20255#issuecomment-310540940)). - `onFailure`: Restart a container in the same pod when it fails. - `Never`: Restart a container with new pod. 1. `.spec.concurrencyPolicy`: How to handle concurrent jobs - `Allow` (Default): Allows concurrent runs - `Forbid`: Does not allow concurrent runs - `Replace`: Replace old job with new job if previous job hasn't finished when it's time to schedule new job 1. `.spec.successfulJobsHistoryLimit`, `.spec.failedJobsHistoryLimit`: How many pods is kept after it succeeded or failed 1. `.spec.startingDeadlineSeconds`: How long jobs keep trying to start. Also, see a [pitfall](#startingdeadlineseconds) section. Pitfalls === StartingDeadlineSeconds --- A cronjob stops starting jobs if it "misses" jobs more than 100 times in a specific period related with `.spec.startingDeadlineSeconds`. The details are explained in [here](https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/#cron-job-limitations). Here is the brief explanation, though they might be wrong or incomplete. - If `startingDeadlineSeconds` isn't set, the number of missed jobs is counted since last scheduled time. And if it exceeds more than 100 times, then jobs won't start. If `startingDeadlineseconds` is set, then missed jobs counted in last `startingDeadlineSeconds`. - The number of missed jobs includes when a new job cannot run because a `concurrencyPolicy` is `Forbid` and previous job is still running. Other pitfalls --- 1. Jobs should be "idempotent", because the same jobs might be created more than once, or no job might be created. 1. CronJobs may run more than once even if `.spec.parallelism` = 1, `.spec.completions` = 1, and `.spec.template.spec.restartPolicy` = "Never" - See [official page](https://kubernetes.io/docs/concepts/workloads/controllers/job/#handling-pod-and-container-failures) for more details. 1. CronJobs usually fail to start more than 30 or 60 seconds (in 2018). - See [this slide (Japanese)](https://speakerdeck.com/potsbo/kubernetes-cronjob-implementation-in-detail-number-k8sjp?slide=3) for more details. 1. Workaround is required for cronjobs with istio sidecars. There is an option to update manifests of istio sidecar to stop the sidecar after corresponding job container stops, or disable injecting istio sidecar. - See [this GitHub issues](https://github.com/istio/istio/issues/11659#issuecomment-479547294) for workarounds to insert istio sidecar for cronjobs - See [this GitHub issues](https://github.com/kubernetes/enhancements/issues/753) to support a sidecar as a kubernetes 1st citizen. After this issue is solved, no workaround won't be required anymore. kubectl commands === 1. How to run a job from cronjob: `kubectl create job --from=cronjob/[cronjob name] [job name]` References ==== 1. [Kubernetes documentation: Running Automated Tasks with a CronJob](https://kubernetes.io/docs/tasks/job/automated-tasks-with-cron-jobs/) 1. [Kubernetes documentation: Jobs](https://kubernetes.io/docs/concepts/workloads/controllers/job/) 1. [How we learned to improve Kubernetes CronJobs at Scale (Part 1 of 2)](https://eng.lyft.com/improving-kubernetes-cronjobs-at-scale-part-1-cf1479df98d4) 1. [What does Kubernetes cronjob’s `startingDeadlineSeconds` exactly mean?](https://medium.com/@hengfeng/what-does-kubernetes-cronjobs-startingdeadlineseconds-exactly-mean-cc2117f9795f)
C++
UTF-8
12,437
2.875
3
[]
no_license
/** * @file rt_app.cpp * @brief Source file for the ray-tracing test application. * In this file I am experimenting with ray tracing. * @author Michael Reim / Github: R-Michi * Copyright (c) 2021 by Michael Reim * * This code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ #include "rt_app.h" #include "glc-1.0.0/GL/glc.h" #include <omp.h> #include <stdexcept> #include <iostream> #include <chrono> inline uint32_t float2bits(float x) { uint32_t i; memcpy(&i, &x, sizeof(float)); return i; } inline float bits2float(uint32_t x) { float f; memcpy(&f, &x, sizeof(uint32_t)); return f; } inline float next_float_up(float x) { // 2 special cases: // if x is positive infinity, then the value can't be incremented any further and it is returned unchanged // if x is negative 0, change it to positive 0, as negative 0 has a different memory representation if (std::isinf(x) && x > 0.0f) return x; if (x == -0.0f) x = 0.0f; // advance x to the next higher float // this can only be done because of the memory representation of the IEEE754 standard uint32_t i = float2bits(x); if (x >= 0) ++i; else --i; return bits2float(i); } inline float next_float_down(float x) { // is the same as next_float_up but in reverse if (std::isinf(x) && x < 0.0f) return x; if (x == 0.0f) x = -0.0f; uint32_t i = float2bits(x); if (x <= 0) ++i; else --i; return bits2float(i); } inline glm::vec3 offset_ray_origin(const glm::vec3& p, const glm::vec3& n, const glm::vec3& w) { float d = 2e-4f; glm::vec3 offset = d * n; if (dot(w, n) < 0) offset = -offset; glm::vec3 po = p + offset; if (offset.x > 0) po.x = next_float_up(po.x); else if (offset.x < 0) po.x = next_float_down(po.x); if (offset.y > 0) po.y = next_float_up(po.y); else if (offset.y < 0) po.y = next_float_down(po.y); if (offset.z > 0) po.z = next_float_up(po.z); else if (offset.z < 0) po.z = next_float_down(po.z); return po; } RT_Application::RT_Application(void) { this->light = { {-1.0f, 0.5f, 0.0f}, {7.0f, 7.0f, 7.0f} }; rt::Sphere spheres[PRIM_COUNT] = { rt::Sphere ( {0.0f, 5.0f, 10000.0f}, 1.0f, Material(glm::vec3(0.0f, 0.0f, 1.0f), 0.5f, 0.8f, 1.0f) ), rt::Sphere ( {3.0f, 0.0f, 3.0f}, 1.0f, Material(glm::vec3(0.0f, 1.0f, 0.0f), 0.5f, 0.8f, 1.0f) ), rt::Sphere ( {0.0f, -1005.0f, 10000.0f}, 1000.0f, Material(glm::vec3(1.0f, 1.0f, 1.0f), 0.5f, 0.8f, 1.0f) ) }; #if 0 rt::CubemapCreateInfo cubemap_ci = {}; cubemap_ci.front = "../../../assets/skyboxes/front.jpg"; cubemap_ci.back = "../../../assets/skyboxes/back.jpg"; cubemap_ci.top = "../../../assets/skyboxes/top.jpg"; cubemap_ci.bottom = "../../../assets/skyboxes/bottom.jpg"; cubemap_ci.left = "../../../assets/skyboxes/left.jpg"; cubemap_ci.right = "../../../assets/skyboxes/right.jpg"; cubemap_ci.filter = rt::RT_FILTER_LINEAR; if (this->environment.load(cubemap_ci) == rt::RT_TEXTURE_ERROR_LOAD) throw std::runtime_error("Failed to load skybox."); #endif // load texture int w, h; uint8_t* data = stbi_load("../../../assets/textures/cobblestone.png", &w, &h, nullptr, 3); rt::ImageCreateInfo image_ci = {}; image_ci.width = w; image_ci.height = h; image_ci.depth = 1; image_ci.channels = 3; this->tex.set_address_mode(rt::RT_TEXTURE_ADDRESS_MODE_REPEAT, rt::RT_TEXTURE_ADDRESS_MODE_REPEAT, rt::RT_TEXTURE_ADDRESS_MODE_CLAMP_TO_BORDER); this->tex.set_filter(rt::RT_FILTER_NEAREST); this->tex.set_border_color(glm::vec4(0.0f, 0.0f, 0.0f, 0.0f)); rt::ImageError error = this->tex.load(image_ci, data); if(error != rt::RT_IMAGE_ERROR_NONE) throw std::runtime_error("Failed to load texture."); std::cout << "texture loaded" << std::endl; stbi_image_free(data); // load spherical map this->spherical_env.set_address_mode(rt::RT_TEXTURE_ADDRESS_MODE_CLAMP_TO_BORDER, rt::RT_TEXTURE_ADDRESS_MODE_CLAMP_TO_BORDER, rt::RT_TEXTURE_ADDRESS_MODE_CLAMP_TO_BORDER); this->spherical_env.set_filter(rt::RT_FILTER_LINEAR); error = rt::TextureLoader::loadf(this->spherical_env, "../../../assets/skyboxes/environment.hdr", 3); if (error != rt::RT_IMAGE_ERROR_NONE) throw std::runtime_error("Failed to load spherical map."); std::cout << "spherical map loaded" << std::endl; // load cubemap rt::CubemapCreateInfo cci = {}; cci.right = "../../../assets/skyboxes/right.jpg"; cci.left = "../../../assets/skyboxes/left.jpg"; cci.top = "../../../assets/skyboxes/top.jpg"; cci.bottom = "../../../assets/skyboxes/bottom.jpg"; cci.front = "../../../assets/skyboxes/front.jpg"; cci.back = "../../../assets/skyboxes/back.jpg"; error = rt::TextureLoader::load_cube(this->cubemap, cci, 3); if (error != rt::RT_IMAGE_ERROR_NONE) throw std::runtime_error("Failed to load cubemap."); std::cout << "cubemap loaded" << std::endl; rt::ImageCreateInfo fbo_ci = {}; fbo_ci.width = SCR_WIDTH; fbo_ci.height = SCR_HEIGHT; rt::BufferLayout buffer_layout; buffer_layout.size = PRIM_COUNT; buffer_layout.first = 0; buffer_layout.last = buffer_layout.size; rt::Buffer buff(buffer_layout); buff.data(0, 3, spheres); this->set_num_threads(1); this->set_framebuffer(fbo_ci); this->clear_color(0.0f, 0.0f, 0.0f); this->draw_buffer(buff); } RT_Application::~RT_Application(void) { // not used dtor of the super class handles everything (in this application) } float RT_Application::sdf(const glm::vec3& p, float t_max, const rt::Primitive** hit_prim) { float d = t_max; // Use maximum length of the ray if there is no object within that range. const size_t n_buff = this->rt_geometry_buffer_count(); for(size_t b = 0; b < n_buff; b++) { const rt::Primitive * const * map = this->rt_geometry()[b].map_rdonly(); const size_t size = this->rt_geometry()[b].layout().size; for(size_t i = 0; i < size; i++) // Iterate through the primitives and find the closest one. { if(map[i] != nullptr) { const float cur_d = map[i]->distance(p); if(cur_d < d && cur_d < t_max) // dont update if current distance exeeds the maximum length of the ray (outside the render distance) { d = cur_d; // update the closest length if the current length is maller than the current closest length if(hit_prim != nullptr) // set the id of the closest sphere *hit_prim = map[i]; } } } } return d; } float RT_Application::shadow(const rt::ray_t& shadow_ray, float t_max, float softness) { static constexpr int MAX_ITERATIONS = 128; // Maximum iterations of the ray marging process. float t = 0.15f; // A small bias to minimize the render artefacts. float res = 1.0f; // amount of light hitting the surface, 1.0 = 100%, 0.0 = 0% int iter_cntr = 0; // Current iteration while(iter_cntr++ < MAX_ITERATIONS && t < t_max) // Also end the loop if the ray-length is the maximum length of longer { glm::vec3 p = shadow_ray.origin + t * shadow_ray.direction; // P = O + t*D float d = this->sdf(p, t_max, nullptr); // get disance to the closest point if(d <= 0.0001f) // 0.0001 or smaller counts as intersecion to accelerate the ray-marging process return 0.0f; // If the ray hits an object directly, there will be no light t += d; /* For penumbra calculation (soft part of the shadow) we need the closest distance to an object along the ray. That the resulting value for the shadow is in the range of 0 to 1, we devide the actual distance by the length of the ray. As we want the smallest result of that ratio, we use the min function in combination with the preveous result ('res'). The softness value is multiplied with 'd', so the size of the penumbra can be adjusted. */ res = glm::min(res, softness * d / t); } return res; } glm::vec3 RT_Application::ray_generation_shader(uint32_t x, uint32_t y) { float ndc_x = gl::convert::from_pixels_pos_x(x, this->rt_dimensions().x) * this->rt_ratio(); float ndc_y = gl::convert::from_pixels_pos_y(y, this->rt_dimensions().y); glm::vec3 origin = {0.0f, 0.0f, 10010.0f}; // origin of the camera glm::vec3 look_at = {0.0f, 0.0f, 10000.0f}; // direction/point the camere is looking at glm::vec3 cam_z = glm::normalize(look_at - origin); // z-direction of the camera glm::vec3 cam_x = glm::normalize(glm::cross(glm::vec3(0.0f, 1.0f, 0.0f), cam_z)); // x-diretion of the camera glm::vec3 cam_y = glm::cross(cam_z, cam_x); // y-direction of the camera // generate ray rt::ray_t ray; ray.origin = origin; ray.direction = glm::normalize(ndc_x * cam_x + ndc_y * cam_y + 1.5f * cam_z); // rotated intersection with the image plane // render the image in hdr glm::vec3 hdr_color(0.0f); trace_ray(ray, RT_RECURSIONS, 100.0f, rt::RT_CULL_MASK_NONE, &hdr_color); // begin ray-tracing process glm::vec3 ldr_color = hdr_color / (hdr_color + glm::vec3(1.0f)); // convert to ldr return ldr_color; } void RT_Application::closest_hit_shader(const rt::ray_t& ray, int recursion, float t, float t_max, const rt::Primitive* hit, rt::RayHitInformation hit_info, void* ray_payload) { rt::Sphere* hit_sphere = (rt::Sphere*)hit; glm::vec3* out_color = (glm::vec3*)ray_payload; glm::vec3 intersection = ray.origin + (t) * ray.direction; // prevent self-intersection const glm::vec3 normal = glm::normalize(intersection - hit_sphere->center()); const glm::vec3 view = -ray.direction; glm::vec3 color(0.0f); glm::vec3 refract_normal; float n; rt::RayCullMask cull_mask = rt::RT_CULL_MASK_NONE; if (hit_info & rt::RT_HIT_INFO_FRONT_BIT) { refract_normal = normal; n = 1.0f / 1.5f; } else if (hit_info & rt::RT_HIT_INFO_BACK_BIT) { refract_normal = -normal; n = 1.5f; } rt::ray_t _sample_ray; _sample_ray.direction = glm::reflect(ray.direction, normal); //_sample_ray.direction = glm::refract(ray.direction, refract_normal, n); _sample_ray.origin = offset_ray_origin(intersection, normal, _sample_ray.direction); //_sample_ray.origin = intersection; this->trace_ray(_sample_ray, recursion-1, t_max, cull_mask, &color); *out_color = color; } void RT_Application::miss_shader(const rt::ray_t& ray, int recursuon, float t_max, void* ray_payload) { //glm::vec3 color = glm::vec3(this->cubemap.sample(ray.direction)); //constexpr float HDRmax = 2.0f; //const float x = HDRmax / (HDRmax + 1); //color = (color * x) / (glm::vec3(1.0f) - color * x); //*((glm::vec3*)ray_payload) = color; *((glm::vec3*)ray_payload) = this->spherical_env.sample(glm::vec4(ray.direction.x, ray.direction.y, ray.direction.z, 0.0f)); } void RT_Application::app_run(void) { this->run(); } const uint8_t* RT_Application::fetch_pixels(void) noexcept { return this->get_framebuffer().map_rdonly(); }
Markdown
UTF-8
4,223
3.09375
3
[]
no_license
# How to Assess Your Organization's Readiness to Migrate at Scale **You will be successful if you are committed!** ## Common Migration Drivers (500+) - Agility/Dev productivity - Digitial transformation - Facility or real-estate decisions - Acquisisitions or divestitures - Operational evolution - Cost reduction - Data center consolidation - Large scale compute intensive workloads - colocation or outsourcing contract changes ## Migration Readiness - Executive sponsorship - Sr leadership - Business case - Base on the migration drivers we want to migrate to the cloud - People - creating a framework for people to grow, most problems are people and process. Focus on training and mobilizing team. - Foundational experience - people who get hands on AWS have a much higher rate of success. People fully understand the value of AWS. - Visibility - Insight and knowledge around what your IT portfolio looks like. - Operating model - What hoops do you have to jump through to get a change done. ## Executive Sponsorship - Formulate and evangelize strategy - Layout communication plan - if we move to the cloud what happens to certain jobs - Support communication channels - Create new roles and learning paths - Realign priorities and allocate resources - Create a framework for measuring success (KPI focused) - Form strong coalition of leaders across the org - Reinforce commitment and reward early wins **Commit, build, and maintain momentum!** Most of the time when projects stall it's because people don't know what their job is. ## Business Case - Directional - General idea, data center - Refined - We have 2000 vms in the data center and would like to BYOL - Detailed - We would like to retire 200, platform 300, and retain 200... ## People The people at the end of the day decide whether you are successful or not. - Training - build technical skills and learn best practices online or with accredited instructor - Self-paced online labs - to learn AWS services and practices skills at low cost - AWS Certification - to validate knowledge with an industry recognized credential Other options: AWS Solution Architects Immersion Days and AWS Professional Services Workshops - Create Center of Excellence og chart - best to have people that understand the culture that are a part of this. - Define RACI matrix for initial migration waves from discovery to operations - who is a good fit for the migration team - Skills assessment - New internal job descriptions ## Foundation Experience Ensure that the people at the table understand what is going on. What the differences between the 6 R's etc. ## Operating Models What are your operating models and how will you address changes in a hybrid mode? What are the main tools processes employed today? What operational capabilities do you need to ramp up that align to the vision? 3 Different Models - Traditional - Go to different teams to get stuff done - Automated Efficiency - Some on prep operations, but alot more automation involved - DevOps - you build it you own it You can be any of these models, but it has to work for your organization. **Figure out what model you want before you do any large scale migration.** ## Visibility Automated service discovery **always** Understand support models, OS, platforms, etc. Once you have visibility get a good understanding of the 6 R's. - Retain - Retire - Rehost - Replatform - Refactor - Repurchase ![](https://image.slidesharecdn.com/cloud-migration-how-to-9b528d4a-35f1-4a76-b8c9-eeae33d22d0b-64655575-180928233700/95/cloud-migration-a-howto-guide-23-638.jpg?cb=1538177837) How do you create migration factories that help automatically migrate people. ## Put it all into action AWS Cloud Adoption Framework See the AWS Migration readiness assessment Migration readiness and planning outcomes - Landing zones - Skills/Center of Excellence - Discovery and planning - Migration business case - Security and compliance Operating model - Migration experience - Migration plan How can help? - AWS Migration Partners - Tools in - Migration - Migration Readiness Assessment - Migration Readiness and Planning ## Resources - https://aws.amazon.com/cloud-migration/
Java
UTF-8
3,217
2.609375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.teamcs.controller; import com.teamcs.database.bean.Contenu; import com.teamcs.database.bean.Materiel; import com.teamcs.service.ContenuService; import com.teamcs.service.MaterielService; import com.teamcs.service.impl.ContenuServiceImpl; import com.teamcs.service.impl.MaterielServiceImpl; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.TextField; import javafx.stage.Stage; /** * FXML Controller class * * @author chris_000 */ public class MaterielsNouveauController implements Initializable { @FXML private TextField libelleField; MaterielService serviceMateriel = new MaterielServiceImpl(); ContenuService serviceContenu = new ContenuServiceImpl(); private Stage dialogStage; private Materiel materiel; private Contenu contenu; private boolean okClicked = false; /** * Sets the stage of this dialog. * * @param dialogStage */ public void setDialogStage(Stage dialogStage) { this.dialogStage = dialogStage; } /** * Returns true if the user clicked OK, false otherwise. * * @return */ public boolean isOkClicked() { return okClicked; } /** * Called when the user clicks ok. */ @FXML private void handleOk() { if (isInputValid()) { materiel = new Materiel(); materiel.setLibelleMateriel(libelleField.getText()); contenu = new Contenu(); contenu.setLibelleContenu(libelleField.getText()); okClicked = true; serviceMateriel.saveMateriel(materiel); serviceContenu.saveContenu(contenu); dialogStage.close(); } } /** * Called when the user clicks cancel. */ @FXML private void handleCancel() { dialogStage.close(); } /** * Validates the user input in the text fields. * * @return true if the input is valid */ private boolean isInputValid() { String errorMessage = ""; if (libelleField.getText() == null || libelleField.getText().length() == 0) { errorMessage += "Invalide libelle!\n"; } if (errorMessage.length() == 0) { return true; } else { // Show the error message. Alert alert = new Alert(Alert.AlertType.ERROR); alert.initOwner(dialogStage); alert.setTitle("Invalid Fields"); alert.setHeaderText("Please correct invalid fields"); alert.setContentText(errorMessage); alert.getDialogPane().getStyleClass().add("myDialogs"); alert.showAndWait(); return false; } } /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { } }
JavaScript
UTF-8
1,685
3.203125
3
[]
no_license
var url = require("url"); // Handler error 500 function handle500(request, response, error) { response.writeHead(500) response.write(`Internal server error : ${error}`) response.end() } // Handler error 404 function handle404(request, response) { response.writeHead(404) response.write(`${url.parse(request.url).pathname} No se encuentra`) response.end() } /* Este es similar al anterior, solo que routes ahora no es un puntero a un funcion sino una estructura que nos permite definir cual es el method que vamos a procesar y la funcion a llamar Esto nos permite definir rutas para GET POST o cualquier otro method especifico */ async function route(routes, request, response) { try { const path = url.parse(request.url).pathname const method = request.method console.log(`Handling ${method} ${path}`) // Ahora evaluamos si existe la entrada en las rutas // Pero también que el method sea el adecuado para procesarla const routeFunc = routes[path] if (routeFunc && routeFunc.method.toUpperCase().indexOf(method.toUpperCase()) >= 0) { const promise = new Promise((resolve, reject) => { try { routeFunc.handler(request, response) resolve() } catch (error) { reject(error) } }); await promise } else { handle404(request, response) } } catch (error) { handle500(request, response, error) } }; // Esto es un modulo, solo las cosas exportadas pueden verse desde otros archivos exports.route = route
Swift
UTF-8
3,004
2.71875
3
[]
no_license
// // ViewController.swift // CTATHelper // // Created by Paul on 9/27/19. // Copyright © 2019 Mathemusician.net. All rights reserved. // import Cocoa class ViewController: NSViewController { @IBOutlet var stackView: NSStackView! var allControls: [NSButton : (CommandType, NSTextField?)] = [:] override func viewDidLoad() { super.viewDidLoad() populateControls(commands: allCommands) } @IBAction func toggleDisplay(_ sender: NSButton) { if sender.state == .on { self.view.window?.level = .floating } else { self.view.window?.level = .normal } } func populateControls(commands: [CommandType]) { assert(allControls.isEmpty) for command in commands { if let command = command as? OneParameterCommand { // Initiate button and text field let button = NSButton(title: command.name, target: nil, action: #selector(commandButtonClicked(sender:))) let textField = NSTextField(string: command.parameter) // Layout let width: CGFloat = command.parameter.count > 2 ? 80 : 40 textField.addConstraint(textField.widthAnchor.constraint(equalToConstant: width)) let rowStackView = NSStackView(views: [button, textField]) rowStackView.setHuggingPriority(.init(rawValue: 749), for: .vertical) // Add stackView.addArrangedSubview(rowStackView) allControls[button] = (command, textField) } else { // Initiate button let button = NSButton(title: command.name, target: nil, action: #selector(commandButtonClicked(sender:))) // Add stackView.addArrangedSubview(button) allControls[button] = (command, nil) } } } @objc func commandButtonClicked(sender: NSButton) { let controls = allControls[sender]! let command: String let prompt: String if var control = controls.0 as? OneParameterCommand { control.parameter = controls.1!.stringValue command = control.command prompt = "\(control.name) \(control.parameter):" } else { command = controls.0.command prompt = "\(controls.0.name):" } runCommand(command, prompt: prompt) } func runCommand(_ command: String, prompt: String? = nil) { let jsScript = (prompt.map({"console.log(\\\"\($0)\\\");"}) ?? "") + command let rawScript = """ tell application "Safari" tell current tab of window 1 do JavaScript "\(jsScript)" end tell end tell """ // print(rawScript) var error: NSDictionary? = nil NSAppleScript(source: rawScript)?.executeAndReturnError(&error) if let error = error { print(error) } } }
Markdown
UTF-8
1,098
2.6875
3
[ "MIT" ]
permissive
# MFA-CLI A CLI client for MFA It's a MFA code manager. You can manage MFA accounts and its secret code. ## Install Download a latest mfa-cli from mfa-cli.zip link on below releases page. https://github.com/tkhr0/mfa-cli/releases Then unzip the file and move binary to $PATH dir. ```sh $ unzip mfa-cli.zip $ ls ./target/release/mfa-cli ./target/release/mfa-cli $ mv target/release/mfa-cli /usr/local/bin $ ls /usr/local/bin/mfa-cli /usr/local/bin/mfa-cli $ mfa-cli -V MFA CLI 0.2.0 ``` ## Usage ```sh # Add a new profiles $ mfa-cli profile add PROFILE_NAME SECRET_CODE # Show MFA code for the profile $ mfa-cli show PROFILE_NAME 123456 # After showing code, watch for changes $ mfa-cli show -w PROFILE_NAME 123456 # Show help $ mfa-cli help ``` mfa-cli store config to file. You will manage the directory by env variables. Here are the values and priorities you can specify. 1. `MFA_CLI_CONFIG_HOME` 1. `XDG_CONFIG_HOME` 1. `HOME` 1. Current directory (If mfa-cli couldn't find these values, it will use current directory) ## License This software is released under the MIT License.
Java
UTF-8
631
2.21875
2
[]
no_license
package com.rupine.helloworld.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import com.rupine.helloworld.service.GreetService; @RestController public class GreetController { @Autowired GreetService gs; @GetMapping("/welcome") public String greet() { return gs.greetService(); } @GetMapping("/welcome1/{id}") public String greet1(@PathVariable("id") int xyz) { return gs.greetService1(xyz); } }
Java
UTF-8
698
2.890625
3
[]
no_license
import java.util.Scanner; /* * 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 Ajay */ public class problem10 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int total = 0; System.out.println("Please enter your words"); while(true){ String word = input.nextLine(); total = total+1; if(word.equalsIgnoreCase("exit")){ System.out.println("your total number of words are " + (total-1)); break; } } } }
PHP
UTF-8
1,188
2.65625
3
[]
no_license
<?php session_start(); //logout if (isset($_SESSION['username']) && !isset($_POST['action'])) { session_destroy(); unset($_SESSION['username']); echo "<script>location.replace('../');</script>"; exit; } if (!isset($_POST['action'])) { echo "<script>alert('Wrong Access');location.replace('../');</script>"; } //login include "Database.php"; if ($_POST['action'] == "login") { if (login($_POST['username'], $_POST['password'])) { $_SESSION['username'] = $_POST['username']; echo "<script>location.replace('../');</script>"; } else { echo "<script>alert('Login Failed');</script>"; echo "<script>location.replace('../auth/login.php');</script>"; } } //register if ($_POST['action'] == "register") { if (register($_POST)) { echo "<script>alert('Welcome!');location.replace('../');</script>"; } else { echo "<script>alert('Register Failed');history.go(-1);</script>"; } } if ($_POST['action'] == "modify") { if (modify($_POST)) { echo "<script>alert('Success');location.replace('../');</script>"; } else { echo "<script>alert('Failed');history.go(-1);</script>"; } }
Shell
UTF-8
3,148
4.28125
4
[]
no_license
#!/bin/bash ################################################################################ ### Script to automate the socs sownload script ################################ ################################################################################ # ### Preparations ### SCRIPTNAME="$(basename "$(test -L "$0" && readlink "$0" || echo "$0")")" # Name # of the script itself. BASEDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Store the name of #the directory the script is executed from. export BASEDIR # Export the base directory path. source "$BASEDIR/Libraries/functions" # Source some functions. # Dot for execution inside the same shell. # ### Options ### while getopts ':b' OPTION ; do case $OPTION in # Execution in Background. b) background="yes" ;; \?) echo "Unbekannte Option \"-$OPTARG\"." >&2 usage $EXIT_ERROR ;; :) echo "Option \"-$OPTARG\" benötigt ein Argument." >&2 usage $EXIT_ERROR ;; *) echo "Dies kann eigentlich gar nicht passiert sein..." >&2 usage $EXIT_BUG ;; esac done shift $(( OPTIND - 1 )) # Skip used option arguments. # if (( $# < 1 )) ; then # Test for minimal argument count. echo "Please provide a file containing download links." >&2 usage $EXIT_ERROR fi # ### Check wehter this script should be run in the background ### if [[ $background == "yes" ]]; then # Check if screen is even installed. check_and_install screen # Reopen this very script but in background. "$SCREEN_BIN" -a -S "autoload_`sorting_date`" "$BASEDIR/autoload" $1 # Quit this instance of the script. exit 0 fi ## Taking input ## while read line; do eval $line # Evaluate the line to gain given variables. ## What if the type wasn't given? ## if [[ $type == '' ]]; then socs_echo "$SCRIPTNAME" "Download type was not given. Guessing..." ## Guess if it could be a torrent? ## if [[ `echo $url | grep ".torrent"` != '' ]]; then # Url contains the file # extension of a torrent. type=torrent # Guess it's a torrent. socs_echo "$SCRIPTNAME" "Assuming a torrent." fi ## No luck in guessing? Check wether it could be a video download ## if [[ $type == '' ]]; then # The type is still undetermined. # Check if youtube-dl is installed. . "$BASEDIR/Configuration/binpaths.sh" youtube-dl for streamer in `"$YOUTUBE_DL_BIN" --list-extractors` ; do # Compare # every extractor with the url to check wether it's a streaming site. if [[ `echo $url | grep -i $streamer` != '' ]]; then type=video # Guess it's a stream. socs_echo "$SCRIPTNAME" "Assuming streaming site $streamer as host." fi done fi ## Still no luck? ## if [[ $type == '' ]]; then socs_echo "$SCRIPTNAME" "Assuming a generic file download." type=file # Then assume a file. fi fi # "$BASEDIR/download" -d "$target" -t "$type" "$url" # Call the script. sleep 10 # Wait a few secings. done < $1 ### The End ### exit 0
Markdown
UTF-8
2,540
2.53125
3
[]
no_license
Formats: [HTML](2006/02/26/index.html) [JSON](2006/02/26/index.json) [XML](2006/02/26/index.xml) ## [2006-02-26](/news/2006/02/26/index.md) ##### World population ### [ The world's population hits 6.5 billion at 0016 UTC, according to the U.S. Census Bureau's World Population Clock. ](/news/2006/02/26/the-world-s-population-hits-6-5-billion-at-0016-utc-according-to-the-u-s-census-bureau-s-world-population-clock.md) _Context: US Census Bureau headquarters, World Population Clock, clock, world population_ ##### Jamaica ### [ Jamaica will have its first female Prime Minister, as Portia Simpson-Miller is elected president of the People's National Party. She will automatically replace P. J. Patterson in a few weeks. ](/news/2006/02/26/jamaica-will-have-its-first-female-prime-minister-as-portia-simpson-miller-is-elected-president-of-the-people-s-national-party-she-will-a.md) _Context: Jamaica, P. J. Patterson, People's National Party, Portia Simpson-Miller, Prime Minister of Jamaica_ ##### Al Askari Mosque bombing ### [ Al Askari Mosque bombing: The International Crisis Group releases a report cautioning the international community to plan for the contingency of a civil war in Iraq. At least 250 people have died in violence resulting from the Al Askari Mosque bombing. ](/news/2006/02/26/al-askari-mosque-bombing-the-international-crisis-group-releases-a-report-cautioning-the-international-community-to-plan-for-the-contingen.md) After a violent week in Iraq, the possibility of large-scale Sunni-Shiite conflict still looms. ##### 2006 Winter Olympics ### [ 2006 Winter Olympics: The Olympic flag is passed to the mayor of Vancouver, home of the 2010 Winter Olympics, during the Closing Ceremony of the 2006 Winter Olympics. ](/news/2006/02/26/2006-winter-olympics-the-olympic-flag-is-passed-to-the-mayor-of-vancouver-home-of-the-2010-winter-olympics-during-the-closing-ceremony-o.md) _Context: 2006 Winter Olympics, 2010 Winter Olympics, Closing Ceremony, Olympic flag, Vancouver, mayor_ ##### Olivier Awards ### [ Olivier Awards: Liam Mower, James Lomas and George Maguire win an award for Best Actor in a musical for their role in "Billy Elliot the Musical". They are the first to do so in a shared capacity. At 13, this makes Mower the youngest actor to ever receive this award. ](/news/2006/02/26/olivier-awards-liam-mower-james-lomas-and-george-maguire-win-an-award-for-best-actor-in-a-musical-for-their-role-in-billy-elliot-the-mus.md) _Context: Billy Elliot the Musical, George Maguire, James Lomas, Liam Mower, Olivier Awards_ ## [Previous Day...](/news/2006/02/25/index.md)
Java
UTF-8
367
1.796875
2
[]
no_license
package com.zhiyi.falcon.gateway.result; import java.io.Serializable; import java.util.List; /** * Created by lirenguan on 7/3/15. */ public class TaskListResult { private List<TaskResult> tasks; public List<TaskResult> getTasks() { return tasks; } public void setTasks(List<TaskResult> tasks) { this.tasks = tasks; } }
Java
UTF-8
3,461
2.53125
3
[]
no_license
package de.hbrs.aspgen.plugin; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.util.Set; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; public class DirectoryRefresher extends Thread { private Socket connection; private final Set<IProject> projects; private volatile boolean running = false; public DirectoryRefresher(final Socket connection, final Set<IProject> projects) { this.connection = connection; this.projects = projects; } public void startListening() { running = true; this.start(); } @Override public void run() { while(running) { try{ receiveMessage(); } catch (final IOException e) { handleDisconnect(); } } } private void receiveMessage() throws IOException { final String updateDir; BufferedReader in; in = new BufferedReader(new InputStreamReader(connection.getInputStream())); updateDir = in.readLine().replace("\\", "/"); for (final IProject project : projects) { final String projectDir = project.getLocation().toPortableString(); if (updateDir.startsWith(projectDir)) { updateProjectFolder(updateDir, project, projectDir); } } } private void updateProjectFolder(final String updateDir, final IProject project, final String projectDir) { boolean couldUpdateFolder = false; String folderToUpdate; folderToUpdate = updateDir.replace(projectDir, ""); folderToUpdate.replaceFirst("/*", ""); if (project.getFolder(folderToUpdate).exists()) { try { project.getFolder(folderToUpdate).refreshLocal(IResource.DEPTH_ONE, null); couldUpdateFolder = true; } catch (final CoreException e) { couldUpdateFolder = false; } } if (!couldUpdateFolder) { try { project.refreshLocal(IResource.DEPTH_INFINITE, null); } catch (final CoreException e) { e.printStackTrace(); } } } private void handleDisconnect() { running = false; try { connection.close(); } catch (final IOException e) { e.printStackTrace(); } PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { @Override public void run() { final Shell activeShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); final MessageBox box = new MessageBox(activeShell, SWT.ICON_WARNING); box.setMessage("Connection was closed"); box.open(); } }); } public void addProjects(final Set<IProject> projects) { this.projects.addAll(projects); } public void refreshConnection(final Socket newConnection) { if (connection.isClosed()) { connection = newConnection; } } public boolean isRunning() { return running; } }
C++
UTF-8
1,079
2.703125
3
[]
no_license
#ifndef _incl_texturebinding #define _incl_texturebinding // // o_TextureBinding.h - Header for oGeM texturebinding // // Oliver Grau, 15-JUL-1993 // #include "o_Property.h" #include <o_Vector.h> #include <vector> using std::vector; /*! \class o_TextureBinding o_TextureBinding.h \brief class for texturebinding */ class o_TextureBinding : public o_Property { public: o_TextureBinding() ; ~o_TextureBinding(); virtual const char *GetClassName() const; //! adds a coordinate at the end of the coordinate list void AddCoordinate( o_Vector2D &coord ); //! sets a coordinate of entry no void SetCoordinate( int no, o_Vector2D &coord ); /*! returns Coordinate number no, or NULL if no is not a valid index range */ o_Vector2D *GetCoordinate( int no ); //! copy coordinates of texture binding void Copy(o_TextureBinding &bind); void Copy(o_Property &org); virtual o_Property *MakeInstance(); //! returns the number of coordinates int NoOfCoord(); private: std::vector<o_Vector2D*> coordlist; }; #endif
Java
UTF-8
1,859
2.9375
3
[]
no_license
package chessHelper; import java.util.ArrayList; public class Evaluation implements Definitions{ public static final int MOBILITY_WEIGHT = 80; public static final int MATERIAL_WEIGHT = 110; public static final int CAPTURE_WEIGHT = 100; public int evaluate (Board b, int color) { MoveGenerator m = new MoveGenerator(); ArrayList<Move> bMoves = m.getAllBLKMoves(b); ArrayList<Move> wMoves = m.getAllWHTMoves(b); int oppColor = color*-1; int score = 0; if ((color < 0 && bMoves.size() == 0) || (color > 0 && wMoves.size() == 0)) { return MATE_VALUE; } if (b.isInCheck(color*-1)) score += 200; //material int myMaterial = b.getMaterial(color); int theirMaterial = b.getMaterial(oppColor); int netMaterial = myMaterial - theirMaterial; score += netMaterial; int mobility = mobilityScore(b, color, bMoves, wMoves); int captureScore = captureScore(b, color, bMoves, wMoves); return score + mobility + captureScore; } public int mobilityScore(Board b, int color, ArrayList<Move> bMoves, ArrayList<Move> wMoves){ boolean white; int score; if (color == 1) { white = true; score = wMoves.size() - bMoves.size(); } else { score = bMoves.size() - wMoves.size(); white = false; } return score; } public int captureScore(Board b, int color, ArrayList<Move> bMoves, ArrayList<Move> wMoves) { int wscore = 0; int bscore = 0; for (int i = 0; i < wMoves.size(); i++) { Move temp = wMoves.get(i); if (temp.capture !=0) { wscore++; } } for (int j = 0; j < bMoves.size(); j++) { Move temp2 = bMoves.get(j); if (temp2.capture !=0) { bscore++; } } if (color == WHITE) { return (wscore-bscore)*CAPTURE_WEIGHT; } else { return (bscore-wscore)*CAPTURE_WEIGHT; } } }
C++
UTF-8
3,357
3.75
4
[]
no_license
#include<iostream> using namespace std; #include<vector> class Test { string str; int var; public: #if 1 //Default constructor,Mandatory for Explicit constructor call Test(),V.V.Imp step Test() { str = ' '; //space character var =0; } #endif Test(string s,int num) { str=s; var=num; } void display() { cout<<"Name: "<<str<<" variable: "<<var<<endl; } }; int main() { #if 0 //class pointer object vector<Test*>v; Test *obj; v.push_back(obj);//pass by address only if(v.find(obj) != v.end()) //if obj is present in vector v.erase(v.find(obj)); #endif #if 0 //class normal object vector<Test>v; Test obj; v.push_back(obj);//pass by address only #endif vector<Test>v; //Only back insertion v.push_back( Test("Raja",1) ); //Explicit constructor call v.push_back( Test("Suri",2) ); //Explicit constructor call //v[0]= Test("Damu",3); //Throws Segmentation fault deque<Test>q; //Only front insertion q.push_front( Test("Raja",1) ); //Explicit constructor call q.push_front( Test("Suri",2) ); //Explicit constructor call forward_list<Test>f; //both front insertion f.push_front( Test("Raja",1) ); //Explicit constructor call f.push_front( Test("Suri",2) ); //Explicit constructor call list<Test>l; //both back and front insertion v.push_back( Test("Raja",1) ); //Explicit constructor call v.push_back( Test("Suri",2) ); //Explicit constructor call l.push_front( Test("Rajan",3) ); //Explicit constructor call l.push_front( Test("Surin",4) ); //Explicit constructor call set<Test>s; s.insert( Test("Raja",1) ); s.insert( Test("Suri",2) ); s.insert( Test("Rajan",3) ); s.insert( Test("Surin",4) ); map<int,Test>m; //class as Value m[0]=Test("Raja",10); m[1]=Test("Suri",20); m[2]=Test("Raja",30); //Previous same key will be overridden with this key-value pair m.insert( make_pair(3,Test("Raja",40)) ); //same key cannot be inserted m.insert( pair<int,Test>(4,Test("Ammi",50)) ); for(map<int,Test>::iterator it=m.begin();it != m.end(); it++) { cout<<"Key is:"<<it->first; cout<<" Value is:"; it->second.display(); //This func displays class members, //Do not use cout for void functions,V.V.Imp step } map<Test,int>m; //class as Key m[Test("Raja",10)] =0; m[Test("Suri",20)] =1; m[Test("Raja",30)] =2; //Previous same key will be overridden with this key-value pair m.insert( make_pair(Test(40,"Raja"),3) ); //same key cannot be inserted m.insert( pair<int,Test>(Test(50,"Ammi"),4) ); for(map<int,Test>::iterator it=m.begin();it != m.end(); it++) { cout<<"Key is:"; it->first.display(); cout<<" Value is:"<<it->second<<endl; } #if 1 //Since all the keys are arranged in sorted order,when passing classname as key,we need to sort it using operator overloading Test& operator<(const Test&obj) { if(name != obj.name) return name<obj.name; else if(name == obj.name) return num<obj.num; } #endif #if 0 //1st Method for(int i =0;i<v.size();i++) { v[i].display(); } #endif #if 1 //2nd Method for(vector<Test>::iterator it = v.begin();it !=v.end();it++) { it->display(); } #endif }
Markdown
UTF-8
3,520
2.734375
3
[ "MIT" ]
permissive
[[Research]][[Neuromorphic]] # Enabling Resource-Aware Mapping of Spiking Neural Networks via Spatial Decomposition [[Jeffrey Krichmar]] ### Introduction - How to efficiently use crossbars when not all neurons have the same number of input synapses - Unrolling technique - Decompose neurons into homogeneous neural units where each has max fanin of two (FIT) - Denser packing per crossbar ### Proposed Technique - ![Pasted image 20210529114749.png](Pasted%20image%2020210529114749.png) - Pruning - elimination of near-zero weights - Unrolling - limit number of presynaptic connections - Weight normalization - ensures quality of decomposed model #### Spatial Decomposition using Model Unrolling - 1 m-input neuron -> (m-1) 2-input neurons - ![Pasted image 20210529115055.png](Pasted%20image%2020210529115055.png) - $y_0=f(u_{m-1})$ - $u_i:$ - $f(n_1.w_1+n_2.w_2) for$ $i=1$ - $f(u_{1-1}+n_{i+1}.w_{i+1})$ $otherwise$ - $f$: neuron function - total number of FIT neurons from N-neuron network: - $N_{new}=\sum_1^N(m_i-1)$ - $m_i$ - fanin of neuron $n_i$ #### Weight Normalization - Weights normalized such that the firing rate of new neuron is proportional to its input activation in original model - Performed separately for each decomposed unit - $w_i=$ - $w_i/S^1_{norm}$ for i=1,2 - $w_i/S^{i-1}_{norm}$ otherwise - $S^i_{norm}=$ - $k(max(a_1+a_2)$ for i=1 - $k(max(a_{i+1})$ otherwise - $a_i$ activation on weight $w_i$ in the original model - Overhead can be reduced by allowing non=uniform decomposition #### Motivating Example - Mapping of functions onto 4x4 crossbar - ![Pasted image 20210529120928.png](Pasted%20image%2020210529120928.png) - Last term of $y_2$ cannot be mapped, normally - Unrolling enables mapping - Fewer crossbars, no loss in model quality, increase in crossbar utilization ### Results - ML Applications used: - ![Pasted image 20210529121317.png](Pasted%20image%2020210529121317.png) - Evaluated on [[DYNAP-SE]] (128x128 crossbar per tile): - ![Pasted image 20210529121350.png](Pasted%20image%2020210529121350.png) - Comparison of Hardware Requirement - ![Pasted image 20210529121422.png](Pasted%20image%2020210529121422.png) - 60% fewer crossbars on average - 10x fewer crossbars in EdgeDet even though EdgeDet has no neurons with more than 128 fanin - Due to many having close to 128 - Hence many instances of 1 crossbar/neuron - CNNs - more layers => more freedom to improve crossbar utilization - RNNs - Cyclic connections decomposed effectively - Comparison of Crossbar Utilization - Neurons: 53% vs. 9% average utilization - ![Pasted image 20210529121856.png](Pasted%20image%2020210529121856.png) - Synapses: 62% vs. 25% average utilization - ![Pasted image 20210529121913.png](Pasted%20image%2020210529121913.png) - Comparison of Wasted Energy - Incorporates neurons and synapses that are not utilized during execution - 62% lower energy usage on average - ![Pasted image 20210529122143.png](Pasted%20image%2020210529122143.png) - Comparison of Model Quality - Same in some cases due to some models having strictly <128 synapses/neuron - 3% better on average for networks that don't satisfy this constraint - ![Pasted image 20210529122317.png](Pasted%20image%2020210529122317.png) ### Discussion - Negative impact on accuracy and energy - Spike latency affected due to unrolling - Alleviated by SpiNeMap somewhat - Additional synapses mapped to shared interconnect - Energy on interconnect increases - Much lower compared to energy savings gained
C#
UTF-8
2,059
3.296875
3
[]
no_license
using System; namespace GamingStore { class GamingStore { static void Main(string[] args) { double budget = double.Parse(Console.ReadLine()); string input = Console.ReadLine(); double totalSpent = 0; double startingBudget = budget; double price = 0; while (input != "Game Time") { string currentGame = input; switch (currentGame) { case "OutFall 4": price = 39.99; break; case "CS: OG": price = 15.99; break; case "Zplinter Zell": price = 19.99; break; case "Honored 2": price = 59.99; break; case "RoverWatch": price = 29.99; break; case "RoverWatch Origins Edition": price = 39.99; break; default: Console.WriteLine("Not Found"); input = Console.ReadLine(); continue; } if (budget < price) { Console.WriteLine("Too Expensive"); } else if (budget >= price) { budget -= price; totalSpent += price; Console.WriteLine($"Bought {currentGame}"); if (budget == 0) { Console.WriteLine("Out of money!"); return; } } input = Console.ReadLine(); } Console.WriteLine($"Total spent: ${totalSpent:f2}. Remaining: ${startingBudget - totalSpent:f2}"); } } }
Python
UTF-8
3,169
2.75
3
[]
no_license
import numpy as np import math import time input_layer_neurons = 2 l1_neurons = 2 l2_neurons = 2 test_x = np.array([[[0,1]], [[1,0]], [[1,1]], [[0,0]]]) test_y = np.array([[[0,1]], [[1,0]], [[1,0]], [[0,1]]]) l1_w = np.random.rand(input_layer_neurons,l1_neurons) l2_w = np.random.rand(l1_neurons,l2_neurons) l1_b = np.random.rand(1,l1_neurons) l2_b = np.random.rand(1,l2_neurons) def sigmoid(x): return 1 / (1 + math.exp(-x)) def activation(x): #Sigmoid [[x1,x2]] = x z = np.array([[sigmoid(x1), sigmoid(x2)]]) return z lr = 10 def sigmoid_prime(x): return math.exp(-x) / ((1 + math.exp(-x)) ** 2) def inverse_activation(x): #Sigmoid [[x1,x2]] = x z = np.array([[sigmoid_prime(x1), sigmoid_prime(x2)]]) return z def backpropogation(x): global l2_w, l2_b, l1_w for (i,sample) in enumerate(x): x1 = np.matmul(sample,l1_w) x1 = x1 + l1_b act1 = activation(x1) x2 = np.matmul(act1,l2_w) x2 = x2 + l2_b y_hat = activation(x2) g_t = test_y[i] print(i,"Current prediction:", y_hat, "actual", g_t) dw5 = (g_t[0][0] - y_hat[0][0]) * inverse_activation(x2)[0][0] * act1[0][0] * lr dw7 = (g_t[0][0] - y_hat[0][0]) * inverse_activation(x2)[0][0] * act1[0][1] * lr dw6 = (g_t[0][1] - y_hat[0][1]) * inverse_activation(x2)[0][1] * act1[0][0] * lr dw8 = (g_t[0][1] - y_hat[0][1]) * inverse_activation(x2)[0][1] * act1[0][1] * lr db3 = (g_t[0][0] - y_hat[0][0]) * inverse_activation(x2)[0][0] * lr db4 = (g_t[0][1] - y_hat[0][1]) * inverse_activation(x2)[0][1] * lr d_l2_w = np.array([[dw5,dw6],[dw7,dw8]]) d_l2_b = np.array([[db3,db4]]) dw1 = (g_t[0][0] - y_hat[0][0]) * inverse_activation(x2)[0][0] * l2_w[0][0] * inverse_activation(x1)[0][0] * sample[0][0] * lr dw1 += (g_t[0][1] - y_hat[0][1]) * inverse_activation(x2)[0][1] * l2_w[0][1] * inverse_activation(x1)[0][0] * sample[0][0] * lr dw2 = (g_t[0][0] - y_hat[0][0]) * inverse_activation(x2)[0][0] * l2_w[1][0] * inverse_activation(x1)[0][1] * sample[0][0] * lr dw2 += (g_t[0][1] - y_hat[0][1]) * inverse_activation(x2)[0][1] * l2_w[1][1] * inverse_activation(x1)[0][1] * sample[0][0] * lr dw3 = (g_t[0][0] - y_hat[0][0]) * inverse_activation(x2)[0][0] * l2_w[0][0] * inverse_activation(x1)[0][0] * sample[0][1] * lr dw3 += (g_t[0][1] - y_hat[0][1]) * inverse_activation(x2)[0][1] * l2_w[0][1] * inverse_activation(x1)[0][0] * sample[0][1] * lr dw4 = (g_t[0][0] - y_hat[0][0]) * inverse_activation(x2)[0][0] * l2_w[1][0] * inverse_activation(x1)[0][1] * sample[0][1] * lr dw4 += (g_t[0][1] - y_hat[0][1]) * inverse_activation(x2)[0][1] * l2_w[1][1] * inverse_activation(x1)[0][1] * sample[0][1] * lr d_l1_w = np.array([[dw1,dw2],[dw3,dw4]]) #print(d_l1_w,"\n") #print(d_l2_w,"\n") #print(d_l2_b,"\n\n\n") l1_w += d_l1_w l2_w += d_l2_w l2_b += d_l2_b while True: #predict(test_x) time.sleep(0.1) backpropogation(test_x) print("\n")
Python
UTF-8
5,399
3.125
3
[]
no_license
# Takes as an input a list of .txt files in which each patent is on its own # line: an output of one-patent-per-line.py | grep -i "COMPANY" > out.txt # Extracts fields for output as a tidy .csv import sys as sys import re as re import pandas as pd def oppl_to_df(company, patent_file): """Takes a wide patent file, and returns a pandas DataFrame Inputs: company: string of company name patent_file: .txt file where each patent owned by company is on a single line Ouput: pandas DataFrame, where rows are patents, and columns are the features: company name patent assignee year granted year applied patent class patent number patent title patent abstract """ # initialize fields as a dictionary fields = {'company_name' : [], 'patent_assignee' : [], 'year_granted' : [], 'year_applied' : [], 'patent_class' : [], 'patent_number' : [], 'patent_title' : [], 'patent_abstract' : []} # specify regular expressions assignee_re = '<assignee>.*?</orgname>' pub_ref_re = '<publication-reference>.*?</publication-reference>' date_tags = '<publication-reference>.*<date>|</date>.*' id_tags = '<publication-reference>.*<doc-number>|</doc-number>.*' app_ref_re = '<application-reference.*?</application-reference>' class_re = '</classification-locarno>.*?</main-classification>' title_re = '<invention-title.*?</invention-title>' abstract_re = '<abstract.*?</abstract>' for line in patent_file.readlines(): # Use regex to find fields, # and append them to appropriate dictionary value # attach company name fields['company_name'].append(company) # extract patent assignee assignee = re.search(assignee_re, line) if assignee: patent_assignee = re.sub('<assignee>.*<orgname>|</orgname>', '', assignee.group()) fields['patent_assignee'].append(patent_assignee) else: fields['patent_assignee'].append('None') # extract year granted and patent number, # both in <publication-reference> pub_ref = re.search(pub_ref_re, line) if pub_ref: year_granted = re.sub(date_tags, '', pub_ref.group()) patent_number = re.sub(id_tags, '', pub_ref.group()) fields['year_granted'].append(year_granted[0:4]) fields['patent_number'].append(patent_number) else: fields['year_granted'].append('None') fields['patent_number'].append('None') # extract year applied app_ref = re.search(app_ref_re, line) if app_ref: year_applied = re.sub('<application.*<date>|</date>.*', '', app_ref.group()) fields['year_applied'].append(year_applied[0:4]) else: fields['year_applied'].append('None') # extract patent classification classification = re.search(class_re, line) if classification: patent_class = re.sub('</class.*<main-classification>|</main.*', '', classification.group()) fields['patent_class'].append(patent_class) else: fields['patent_class'].append('None') # extract patent title title = re.search(title_re, line) if title: patent_title = re.sub('<invention.*?>|</invention.*', '', title.group()) fields['patent_title'].append(patent_title) else: fields['patent_title'].append('None') # extract patent abstract abstract_field = re.search(abstract_re, line) if abstract_field: abstract = re.sub('<abstract.*<p.*?>|</abstract>', '', abstract_field.group()) fields['patent_abstract'].append(abstract) else: fields['patent_abstract'].append('None') # transform dictionary to pandas DataFrame return pd.DataFrame(fields) def run(): # paths to patent files for each company. Each patent is on a single line. oppl_medtronic = open('../oppl_medtronic.txt') oppl_stryker = open('../oppl_stryker.txt') oppl_bs = open('../oppl_boston_scientific.txt') oppl_abbott = open('../oppl_abbott.txt') # define lists of companies, and the patent files for feature extraction loop oppl_files = [oppl_medtronic, oppl_stryker, oppl_bs, oppl_abbott] companies = ['Medtronic', 'Stryker', 'Boston Scientific', 'Abbott'] # convert each patent file into a tidy pandas data frame dfs = [oppl_to_df(companies[i], oppl_files[i]) for i in range(len(companies))] # concatenate the data frames, and write to .csv df_combined = pd.concat(dfs, ignore_index=True) df_combined.to_csv('medtronic_and_competitor_patents_05-15.csv', index=False) if __name__ == "__main__": run()
C
UTF-8
795
4
4
[]
no_license
// // main.c // 107 // // Created by Ayşıl Simge Karacan on 9.01.2020. // Copyright © 2020 Ayşıl Simge Karacan. All rights reserved. // //Write a C program to count total number of even and odd elements in an array. #include <stdio.h> #define MAX_SIZE 1000 int main() { int size,i,odd=0,even=0; int arr[MAX_SIZE]; printf("Enter the size of the array: "); scanf("%d",&size); printf("Enter the elements of the array: \n"); for (i=0; i<size; i++) { scanf("%d",&arr[size]); } for (i=0; i<size; i++) { if (arr[i] % 2 == 0) { even++; } else { odd++; } } printf("Number of odd elements: %d\n",odd); printf("Number of even elements: %d\n",even); return 0; }
PHP
UTF-8
1,452
3.0625
3
[ "MIT" ]
permissive
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * Script * * Generates a script inclusion of a JavaScript file * Based on the CodeIgniters original Link Tag. * * * @access public * @param mixed javascript sources or an array * @param string language * @param string type * @param boolean should index_page be added to the javascript path * @author Isern Palaus <ipalaus@ipalaus.com> * @return string */ if ( ! function_exists('script_tag')) { function script_tag($src = '', $language = 'javascript', $type = 'text/javascript', $index_page = FALSE) { $CI =& get_instance(); $script = '<script'; if (is_array($src)) { foreach ($src as $k=>$v) { if ($k == 'src' AND strpos($v, '://') === FALSE) { if ($index_page === TRUE) { $script .= ' src="'.$CI->config->site_url($v).'"'; } else { $script .= ' src="'.$CI->config->slash_item('base_url').$v.'"'; } } else { $script .= "$k=\"$v\""; } } $script .= "></script>\n"; } else { if ( strpos($src, '://') !== FALSE) { $script .= ' src="'.$src.'" '; } elseif ($index_page === TRUE) { $script .= ' src="'.$CI->config->site_url($src).'" '; } else { $script .= ' src="'.$CI->config->slash_item('base_url').$src.'" '; } $script .= 'language="'.$language.'" type="'.$type.'"'; $script .= '></script>'."\n"; } return $script; } } ?>
C++
UTF-8
8,152
4.25
4
[]
no_license
#include <iostream> #include <cstdlib> using namespace std; // Definition of a node of Link List typedef struct node { int data; struct node * next; }NODE; // Code for presenting choices for operations to be performed int choices() { int ch = 0; cout << "\n\nWhat would you like to do ? \n" <<endl; cout << "\t(1) Initialize an empty link list."<<endl; cout << "\t(2) Insert a node." << endl; cout << "\t(3) Delete a node." << endl; cout << "\t(4) Swap two node." << endl; cout << "\t(5) Reverse Linklist." << endl; cout << "\t(6) Print Linklist." << endl; cout << "\t(7) Print length of Linklist." << endl; cout << "\t(8) Search a node in Linklist." << endl; cout << "\t(9) Exit." << endl; cout << "\nEnter Choice : "; cin >> ch; while (ch<1 || ch >9) { cout << "Please enter choice between (1) to (9) : " << endl; cin >> ch; } return ch; } // Code to initialize the link list NODE * init() { NODE * head = (NODE*) malloc (sizeof (NODE)); head -> next = NULL; head -> data = 0; cout << "Link List initialized"<<endl; return head; } // Code to insert a node in the link list. void insert (NODE * head) { int ch; int d; cout << "Enter the data you want to insert ? "; cin >> d; cout << "Where do you want to insert the node ?"<<endl; cout << "\t(1) At the beginning of the list."<<endl; cout << "\t(2) At the end of the list."<<endl; cout << "\t(3) After a node with particular key value."<<endl; cout << "Enter choice : "; cin >> ch; NODE * ctr; NODE * temp = (NODE*) malloc (sizeof (NODE)); temp -> data = d; switch(ch) { case 1: temp -> next = head -> next; head -> next = temp; cout << "\nNode inserted at the beginning of the list" <<endl; break; case 2: ctr = head; while (ctr->next != NULL) { ctr = ctr -> next; } temp -> next = NULL; ctr -> next = temp; cout << "\nNode inserted at the end of the list" <<endl; break; case 3: int key; cout << "Enter the key after which you want to insert the node. "; cin >> key; ctr = head; while (ctr->data != key && ctr -> next != NULL) { ctr = ctr -> next; } if (ctr -> data == key ) { temp -> next = ctr -> next; ctr -> next = temp; } else { cout << "The key does not exist. "; temp -> next = NULL; ctr -> next = temp; cout << "\nNode inserted at the end of the list" <<endl; } break; } } // code for deleting a node int del(NODE * head) { NODE * temp= head; if (head -> next == NULL) { cout << "Linklist is empty. Nothing to delete !" << endl; return 0; } int ch; cout << "Which node to delete ?"<<endl; cout << "\t(1) First node." << endl; cout << "\t(2) Last node."<<endl; cout << "\t(3) Node with a particular key value."<<endl; cout << "Enter choice : "; cin >> ch; switch (ch) { case 1: cout << "Deleted node with data : " << head -> next -> data << endl; head ->next = head ->next -> next; break; case 2: while (temp -> next -> next != NULL) { temp = temp -> next; } cout << "Deleted node with data : " << temp -> next -> data << endl; temp -> next = NULL; break; case 3: int key; cout << "Enter the key value to delete : " <<endl; cin >> key; while (temp -> next -> data != key && temp -> next != NULL ) { temp = temp -> next; } if (temp -> next -> data == key) { cout << "Deleting node with data : " << key <<endl; temp -> next = temp -> next -> next; } else { cout << "The key entered does not exist. Nothing to do !"; } } return 1; } // Code for reversing the link list void reverse(NODE * head) { NODE * prev, * curr, * nex ; curr = head->next; if (head->next == NULL) { cout << " Linklist is empty. Nothing to reverse."; } else { prev = NULL; while (curr -> next != NULL) { nex = curr -> next; curr -> next = prev; prev = curr; curr = nex; } curr->next = prev; head->next = curr; cout << " Linklist reversed."; } } // Code to search the linklist int search (NODE * head) { int key; cout << "Enter the key value to search : "; cin >> key; NODE * temp = head -> next; int count = 0; while (temp != NULL) { count ++; if (temp -> data == key) { cout << "Key = " << key <<" found in the link list at node "<< count <<endl; return 1; } temp = temp -> next; } cout << "Key = " << key <<" not found in the link list"<<endl; return 0; } // Code to print the linklist void display(NODE * head) { cout << "HEAD --> "; NODE * ctr = head -> next; while(ctr != NULL) { cout << ctr -> data << " --> "; ctr = ctr -> next; } cout << "END"<<endl; } // Code to print the length of the linklist void length(NODE * head) { NODE * temp = head -> next; int l = 0; while (temp != NULL) { temp = temp -> next; l++; } cout << "The length of the linklist is : " << l << endl; } // Main function int main() { cout << "Single - Link List"<< endl; cout << "=================="; int c; NODE * head = NULL; NODE * ctr = head; while (1) { c = choices(); switch(c) { case 1: // Initialize if (head == NULL) { head = init(); } else { cout << "\nERROR : Link list already exist." << endl; } break; case 2: // Insert if (head == NULL) { cout << "\nERROR : Linklist not initialized! Initialize linklist to insert node." <<endl; } else { insert (head); } break; case 3: // Delete if (head == NULL) { cout << "\nERROR : Linklist not initialized! Initialize linklist before trying to delete node." <<endl; } else { del (head); } break; case 4: // Swap // swap break; case 5: // Reverse if (head == NULL) { cout << "\nERROR : Linklist not initialized! Initialize linklist before trying to reverse it." <<endl; } else { reverse(head); } break; case 6: // Print display(head); break; case 7: // Length if (head == NULL) { cout << "\nERROR : Linklist not initialized! Initialize linklist to count length." <<endl; } else { length(head); } break; case 8: // Search if (head == NULL) { cout << "\nERROR : No link list to search in !! Initialize link list first;" << endl; } else { search(head); } break; case 9: // Exit return 0; default: cout << "Wrong choice entered ! "<<endl; } } }
C#
UTF-8
946
3.765625
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Q3 { class Question3 { static void Main(string[] args) { double length, width, area, woodLength; Console.Write("Enter Window Width (in mm):\t"); width = Convert.ToDouble(Console.ReadLine()); Console.Write("Enter Window Length (in mm):\t"); length = Convert.ToDouble(Console.ReadLine()); width = convertToMeter(width); length = convertToMeter(length); area = length * width; woodLength = (length * 2) + ( width * 2); Console.WriteLine("Wood amount:\t\t\t" + woodLength + "m"); Console.WriteLine("Glass amount:\t\t\t" + area + " sqr m"); } static double convertToMeter(double val) { return val / 1000; } } }
Python
UTF-8
237
2.8125
3
[]
no_license
def sock_merchant(lst): colors = {} for i in lst: if i not in colors: colors[i] = 1 else: colors[i] += 1 counts = [colors[i]//2 for i in colors] return sum(counts) print(sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20]))
Python
UTF-8
1,187
2.5625
3
[]
no_license
''' --------《Python从菜鸟到高手》源代码------------ 欧瑞科技版权所有 作者:李宁 如有任何技术问题,请加QQ技术讨论群:264268059 或关注“极客起源”订阅号或“欧瑞科技”服务号或扫码关注订阅号和服务号,二维码在源代码根目录 如果QQ群已满,请访问https://geekori.com,在右侧查看最新的QQ群,同时可以扫码关注公众号 “欧瑞学院”是欧瑞科技旗下在线IT教育学院,包含大量IT前沿视频课程, 请访问http://geekori.com/edu或关注前面提到的订阅号和服务号,进入移动版的欧瑞学院 “极客题库”是欧瑞科技旗下在线题库,请扫描源代码根目录中的小程序码安装“极客题库”小程序 关于更多信息,请访问下面的页面 https://geekori.com/help/videocourse/readme.html ''' from flask import Flask, request app = Flask(__name__) @app.route('/') def helloworld(): return 'hello world' @app.route('/register', methods=['POST']) def register(): print(request.form.get('name')) print(request.form.get('age')) return '注册成功' if __name__ == '__main__': app.run()
C++
UTF-8
2,130
3.65625
4
[]
no_license
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *link; }; struct node *head; node* getnode(int data) { node* newNode = (node*)malloc(sizeof(node)); newNode->data = data; newNode->link = NULL; return newNode; } void list(int n) { struct node *temp,*newnode; int i,data,count=0; head=(struct node*)malloc(sizeof(node)); if(head==NULL) { printf("Insufficient space"); } printf("Enter data of first node: "); scanf("%d",&data); head->data=data; head->link=NULL; temp=head; count++; for(i=0;i<n-1;i++) { printf("Enter data for node %d: ",count+1); scanf("%d",&data); newnode=getnode(data); temp->link=newnode; newnode->link=head; temp=newnode; count++; } } void printall() { printf("Current list is: "); struct node* temp; if(head==NULL) {printf("Empty LIST "); } temp=head; while(temp->link!=head) { printf("%d->",temp->data); temp=temp->link; } printf("%d",temp->data); } /* void printallspecial() { struct node* temp; temp=head; int count=1; while(temp!=NULL) { printf("%d{%d}->",temp->data,count); temp=temp->link; count++; } }*/ void deletebeg() { struct node *temp,*temp2; temp=head; temp2=head; while(temp->link!=head) { temp=temp->link; } temp->link=head->link; free(temp2); head=temp->link; } void deleteend() { struct node *temp,*temp2; temp=head; while(temp->link->link!=head) { temp=temp->link; } temp2=temp->link; temp->link=head; free(temp2); } int main() { int n; printf("Enter the value of n: "); scanf("%d",&n); list(n); printall(); int ch; int ch1=1; while(ch1==1) { printf(" \nMenu for operations: Enter 1 for deletion at beginning and 2 for deletion at end: "); scanf("%d",&ch); switch(ch) { case 1: deletebeg(); printall(); break; case 2: deleteend(); printall(); break; /*case 3: deletemid(); printall();*/ } printf("Enter more? 1 for yes and 0 for no "); scanf("%d",&ch1); } return 0; }
Python
UTF-8
266
2.8125
3
[ "MIT" ]
permissive
import os import inflection class FileBase: def __init__(self, filepath): self.filepath = os.path.normpath(filepath) def to_filename(self, root_path): filepath = self.remove_base_directory(self.filepath, root_path) return filepath
Java
UTF-8
2,417
2.859375
3
[]
no_license
package com.aquatic.service.preprocessing.entity; import java.util.ArrayList; import java.util.List; public class Sample { //һ������������ private List<Parameters> series; //һ�������еIJ����������� private int numberOfNodes; @Override public String toString() { String matrix=""; for(Parameters para:series){ String row = "["+ para.toString() +"]"; matrix = matrix + row; } return matrix; } public void arrayToList(double[][] valueArray){ int rows = valueArray.length; int cols = valueArray[0].length; this.numberOfNodes = cols; for(int i=0;i<cols;i++){ Parameters para = new Parameters(); List<Double> paraList = new ArrayList<>(); for(int j=0;j<rows;j++){ paraList.add(valueArray[j][i]); } para.setParaList(paraList); this.series.add(para); } } public void setListValue(double value,int row,int col){ series.get(col).getParaList().set(row, value); } public Double getListValue(int row,int col){ return series.get(col).getParaList().get(row); } public Sample() { series = new ArrayList<>(); numberOfNodes = 0; } public List<Parameters> getSeries() { return series; } public void setSeries(List<Parameters> series) { this.series = series; } public int getNumberOfNodes() { return numberOfNodes; } public void setNumberOfNodes(int numberOfNodes) { this.numberOfNodes = numberOfNodes; } public boolean compare(Sample s){ boolean equal = false; int count = 0; if(this.numberOfNodes==s.numberOfNodes){ List<Parameters> paraList = s.getSeries(); int index = 0; for(Parameters para:paraList){ if(para.equals(this.series.get(index++))){ count++; } } } if(count==s.numberOfNodes){ equal = true; } return equal; } public void setTime(Sample sample, Sample time) { List<Parameters> origin = sample.getSeries(); List<Parameters> timeList = time.getSeries(); int count = 0; for(Parameters param:origin){ Parameters current = timeList.get(count); param.setDate(current.getDate()); param.setTime(current.getTime()); count++; } } // ȡij���������� public double[] listToArray(int i) { double[] paraArray = new double[series.size()]; int count=0; for(Parameters para:series){ paraArray[count++] = para.getParaList().get(i); } return paraArray; } }
C#
UTF-8
6,056
3.140625
3
[ "Unlicense" ]
permissive
using System; using System.Collections.Generic; namespace Func.Net { //Optional implementation for functional programming public static class Optional { public static Optional<T> Of<T>(T value) { Validations.RequireNonNull(value); return new Optional<T>(value, true); } public static Optional<T> OfNullable<T>(T value) => value == null ? Optional<T>.Empty() : Of(value); public static Optional<T> Empty<T>() => Optional<T>.Empty(); } public struct Optional<T> : IEquatable<Optional<T>>, IComparable<Optional<T>> { public static Optional<T> Empty() => s_empty; private static readonly Optional<T> s_empty = new Optional<T>(default(T), false); private readonly T m_value; public bool IsPresent { get; } public bool IsEmpty => !IsPresent; internal Optional(T value, bool hasValue) { m_value = value; IsPresent = hasValue; } public T Get() { if (IsPresent) { return m_value; } throw new ArgumentNullException("No value present"); } public void IfPresent(Action<T> consumer) { if (IsPresent) { consumer.Invoke(m_value); } } public void IfNotPresent(Action action) { if (IsPresent) { action.Invoke(); } } public Optional<T> Filter(Func<T, bool> predicate) { Validations.RequireNonNull(predicate, nameof(predicate)); if (IsEmpty) { return this; } return predicate(m_value) ? this : s_empty; } public Optional<TResult> Map<TResult>(Func<T, TResult> mapper) { Validations.RequireNonNull(mapper, nameof(mapper)); return doMatch(v => Optional.OfNullable(mapper(v)), Optional<TResult>.Empty); } public Optional<TResult> FlatMap<TResult>(Func<T, Optional<TResult>> mapper) { Validations.RequireNonNull(mapper, nameof(mapper)); if (IsPresent) { return mapper(m_value); } return Optional<TResult>.Empty(); } public T OrElse(T other) => IsPresent ? m_value : other; public T OrElse(Func<T> factory) { Validations.RequireNonNull(factory, nameof(factory)); return IsPresent ? m_value : factory(); } public Optional<T> OrOptional(T other) => IsPresent ? this : Optional.OfNullable(other); public Optional<T> OrOptional(Func<T> factory) { Validations.RequireNonNull(factory, nameof(factory)); return IsPresent ? this : Optional.OfNullable(factory()); } public T OrElseThrow<TException>(Func<TException> exceptionFactory) where TException : Exception { Validations.RequireNonNull(exceptionFactory, nameof(exceptionFactory)); if (IsPresent) { return m_value; } throw exceptionFactory.Invoke(); } public TResult Match<TResult>(Func<T, TResult> onPresent, Func<TResult> onEmpty) { return doMatch(onPresent, onEmpty); } private TResult doMatch<TResult>(Func<T, TResult> onPresent, Func<TResult> onEmpty) { Validations.RequireNonNull(onPresent, nameof(onPresent)); Validations.RequireNonNull(onEmpty, nameof(onEmpty)); return IsPresent ? onPresent(m_value) : onEmpty(); } public void Match(Action<T> onPresent, Action onEmpty) { Validations.RequireNonNull(onPresent, nameof(onPresent)); Validations.RequireNonNull(onEmpty, nameof(onEmpty)); if (IsPresent) { onPresent(m_value); } else { onEmpty(); } } public Optional<T> PeekEmpty(Action onEmpty) { Validations.RequireNonNull(onEmpty, nameof(onEmpty)); if (IsEmpty) onEmpty(); return this; } public Optional<T> PeekPresent(Action<T> onPresent) { Validations.RequireNonNull(onPresent, nameof(onPresent)); if (IsPresent) onPresent(m_value); return this; } public bool Equals(Optional<T> other) { if (IsEmpty && other.IsEmpty) { return true; } if (IsPresent && other.IsPresent) { return EqualityComparer<T>.Default.Equals(m_value, other.m_value); } return false; } public override bool Equals(object obj) => obj is Optional<T> ? Equals((Optional<T>)obj) : false; public override int GetHashCode() { if (IsPresent) { if (m_value == null) { return 1; } return m_value.GetHashCode(); } return 0; } public int CompareTo(Optional<T> other) { if (IsPresent && other.IsEmpty) { return 1; } if (IsEmpty && other.IsPresent) { return -1; } return Comparer<T>.Default.Compare(m_value, other.m_value); } public override string ToString() { if (IsPresent) { if (m_value == null) { return "Optional[null]"; } return $"Optional[{m_value}]"; } return "Optional[Empty]"; } } }
JavaScript
UTF-8
3,057
2.625
3
[]
no_license
// fetch data d3.json('data/party.json', function(response) { var getAllTimes = function(actions) { return _.chain(actions).pluck('time').uniq().value(); }, getPartiersAtTime = function(actions, time) { return _.chain(actions).groupBy(function(action) { return action.partier; }).filter(function(actions) { return actions[0].time <= time && (actions[1] ? time < actions[1].time : true); }).map(function(actions) { return { name: actions[0].partier, entered: actions[0].time === time, exit: actions[1] && (actions[1].time - 100 === time) }; }).value(); } var allTimes = getAllTimes(response), selectedTime = allTimes[0], partiersAtTime = getPartiersAtTime(response, selectedTime); var container = d3.select('.party_02'); // first render the times var times = container.append('div') .classed('times', true) .selectAll('.partyTime') .data(getAllTimes(response)); times.enter().append('div') .classed({ 'partyTime': true, 'btn': true, 'btn-xs': true, 'btn-default': function(time) { return time !== selectedTime; }, 'btn-primary': function(time) { return time === selectedTime; } }).text(function(time) { return time; }); // then render the partiers var partiers = container.append('div') .classed('partiers', true) .selectAll('.partier') .data(partiersAtTime, function(partier) { return partier.name; }); partiers.enter().append('div') .classed({ 'partier': true, 'label': true, 'label-default': function(partier) { return !partier.entered && !partier.exit; }, 'label-primary': function(partier) { return partier.entered; }, 'label-warning': function(partier) { return partier.exit; } }).text(function(partier) { return partier.name; }); times.on('click', function() { selectedTime = d3.select(d3.event.target).datum(); partiersAtTime = getPartiersAtTime(response, selectedTime); times.classed({ 'btn-default': function(time) { return time !== selectedTime; }, 'btn-primary': function(time) { return time === selectedTime; } }) // rebind the updated partier data partiers = partiers.data(partiersAtTime, function(partier) { return partier.name; }) partiers.enter().append('span'); partiers.exit().remove(); // update partiers.classed({ 'partier': true, 'label': true, 'label-default': function(partier) { return !partier.entered && !partier.exit; }, 'label-primary': function(partier) { return partier.entered; }, 'label-warning': function(partier) { return partier.exit; } }).text(function(partier) { return partier.name; }); }) });
Markdown
UTF-8
645
4.25
4
[]
no_license
# Kata - [Valid Parentheses](https://www.codewars.com/kata/52774a314c2333f0a7000688) ### Description: Write a function called `validParentheses` that takes a string of parentheses, and determines if the order of the parentheses is valid. validParentheses should return true if the string is valid, and false if it's invalid. Examples: `validParentheses( "()" )` => returns true `validParentheses( ")(()))" )` => returns false `validParentheses( "(" )` => returns false `validParentheses( "(())((()())())" )` => returns true All input strings will be nonempty, and will only consist of open parentheses '(' and/or closed parentheses ')'
TypeScript
UTF-8
876
2.796875
3
[]
no_license
import { getRepository } from "typeorm"; import { Url } from "../../entity/Url"; import { AsyncForEach } from "../../utils/jsUtils"; interface UrlSeed { url: string; accessKey: string; accessCount: number; } export const urlSeeds: UrlSeed[] = [ { url: "https://www.naver.com/", accessKey: "1EiA912zuW", accessCount: 49, }, { url: "https://www.google.com/", accessKey: "81yQ0n39Rf", accessCount: 13, }, { url: "https://www.youtube.com/", accessKey: "existKey", accessCount: 0, }, ]; export const getRandomUrlSeed = () => { return urlSeeds[Math.floor(Math.random() * urlSeeds.length)]; }; export const urlSeeder = async () => { const urlRepository = getRepository(Url); await AsyncForEach(urlSeeds, async (urlSeed) => { const url = new Url(); Object.assign(url, urlSeed); await urlRepository.save(url); }); };
Python
UTF-8
1,187
3.328125
3
[]
no_license
# -*- coding: utf-8 -*- """some helper functions.""" import numpy as np def compute_loss(y, tx, w): """Calculate the loss. You can calculate the loss using mse or mae. assumes w,y row arrays """ # convert row arrays to matrices in correct shape w = np.matrix(w).T y = np.matrix(y).T # calculate e e = y- np.dot(tx,w) #calculate loss loss = np.dot(e.T,e)[0,0]/ 2 / y.shape[0] # MSE return loss def generate_w(num_intervals): """Generate a grid of values for w0 and w1.""" w0 = np.linspace(-100, 200, num_intervals) w1 = np.linspace(-150, 150, num_intervals) return w0, w1 def get_best_parameters(w0, w1, losses): """Get the best w from the result of grid search.""" min_row, min_col = np.unravel_index(np.argmin(losses), losses.shape) return losses[min_row, min_col], w0[min_row], w1[min_col] def grid_search(y, tx, w0, w1): """Algorithm for grid search. w0 and w1 are arrays """ losses = np.zeros((len(w0), len(w1))) for i0 in w0: for i1 in w1: losses[w0.tolist().index(i0),w1.tolist().index(i1)] = compute_loss(y,tx,[i0,i1]) return losses
Python
UTF-8
4,825
3
3
[ "MIT" ]
permissive
''' PUSHBLOCK the agent must push the block onto the goal square Reward ------ step: -1 block moves closer to goal: 2, if warmercolder==True block is on top of goal: 1000 Success ------- block is on top of goal Parameters ---------- frame : bool True to include a frame object that contains the agent (default: True) colors : bool True to color code the objects (default: True) warmercolder : bool True if the reward should indicate whether the block is moving toward or away from the goal (default: False) num_blocks : int the number of blocks to include (default: 1) ''' import numpy as np from pixelworld.envs import pixelworld as px from pixelworld.envs.pixelworld.utils import roundup, PointMath as pmath class DistanceObjectAttribute( px.core.FloatObjectAttribute, px.core.ChangeTrackingObjectAttribute, px.core.DerivedObjectAttribute): """distance between the block and the goal""" _depends_on = ['position'] _step_before = ['position'] agent = None def prepare(self): self.goal = self.world.objects['goal'] def _get_data(self, idx): p_goal = self.goal.position p = self._other_attr['position'].get(idx) rv = pmath.magnitude(p - p_goal) return rv class WarmerObjectAttribute( px.core.BooleanObjectAttribute, px.core.DerivedObjectAttribute): """indicates whether the block moved closer to the goal""" _depends_on = ['distance'] def _get_data(self, idx): return np.any(self._other_attr['distance'].change(step=True) < 0) class BlockObject(px.objects.BasicObject): _attributes = ['distance'] class GoalObject(px.objects.BasicObject): _defaults = {'mass': 0, 'zorder': -1} class AgentObject(px.objects.SelfObject): _attributes = ['warmer'] class PushBlockGoal(px.core.Goal): """True when some block is on top of the goal""" touching = None reward = 1000 def prepare(self): self.distance = self.world.object_attributes['distance'] def _is_achieved(self): return np.any(self.distance() <= 0.5) class PushBlockJudge(px.core.Judge): """a judge that rewards the block being on the goal, penalizes inefficiency, and optionally rewards moving a block closer to the goal""" agent = None warmercolder = None def __init__(self, world, warmercolder=False, **kwargs): self.warmercolder = warmercolder super(PushBlockJudge, self).__init__(world, **kwargs) def prepare(self): self.agent = self.world.objects['agent'] def _calculate_reward(self, goals, events): reward = 0 #for moving closer to a block if self.warmercolder and self.agent.warmer: reward += 2 return reward class PushBlockWorld(px.core.PixelWorld): def __init__(self, frame=True, colors=True, warmercolder=False, num_blocks=1, objects=None, goals=None, judge=None, **kwargs): """ Parameters ---------- frame : bool, optional True to include a frame object that contains the agent colors : bool, optional True to color code the objects warmercolder : bool, optional True if the Judge should reward moving closer to a block num_blocks : int, optional the number of blocks to include objects : list, optional see PixelWorld goals : list, optional see PixelWorld judge : Judge, optional see PixelWorld **kwargs extra arguments for PixelWorld """ if objects is None: objects = [] #frame if frame: objects += ['frame'] #blocks block_color = 3 if colors else 1 objects += num_blocks * [['block', {'color': block_color}]] #goal goal_color = 4 if colors else 1 objects += [['goal', {'color': goal_color}]] #moveable agent agent_color = 2 if colors else 1 objects += [['agent', {'color': agent_color}]] if goals is None: goals = ['push_block'] if judge is None: judge = ['push_block', {'warmercolder': warmercolder}] super(PushBlockWorld, self).__init__(objects=objects, goals=goals, judge=judge, **kwargs) world = PushBlockWorld randomizer = 'random_positions'
Java
UTF-8
10,017
1.882813
2
[]
no_license
package com.lolapau.cobradordelfrac; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import org.json.JSONObject; import android.app.AlarmManager; import android.app.AlertDialog; import android.app.Dialog; import android.app.PendingIntent; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.StrictMode; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockListActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.lolapau.cobradordelfrac.http.CustomHttpClient; import com.lolapau.cobradordelfrac.http.UrlBuilder; import com.lolapau.cobradordelfrac.parser.json.HttpResponseParser; import com.lolapau.cobradordelfrac.types.Debt; import com.lolapau.cobradordelfrac.types.Utility; public class HomeActivity extends SherlockListActivity { public static String id; public static String username; public static final String DEBTOR = "Debtor"; public static final String QUANTITY = "Quantity"; public static final String COMMENTS = "Comments"; public static final int RESULT_GOTO_DEBTS = 2; public static final int RESULT_GOTO_CONTACTS = 3; public static final int RESULT_GOTO_NEWD = 4; public static final int RESULT_GOTO_NEWC = 5; public static final int RESULT_LOGOUT = 6; private static final int DELETE_ID = Menu.FIRST; private int position; private ArrayList<Debt> mDebtList = new ArrayList<Debt>(); private ArrayList<HashMap<String, String>> debtList; private Dialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences storage = getSharedPreferences(Login.USER_ID, 0); id = storage.getString("u_id", ""); username = storage.getString("u_name", ""); if(id.length() == 0){ Intent intent = new Intent(this, Login.class); startActivity(intent); finish(); } ActionBar actionBar = getSupportActionBar(); actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#7aa32d"))); actionBar.show(); setContentView(R.layout.debt_list); setTitle(R.string.title_activity_home); //In order to avoid network android.os.Network error for making connections from Main Activity if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } fillData(); registerForContextMenu(getListView()); Utility u = new Utility(); u.setListViewHeightBasedOnChildren(getListView()); setNotifications(); } // make the menu work @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); //actionbar menu getSupportMenuInflater().inflate(R.menu.home_activity_menu, menu); return true; } // when a user selects a menu item @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_debtors: return true; case R.id.menu_debts: showDebts(); return true; case R.id.menu_add_debt: createDebt(); return true; case R.id.menu_friends: showContacts(); return true; case R.id.sign_out_menu: signOut(); return true; case R.id.add_friend_menu: addFriend(); return true; default: return false; } } private void showDebts(){ dialog = getUpdatingDialog(); dialog.show(); Intent i = new Intent(this, DebtsActivity.class); startActivityForResult(i, 0); } private void showContacts(){ dialog = getUpdatingDialog(); dialog.show(); Intent i = new Intent(this, ViewContactsActivity.class); startActivityForResult(i, 4); } private void addFriend(){ dialog = getUpdatingDialog(); dialog.show(); Intent in = new Intent(this, NewContactActivity.class); startActivityForResult(in, 3); } private void createDebt() { dialog = getUpdatingDialog(); dialog.show(); Intent i = new Intent(this, NewDebtActivity.class); startActivityForResult(i, 1); } private void fillData(){ Dialog dialog = null; String response = null; debtList = null; dialog = getUpdatingDialog(); dialog.show(); String [] params ={"user_creditor_id", id}; try { response = CustomHttpClient.executeHttpGet(UrlBuilder.paramsToUrl(params, "debts")); debtList = HttpResponseParser.getDebts(mDebtList, response, true); dialog.cancel(); } catch (Exception e) { dialog.cancel(); getErrorConnectionDialog().show(); } if(debtList != null){ ListAdapter adapter = new SimpleAdapter(this, debtList, R.layout.debt_row, new String[] { DEBTOR, QUANTITY, COMMENTS }, new int[] { R.id.debtor, R.id.quantity, R.id.comments }); setListAdapter(adapter); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, DELETE_ID, 0, R.string.menu_delete); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { switch(item.getItemId()) { case DELETE_ID: AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); position = info.position; getDeleteDialog().show(); return true; } return super.onContextItemSelected(item); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(dialog != null) dialog.cancel(); if(resultCode == RESULT_LOGOUT){ signOut(); } else if(resultCode == RESULT_GOTO_DEBTS){ showDebts(); } else if(resultCode == RESULT_GOTO_CONTACTS){ showContacts(); } else if(resultCode == RESULT_GOTO_NEWC){ addFriend(); } else if(resultCode == RESULT_GOTO_NEWD){ createDebt(); } else fillData(); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Intent i = new Intent(this, DebtEdit.class); i.putExtra("DEBT", mDebtList.get(position)); startActivityForResult(i, 2); } private void deleteDebt(Debt debt){ Dialog updating = getUpdatingDialog(); updating.show(); try { JSONObject json = new JSONObject(); CustomHttpClient.executeHttpPut(UrlBuilder.debtToQuery(debt), json); } catch (Exception e) { updating.cancel(); getErrorConnectionDialog().show(); e.printStackTrace(); } finally{ updating.cancel(); } } private void signOut(){ SharedPreferences storage = getSharedPreferences(Login.USER_ID, 0); SharedPreferences.Editor editor = storage.edit(); editor.clear(); editor.commit(); finish(); } /* * Notifications part */ private void setNotifications(){ if(Reminder.mNotificationManager != null) Reminder.mNotificationManager.cancel(0); else{ Intent myIntent = new Intent(this , Reminder.class); AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 18); calendar.set(Calendar.MINUTE, 54); calendar.set(Calendar.SECOND, 00); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 60*24*60*1000 , pendingIntent); //set repeating every 24 hours } } /* * Dialog part */ private Dialog getUpdatingDialog(){ Dialog dialog = null; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.updating); dialog = builder.create(); return dialog; } private Dialog getDeleteDialog(){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.menu_delete); builder.setMessage(R.string.message_confirm); builder.setPositiveButton(R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteDebt(mDebtList.get(position)); fillData(); dialog.cancel(); } }); builder.setNegativeButton(R.string.cancel, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); return builder.create(); } private Dialog getErrorConnectionDialog(){ Dialog dialog = null; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.error_connection); builder.setMessage(R.string.text_error_connection); builder.setPositiveButton(R.string.try_again, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { fillData(); } }); dialog = builder.create(); return dialog; } }
JavaScript
UTF-8
3,155
2.953125
3
[ "MIT" ]
permissive
import createElement from '../../createElement'; export default function normalizeNode(obj) { if(obj == null) { return null; } const typeOfObj = typeof obj; if(typeOfObj !== 'object') { return typeOfObj === 'string'? obj || null : typeOfObj === 'boolean'? null : '' + obj; } if(!Array.isArray(obj)) { return obj; } if(obj.length === 0) { return null; } let res = obj, i = 0, hasContentBefore = false, child; const len = obj.length, alreadyNormalizeChildren = Object.create(null); while(i < len) { child = i in alreadyNormalizeChildren? alreadyNormalizeChildren[i] : normalizeNode(obj[i]); if(child === null) { if(res !== null) { if(!hasContentBefore) { res = null; } else if(res === obj) { res = obj.slice(0, i); } } } else if(typeof child === 'object') { if(Array.isArray(child)) { res = hasContentBefore? (res === obj? res.slice(0, i) : Array.isArray(res)? res : [nodeToElement(res)]).concat(child) : child.slice(); } else if(res !== obj) { if(!hasContentBefore) { res = child; } else if(Array.isArray(res)) { res.push(child); } else { res = [nodeToElement(res), child]; } } else if(child !== obj[i]) { if(hasContentBefore) { res = res.slice(0, i); res.push(child); } else { res = child; } } hasContentBefore = true; } else { let nextChild, j = i; // join all next text nodes while(++j < len) { nextChild = alreadyNormalizeChildren[j] = normalizeNode(obj[j]); if(typeof nextChild === 'string') { child += nextChild; } else if(nextChild !== null) { break; } } if(hasContentBefore) { if(Array.isArray(res)) { if(res === obj) { res = res.slice(0, i); } res.push(nodeToElement(child)); } else { res = [res, nodeToElement(child)]; } } else { res = '' + child; } i = j - 1; hasContentBefore = true; } ++i; } return res; } function nodeToElement(obj) { return typeof obj === 'object'? obj : createElement('plaintext', null, null, obj); }
Ruby
UTF-8
135
3.046875
3
[]
no_license
puts "Salut, on fait des fausses adresses mails ?" i = 01 num = 50 while (i <= num) mail = ["jean#{i}@gmail.com"] puts mail i=i+1 end
PHP
UTF-8
2,265
2.78125
3
[ "MIT" ]
permissive
<?php use PHPUnit\Framework\TestCase; use resolvers\QuotesResolver; use models\Quote as QuoteModel; use repositories\QuoteRepositoryInterface; class QuoteRepositoryMock implements QuoteRepositoryInterface { public function get(int $id): QuoteModel { } public function find(int $first, ?int $after, ?string $quote, ?array $orderBy) { $array = []; for($i = 0; $i < $first; $i++) { $array[] = new QuoteModel(['id' => $i + 1, 'quote' => "quote{$i}", 'authorId' => $i]); } return $array; } public function count(?string $quote): int { return 15; } public function create(int $authorId, string $quote): QuoteModel { } public function delete(int $id): ?QuoteModel { } public function update(int $id, ?string $quote): ?QuoteModel { } } final class QuotesResolverTest extends TestCase { public function testResolve(): void { $resolver = new QuotesResolver(new QuoteRepositoryMock()); $args = [ 'first' => 5, ]; $response = $resolver->resolve($args); $this->assertEquals( 15, $response['totalCount'] ); $this->assertEquals( base64_encode('cursor5'), $response['pageInfo']['endCursor'] ); $this->assertEquals( true, $response['pageInfo']['hasNextPage'] ); $this->assertEquals( false, $response['pageInfo']['hasPreviousPage'] ); $this->assertEquals( base64_encode('cursor1'), $response['pageInfo']['startCursor'] ); $this->assertEquals( base64_encode('cursor1'), $response['edges'][0]['cursor'] ); $this->assertEquals( 1, $response['edges'][0]['node']->getId() ); $this->assertEquals( 'quote0', $response['edges'][0]['node']->getQuote() ); $this->assertEquals( 0, $response['edges'][0]['node']->getAuthorId() ); $this->assertEquals( base64_encode('cursor5'), $response['edges'][4]['cursor'] ); $this->assertEquals( 5, $response['edges'][4]['node']->getId() ); $this->assertEquals( 'quote4', $response['edges'][4]['node']->getQuote() ); $this->assertEquals( 4, $response['edges'][4]['node']->getAuthorId() ); } }
Markdown
UTF-8
2,251
2.71875
3
[ "Unlicense" ]
permissive
### PHP SnapScan Class Open a terminal and start playing. #### Clone in ```shell git clone git@github.com:drpain/SnapScan.git cd SnapScan ``` #### Like Docker, run this with it :-D ```shell docker run -it --rm --name PHP-SnapScan \ -v "$PWD":/usr/src/myapp \ -w /usr/src/myapp \ php:5.6-cli php index.php ``` Hopefully you have Docker installed already, otherwise this will not work. #### Example usage 'index.php' ```php <?php // This file shows you sample usage of the SnapScan class I wrote // SnapScan is a awesome service, and I would like to contribute to it's success // Even if it just shows you possible usage // Add the required files require_once('class.qrcode.php'); require_once('class.snapscan.php'); // Initialize SnapScan. Used to be able to generate your Custom SnapScan // QRCode $snapMerchantId = "SnapSanID1232_test"; SnapScan::Init($snapMerchantId); // Generating your custom QR Code. There are some options available // Where amount is the only required parameter. // $strict means that a client can overpay, but not overpay. // // QR($amount=false, $id=false, $strict=true, $size=300, $margin=0) // Generate a R50 QRCode $QRCode = SnapScan::QR(50); ?> <img src="<?php echo $QRCode ?>" width="300" height="300" alt="ScanScan Barcode" /> <?php // Generate the QR Code with a unique reference to keep track of the transaction // Generate a R100 QRCode, with a Unique Reference $uniqueId = "Super_Awesome_Unique_ID_101201"; $QRCode = SnapScan::QR(100, $uniqueId); ?> <img src="<?php echo $QRCode ?>" width="300" height="300" alt="ScanScan Barcode" /> <?php // To be able to do calls against the API, you will need to obtain a // API Token from SnapScan, and specify it. $snapToken = "0a63fca2-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; SnapScan::setApiToken($snapToken); // After you have set your API Token you can check that a transaction was successful $uniqueId = "Super_Awesome_Unique_ID_101201"; $checkPayment = SnapScan::checkPayment($uniqueId); // returns [] With payment details / False depending on whether the payment was successful // Or fails miserably if (!empty($checkPayment)) { echo "FOUND PAYMENT!!!" . PHP_EOL; echo print_r($checkPayment, true) . PHP_EOL; } else { echo "PAYMENT NOT FOUND!" . PHP_EOL; }
Swift
UTF-8
5,087
2.953125
3
[]
no_license
// // TreeNode.swift // AVLTree // // Created by Alex Nichol on 6/10/14. // Copyright (c) 2014 Alex Nichol. All rights reserved. // import Cocoa class TreeNode : NSView { var left: TreeNode? var right: TreeNode? var depth: Int = 0 var value: Int! var label: NSTextField! class func nodeDepth(aNode: TreeNode?) -> Int { if aNode { return aNode!.depth + 1 } else { return 0 } } init(frame: CGRect) { super.init(frame: frame) } init(value aValue: Int) { super.init() self.autoresizesSubviews = false value = aValue label = NSTextField(frame: CGRectMake(0, 0, 1, 1)) label.stringValue = "\(value)" label.alignment = .CenterTextAlignment label.editable = false label.selectable = false label.backgroundColor = NSColor.clearColor() label.bordered = false self.addSubview(label) } func insertNode(node: TreeNode) { if node.value < value { if !left { left = node } else { left!.insertNode(node) } } else { if !right { right = node } else { right!.insertNode(node) } } recalculateDepth() left = left ? left!.rebalance() : nil right = right ? right!.rebalance() : nil } func recalculateDepth() -> Int { let leftDepth = (left ? left!.recalculateDepth() + 1 : 0) let rightDepth = (right ? right!.recalculateDepth() + 1 : 0) depth = max(leftDepth, rightDepth) return depth } func isRightHeavy() -> Bool { if !right { return false } else if !left { return true } else { return right!.depth > left!.depth } } func rebalance() -> TreeNode { let leftDepth = (left ? left!.recalculateDepth() + 1 : 0) let rightDepth = (right ? right!.recalculateDepth() + 1 : 0) if leftDepth + 1 < rightDepth { // right is too dominant, do a floopty if right!.isRightHeavy() { var oldRight = right! right = right!.left oldRight.left = self return oldRight } else { var newTop = right!.left var oldRight = right! right = newTop!.left oldRight.left = newTop!.right newTop!.right = oldRight newTop!.left = self return newTop! } } else if rightDepth + 1 < leftDepth { if !left!.isRightHeavy() { var oldLeft = left! left = left!.right oldLeft.right = self return oldLeft } else { var newTop = left!.right var oldLeft = left! left = newTop!.right oldLeft.right = newTop!.left newTop!.left = oldLeft newTop!.right = self return newTop! } } else { return self } } func padding(size: CGSize) -> CGFloat { let nodeCount : CGFloat = CGFloat((1 << (depth + 1)) - 1) return (size.width / nodeCount) / 20.0 } func calculateNodeSize(size: CGSize) -> CGFloat { let heightBound = (size.height - (CGFloat(depth) * padding(size))) / CGFloat(depth + 1) let nodeCount : CGFloat = CGFloat((1 << (depth + 1)) - 1) let widthBound = (size.width - (nodeCount - 1) * padding(size)) / nodeCount return min(heightBound, widthBound) } func performLayout(rect: CGRect, size: CGSize, padding: CGFloat, animated: Bool) { if animated { self.animator().frame = CGRectMake(rect.origin.x + (rect.size.width - size.width) / 2, rect.origin.y, size.width, size.height) self.label.frame = CGRectMake(0, (size.height - 22) / 2, size.width, 22) } else { self.frame = CGRectMake(rect.origin.x + (rect.size.width - size.width) / 2, rect.origin.y, size.width, size.height) self.label.frame = CGRectMake(0, (size.height - 22) / 2, size.width, 22) } var leftFrame = CGRectMake(rect.origin.x, rect.origin.y + size.height + padding, (rect.size.width - size.width) / 2.0 - padding, rect.size.height - size.height - padding) var rightFrame = CGRectMake(rect.origin.x + (rect.size.width + size.width) / 2 + padding, leftFrame.origin.y, leftFrame.size.width, leftFrame.size.height) left?.performLayout(leftFrame, size: size, padding: padding, animated: animated) right?.performLayout(rightFrame, size: size, padding: padding, animated: animated) } func addTo(view: NSView) { if self.superview != view { if self.superview { self.removeFromSuperview() } view.addSubview(self) } right?.addTo(view) left?.addTo(view) } func removeFrom(view: NSView) { if self.superview == view { self.removeFromSuperview() } right?.removeFrom(view) left?.removeFrom(view) } override func drawRect(dirtyRect: NSRect) { NSColor.clearColor().set() NSRectFillUsingOperation(self.bounds, .CompositeSourceOver) NSColor.yellowColor().set() NSBezierPath(ovalInRect: self.bounds).fill() } }
Shell
UTF-8
475
3.125
3
[]
no_license
#! /bin/bash # Will Check for the existance of stats for a team for a week and update them if they exist # Otherwise will create them week=$1 echo '--- Ingesting Football Outsiders Data ---' python3 ./football-outsiders/foScrapeUpdate.py "$week" echo '--- DONE ---' echo '--- Ingesting Team Rankings Data ---' python3 ./team-rankings/trScrape.py "$week" echo '--- DONE ---' echo '--- Ingesting ESPN Data ---' python3 ./espn/espnScrape.py "$week" echo '--- Complete ---'
Python
UTF-8
12,478
3.109375
3
[]
no_license
# dependencies for our dijkstra's implementation from .utils import * from .timedistance import * from .delay import * from .route import * from math import sin, cos, sqrt, atan2, radians,inf from queue import PriorityQueue from math import inf import networkx as nx class Routing: """ Modified Dijsktra @attribute G (Graph) : transport network graph @attribute stop_name_to_id (Dict[Name,ID]) : dictionnary from stop names to ids """ #------------------------------------------------------------------------------------------------------------- #------------------------------------------- Object creation ------------------------------------------------ #------------------------------------------------------------------------------------------------------------- MAX_WAITING_TIME = 45 * 60 # maximum waiting time def __init__(self, G:Graph, stop_name_to_id:Dict[Name,ID]): """ Route constructor """ self.G = G self.stop_name_to_id = stop_name_to_id #------------------------------------------------------------------------------------------------------------- #------------------------------------------- Simple planning ------------------------------------------------ #------------------------------------------------------------------------------------------------------------- def stochastic_dijkstra(self, start: Union[Name,ID], # start node (either name or id. If id, names_format to False) end: Union[Name,ID], # end node (either name or id. If id, names_format to False) arr_time:Union[str,Time], # target arrival time (ex '12:45:00' or timestamp) threshold = 0.8, # target probability of making all connections in time names_format=True # If we want to use IDs for start and end set to False ) -> Optional[Route]: """ Modified Dijkstra's shortest path algorithm to include probabilities """ def build_route() -> Optional[Route]: """ Get the shortest path of nodes by going backwards through prev list """ if start not in prev.keys(): return None route = Route(self.G) node = start dist = distances[start] path = [] while node != end: route.append(node,dist) node = prev[node] dist = distances[node] route.append(node,dist) return route def neighbours(stop:ID): """ Returns valid neighbors (edges) of a stop. Valid neighbors must satisfy time and probability constraints and no two walking edges in a row. """ prev_props = distances[stop].prev_props previous_dep_time = distances[stop].previous_dep_time() current_best_dep_time = arr_time - distances[start]() possible_neighbours = self.G.out_edges(stop,data=True) # get edges with properties def time_filter(e:Tuple[ID,ID,EdgeProps]) -> bool: """ Function used to filter the neighbors (edges) of the stop. An edge is valid if it is a walking edge (except if it is the second in a row) or if it is in the time range, meaning that the arrival time is sufficiently early to not miss the connection, but sufficiently late to not wait too much. It also filters edges that have no chance of yielding a better result than the best we have so far, and the edges that have a probability less than the threshold. """ u,v,props = e # unpack edge isFoot = lambda: props['ttype'] == 'Foot' # True if it is a walking edge consecutiveFoot = lambda: isFoot() and prev_props['ttype'] == 'Foot' # True if it is the second walking edge in a row inTimeRange = lambda: (previous_dep_time >= props['arr_time'] # True if the arrival time is sufficiently early and props['arr_time'] >= previous_dep_time - Routing.MAX_WAITING_TIME # True if the arrival time is sufficiently late and props['dep_time'] >= current_best_dep_time) # True if it has a chance of beating the best result we have so far # reverse props to compute pre arrival delay enoughProba = lambda:Delay.connection_probability(prev_props=props,curr_props=prev_props) >= threshold # True if the probability is higher than the threshold return (isFoot() or inTimeRange()) and not consecutiveFoot() and enoughProba() return filter(time_filter,possible_neighbours) # Initialise variables and format input if type(arr_time)==str: # convert to timestamp if initially given as strings arr_time = Utils.to_timestamp(arr_time) if names_format: # If names are given as strings => get their ids start = self.stop_name_to_id[start]['stop_id'] end = self.stop_name_to_id[end]['stop_id'] prev = {} # predecessor of current node on shortest path distances = {v: TimeDistance(time=arr_time) for v in nx.nodes(self.G)} # initialize distances from end to any given node visited = set() # nodes we've visited # prioritize nodes from start -> node with the shortest distance! queue = PriorityQueue() distances[end].updated() # dist from end -> end is zero queue.put((distances[end], end)) # add end node for exploration # main search phase of algorithm while not queue.empty(): _, curr = queue.get() visited.add(curr) for _,neighbor,properties in neighbours(curr): # look at curr's adjacent nodes new_dist = distances[curr] + properties # if we found a shorter path if new_dist < distances[neighbor]: # update the distance, we found a shorter one! distances[neighbor] = new_dist.updated() # update the previous node to be prev on new shortest path prev[neighbor] = curr # if we haven't visited the neighbor if neighbor not in visited: # insert into priority queue and mark as visited visited.add(neighbor) queue.put((distances[neighbor],neighbor)) # prioritize search on small distances # compute the route return build_route() #------------------------------------------------------------------------------------------------------------- #------------------------------------------- Robust planning ------------------------------------------------ #------------------------------------------------------------------------------------------------------------- def robust(self, start : str, # start node (either name or id. If id, names_format to False) end : str, # end node (either name or id. If id, names_format to False) arr_time: str, # target arrival time (ex '12:45:00' or timestamp) threshold = 0.8, # target probability of making all connections in time): max_iter = 10, # max number of iterations allowed to find a path number_of_routes = 1, # number of different routes we want to compute verbose = False # allow for nice iteration printing if required ) -> Optional[List[Route]]: """ Tries to find routes from start to end with success probability higher than threshold. It repeatedly computes the fastest route, store it if the success probability is higher than the threshold, and delete the edge that induce the smallest probability. It stops when max_iter iterations have been done or when number_of_routes valid routes have been found. """ routes_list = [] graph = self.G.copy() # compute fastest route route = self.stochastic_dijkstra(start, end, arr_time, threshold) if route is None: # no route between start and end return None # probability of the route, and properties of the edge with smallest probability on the route proba, (u,v,props) = route.success_proba() if verbose : print(f"Iteration : 1 || Proba : {proba}") if proba >= threshold: # we have found a valid route routes_list.append(route) def find_edge_key(u : ID, v : ID, props: EdgeProps) -> Optional[ID]: """ Find in the graph the key of the edge from u to v that has the properties props """ # test whether e is the edge we are looking for isSameEdge = lambda e: ((edges[e]['dep_time'] == props['dep_time'] and edges[e]['arr_time'] == props['arr_time'] and edges[e]['trip_id'] == props['trip_id']) or (props['ttype'] == 'Foot' and edges[e]['ttype'] == 'Foot')) #iterate on edges between u and v to find the one we want edges = graph[u][v] for e in edges: if isSameEdge(e): return e return None # Try to find routes that matches the wished probability threshold i = 1 while i < max_iter and len(routes_list) < number_of_routes : # find the key of the least probable edge to_remove = find_edge_key(u,v,props) # remove it from the graph graph.remove_edge(u,v,key=to_remove) # rerun the routing algorithm new_routing = Routing(graph, self.stop_name_to_id) new_route = new_routing.stochastic_dijkstra(start, end, arr_time, threshold) if new_route is None: # there are no more routes between start and end. We just return the list we have so far. if not routes_list : # if the list is empty, we add the most robust route we have if verbose : print(f"No path found satisfying {threshold} probability") routes_list.append(route) # Add best route we have return routes_list # new probability of the route, and properties of the edge with smallest probability new_proba, (u,v,props) = new_route.success_proba() if verbose : print(f"Iteration : {i+1} || Proba : {new_proba:2.3f}") # if the probability is higher than the threshold, we add the route to the list if new_proba >= threshold: routes_list.append(new_route) # update current best route if proba < new_proba: proba = new_proba route = new_route i += 1 # if we have not found any route satisfying the threshold, we return the best we have if not routes_list : if verbose : print(f"No path found satisfying {threshold} probability in {max_iter} trials") routes_list.append(route) # Add most robust path found return routes_list
Ruby
UTF-8
242
3.15625
3
[]
no_license
class Robot def name @name ||= initialize_name end def reset @name = nil end private def initialize_name digits = [] digits << ('A'..'Z').to_a.shuffle[0,2] digits << rand(100..999) digits.join end end
Java
UTF-8
189
1.6875
2
[]
no_license
package org.concord.iot.listeners; /** * @author Charles Xie * */ public interface GraphListener { public void graphClosed(GraphEvent e); public void graphOpened(GraphEvent e); }
JavaScript
UTF-8
6,974
3.1875
3
[]
no_license
// Задаємо початкові точки // -9,-2,-10,-4,-10,-6,-9,-7,2,-7,3,-7,4,-7,3,-10,5,-9,7,-2,8,-2,8,0,9,0 let points = []; let html = ""; let Zn = []; let ZnIndexes = []; let pointsWithoutCenters = []; let distances = []; let maxDistance = [0]; let m; let max = 0; let lastDistances = []; let clusters = []; let extraArrayX = new Array(); let extraArrayY = new Array(); let extraArrayX2 = new Array(); let extraArrayY2 = new Array(); const start = () => { let coordinates = document.getElementById("points").value; var p = coordinates.split(",").map(Number); points = p; step1(); }; /////// Візуалізація роботи алгоритму /////// const getData = () => { for (let i = 0; i < clusters.length; i++) { let xArr = new Array(); for (let j = 0; j < clusters[i].length; j++) { xArr[j] = clusters[i][j][0]; } extraArrayX[i] = xArr; } for (let i = 0; i < clusters.length; i++) { let yArr = new Array(); for (let j = 0; j < clusters[i].length; j++) { yArr[j] = clusters[i][j][1]; } extraArrayY[i] = yArr; } start2(); }; const start2 = () => { var data = []; for (let i = 0; i < clusters.length; i++) { let name = `S${i + 1}`; data.push({ x: extraArrayX[i], y: extraArrayY[i], mode: "markers", type: "scatter", name: name, marker: { size: 12 } }); } for (let i = 0; i < Zn.length; i++) { let name = `Z${i + 1}`; data.push({ x: [Zn[i][0]], y: [Zn[i][1]], mode: "markers", type: "scatter", name: name, marker: { size: 12, color: ["#2a3d3a"] } }); } data.push({ x: [10], y: [10], mode: "markers", type: "scatter", name: name, marker: { size: 12, color: ["#ffffff"] } }); data.push({ x: [-10], y: [-10], mode: "markers", type: "scatter", name: name, marker: { size: 12, color: ["#ffffff"] } }); Plotly.newPlot("container", data, { showSendToCloud: false }); }; ////////////////////////////////////////////////// // Крок 1 const setInitialCenter = () => { Zn.push([points[0], points[1]]); ZnIndexes.push([0, 1]); }; const step1 = () => { setInitialCenter(); pointsWithoutCenters = points; pointsWithoutCenters.splice(ZnIndexes[0][0], 2); html += `<b>1.</b> Координати початкового центра <b>Z1</b>: (${Zn[0]}) <br>`; html += `S' = { ${pointsWithoutCenters} }<br>`; step2(); }; // Крок 2 const getDistances = () => { for (let i = 0, j = 0; i < pointsWithoutCenters.length / 2; i++, j += 2) { distances.push( Math.sqrt( Math.pow(Zn[0][0] - pointsWithoutCenters[j], 2) + Math.pow(Zn[0][1] - pointsWithoutCenters[j + 1], 2) ) ); } }; const maxDistances = () => { for (let i = 0; i < distances.length; i++) { if (distances[i] > maxDistance[0]) { maxDistance[0] = distances[i]; } } }; const step2 = () => { getDistances(); maxDistances(); Zn.push([ pointsWithoutCenters[distances.indexOf(maxDistance[0]) * 2], pointsWithoutCenters[distances.indexOf(maxDistance[0]) * 2 + 1] ]); pointsWithoutCenters.splice(distances.indexOf(maxDistance[0]) * 2, 2); m = Zn.length; html += `<b>2.</b> Координати центра <b>Z2</b>: (${Zn[1]}) <br>`; html += `S' = { ${pointsWithoutCenters} }<br>`; step3(); }; // Крок 3 const step3 = () => { if (pointsWithoutCenters.length > 1) { html += `<b>3.</b> Множина S' не порожня <br>`; let MinDistances = []; let distances = []; for (let i = 0; i < Zn.length; i++) { let dis = []; for (let j = 0, k = 0; j < pointsWithoutCenters.length / 2; j++, k += 2) { dis.push( Math.sqrt( Math.pow(Zn[i][0] - pointsWithoutCenters[k], 2) + Math.pow(Zn[i][1] - pointsWithoutCenters[k + 1], 2) ) ); } distances[i] = dis; } for (let i = 0; i < pointsWithoutCenters.length / 2; i++) { let minValue = 999; for (let j = 0; j < Zn.length; j++) { if (distances[j][i] < minValue) { minValue = distances[j][i]; } } MinDistances.push(minValue); } for (let i = 0; i < MinDistances.length; i++) { if (MinDistances[i] > max) { max = MinDistances[i]; } } let localMax = max; max = 0; html += `Максимум із знайдених мінімальних відстаней: <br> d' = ${localMax} <br>`; let k = 0.5; let sum = 0; for (let i = 0; i < maxDistance.length; i++) { sum += maxDistance[i]; } let value = (k * sum) / (m - 1); if (localMax <= value) { html += `d' <= ki * (d1 + ... + dm-1 ) / (m-1) <br>`; step4(); } else { html += `d' > ki * (d1 + ... + dm-1 ) / (m-1) <br>`; maxDistance.push(localMax); m++; Zn.push([ pointsWithoutCenters[MinDistances.indexOf(localMax) * 2], pointsWithoutCenters[MinDistances.indexOf(localMax) * 2 + 1] ]); pointsWithoutCenters.splice(MinDistances.indexOf(localMax) * 2, 2); html += `Координати центрів: <br>`; for (let i = 0; i < Zn.length; i++) { html += `<b>Z${i + 1}</b> (${Zn[i][0]}:${Zn[i][1]}) <br>`; } html += `S' = { ${pointsWithoutCenters} }<br>`; step3(); } } else { html += `<b>3.</b> Множина S' - порожня <br>`; step4(); } }; // Крок 4 const step4 = () => { let d = []; // може бути пов'язано з цим for (let i = 0; i < Zn.length; i++) { let dis = []; for (let j = 0, k = 0; j < pointsWithoutCenters.length / 2; j++, k += 2) { dis.push( Math.sqrt( Math.pow(Zn[i][0] - pointsWithoutCenters[k], 2) + Math.pow(Zn[i][1] - pointsWithoutCenters[k + 1], 2) ) ); } d[i] = dis; // і цим } for (let i = 0; i < Zn.length; i++) { clusters.push([]); } for (let i = 0; i < pointsWithoutCenters.length / 2; i++) { let min = 999; let index; for (let j = 0; j < Zn.length; j++) { if (d[j][i] < min) { min = d[j][i]; index = j; } } clusters[index].push([ pointsWithoutCenters[d[index].indexOf(min) * 2], pointsWithoutCenters[d[index].indexOf(min) * 2 + 1] ]); } html += `Координати центрів: <br>`; for (let i = 0; i < Zn.length; i++) { html += `<b>Z${i + 1}</b> (${Zn[i][0]}:${Zn[i][1]}) <br>`; } for (let i = 0; i < clusters.length; i++) { html += `Кластер <b>S${i + 1}</b>: <br>`; for (let j = 0; j < clusters[i].length; j++) { html += `(${clusters[i][j][0]}:${clusters[i][j][1]}) `; } html += `<br>`; } html += `----------------------Кінець роботи--------------------><br>`; getData(); document.getElementById("math").innerHTML = html; };
Shell
UTF-8
699
3.015625
3
[ "MIT" ]
permissive
#!/usr/bin/env bash set -euo pipefail function installHammerspoon() { brew install --cask hammerspoon # enable AppleScript: https://github.com/Hammerspoon/hammerspoon/blob/c16bbeb8606486076cbcedf6891b1137bf65b8ec/Hammerspoon/HSAppleScript.m#L69-L71 defaults write org.hammerspoon.Hammerspoon HSAppleScriptEnabledKey 1 # install the hs cli osascript -l AppleScript -e 'tell application "Hammerspoon" to execute lua code "hs.ipc.cliInstall(nil, true)"' } installHammerspoon make docs make package assets=() for asset in *.zip; do assets+=("-a" "$asset") done version="v${VERSION}-$(git rev-parse --short HEAD)" hub release create "${asset[*]}" -m "${version}" "${version}"
Python
UTF-8
949
2.78125
3
[]
no_license
#!/bin/python from pyModbusTCP.server import ModbusServer, DataBank from time import sleep from random import uniform import logging import sys #Create an instance of ModbusServer logger = logging.getLogger(__name__) logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) try: logging.info("Iniciando") server = ModbusServer(host="localhost", port=5020) logging.info("Start server...") #print("Start server...") server.start() logging.info("Server is online") print("Server is online") state=[0] while True: DataBank.set_words(0,[int(uniform(0,100))]) if state != DataBank.get_words(1): state = DataBank.get_words(1) print("Value of Registers 1 has changed to =" + str(state)) sleep(0.5) except Exception as e: logging.info("Error: {0}".format(str(e))) print("Shutdown server ....") server.stop() print("Server is offline")