language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C++
UTF-8
2,584
3.265625
3
[]
no_license
#include<iostream> #define MAX_INNING 50 #define PLAYER 9 using namespace std; int N; int inning[MAX_INNING][9]; int max_score = 0; enum {OUT, HIT1, HIT2, HIT3, HOMERUN}; void baseball(int order[]) { // 0번 선수를 4번 타자(인덱스 3)로 끼워 넣음 // order는 dfs에서 다시 사용되는 포인터이므로 // 새로운 배열 my_order가 필요 int my_order[9]; for(int i=0; i<3; i++) my_order[i] = order[i]; for(int i=3; i<8; i++) my_order[i+1] = order[i]; my_order[3] = 0; int score = 0, nth_player = 0; // N 이닝을 진행 for(int i=0; i<N; i++){ int outcount = 0; bool base1 = false, base2 = false, base3 = false; while(outcount < 3){ switch(inning[i][ my_order[nth_player] ]){ case(OUT): outcount++; break; case(HIT1): if(base3){ score++; base3 = false; } if(base2){ base3 = true; base2 = false; } if(base1){ base2 = true; base1 = false; } base1 = true; break; case(HIT2): if(base3){ score++; base3 = false; } if(base2){ score++; base2 = false; } if(base1){ base3 = true; base1 = false; } base2 = true; break; case(HIT3): if(base3){ score++; base3 = false; } if(base2){ score++; base2 = false; } if(base1){ score++; base1 = false; } base3 = true; break; case(HOMERUN): if(base3){ score++; base3 = false; } if(base2){ score++; base2 = false; } if(base1){ score++; base1 = false; } score++; break; } nth_player = (nth_player + 1) % 9; } } max_score = max(max_score, score); } void dfs(unsigned int mask, int k, int prev, int order[]) { // order[0] ~ order[7]에 1 ~ 8의 순열을 만듦 (1번 ~ 8번 선수 순서 정하기) // order[8]은 그대로 0인 상태 if(k == PLAYER-1){ baseball(order); return; } for(int i=0; i<PLAYER-1; i++){ if(mask & (1 << i)) continue; order[k] = i + 1; dfs(mask | (1 << i), k+1, i, order); } } int main() { cin >> N; for(int i=0; i<N; i++){ for(int j=0; j<PLAYER; j++){ cin >> inning[i][j]; } } int order[9] = {0}; dfs(0, 0, -1, order); cout << max_score; }
Markdown
UTF-8
1,313
3.203125
3
[]
no_license
# javascript-beginners-projects ## hello world in this repo I'll work on some simple projects in range beginners-intermediate level, in every folder, you will find `index.html` for **html** file (wow, like you didn't know) **css** and **Js** files. in case you want to take the challenge and make it before you saw the code then you have to read the `description.md` file, It's a description of the project and how it'll be like >it's not necessary to have the same code as mine, maybe yours is cleaner, and don't focus on that now ***Just make it works*** ## usage to download and see all the projects on your local machine then >you are a coder, then I'll explain the CLI methode (wow, like you didn't know that 😑) * install `Git` and `node` in your local machin * oprn **git bash**, **CMD** or whatever and add the commands bellow * cd (add the path of where you want to download the repo) * `git clone git@github.com:CH4R4F/javascript-beginners-projects.git` * cd javascript-beginners-projects now you can open the folder on VScode or whatever and read or edit them I'll add new projects when I have some ideas or if you have ones then send a pull request **Notes** those projects may not be responsive, it's because i'm focusing on the Js part not media queries and remember, just make it works fine
C#
UTF-8
1,536
3.25
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PetManager.Managers; using PetManager.Models; namespace PetClient { class Program { static void Main(string[] args) { ModelManager mgr = new ModelManager(); //The first endpoint will accept any number of pet ids as a parameter and return each animals data in a JSON results array. List<int> intList = new List<int> { 1,2,3,4,5,6,7,8,9 }; string result = mgr.GetPetsByIdsList(intList); Console.WriteLine(result); Console.WriteLine("\n"); //The 2nd endpoint will accept any number of status' and return all animals that are applicable. var statusList = new List<PetStatus> { PetStatus.JustArrived, PetStatus.Deployed }; string result2 = mgr.GetPetsByStatus(statusList); Console.WriteLine(result2); Console.WriteLine("\n"); //The third endpoint will allow for creation of a new record. var newAnimal = new Animal { AnimalsID = 3, City = "New York", Located = DateTime.Now, Moniker = "Pookie", AnimalStatusID = 6 }; string result3 = mgr.SaveNewPet(newAnimal); Console.WriteLine(result3); Console.ReadLine(); } } }
Java
UTF-8
5,377
2.90625
3
[ "BSD-3-Clause" ]
permissive
/** * @author Brennan Colberg * @since Dec 7, 2017 */ package bv.framework.state; import java.util.ArrayList; import bv.framework.core.Core; import bv.framework.core.GameStateManager; import bv.framework.graphics.Renderable; import bv.framework.graphics.Renderer; import bv.framework.math.CVector; import bv.framework.math.PVector; import bv.framework.math.Poly; import bv.framework.math.Rect; import bv.framework.physics.Collidable; import bv.framework.physics.Entity; import bv.framework.physics.Physics; import bv.framework.syntax.BMath; /** * @author Brennan Colberg * @since Dec 7, 2017 */ public abstract class GameState extends Entity implements Renderable, Tickable { /* VARIABLES */ /** Used as a scaling factor; increase to zoom out, decrease to zoom in. */ public double zoomFactor = 1; /** This {@link ArrayList} of {@link Object}s is used to store ALL relevant objects to a single GameState. * Any object should be placed here, and will automatically be dealt with: * {@link Tickable}s will be ticked, * {@link Renderable}s will be rendered, * and {@link Physics} objects will be updatePhysicsed. */ public ArrayList<Object> objects = new ArrayList<Object>(); public CVector maxBounds = new CVector(Core.STARTING_SCREEN_SIZE.getValue(0) * 2, Core.STARTING_SCREEN_SIZE.getValue(1) * 2); public CVector minBounds = new CVector(-Core.STARTING_SCREEN_SIZE.getValue(0) * 2, -Core.STARTING_SCREEN_SIZE.getValue(1) * 2); /* CONSTRUCTORS */ /** Default constructor; simply sets magnification to normal (1 PPU) and calls init(). DO NOT OVERRIDE; instead, put custom code into init() */ public GameState() { this(1); } /** Custom zoom constructor; sets magnification to what you would like (see {@link GameState.pixelsPerUnit}. DO NOT OVERRIDE; instead, put custom code into init() * @param pixelsPerUnit is the custom zoom you would like. */ public GameState(double pixelsPerUnit) { this.zoomFactor = pixelsPerUnit; init(); } /** Runs when this {@link GameState} is first created; use this for custom code rather than overriding any constructors. * Completely empty by default; blank canvas for your enjoyment! */ public abstract void init(); /* METHODS */ /** Passes on the tick() command to ALL {@link Tickable} objects in its objects list. Automatic. */ public final void tickObjects() { this.tick(); for (int i = 0; i < objects.size(); i++) { if (objects.get(i) instanceof Tickable) ((Tickable) objects.get(i)).tick(); } } /** Passes on the updatePhysics() command to ALL {@link Physics}-implementing objects in its objects list. Automatic. */ public final void updateObjectPhysics() { this.updatePhysics(); for (int i = 0; i < objects.size(); i++) { if (objects.get(i) instanceof Physics) ((Physics) objects.get(i)).updatePhysics(); } } /** Passes on the render(r) command to ALL {@link Renderable} objects in its objects list. Automatic. */ public final void renderObjects(Renderer r) { this.render(r); for (int i = 0; i < objects.size(); i++) { if (objects.get(i) instanceof Renderable) ((Renderable) objects.get(i)).render(r); } } public void render(Renderer r) { } /** Fun math stuff to calculate collisions between two {@link Collidable} objects! * Automatically considers all {@link Collidable} objects, and if any are overlapping calls each's onCollision method. */ public final void calculateCollisions() { for (int i = 0; i < objects.size(); i++) if (objects.get(i) instanceof Collidable) { Collidable objectI = (Collidable) objects.get(i); for (int j = i; j < objects.size(); j++) if (objects.get(j) instanceof Collidable) { Collidable objectJ = (Collidable) objects.get(j); if (objectI != objectJ) { if (objectI.trigger().intersects(objectJ.trigger())) { PVector[] velocities = BMath.collisionVelocity((Entity)objectI, (Entity)objectJ); objectI.onCollision(velocities[0], (Entity)objectJ); objectJ.onCollision(velocities[1], (Entity)objectI); } } } } } /** Runs every time this GameState is newly called into the {@link GameStateManager}'s focus. * Completely empty, blank canvas for your enjoyment. */ public abstract void load(); /* GETTERS & SETTERS */ /** @return the size of the currently rendered screen, in {@link CVector} form */ public CVector getSize() { return (CVector) Core.renderEngine.getDisplay().getSize().scaledBy(1/zoomFactor); } /* TECHNICAL METHODS */ /** @return the currently rendered field, accurate in size and position, in {@link Rect} form */ public Rect rectBounds() { Rect result = Core.renderEngine.getDisplay().rectBounds(); result.setPosition(getPosition()); result.getSize().scale(1/zoomFactor); return result; } /** @return the currently rendered field, accurate in size and position, in {@link Poly} form of a {@link Rect} */ public Poly polyBounds() { return rectBounds().polyBounds(); } /** @param point the point to test, in {@link CVector} form * @return whether or not a given point (in {@link CVector} form) is within the currently rendered screen */ public boolean inBounds(CVector point) { return ((point.getValue(0) > minBounds.getValue(0)) && (point.getValue(1) > minBounds.getValue(1)) && (point.getValue(0) < maxBounds.getValue(0)) && (point.getValue(1) < maxBounds.getValue(1))); } }
Java
UTF-8
332
2.90625
3
[]
no_license
package people; public class Player { private int health; private String name; public void setHealth(int heal) { health = heal; } public int getHealth() { return health; } public void setName(String nam) { name = nam; } public String getName() { return name; } }
C++
UTF-8
636
2.75
3
[]
no_license
/*! \brief file reader for HTML help pages * * \file filereader.cpp * \author Christopher Browne * \date 22.04.2016 */ #include "filereader.h" FileReader::FileReader(QString fileName) : fileName(fileName) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { throw QString("File cannot be found"); } QTextStream in(&file); while (!in.atEnd()) { lines.append(in.readLine()); } file.close(); } QStringList FileReader::getStringList() { return lines; } QString FileReader::getString() { QString str = ""; for (QString s : lines) { str += s; } return str; }
Python
UTF-8
247
3.484375
3
[]
no_license
# CRIE UMA LISTA VAZIA E RECEBA UM INPUT DE TRES NUMEROS lista = [] lista.append(int(input('Digite o primeiro número: '))) lista.append(int(input('Digite o segundo número: '))) lista.append(int(input('Digite o terceiro número: '))) print(lista)
Python
UTF-8
1,086
2.96875
3
[]
no_license
import socket serverIP = '127.0.0.1' serverPort = 17000 BUFFER_SIZE = 1024 clintSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while 1: shape = input( "select shape:" ) if not (shape in ['circle', 'sequare', 'rectangle', 'triangle']): print( 'please select valid sharpe!' ) continue elif (shape == 'circle'): x = input( "please input redius:" ) message = 'circle,' + x elif (shape == 'square'): x = input( "please input side:" ) message = 'square,' + x elif (shape == 'rectangle'): x = input( "please input width:" ) y = input( 'please input height:' ) message = 'rectangle,' + x + ',' + y elif (shape == 'triangle'): x = input( "please input base:" ) y = input( "please input height:" ) message = 'triangle,' + x + ',' + y clintSocket.sendto(message.encode('utf-8'),(serverIP,serverPort)) response , address = clintSocket.recvfrom(BUFFER_SIZE) print (message + ' = ' + response.decode('utf-8')) clintSocket.close()
Markdown
UTF-8
4,032
2.890625
3
[]
no_license
data/workexperience.js ====================== The expected structure of workexperience.js is described below: ```javascript var _workexperience = { // Array with each object representing one work position "jobs": [ { // Name of the company (Compulsary field) "company": "Generic company", // A short description of the company (tagline) (Optional) "companyinfo": "A mobile and cloud company", // Job title of the position held (Optional) "jobtitle": "SDE", // Location of the job (Optional) "location": "Hyderabad, India", // Durtion for which the job was held (Optional) "duration": "Jan, 2010 - March, 2013", // Is this the current job held (Optional) "iscurrentjob": false, // Description paragraph (Optional) /* It is defined in the form as an array for each paragraph each obect in array consists of 2 fields "type" followed by either "text" or "points". Thier usage is demonstrated below. "type": "para" is used for a regular paragraph "type": "bullets" is used for a unordered list */ "description": [ { "type": "para", "text": "Mauris tempus purus accumsan magna porta dapibus. Phasellus in sapien vel sapien tincidunt mattis. Cras mattis tristique tellus, sit amet pulvinar neque feugiat vel. Sed adipiscing lobortis fringilla. Nullam facilisis magna ac dolor vulputate, non sodales nulla aliquet. Vivamus magna libero, euismod eget ligula non, egestas dictum tortor. Vivamus tempus lobortis turpis sed tempor." }, { "type": "bullets", "points": [ "orem ipsum dolor sit amet, consectetur adipiscing elit. Proin ut sollicitudin ante, vitae pellentesque orci.", "Mauris tempus purus accumsan magna porta dapibus. Phasellus in sapien vel sapien tincidunt mattis.", "Vivamus ultrices leo quis adipiscing rhoncus. Suspendisse sit amet sollicitudin velit, in pretium orci." ] } ], // Link to logo of company (Optional) "logo_link": "./data/logos/company1.gif" }, // The above described structure can be repeated multiple times as shown below { "company": "Second Generic company", "companyinfo": "A networking company", "jobtitle": "SDE Intern", "location": "Chennai, India", "duration": "Dec, 2008 - March, 2009", "iscurrentjob": false, "description": [ { "type": "bullets", "points": [ "orem ipsum dolor sit amet, consectetur adipiscing elit. Proin ut sollicitudin ante, vitae pellentesque orci.", "Mauris tempus purus accumsan magna porta dapibus. Phasellus in sapien vel sapien tincidunt mattis.", "Vivamus ultrices leo quis adipiscing rhoncus. Suspendisse sit amet sollicitudin velit, in pretium orci." ] }, { "type": "para", "text": "Mauris tempus purus accumsan magna porta dapibus. Phasellus in sapien vel sapien tincidunt mattis. Cras mattis tristique tellus, sit amet pulvinar neque feugiat vel. Sed adipiscing lobortis fringilla. Nullam facilisis magna ac dolor vulputate, non sodales nulla aliquet. Vivamus magna libero, euismod eget ligula non, egestas dictum tortor. Vivamus tempus lobortis turpis sed tempor." } ], "logo_link": "./data/logos/company2.png" } ] }; ``` [Back to README.md](../README.md)
Python
UTF-8
1,528
3.125
3
[]
no_license
#!/usr/bin/env python # _*_ coding: utf-8 _*_ """ @author: caimengzhi @license: (C) Copyright 2013-2017. @contact: 610658552@qq.com @software: pycharm 2017.02 @project: cmz @file: 图形.py @time: 2018/7/16 17:34 @desc: test on python3.x """ # from PIL import Image, ImageFont, ImageDraw # text = "EwWIieAT" # im = Image.new("RGB",(130,35), (255, 255, 255)) # dr = ImageDraw.Draw(im) # font = ImageFont.truetype("msyh.ttf", 24) # #simsunb.ttf 这个从windows fonts copy一个过来 # dr.text((10, 5), text, font=font, fill="#000000") # im.show() # im.save("t.png") from PIL import Image, ImageDraw, ImageFont, ImageFilter import random # 随机字母: def rndChar(): return chr(random.randint(65, 90)) # 随机颜色1: def rndColor(): return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)) # 随机颜色2: def rndColor2(): return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)) # 240 x 60: width = 60 * 4 height = 60 image = Image.new('RGB', (width, height), (255, 255, 255)) # 创建Font对象: font = ImageFont.truetype('msyh.ttf', 36) # 创建Draw对象: draw = ImageDraw.Draw(image) # 填充每个像素: for x in range(width): for y in range(height): draw.point((x, y), fill=rndColor()) # 输出文字: for t in range(4): draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2()) # 模糊: image = image.filter(ImageFilter.BLUR) image.save('code.jpg', 'jpeg') image.show() # python3 图形.py # 然后输出随机字符串
Python
UTF-8
189
3.5
4
[]
no_license
M = int(input()) position = 1 for _ in range(M): X, Y = map(int, input().split()) if X == position: position = Y elif Y == position: position = X print(position)
Java
UTF-8
3,095
2.28125
2
[]
no_license
package com.inspirenetz.api.test.core.builder; import com.inspirenetz.api.core.domain.CardNumberBatchInfo; import java.sql.Time; import java.sql.Date; /** * Created by ameen on 20/10/15. */ public class CardNumberBatchInfoBuilder { private Long cnbId; private Long cnbMerchantNo; private String cnbName; private Date cnbDate; private Time cnbTime; private Integer cnbProcessStatus; private Date createdAt; private String createdBy; private Date updatedAt; private String updatedBy; private CardNumberBatchInfoBuilder() { } public static CardNumberBatchInfoBuilder aCardNumberBatchInfo() { return new CardNumberBatchInfoBuilder(); } public CardNumberBatchInfoBuilder withCnbId(Long cnbId) { this.cnbId = cnbId; return this; } public CardNumberBatchInfoBuilder withCnbMerchantNo(Long cnbMerchantNo) { this.cnbMerchantNo = cnbMerchantNo; return this; } public CardNumberBatchInfoBuilder withCnbName(String cnbName) { this.cnbName = cnbName; return this; } public CardNumberBatchInfoBuilder withCnbDate(Date cnbDate) { this.cnbDate = cnbDate; return this; } public CardNumberBatchInfoBuilder withCnbTime(Time cnbTime) { this.cnbTime = cnbTime; return this; } public CardNumberBatchInfoBuilder withCnbProcessStatus(Integer cnbProcessStatus) { this.cnbProcessStatus = cnbProcessStatus; return this; } public CardNumberBatchInfoBuilder withCreatedAt(Date createdAt) { this.createdAt = createdAt; return this; } public CardNumberBatchInfoBuilder withCreatedBy(String createdBy) { this.createdBy = createdBy; return this; } public CardNumberBatchInfoBuilder withUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; return this; } public CardNumberBatchInfoBuilder withUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; return this; } public CardNumberBatchInfoBuilder but() { return aCardNumberBatchInfo().withCnbId(cnbId).withCnbMerchantNo(cnbMerchantNo).withCnbName(cnbName).withCnbDate(cnbDate).withCnbTime(cnbTime).withCnbProcessStatus(cnbProcessStatus).withCreatedAt(createdAt).withCreatedBy(createdBy).withUpdatedAt(updatedAt).withUpdatedBy(updatedBy); } public CardNumberBatchInfo build() { CardNumberBatchInfo cardNumberBatchInfo = new CardNumberBatchInfo(); cardNumberBatchInfo.setCnbId(cnbId); cardNumberBatchInfo.setCnbMerchantNo(cnbMerchantNo); cardNumberBatchInfo.setCnbName(cnbName); cardNumberBatchInfo.setCnbDate(cnbDate); cardNumberBatchInfo.setCnbTime(cnbTime); cardNumberBatchInfo.setCnbProcessStatus(cnbProcessStatus); cardNumberBatchInfo.setCreatedAt(createdAt); cardNumberBatchInfo.setCreatedBy(createdBy); cardNumberBatchInfo.setUpdatedAt(updatedAt); cardNumberBatchInfo.setUpdatedBy(updatedBy); return cardNumberBatchInfo; } }
C#
UHC
1,274
2.859375
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Cell { protected CellType cellType; public CellType GetCellType { get { return cellType; } set { cellType = value; } } protected CellBehaviour cellBehaviour; public CellBehaviour Behaviour { get { return cellBehaviour; } set { cellBehaviour = value; cellBehaviour.SetCell(this); } } public Cell(CellType type) { cellType = type; } public Cell InstantiateCellObj(GameObject cellPrefab, Transform containerObj) { // cell GameObject newobj = Object.Instantiate(cellPrefab, new Vector3(0, 0, 0), Quaternion.identity); // ̳(Board) ϵ cell newobj.transform.parent = containerObj; // Cell Ʈ CellBehaviour ͼ SetCell Behaviour = newobj.transform.GetComponent<CellBehaviour>(); return this; } public void Move(float x, float y) { cellBehaviour.transform.position = new Vector3(x, y); } public bool IsObstracle() { return GetCellType == CellType.EMPTY; } }
Python
UTF-8
2,573
3.515625
4
[]
no_license
# !/usr/bin/python3 """ http://adventofcode.com/2017/day/8 autor: Martin Javorka """ class Day8: def __init__(self): self.input = list() self.registers = list() self.max = 0 self.read_file() self.init_registers() self.part1() def read_file(self): with open("input", 'r') as file: self.input = [line.split(' ') for line in file] def init_registers(self): for line in self.input: if [line[0], 0] not in self.registers: self.registers.append([line[0], 0]) if [line[4], 0] not in self.registers: self.registers.append([line[4], 0]) def get_register_value(self, register): for reg in self.registers: if reg[0] == register: return reg[1] return 0 def get_largest_value(self): maximum = self.registers[0][1] for reg in self.registers: if reg[1] > maximum: maximum = reg[1] print("maximum at the end:") print(maximum) def evaluate_condition(self, line): if line[5] == '>': return self.get_register_value(line[4]) > int(line[6]) if line[5] == '<': return self.get_register_value(line[4]) < int(line[6]) if line[5] == '>=': return self.get_register_value(line[4]) >= int(line[6]) if line[5] == '<=': return self.get_register_value(line[4]) <= int(line[6]) if line[5] == '==': return self.get_register_value(line[4]) == int(line[6]) if line[5] == '!=': return self.get_register_value(line[4]) != int(line[6]) return False def update_value(self, line): for idx, reg in enumerate(self.registers): if reg[0] == line[0]: if line[1] == 'inc': new_value = reg[1] + int(line[2]) self.registers[idx] = [reg[0], new_value] if new_value > self.max: self.max = new_value if line[1] == 'dec': new_value = reg[1] - int(line[2]) self.registers[idx] = [reg[0], new_value] if new_value > self.max: self.max = new_value return def part1(self): for line in self.input: if self.evaluate_condition(line): self.update_value(line) self.get_largest_value() print('highest value during process') print(self.max) Day8()
C#
UTF-8
3,928
2.921875
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Text.RegularExpressions; namespace MegaDesk_3_BradRAllen { public partial class SearchQuotes : Form { private const string QUOTE_FILE = @"qoutes.txt"; //path or location of csv file of quotes private int firstChange = 0; public SearchQuotes() { InitializeComponent(); //build List<T> class to populate the SurfaceMaterial_tb combo box List<SurfaceMaterial> surfaceMaterials = Enum.GetValues(typeof(SurfaceMaterial)).Cast<SurfaceMaterial>().ToList(); SurfaceMaterial_cb.DataSource = surfaceMaterials; SurfaceMaterial_cb.SelectedIndex = -1; } private void closeForm_btn_Click(object sender, EventArgs e) { var mainMenu = (MainMenu)Tag; mainMenu.Show(); Close(); } //clear list if necessary and then show selected material private void SurfaceMaterial_cb_SelectedIndexChanged(object sender, EventArgs e) { if (firstChange < 2) { //selected index gets changed twice before we even see the form... firstChange++; return; } else { try { // clear then get the selected material from the combo box SearchResultsListView.Clear(); string MaterialSelected = SurfaceMaterial_cb.SelectedItem.ToString(); // get qoutes from qoute file if (!File.Exists(QUOTE_FILE)) { MessageBox.Show("No qoute file found in the application root", "Error Reading File"); } else { //build out the list view SearchResultsListView.Columns.Add("Name", 150, HorizontalAlignment.Center); SearchResultsListView.Columns.Add("Date", 180, HorizontalAlignment.Center); SearchResultsListView.Columns.Add("Days", 50, HorizontalAlignment.Center); SearchResultsListView.Columns.Add("Total", 95, HorizontalAlignment.Center); SearchResultsListView.Columns.Add("Width", 50, HorizontalAlignment.Center); SearchResultsListView.Columns.Add("Depth", 50, HorizontalAlignment.Center); SearchResultsListView.Columns.Add("Drawers", 50, HorizontalAlignment.Center); SearchResultsListView.Columns.Add("Surface", 100, HorizontalAlignment.Center); using (StreamReader sr = new StreamReader(QUOTE_FILE)) { while (!sr.EndOfStream) { string[] fieldvalue = sr.ReadLine().Split('|'); if (fieldvalue[7] == MaterialSelected) { SearchResultsListView.Items.Add(new ListViewItem(new[]{ fieldvalue[0], fieldvalue[1], fieldvalue[2], "$"+ fieldvalue[3], fieldvalue[4], fieldvalue[5], fieldvalue[6], fieldvalue[7] })); } } }; } } catch (Exception ex) { MessageBox.Show("Error loading ListView from Quote File." + "\n\n" + ex); } } } } }
C
UTF-8
400
3.328125
3
[]
no_license
#include <stdio.h> #include <conio.h> float average(float marks[5]); int main(){ float avg,marks[5]={2.0,3.5,1.5,9.0,10.0}; int A[5]={1,2,3,4,5}; avg=average(marks); printf("\nThe Average = %.2f\n",avg); system("pause"); return 0; } float average(float marks[5]) { int i; float sum,average; for(i=0;i<5;i++) { sum+=marks[i]; printf("\n%.2f",sum); } average=sum/5; return average; }
C++
UTF-8
1,041
3.171875
3
[]
no_license
// Tyler R. Donaldson // tylerdonaldson@hotmail.com // 4/9/2012 // Definition of necessary templates for odd functions. //***************************************************** // Functionality: // 1. Input Validation - Added on 4/9/2012 //***************************************************** #ifndef TEMPLATES_H #define TEMPLATE_H #include <limits> using std::numeric_limits; using std::max; using std::streamsize; namespace Donaldson { // Template input validation function. // Accepts the value as a reference parameter. // Accepts the lowest and highest values the can be // input without telling the user to enter a different value. template<class T> T validation(T &value, T low, T high) { bool failed; do { cin.clear(); if(cin >> value && (value >= low && value <= high)) failed = false; else { failed = true; cout << "New choice please: "; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); } }while(failed == true); return value; } } #endif
JavaScript
UTF-8
1,682
2.5625
3
[]
no_license
import { SUBMENU_CLOSE, SUBMENU_CLOSE_ALL, SUBMENU_OPEN, SUBMENU_SUB_CLOSE, SUBMENU_SUB_CLOSE_ALL, SUBMENU_SUB_OPEN, } from "../constants/submenuConstants"; import { isActivesValues, subIsActivesValues } from "../data/submenu"; export const submenuReducer = ( state = { isActives: isActivesValues }, action ) => { switch (action.type) { case SUBMENU_OPEN: const newIsActives = state.isActives.map((active, index) => { if (index === action.payload.index) return true; return active; }); return { ...state, isActives: newIsActives }; case SUBMENU_CLOSE: return { ...state, isActives: state.isActives.map((active, index) => { if (index === action.payload.index) return false; return active; }), }; case SUBMENU_CLOSE_ALL: return { ...state, isActives: state.isActives.map(() => false) }; default: return state; } }; export const subSubmenuReducer = ( state = { isActives: subIsActivesValues }, action ) => { switch (action.type) { case SUBMENU_SUB_OPEN: const newIsActives = state.isActives.map((active, index) => { if (index === action.payload.index) return true; return active; }); return { ...state, isActives: newIsActives }; case SUBMENU_SUB_CLOSE: return { ...state, isActives: state.isActives.map((active, index) => { if (index === action.payload.index) return false; return active; }), }; case SUBMENU_SUB_CLOSE_ALL: return { ...state, isActives: state.isActives.map(() => false) }; default: return state; } };
Markdown
UTF-8
3,578
2.5625
3
[ "MIT" ]
permissive
# Install docker and docker-compose To install and configure Ambar you need an expertise in unix, Docker and Docker Compose. If you have any difficulties installing and running Ambar you can request a dedicated support session by mailing us on [hello@ambar.cloud](mailto:hello@ambar.cloud) Please refer to official [Docker](https://docs.docker.com/install/) and [Docker Compose](https://docs.docker.com/compose/install/) installation instructions. To check if everything is installed correctly please run: ``` > docker -v Docker version 18.03.0-ce, build 0520e24 > docker-compose -v docker-compose version 1.20.1, build 5d8c71b ``` # Set up your environment To make Ambar run properly on your host, you shoud set these system parameters (as superuser): ``` sysctl -w vm.max_map_count=262144 sysctl -w net.ipv4.ip_local_port_range="15000 61000" sysctl -w net.ipv4.tcp_fin_timeout=30 sysctl -w net.core.somaxconn=1024 sysctl -w net.core.netdev_max_backlog=2000 sysctl -w net.ipv4.tcp_max_syn_backlog=2048 sysctl -w vm.overcommit_memory=1 ``` To keep these setting after reboot you should add them into your `/etc/sysctl.conf` file. # Create docker-compose file Download latest [docker-compose file](https://github.com/RD17/ambar/blob/master/docker-compose.yml) from our GitHub. Then modify it: - Replace ```${dataPath}``` values with desired path to the folder where you want Ambar to store all its data. - Replace ```${langAnalyzer}``` value with language analyzer you want Ambar apply while indexing your documents, supported analyzers: English ```ambar_en```, Russian ```ambar_ru```, German ```ambar_de```, Italian ```ambar_it```, Polish ```ambar_pl```, Chinese ```ambar_cn```, CJK ```ambar_cjk``` - Replace ```${ambarHostIpAddress}``` value with the IP address of your Ambar server ## Set up your crawlers - Find ```${crawlerName}``` block - this is a template for your new crawler - Replace ```${crawlerName}``` with desired name for your crawler (only lowercase latin letters and dashes are supported). Check that service block name and crawler name are the same - Replace ```${pathToCrawl}``` with path to a local folder to be crawled, if you want to crawl SMB or FTP - just mount it with standard unix tools ### Optional settings - `ignoreFolders` - ignore fodlers by [glob pattern](https://github.com/isaacs/node-glob#glob-primer) - `ignoreExtensions` - ignore file extensions by [glob pattern](https://github.com/isaacs/node-glob#glob-primer) (default: .{exe,dll}) - `ignoreFileNames` - ignore file names by [glob pattern](https://github.com/isaacs/node-glob#glob-primer) (default: ~*) - `maxFileSize` - max file size (default: 300mb) ### Crawler configuration example: ``` Docs: depends_on: serviceapi: condition: service_healthy image: ambar/ambar-local-crawler restart: always networks: - internal_network expose: - "8082" environment: - name=Docs - ignoreFolders=**/ForSharing/** - ignoreExtensions=.{exe,dll,rar} - ignoreFileNames=*backup* - maxFileSize=15mb volumes: - /media/Docs:/usr/data ``` You can add more crawlers by copying ```${crawlerName}``` segment and editing its settings (don't forget to edit the service name). # Start Ambar Run ```docker-compose pull``` to pull latest Ambar images. To start Ambar run ```docker-compose up -d```. Ambar UI will be accessible on ```http://${ambarHostIpAddress}/``` If you have any difficulties installing and running Ambar you can request a dedicated support session by mailing us on [hello@ambar.cloud](mailto:hello@ambar.cloud)
TypeScript
UTF-8
1,493
2.515625
3
[ "MIT" ]
permissive
import { DataSource } from './datasource'; import { MongoClient } from 'mongodb'; export class MongoDBSource implements DataSource { public client: MongoClient; private static _instance: MongoDBSource; private constructor() { } public async connect(): Promise<void> { console.log("connecting to mongo"); this.client = await (new MongoClient(process.env.mongodb_url, { useUnifiedTopology: true })).connect(); console.log("connected to mongo"); } public static getInstance(): MongoDBSource { if (MongoDBSource._instance) { return MongoDBSource._instance; } else { MongoDBSource._instance = new MongoDBSource; return MongoDBSource._instance; } } public async query( query: any, callback: (error: any, results: any) => {}, collectionName?: string, ) { try { console.log("querying mongo"); const db = this.client.db(process.env.mongodb_database); const collection = db.collection(collectionName); collection.find(query).toArray((err, docs) => { if (err) console.error(err); if (docs && docs.length) console.log(`found ${docs.length || 0} docs`); return callback(err, docs); }); } catch(error) { console.error('whoops', error); return callback(error, []); } } public async end() { MongoDBSource.getInstance().client.close(); } } export default MongoDBSource;
Markdown
UTF-8
3,199
2.78125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "CC-BY-4.0", "CC-BY-SA-3.0" ]
permissive
# Examples Many of the Flickr API services require an API key or user authentication. Before using these examples, sign up for an app here: https://www.flickr.com/services/apps/create/ These examples assume you have set the following environment variables: | Variable | Value | | --------------------------- | ----------------------------------------- | | `FLICKR_API_KEY` | Your application's API key<sup>*</sup> | | `FLICKR_CONSUMER_KEY` | Your application's API key<sup>†</sup> | | `FLICKR_CONSUMER_SECRET` | Your application's API secret<sup>†</sup> | | `FLICKR_OAUTH_TOKEN` | A verified OAuth token<sup>‡</sup> | | `FLICKR_OAUTH_TOKEN_SECRET` | A verified OAuth token secret<sup>‡</sup> | - <sup>*</sup> Required for public REST API methods - <sup>†</sup> Required for obtaining an OAuth token - <sup>‡</sup> Required for OAuth signing ### feeds.js This example demonstrates how to retrieve public Flickr Feed data. ``` $ node ./feeds.js ``` ### flickr.photos.getInfo.js This example demonstrates how to use the Flickr REST API to retrieve public information about a photo. ``` $ export FLICKR_API_KEY=# your api key $ node ./flickr.photos.getInfo.js ``` ### flickr.photos.search.js This example demonstrates how to use the Flickr REST API to search for photos. ``` $ export FLICKR_API_KEY=# your api key $ node ./flickr.photos.search.js ``` ### oauth.js This example demonstrates how to use the OAuth service to obtain an OAuth token and secret to make requests on behalf of a user. OAuth callback URLs **must be https**, so this example's server needs an SSL cert to run. Generate a self-signed cert by running `make` in this directory. ``` $ make $ export FLICKR_CONSUMER_KEY=# your application's key $ export FLICKR_CONSUMER_SECRET=# your application's secret $ node ./oauth.js ``` ### replace.js This example demonstrates how to replace a photo on behalf of a user. ``` $ export FLICKR_CONSUMER_KEY=# your application's key $ export FLICKR_CONSUMER_SECRET=# your application's secret $ export FLICKR_OAUTH_TOKEN=# a verified oauth token $ export FLICKR_OAUTH_TOKEN_SECRET=# a verified oauth token secret $ node ./replace.js <your photo id> ``` > 💡 Tip: Use the Upload example to upload a photo to replace ### upload.js This example demonstrates how to upload a photo on behalf of a user. ``` $ export FLICKR_CONSUMER_KEY=# your application's key $ export FLICKR_CONSUMER_SECRET=# your application's secret $ export FLICKR_OAUTH_TOKEN=# a verified oauth token $ export FLICKR_OAUTH_TOKEN_SECRET=# a verified oauth token secret $ node ./upload.js ``` > 💡 Tip: Use the OAuth example to obtain an OAuth token and secret ### Credits "[The "Works on My Machine" Certification Program Badge](https://blog.codinghorror.com/the-works-on-my-machine-certification-program/)" by [Jeff Atwood](https://blog.codinghorror.com/about-me/) and [Jon Galloway](http://weblogs.asp.net/jgalloway/) is licensed under [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/) [[source](https://discourse.codinghorror.com/t/the-works-on-my-machine-certification-program/599/82)]
Java
UTF-8
3,068
2.25
2
[]
no_license
package com.bazzillion.ingrid.shelfie; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import androidx.preference.CheckBoxPreference; import androidx.preference.EditTextPreference; import androidx.preference.ListPreference; import androidx.preference.MultiSelectListPreference; import androidx.preference.Preference; import androidx.preference.PreferenceFragmentCompat; import androidx.preference.PreferenceScreen; import android.text.TextUtils; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import java.util.Set; public class PreferenceFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { addPreferencesFromResource(R.xml.preferences); PreferenceScreen preferenceScreen = getPreferenceScreen(); int count = preferenceScreen.getPreferenceCount(); for (int i = 0; i < count; i++) { Preference preference = preferenceScreen.getPreference(i); if (!(preference instanceof CheckBoxPreference)) { setPreferenceSummary(preference); } } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Preference preference = findPreference(key); if (preference != null) { if (!(preference instanceof CheckBoxPreference)) { setPreferenceSummary(preference); } } } private void setPreferenceSummary(Preference preference) { if (preference instanceof ListPreference) { ListPreference listPreference = (ListPreference) preference; listPreference.setSummary(listPreference.getEntry()); } else if (preference instanceof MultiSelectListPreference){ MultiSelectListPreference multiSelectListPreference = (MultiSelectListPreference)preference; Set<String> values = multiSelectListPreference.getValues(); Object[] valuesArray = values.toArray(); List<String> entriesList = new ArrayList<>(); for ( int i = 0 ; i < valuesArray.length ; i++){ String value = (String) valuesArray[i]; int index = multiSelectListPreference.findIndexOfValue(value); entriesList.add(multiSelectListPreference.getEntries()[index].toString()); } multiSelectListPreference.setSummary(TextUtils.join(", ", entriesList)); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public void onDestroy() { super.onDestroy(); getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); } }
C++
UTF-8
701
2.859375
3
[]
no_license
class Solution { public: vector<vector<int>> binTreeSortedLevels(int arr[], int n) { vector<vector<int>> ans; int ju = 1; int co = 0; vector<int> temp; for (int i = 0; i < n; i++) { co++; temp.push_back(arr[i]); if (co == ju) { ju *= 2; co = 0; sort(temp.begin(), temp.end()); ans.push_back(temp); temp.clear(); } } if (!temp.empty()) { sort(temp.begin(), temp.end()); ans.push_back(temp); temp.clear(); } return ans; } };
Python
UTF-8
494
3.6875
4
[]
no_license
"""----------Day20----------""" #repeated values can't be print set1 = { 'Hello' , 'Yes' , 5 , 1 , 'Yes' , 3 , 5 } print(set1) #Loop through the set and print the values set2 = { 'A' , 'B' , 'C' , 'D' } for x in set2: print(x) #Check if value is present in the set set3 = { 'Hello' , 'Yes' , 5 , 1 , 3 } print("Yes" in set3) #add one value set4 = { 'A' , 'B' , 'C' , 'D' } set4.add("help")#add one value print(set4) #add many values set4.update({ 'Hello' , 'Yes' , 5 , 1 , 3 }) print(set4)
Java
UTF-8
3,832
2
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2020 Ingyu Hwang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.resilience4j.timelimiter.monitoring.endpoint; import io.github.resilience4j.common.timelimiter.monitoring.endpoint.TimeLimiterEventDTO; import io.github.resilience4j.common.timelimiter.monitoring.endpoint.TimeLimiterEventsEndpointResponse; import io.github.resilience4j.consumer.CircularEventConsumer; import io.github.resilience4j.consumer.EventConsumerRegistry; import io.github.resilience4j.timelimiter.event.TimeLimiterEvent; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Comparator; import java.util.List; @Controller @RequestMapping(value = "timelimiter/") public class TimeLimiterEventsEndpoint { private final EventConsumerRegistry<TimeLimiterEvent> eventsConsumerRegistry; public TimeLimiterEventsEndpoint(EventConsumerRegistry<TimeLimiterEvent> eventsConsumerRegistry) { this.eventsConsumerRegistry = eventsConsumerRegistry; } @GetMapping(value = "events", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public TimeLimiterEventsEndpointResponse getAllTimeLimiterEvents() { List<TimeLimiterEventDTO> eventsList = eventsConsumerRegistry.getAllEventConsumer() .flatMap(CircularEventConsumer::getBufferedEvents) .sorted(Comparator.comparing(TimeLimiterEvent::getCreationTime)) .map(TimeLimiterEventDTO::createTimeLimiterEventDTO).toJavaList(); return new TimeLimiterEventsEndpointResponse(eventsList); } @GetMapping(value = "events/{timeLimiterName}", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public TimeLimiterEventsEndpointResponse getEventsFilteredByTimeLimiterName( @PathVariable("timeLimiterName") String timeLimiterName) { List<TimeLimiterEventDTO> eventsList = eventsConsumerRegistry.getEventConsumer(timeLimiterName).getBufferedEvents() .filter(event -> event.getTimeLimiterName().equals(timeLimiterName)) .map(TimeLimiterEventDTO::createTimeLimiterEventDTO).toJavaList(); return new TimeLimiterEventsEndpointResponse(eventsList); } @GetMapping(value = "events/{timeLimiterName}/{eventType}", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public TimeLimiterEventsEndpointResponse getEventsFilteredByTimeLimiterNameAndEventType( @PathVariable("timeLimiterName") String timeLimiterName, @PathVariable("eventType") String eventType) { TimeLimiterEvent.Type targetType = TimeLimiterEvent.Type.valueOf(eventType.toUpperCase()); List<TimeLimiterEventDTO> eventsList = eventsConsumerRegistry.getEventConsumer(timeLimiterName) .getBufferedEvents() .filter(event -> event.getTimeLimiterName().equals(timeLimiterName)) .filter(event -> event.getEventType() == targetType) .map(TimeLimiterEventDTO::createTimeLimiterEventDTO).toJavaList(); return new TimeLimiterEventsEndpointResponse(eventsList); } }
C#
UTF-8
2,324
3.15625
3
[]
no_license
 namespace rt_2_the_next_week.raytrace.Mathematics { /// <summary> /// [Axis aligned bounding box](https://en.wikipedia.org/wiki/Bounding_volume) /// </summary> public class AABB { Vec3 _min; Vec3 _max; public Vec3 Min { get => _min; } public Vec3 Max { get => _max; } public AABB(Vec3 a, Vec3 b) { _min = Vec3.Create(ffmin(a.X, b.X), ffmin(a.Y, b.Y), ffmin(a.Z, b.Z)); _max = Vec3.Create(ffmax(a.X, b.X), ffmax(a.Y, b.Y), ffmax(a.Z, b.Z)); } static double ffmin(double a, double b) { return a < b ? a : b; } static double ffmax(double a, double b) { return a > b ? a : b; } public static AABB operator |(AABB a, AABB b) { Vec3 small = Vec3.Create(ffmin(a.Min.X, b.Min.X), ffmin(a.Min.Y, b.Min.Y), ffmin(a.Min.Z, b.Min.Z)); Vec3 big = Vec3.Create(ffmax(a.Max.X, b.Max.X), ffmax(a.Max.Y, b.Max.Y), ffmax(a.Max.Z, b.Max.Z)); return new AABB(small, big); } public static AABB operator |(AABB a, Vec3 b) { Vec3 small = Vec3.Create(ffmin(a.Min.X, b.X), ffmin(a.Min.Y, b.Y), ffmin(a.Min.Z, b.Z)); Vec3 big = Vec3.Create(ffmax(a.Max.X, b.X), ffmax(a.Max.Y, b.Y), ffmax(a.Max.Z, b.Z)); return new AABB(small, big); } public bool Hit(Ray r, double t_min, double t_max) { for (int a = 0; a < 3; ++ a) { //double t0 = ffmin((_min[a] - r.Origin[a]) / r.Direction[a], (_max[a] - r.Origin[a]) / r.Direction[a]); //double t1 = ffmax((_min[a] - r.Origin[a]) / r.Direction[a], (_max[a] - r.Origin[a]) / r.Direction[a]); //double tmin = ffmax(t0, t_min); //double tmax = ffmin(t1, t_max); double invD = 1 / r.Direction[a]; double t0 = (_min[a] - r.Origin[a]) * invD; double t1 = (_max[a] - r.Origin[a]) * invD; if (invD < 0) (t0, t1) = (t1, t0); double tmin = t0 > t_min ? t0 : t_min; double tmax = t1 < t_max ? t1 : t_max; if (tmax <= tmin) return false; } return true; } } }
Python
UTF-8
1,131
3.15625
3
[]
no_license
def Register(): hand=open("users.txt","a") print ("--------------") print ("Registration") print ("--------------") users=input("Enter your username : ") passes=input("Enter your password : ") hand.write(users+"\t"+passes+"\n") hand.close() def login(): print ("--------------") print ("Login") print ("--------------") hand=open("users.txt","r") data=hand.read() hand.close() data=data.split("\n") users=input("Enter your username : ") passes=input("Enter your password : ") for i in range (0,len(data)): if ((users+"\t"+passes)==(data[i])): print("Login Sucessfull ") break elif((users+"\t"+passes)!=(data[i]) and (i==len(data)-1)): print("Wrong username or password") while True: opt=input("Do you have an account ? (y/n) or type \"done\" to exit :") if (opt=="y"): login() elif(opt=="n"): Register() elif(opt=="done"): break elif(opt=="dev12345"): hand=open("users.txt","r") data=hand.read() hand.close() print(data)
Java
UTF-8
3,875
2.171875
2
[]
no_license
package com.gdibernardo.emailservice.pubsub.subscriber; import com.gdibernardo.emailservice.email.Email; import com.gdibernardo.emailservice.email.EmailStatus; import com.gdibernardo.emailservice.email.service.DatastoreEmailService; import com.gdibernardo.emailservice.email.service.EmailSenderService; import com.gdibernardo.emailservice.pubsub.EmailMessage; import com.gdibernardo.emailservice.util.Utils; import com.google.appengine.api.datastore.DatastoreFailureException; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.logging.Logger; import java.util.stream.Collectors; @RestController public class EmailMessagePushReceiver { private static final Logger log = Logger.getLogger(EmailMessagePushReceiver.class.getName()); private static final String PUBSUB_VERIFICATION_TOKEN = "PUBSUB_VERIFICATION_TOKEN"; @Autowired private EmailSenderService emailSenderService; @Autowired private DatastoreEmailService datastoreEmailService; private String pubSubVerificationToken; @PostMapping("/pubsub/push") public void pubSubPushReceive(HttpServletRequest request, HttpServletResponse response) throws IOException { if(request.getParameter("token").compareTo(pubSubVerificationToken) != 0) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } String requestBody = request.getReader().lines().collect(Collectors.joining("\n")); JsonElement jsonRoot = new JsonParser().parse(requestBody); String messageData = jsonRoot.getAsJsonObject() .get("message") .getAsJsonObject() .get("data") .getAsString(); try { EmailMessage receivedMessage = EmailMessage.fromJSONString(Utils.decodeBase64(messageData)); log.info(String.format("EmailMessagePushReceiver: Received message %s", receivedMessage.toString())); Email email = datastoreEmailService.fetchEmail(receivedMessage.getId()); if(email.getStatus() == EmailStatus.SENT) { return; } if(emailSenderService.send(email)) { email.setStatus(EmailStatus.SENT); } else { email.setStatus(EmailStatus.PENDING); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } if(datastoreEmailService.persistEmail(email) == 0) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } catch (EntityNotFoundException exception) { log.warning(String.format("EmailMessagePushReceiver: Cannot fetch email: %s.", exception.getMessage())); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } catch (DatastoreFailureException exception) { log.warning(String.format("EmailMessagePushReceiver: Datastore failure %s.", exception.getMessage())); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } catch (Exception exception) { log.warning(String.format("EmailMessagePushReceiver: Cannot parse received message: %s.", exception.getMessage())); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } @PostConstruct private void loadPubSubVerificationToken() { pubSubVerificationToken = System.getenv(PUBSUB_VERIFICATION_TOKEN); } }
Python
UTF-8
198
3.53125
4
[]
no_license
print(True) print(False) print('True == 1', True == 1) print('False == 0', False == 0) print(True + False + 66) print(bool('I think, therefore I am')) print(bool('')) print(bool(-1)) print(bool(0))
C++
UTF-8
1,613
2.796875
3
[ "MIT" ]
permissive
#ifndef __sort_iterator_traits_HPP__ #define __sort_iterator_traits_HPP__ # include <iterator> namespace sort { template <class It> using It_traits = std::iterator_traits<It>; template <class It> using It_val = typename It_traits<It>::value_type; template <class It> using It_diff_t = typename It_traits<It>::difference_type; template <class It> using It_ref = typename It_traits<It>::reference; template <class It> using It_ptr = typename It_traits<It>::pointer; template <class It> using It_tag = typename It_traits<It>::iterator_category; template <class It> using It_ptr_const = It_val<It> * const; template <class It> using It_const_ptr = const It_ptr<It>; template <class It> using It_const_ptr_const = const It_ptr_const<It>; namespace impl { template <class It, class = It_tag<It>> struct It_dis_is_larger_than { using diff_t = It_diff_t<It>; bool operator () (const It &beg, const It &end, const diff_t &v) const { diff_t cnt{0}; for(auto it = beg; it != end; ++it) if(++cnt >v) return 1; return 0; } }; template <class It> struct It_dis_is_larger_than<It, std::random_access_iterator_tag> { using diff_t = It_diff_t<It>; bool operator () (const It &beg, const It &end, const diff_t &v) const { return end - beg > v; } }; }//namespace impl template <class It> bool It_dis_is_larger_than(const It &beg, const It &end, const It_diff_t<It> &v) { return impl::It_dis_is_larger_than<It>{}(beg, end, v); } template <class It> inline constexpr const bool is_list_v = 0; }//namespace sort #endif
Markdown
UTF-8
1,724
2.765625
3
[]
no_license
# 1.data_juggler Functions for converting and exchanging data ## Sql to JSON ### Example 1: #### Create next proc in your MSSQL database: ```sql CREATE PROC sp_data_juggler_test1 as select 'example' as [expamle], GETDATE() as [date], 123.45 [Num], null as [main:] select 'YT-12565' as DocNum, 1 [doc_id:], convert(date,'04.05.2020') as DocDate, null as [:main] union select 'MR-4545' as DocNum, 2 [doc_id:], convert(date,'05.05.2020') as DocDate, null as [:main] select 1 [:doc_id], 555666 [good_id], 12 as [qnt] union select 1 [:doc_id], 777888 [good_id], 6 as [qnt] union select 2 [:doc_id], 555666 [good_id], 2 as [qnt] union select 2 [:doc_id], 777888 [good_id], 7 as [qnt] ``` #### Run sql_to_json_test1.py ```python from data_juggler import data_juggler if __name__ == '__main__': source = "sqlserver://login:pass@server/base/?" data_source = source + "data=sp_data_juggler_test1" dj = data_juggler.data_juggler(data_source) dj.join("data") print(dj.to_json("data")) ``` #### See result: ```json { "expamle": "example", "date": "07.05.2020 12:13:15", "Num": 123.45, "main": [ { "DocNum": "YT-12565", "DocDate": "04.05.2020", "doc_id": [ { "good_id": 555666, "qnt": 12 }, { "good_id": 777888, "qnt": 6 } ] }, { "DocNum": "MR-4545", "DocDate": "05.05.2020", "doc_id": [ { "good_id": 555666, "qnt": 2 }, { "good_id": 777888, "qnt": 7 } ] } ] } ``` ### Example 2: soon # 2.spryreport.py ## JSON to mustache XLSX (spryreport.py) #### description soon
Java
UTF-8
674
2.828125
3
[]
no_license
package controller; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; public class Textures { /** * the games background */ public static BufferedImage background; /** * loads all textures */ public static void load() { background = loadImage("/res/background.png"); } /** * loads a texture * * @param path * @return */ private static BufferedImage loadImage(String path) { try { return ImageIO.read(Textures.class.getResourceAsStream(path)); } catch(Exception e) { e.printStackTrace(); return null; } } }
C#
UTF-8
1,139
2.625
3
[ "MIT" ]
permissive
using System; using System.Windows.Forms; using System.Diagnostics; using System.IO; namespace CubeIconReverter { static class Program { public static string filename = "CubeIconReverter.exe"; /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { /*if (Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location) != filename) { File.WriteAllText("temp.bat", $"/C taskkill /f /im {Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location)} & if exist CubeIconReverter.exe (del /q CubeIconReverter.exe )& ren {System.Reflection.Assembly.GetEntryAssembly().Location} {filename} & start CubeIconReverter@{Updater.releases.tag_name}.exe"); Process.Start("cmd.exe", "temp.bat"); } if (File.Exists("temp.bat")) { File.Delete("temp.bat"); }*/ Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
SQL
UTF-8
5,671
3.0625
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 5.0.3 -- https://www.phpmyadmin.net/ -- -- Servidor: localhost:3306 -- Tiempo de generación: 22-02-2021 a las 20:55:28 -- Versión del servidor: 10.1.48-MariaDB-0+deb9u1 -- Versión de PHP: 7.3.26 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `palolto_cygame` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `acceso` -- CREATE TABLE `acceso` ( `id_acceso` int(11) NOT NULL, `usuario` varchar(45) DEFAULT NULL, `password` varchar(45) DEFAULT NULL, `nombre` varchar(150) DEFAULT NULL, `apellido` varchar(100) DEFAULT NULL, `email` varchar(100) DEFAULT NULL, `categoria` varchar(100) DEFAULT NULL, `ultimo_ingreso` date DEFAULT NULL, `ingresos` int(11) DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `acceso` -- INSERT INTO `acceso` (`id_acceso`, `usuario`, `password`, `nombre`, `apellido`, `email`, `categoria`, `ultimo_ingreso`, `ingresos`) VALUES (1, 'admin', 'Pass2@20reg', 'Usuario', 'Administrador', 'victor.escalante@mymarketlogic.com', 'admin', '2020-01-17', 24); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `registro` -- CREATE TABLE `registro` ( `reg_id` int(10) UNSIGNED NOT NULL, `reg_origen` varchar(180) NOT NULL, `reg_nombre` varchar(255) CHARACTER SET latin1 NOT NULL DEFAULT '', `reg_email` varchar(100) CHARACTER SET latin1 NOT NULL DEFAULT '', `reg_empresa` varchar(255) DEFAULT NULL, `reg_puesto` varchar(255) DEFAULT NULL, `reg_alias` varchar(50) NOT NULL, `reg_avatar` varchar(180) NOT NULL, `reg_score` int(11) NOT NULL DEFAULT '0', `reg_intentos` int(11) NOT NULL DEFAULT '3', `qrcode` varchar(255) DEFAULT NULL, `envios` int(11) DEFAULT '1', `flag_cc` int(11) NOT NULL DEFAULT '0', `reg_estatus` int(11) NOT NULL DEFAULT '0', `reg_fecha_alta` date DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `registro` -- INSERT INTO `registro` (`reg_id`, `reg_origen`, `reg_nombre`, `reg_email`, `reg_empresa`, `reg_puesto`, `reg_alias`, `reg_avatar`, `reg_score`, `reg_intentos`, `qrcode`, `envios`, `flag_cc`, `reg_estatus`, `reg_fecha_alta`) VALUES (1, 'WEBFORM', 'Roxana ', 'rvallejo@developmentfactor.com.mx', 'Development Factor', 'Ejecutiva de cuenta', 'Roxx', 'avatar_player_14.png', 6010, 2, '873734996780', 1, 0, 0, '2020-12-21'), (2, 'WEBFORM', 'Roxana ', 'roxana.vallejo@developmentfactor.com.mx', 'Development Factor', 'Ejecutiva de cuenta', 'Roxy', 'avatar_player_15.png', 15, 1, '531594167052', 1, 0, 0, '2020-12-21'), (3, 'WEBFORM', 'Víctor Hugo', 'vescalante@dfactor.com', 'DevFactor', 'Desarrollo', 'vicx', 'avatar_player_07.png', 57021, 3, '677285217327', 1, 0, 0, '2020-12-21'), (4, 'WEBFORM', 'MIGUEL', 'mbarbosa@developmentfactor.com.mx', 'DEVELOPMENT FACTOR', 'CREATIVO', 'MIKE', 'avatar_player_10.png', 1640, 2, '243929395553', 1, 0, 0, '2020-12-22'), (5, 'WEBFORM', 'Yazmin', 'yarch@developmentfactor.com.mx', 'dfactor', 'MKT', 'arch', 'avatar_player_13.png', 0, 2, '279002656161', 1, 0, 0, '2021-01-07'), (6, 'WEBFORM', 'Angel Monroy', 'amonroy@developmentfactor.com.mx', 'PRUEBA DE REGISTRO', 'DWEB', 'Amonroydfactor', 'avatar_player_13.png', 21310, 0, '873552740834', 1, 0, 0, '2021-01-20'), (13, 'WEBFORM', 'Miguel Bello', 'miguelbello@proelium.mx', 'Proelium', 'CEO', 'Mikel', 'avatar_player_07.png', 1600, 2, '284993661638', 1, 0, 0, '2021-01-21'), (7, 'WEBFORM', 'Ruben', 'rrodriguez@dfactor.com.mx', 'Successophy Comunicacion Estrategica SA de CV', 'Gerente', 'rubz', 'avatar_player_08.png', 5535, 1, '053865080596', 1, 0, 0, '2021-01-20'), (8, 'WEBFORM', 'juan', 'IDV23900@GMAIL.COM', ' RUIZ IÑ', 'Diseñador', 'sas', 'avatar_player_15.png', 925, 2, '745586943772', 1, 0, 0, '2021-01-20'), (9, 'WEBFORM', 'Dann', 'ggarcia@developmentfactor.com.mx', 'DFactor', 'CAMAROGRAFO ', 'Danno', 'avatar_player_11.png', 0, 3, '420219642118', 1, 0, 0, '2021-01-20'), (10, 'WEBFORM', 'Marco Antonio', 'mmartinez@developmentfactor.com.mx', 'Development Factor', 'Diseñador', 'mmartinez', 'avatar_player_15.png', 685, 1, '870798089737', 1, 0, 0, '2021-01-20'), (11, 'WEBFORM', 'Alan David', 'aaquino@developmentfactor.mx', 'Dfactor', 'DG', 'Davis', 'avatar_player_07.png', 0, 3, '836400542798', 1, 0, 0, '2021-01-20'), (12, 'WEBFORM', 'Eliel Cristalinas Villanueva', 'sistemas@developmentfactor.com.mx', 'dfactor', 'Sistemas', '73173', 'avatar_player_07.png', 540, 2, '966501401742', 1, 0, 0, '2021-01-20'), (14, 'WEBFORM', 'Marisol Gonzalez', 'mgonzalezo@paloaltonetworks.com', 'Palo Alto Networks', 'Head of Marketing', 'Marisol', 'avatar_player_07.png', 4170, 0, '775830097549', 1, 0, 0, '2021-01-27'), (15, 'WEBFORM', 'Haide Escorcia', 'hescorcia@developmentfactor.com.mx', 'Development Factor', 'CEO', 'Haide', 'avatar_player_14.png', 0, 3, '951340261555', 1, 0, 0, '2021-02-17'), (16, 'WEBFORM', 'leonardo', 'lulloaponce@algo-studio.com.mx', 'Algo', 'Creativo ', 'Leo', 'avatar_player_06.png', 0, 2, '288687317256', 1, 0, 0, '2021-02-17'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `acceso` -- ALTER TABLE `acceso` ADD PRIMARY KEY (`id_acceso`); -- -- Indices de la tabla `registro` -- ALTER TABLE `registro` ADD PRIMARY KEY (`reg_id`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `acceso` -- ALTER TABLE `acceso` MODIFY `id_acceso` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT de la tabla `registro` -- ALTER TABLE `registro` MODIFY `reg_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
C++
UTF-8
1,958
2.671875
3
[]
no_license
// Copyright (c) 2012 The Foundry Visionmongers Ltd. All Rights Reserved. #include "KatanaAttrFileReader.h" #include "PTreeHelper.h" #include <iostream> extern "C" FileReader* createAttrFileReader() { return new KatanaAttrFileReader(); } AttrData KatanaAttrFileReader::read(std::string filepath) { AttrData data; if(filepath == "") return data; // Parse the file PTreeHelper parser; ptree root; try { root = parser.parse(filepath); } catch (const std::exception &) { std::cerr << "ERROR: failed parsing XML file '" << filepath << "' for attributes data\n"; } if (!root.empty()) { // if it parsed correctly, then iterate through the attributesList tags for(ptree::const_iterator ci=root.begin(); ci!=root.end(); ci++) { std::string const & type = (*ci).first; ptree attributesList = (*ci).second; if (type != "attributeList") // here, if type is "<xmlattr>", it's just the XML attribute // container, which is OK continue; //TODO: error message? std::string location = PTreeHelper::getAttr(attributesList, "location"); AttrDataEntries attrDataEntries; for(ptree::const_iterator cj=attributesList.begin(); cj != attributesList.end(); ++cj) { std::string const & type2 = (*cj).first; ptree attribute = (*cj).second; if (type2 != "attribute") continue; //TODO: error message if not <xmlattr>? std::string name = PTreeHelper::getAttr(attribute, "name"); std::string type = PTreeHelper::getAttr(attribute, "type"); std::string value = PTreeHelper::getAttr(attribute, "value"); attrDataEntries[name] = value; } data[location] = attrDataEntries; } } return data; }
Go
UTF-8
792
2.515625
3
[]
no_license
package config import ( "github.com/ilyakaznacheev/cleanenv" ) type ( Config struct { Server `yaml:"server"` Postgres `yaml:"postgres"` CurrencyApi `yaml:"currency_api"` } Server struct { BindAddr string `yaml:"bind_addr"` } Postgres struct { Host string `yaml:"host" env:"DB_HOST"` Port string `yaml:"port" env:"DB_PORT"` User string `yaml:"user" env:"DB_USERNAME"` Password string `yaml:"password" env:"DB_PASSWORD"` DBName string `yaml:"dbname" env:"DB_NAME"` SSLMode string `yaml:"sslmode" env:"DB_SSLMODE"` } CurrencyApi struct { Key string `yaml:"key"` } ) func NewConfig(filePath string) (*Config, error) { var cfg Config if err := cleanenv.ReadConfig(filePath, &cfg); err != nil { return nil, err } return &cfg, nil }
Java
ISO-8859-1
1,425
3.78125
4
[]
no_license
package aa21; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Map; import java.util.Scanner; public class MapaAlunoTeste { public static void main(String[] args) { Aluno a1 = new Aluno(1, "Matheus", "SP3030687", "Linguagem de programao"); Aluno a2 = new Aluno(2, "Thiago", "SP3035687", "Linguagem de programao"); Aluno a3 = new Aluno(3, "Diego", "SP30301154", "Banco de dados"); Aluno a4 = new Aluno(4, "Rafael", "SP3030454", "Engenharia de software"); Aluno a5 = new Aluno(5, "Antnio", "SP308787", "Desenvolvimento Web"); Map<Integer, Aluno> mapa = new HashMap<>(); mapa.put(1, a1); mapa.put(2, a2); mapa.put(3, a3); mapa.put(4, a4); mapa.put(5, a5); Scanner sc = new Scanner(System.in); System.out.println("Digite a matrcula do aluno:"); try { Aluno search = mapa.get(sc.nextInt()); System.out.println( "\nMatrcula: " + search.getMatricula() + "\nNome: " + search.getNome() + "\nPronturio: " + search.getProntuario() + "\nCurso: " + search.getCurso()); } catch(NullPointerException e) { System.out.println("Aluno no encontrado.\nO programa foi finalizado."); System.exit(1); } catch(InputMismatchException e2) { System.out.println("Voc deve inserir apenas nmeros inteiros.\nO programa foi finalizado."); System.exit(1); } finally { sc.close(); } } }
Python
UTF-8
303
3.171875
3
[]
no_license
import io def main(ca): n = input() data = raw_input().split() r = 0 for i in range(n): if i+1 != int(data[i]): r += 1 print "Case #" + str(ca) + ": " + str(r) if __name__=="__main__": cas = input() for i in range(cas): main(i+1)
PHP
UTF-8
535
3.109375
3
[]
no_license
<?php namespace CSTruter\Service\Results; /** * Json Result Class * * This class outputs whatever gets passed to it as JSON, along with its * appropriate headers. * * @package CSTruter\Service\Results * @author Christoff Truter <christoff@cstruter.com> * @copyright 2005-2015 CS Truter * @version 0.1.0 */ class JsonResult implements IHttpResult { private $body; public function __construct($body) { $this->body = $body; } public function render() { header('Content-Type: application/json'); echo json_encode($this->body); } } ?>
Markdown
UTF-8
1,824
3.421875
3
[]
no_license
README ======== Overview --------- PhpBit is a little OOP library created to make work with Stream of Bits more easy There are 3 types of numbers: Byte, Word and Dword. Sizes are 8, 16 and 32 bits respectively Usage --------- #### Create number #### $byte = new Byte(0xF0); echo $byte; // 11110000 or $byte = new Byte("11110000"); echo $byte; // 11110000 #### Work with bits #### $byte->setBit(1,0); // 01110000 $byte->setBit(8,1); // 01110001 $byte->invert(); // 10001110 $byte->shiftLeft(1); // 00011100 $byte->shiftRight(1); // 00001110 $byte->makeOr(new Byte("10000000")); // 10001110 #### Create more nums #### $word = new Word($byte, $byte); echo $word; // 1000111010001110 #### Format output #### echo $word->toS(8, " | "); // 10001110 | 10001110 | echo $word->toHexString(); // 8E8E #### Create stream #### $stream = new Stream(); $stream->add($word); $stream->add($word); $stream->add(new Byte(0xF0)); echo $stream; // 1000111010001110 1000111010001110 11110000 #### Pack stream and dump to file #### file_put_contents("stream", $stream->pack()); or file_put_contents("stream", $stream->pack(Stream::PACK_MODE_LITTLEENDIAN)); #### Unpack stream and get access to bits #### $data = file_get_contents("stream"); $format = "2|2|1"; $stream = Stream::createFrom($data, $format); echo $stream; // 1000111010001110 1000111010001110 11110000 echo var_dump($stream->get(3)->getBit(1)); // 1
Python
UTF-8
1,414
2.828125
3
[]
no_license
import math import os import sys from collections import deque # from fractions import gcd input = sys.stdin.readline sys.setrecursionlimit(2147483647) INF = float("inf") IINF = 10 ** 18 MOD = 10 ** 9 + 7 def main(): N = int(input()) graph = [[] for i in range(N+1)] colors = [-1] * (N + 1) init = -1 display_order = [] for i in range(N-1): u, v = map(int, input().split()) graph[u].append(v) graph[v].append(u) display_order.append(v-1) q = deque() q.append((1, 0)) visited = [False] * (N + 1) visited[1] = True while len(q) != 0: idx, color = q.popleft() nxt = graph[idx] cnt = 1 # print('visiting', nxt) for e in nxt: if colors[e] == -1 and not visited[e]: if cnt == color: cnt += 1 colors[e] = cnt q.append((e, cnt)) visited[e] = True cnt += 1 else: colors[e] = cnt q.append((e, cnt)) visited[e] = True cnt += 1 print(max(colors)) # print(*colors) # print(*display_order) for i in display_order: # print(i) print(colors[i+1]) # for i in range(2, len(colors)): # print(colors[i]) if __name__ == '__main__': main()
Markdown
UTF-8
4,982
2.734375
3
[]
no_license
# Reproducible Research: Peer Assessment 1 ## Loading and preprocessing the data ```r data<-read.csv("activity/activity.csv") View(data) ``` ## What is mean total number of steps taken per day? ```r steps_per_day<-aggregate(steps ~ date, data, sum) head(steps_per_day) ``` ``` ## date steps ## 1 2012-10-02 126 ## 2 2012-10-03 11352 ## 3 2012-10-04 12116 ## 4 2012-10-05 13294 ## 5 2012-10-06 15420 ## 6 2012-10-07 11015 ``` ```r View(steps_per_day) hist(steps_per_day$steps, main = "Total Steps per Day", col="orange", xlab = "No. of Steps") ``` ![](PA1_template_files/figure-html/unnamed-chunk-2-1.png) ```r rmean<-mean(steps_per_day$steps) rmedian<-median(steps_per_day$steps) ``` The mean is ``` ## [1] 10766.19 ``` and the median is.R ``` ## [1] 10765 ``` ## What is the average daily activity pattern? ```r dailyactivitypattern<-aggregate(steps ~ interval, data, mean) head(dailyactivitypattern) ``` ``` ## interval steps ## 1 0 1.7169811 ## 2 5 0.3396226 ## 3 10 0.1320755 ## 4 15 0.1509434 ## 5 20 0.0754717 ## 6 25 2.0943396 ``` ```r View(dailyactivitypattern) ##Make a time series plot (i.e. type = "l") of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all days (y-axis) plot(dailyactivitypattern, type="l", col="red", xlab="interval", ylab="steps",main = "Daily Activity pattern") ``` ![](PA1_template_files/figure-html/unnamed-chunk-5-1.png) ```r ##Which 5-minute interval, on average across all the days in the dataset, contains the maximum number of steps? max_interval<-dailyactivitypattern[which.max(dailyactivitypattern$steps), 1] ``` ## Imputing missing values ```r ##Calculate and report the total number of missing values in the dataset (i.e. the total number of rows with NAs) narows<- is.na(data) ``` Total number of missing values ``` ## [1] 2304 ``` ```r ##Devise a strategy for filling in all of the missing values in the dataset. The strategy does not need to be sophisticated. For example, you could use the mean/median for that day, or the mean for that 5-minute interval, etc. library(acepack) ``` ``` ## Warning: package 'acepack' was built under R version 3.2.3 ``` ```r library(Hmisc) ``` ``` ## Warning: package 'Hmisc' was built under R version 3.2.3 ``` ``` ## Loading required package: lattice ``` ``` ## Loading required package: survival ``` ``` ## Loading required package: Formula ``` ``` ## Warning: package 'Formula' was built under R version 3.2.3 ``` ``` ## Loading required package: ggplot2 ``` ``` ## Warning: package 'ggplot2' was built under R version 3.2.3 ``` ``` ## ## Attaching package: 'Hmisc' ``` ``` ## The following objects are masked from 'package:base': ## ## format.pval, round.POSIXt, trunc.POSIXt, units ``` ```r data$steps<-impute(data$steps, fun=mean) View(data$steps) ``` ```r ##Create a new dataset that is equal to the original dataset but with the missing data filled in. Newdata <-data View(Newdata) ``` ```r ##Make a histogram of the total number of steps taken each day and Calculate and report the mean and median total number of steps taken per day. Do these values differ from the estimates from the first part of the assignment? What is the impact of imputing missing data on the estimates of the total daily number of steps? Newsteps_per_day<-aggregate(steps ~ date, Newdata, sum) hist(Newsteps_per_day$steps, main = "Total Steps per Day", col="orange", xlab = "No. of Steps") ``` ![](PA1_template_files/figure-html/unnamed-chunk-10-1.png) ```r rmeansteps<-mean(Newsteps_per_day$steps) rmediansteps<-median(Newsteps_per_day$steps) ``` The mean is ``` ## [1] 10766.19 ``` and the median is.R ``` ## [1] 10766.19 ``` ## Are there differences in activity patterns between weekdays and weekends? ```r ##Create a new factor variable in the dataset with two levels - "weekday" and "weekend" indicating whether a given date is a weekday or weekend day. Newdata$WeekDay <- ifelse(weekdays(as.Date(Newdata$date))==c("Sunday"), "weekend", "weekday") View(Newdata) ``` ```r ##Make a panel plot containing a time series plot (i.e. type = "l") of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all weekday days or weekend days (y-axis). weekdayActivity <- aggregate(steps ~ WeekDay+interval, Newdata, mean) ggplot(weekdayActivity, aes(interval, steps)) + geom_line(color="blue") + facet_wrap(~ WeekDay,nrow=2,ncol=1) + xlab("5-minute interval") + ylab("Number of steps")+theme_light() ``` ![](PA1_template_files/figure-html/unnamed-chunk-14-1.png)
C++
UTF-8
2,121
2.625
3
[]
no_license
// test mpi.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "mpi.h" #include <stdio.h> #include <stdlib.h> #define N 1000 #define MASTER 0 #define NO_OF_ELEMENTS 25 int array[N]; int local_array[N]; int main(int argc, char* argv[]) { int proc_id, no_of_procs; MPI_Status status; int total_sum, partial_sum; int i, id, no_of_elem_for_child, step, start, end; float update(int myoffset, int chunk, int myid); MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &proc_id); MPI_Comm_size(MPI_COMM_WORLD, &no_of_procs); if (proc_id == MASTER) { step = NO_OF_ELEMENTS / (no_of_procs); for (i = 0; i < NO_OF_ELEMENTS; i++) array[i] = i; /*Master does work too*/ partial_sum = 0; for (i = 0; i < step; i++) { partial_sum += array[i]; } printf("Partial sum calculated by Master process %d : %d\n", proc_id, partial_sum); for (id = 1; id < no_of_procs; id++) { start = id * step; if (id == no_of_procs - 1) { end = NO_OF_ELEMENTS - 1; } else { end = (id + 1) * step - 1; } no_of_elem_for_child = end - start + 1; MPI_Send(&no_of_elem_for_child, 1, MPI_INT, id, 1, MPI_COMM_WORLD); MPI_Send(&array[start], no_of_elem_for_child, MPI_INT, id, 1, MPI_COMM_WORLD); } total_sum = 0; total_sum += partial_sum; /*Compute total sum*/ for (id = 1; id < no_of_procs; id++) { MPI_Recv(&partial_sum, 1, MPI_INT, id, 1, MPI_COMM_WORLD, &status); total_sum += partial_sum; } printf("Total: %d\n", total_sum); } else { /*Receive values sent by Master*/ MPI_Recv(&no_of_elem_for_child, 1, MPI_INT, MASTER, 1, MPI_COMM_WORLD, &status); MPI_Recv(&local_array, no_of_elem_for_child, MPI_INT, MASTER, 1, MPI_COMM_WORLD, &status); partial_sum = 0; for (i = 0; i < no_of_elem_for_child; i++) partial_sum += local_array[i]; printf("Partial sum calculated by process %d : %d\n", proc_id, partial_sum); MPI_Send(&partial_sum, 1, MPI_INT, MASTER, 1, MPI_COMM_WORLD); } MPI_Finalize(); return 0; }
Java
UTF-8
942
2.390625
2
[]
no_license
package pageObjects; import org.openqa.selenium.remote.RemoteWebDriver; import resource.webPage;; public class PageLogin extends webPage { RemoteWebDriver login = browser; public PageLogin() throws Exception{ Thread.sleep(2000); if(login.findElementById("username").isDisplayed()) System.out.println("Pagina Login carregada!"); } public void preencherUsuario(String usuario) throws Exception{ login.findElementById("username").sendKeys(usuario); } public void preencherSenha(String senha) throws Exception{ login.findElementById("password").sendKeys(senha); } public void pressionarLogin() throws Exception{ login.findElementById("login-button").click(); } public void preencherNovaConta(String usuario) throws Exception{ login.findElementById("sign-up-username").sendKeys(usuario); } public void pressionarNovaConta() throws Exception{ login.findElementById("verify-email-button").click(); } }
C
UTF-8
509
3.109375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> int main() { int *A, n, i, up, down; scanf("%d", &n); A = (int *)calloc(n, sizeof(int)); for(i = 0;i < n;i++) scanf("%d", &A[i]); up = down = 0; for(i = 0;i < n - 1;i++) { if(A[i] > A[i + 1]) down++; else if(A[i] < A[i + 1]) up++; if((down != 0) && (up != 0)) break; } if(((down != 0) && (up != 0)) || ((down == 0) && (up == 0))) printf("섞임"); else if(down != 0) printf("내림차순"); else printf("오름차순"); free(A); return 0; }
JavaScript
UTF-8
1,037
2.53125
3
[]
no_license
import { GET_STUDY_TODOS_BY_STUDY_ID, CREATE_STUDY_TODO_BY_STUDY_ID, UPDATE_STUDY_TODO_BY_STUDY_ID, DELETE_STUDY_TODO_BY_STUDY_ID, STUDY_TODO_ERROR, } from '../types'; const initialState = { todos: [], loading: true, error: null, }; export default (state = initialState, { type, payload }) => { switch (type) { case GET_STUDY_TODOS_BY_STUDY_ID: return { ...state, todos: payload, loading: false }; case CREATE_STUDY_TODO_BY_STUDY_ID: return { ...state, todos: [...state.todos, payload], loading: false }; case UPDATE_STUDY_TODO_BY_STUDY_ID: return { ...state, todos: state.todos.map((todo) => (todo._id === payload._id ? payload : todo)), loading: false, }; case DELETE_STUDY_TODO_BY_STUDY_ID: return { ...state, todos: state.todos.filter((todo) => todo._id !== payload), loading: false, }; case STUDY_TODO_ERROR: return { ...state, error: payload, loading: false }; default: return state; } };
Python
UTF-8
4,320
2.703125
3
[]
no_license
import sys import numpy import nltk import pandas from sklearn.feature_extraction.text import TfidfVectorizer from nltk import WordNetLemmatizer, pos_tag from nltk import wordnet from nltk.corpus import stopwords from nltk.tokenize import RegexpTokenizer def calculate_confusion(centers, correct_labels, labels, k): my_dict = {} for i in range(len(labels)): if (correct_labels[i], labels[i]) in my_dict: my_dict[correct_labels[i], labels[i]] = my_dict[correct_labels[i], labels[i]] + 1 else: my_dict[correct_labels[i], labels[i]] = 1 total = 0 correct = [0] * k for value in my_dict.values(): for count in range(k): if value > correct[count]: correct[count] = value break total += value correct_sum = 0 for count in range(k): correct_sum += correct[count] print("Kmeans accuracy: {}".format(correct_sum/total)) return None def distances_argmin(matrix, centers): label = [] for i in range(0, len(matrix)): min_distance = sys.maxsize group = -1 for j in range(len(centers)): distance = l2_distances(matrix[i], centers[j]) if distance < min_distance: min_distance = distance group = j label.append(group) return label def kMeans(matrix, k): new_ind = numpy.random.RandomState() i = new_ind.permutation(matrix.shape[0])[:k] centers = matrix[i] while(True): labels = distances_argmin(matrix, centers) new_centers = numpy.empty_like(centers) for i in range(len(centers)): # len(centers) aka i is equal to k mylist = [] for j in range(len(labels)): # j is equal to matrix row index if labels[j] == i: mylist.append(j) new_centers[i] = sum(matrix[mylist])/len(mylist) if numpy.all(centers == new_centers): break centers = new_centers return centers, labels def l2_distances(data_one, data_two): return numpy.sqrt(((data_one - data_two)**2).sum(axis=0)) def k_nearest_neighbor(vectors, labels, k): temp = [] for data in vectors: distance = [] for other_data in vectors: distance.append(l2_distances(data, other_data)) close = [] for x in sorted(zip(distance, labels)): close.append(x) temp.append(max(set(close[0:k]), key=close.count)) accuracy = 0 for i in range(len(labels)): if labels[i] in temp[i]: accuracy += 1 print("KNN accuracy: {}".format(accuracy/len(labels))) return def main(): nltk.download('wordnet') nltk.download('stopwords') nltk.download('averaged_perceptron_tagger') print("Advisory: Run will take approximately 5 minutes to complete!") k = 2 lemmatizer = WordNetLemmatizer() token = RegexpTokenizer(r'\w+') tag_dict = {"J": wordnet.wordnet.ADJ, "N": wordnet.wordnet.NOUN, "V": wordnet.wordnet.VERB, "R": wordnet.wordnet.ADV} stopword = set(stopwords.words('english')) with open('data/smsspamcollection/SMSSpamCollection', 'r') as file: text = file.readlines() all_text = [] labels = [] for i, j in enumerate(text): split_text = j.rsplit('\t') temp = split_text[1] tokens = token.tokenize(temp) new_tokens = [w for w in tokens if not w in stopword] tokens = new_tokens lemmatized_output = ' '.join([lemmatizer.lemmatize(w, tag_dict.get(tag[0], wordnet.wordnet.NOUN)) for w, tag in pos_tag(tokens)]) all_text.append(lemmatized_output) labels.append(split_text[0]) vectorizer = TfidfVectorizer() vectors = vectorizer.fit_transform(all_text) better_vectors = pandas.DataFrame(vectors.toarray().transpose(), index=vectorizer.get_feature_names()) better_vectors = better_vectors.transpose() data = numpy.array(better_vectors) (centers, new_labels) = kMeans(data, k) calculate_confusion(centers, labels, new_labels, k) k_nearest_neighbor(data, labels, k) if __name__ == "__main__": main()
TypeScript
UTF-8
187
2.546875
3
[ "MIT" ]
permissive
export const getEfficiency = ( nominator: number, denominator: number ): string => { const efficiency = (100 * nominator) / denominator return efficiency.toFixed(1) + '% eff.' }
Markdown
UTF-8
3,026
3
3
[]
no_license
--- title: Solutions for digital slug: solutions-for-digital date: SeoDesc: If you’re looking for a leaner, more dynamic approach to managing print, you’ll find that printIQ is a refreshing change from the “old style” of print MIS. With dedicated workflows and streamlined job management tools, printIQ is the perfect match for your digital print business. --- <style> h3 { color: green; } </style> Whether you’re a full digital shop or if you’re just starting to expand into the digital space, it’s essential that your software supports the environment that you are competing in. With shorter runs, faster turnarounds and tighter margins, your business needs to run efficiently with a hands-off approach. ### Your online solution printIQ is a 100% web based Management Workflow System (Far more than just an MIS) so the web2print solution is built-in as opposed to a bolt-on solution. It means that everything has been developed with your customer’s access in mind. - Fully secured access to the customer portal - Customers quote all types of work themselves - Artwork submission - Online proofing - Credit card payment gateway - Job track module ### Pricing We understand that digital pricing is very different to commercial print estimating. For this reason, we have added dedicated pricing functionality to cope with everything digital. We’re in the unique position of being able to support your pricing model while everyone else is forcing you to adapt it to suit the limitations of their software. - Click based charging on every print and finishing operation - Dedicated handling for simplex vs duplex print jobs - Easily create rate cards based on the finished size and quantity ordered - The ability to use market driven pricing for your sell price while still maintaining actual costs ### Production printIQ’s job management tools are unique in the way that they are designed for the digital space. The aim is to achieve a paperless workflow with everyone working off real time data. - Online production boards give you the full view of the floor regardless of where you are - Tablet optimization, and smartphone app, to keep you moving - Digital job bag to manage the job in real time which in turn feeds status updates back to the production board - Switch production path without affecting your quote - The job track module keeps your customers and sales staff informed ### Automation We believe that we have achieved the holy grail of print company automation. For a concept that just a few short years ago was really just a brain storming session on a whiteboard, we’re now in a position to demonstrate how true automation from the web to your press can be achieved through printIQ. - Customers complete quotes and orders online, right through to paying by credit card - Manage your proofing from within the MWS right through to annotation and acceptance / rejection by your customer - Automated artwork pre-flighting - Integration direct to your digital press
C
UTF-8
826
2.53125
3
[]
no_license
#pragma once #include "aex/klist.h" #include "aex/fs/fd.h" #include "aex/fs/fs.h" enum dev_type { DEV_TYPE_CHAR = 1, DEV_TYPE_BLOCK = 2, DEV_TYPE_NET = 3, }; struct dev_fd { void* data; }; typedef struct dev_fd dev_fd_t; struct dev_char_ops { int (*open) (int fd, dev_fd_t* dfd); int (*read) (int fd, dev_fd_t* dfd, uint8_t* buffer, int len); int (*write)(int fd, dev_fd_t* dfd, uint8_t* buffer, int len); void (*close)(int fd, dev_fd_t* dfd); long (*ioctl)(int fd, dev_fd_t* dfd, long, void*); }; struct dev { char name[32]; uint8_t type; void* type_specific; }; typedef struct dev dev_t; int dev_register(dev_t* dev); int dev_current_amount(); int dev_list(dev_t** list); bool dev_exists(int id); /* * Returns the type of a device. */ int dev_type(int id);
Java
UTF-8
3,734
2.96875
3
[]
no_license
import junit.framework.TestCase; public class RationalTest extends TestCase { protected Rational HALF; protected void setUp() { HALF = new Rational( 1, 2 ); } // Create new test public RationalTest (String name) { super(name); } public void testEquality() { assertEquals(new Rational(1,3), new Rational(1,3)); assertEquals(new Rational(1,3), new Rational(2,6)); assertEquals(new Rational(3,3), new Rational(1,1)); } // Test for nonequality public void testNonEquality() { assertFalse(new Rational(2,3).equals( new Rational(1,3))); } public void testAccessors() { assertEquals(new Rational(2,3).numerator(), 2); assertEquals(new Rational(2,3).denominator(), 3); } public void testRoot() { Rational s = new Rational( 1, 4 ); Rational sRoot = null; try { sRoot = s.root(); } catch (IllegalArgumentToSquareRootException e) { e.printStackTrace(); } assertTrue( sRoot.isLessThan( HALF.plus( Rational.getTolerance() ) ) && HALF.minus( Rational.getTolerance() ).isLessThan( sRoot ) ); } ///////////////////////// /* public void testRoot2() { Rational s = new Rational( -1, 4 ); Rational sRoot = null; try { sRoot = s.root(); } catch (IllegalArgumentToSquareRootException e) { e.printStackTrace(); } assertTrue( sRoot.isLessThan( HALF.plus( Rational.getTolerance() ) ) && HALF.minus( Rational.getTolerance() ).isLessThan( sRoot ) ); }*/ public void testPlus(){ Rational x = new Rational(1,2); Rational zero = new Rational(0,2); Rational z = new Rational(-1,2); //Rational w = assertTrue(x.plus(z).equals(zero)); } public void testTimes(){ Rational x = new Rational(1,2); Rational zero = new Rational(0,2); Rational z = new Rational(-1,2); assertTrue(x.times(zero).equals(zero)); } public void testMinus(){ Rational x = new Rational(1,2); Rational zero = new Rational(0,2); Rational z = new Rational(-1,2); assertTrue(zero.minus(x).equals(z)); } public void testMinus2(){ Rational x=new Rational(1073741824,1); Rational y=new Rational(-1073741824,1); Rational zero=new Rational(0,1); assertTrue(!x.minus(y).isLessThan(zero)); } public void testDivides(){ Rational x = new Rational(1,2); Rational zero = new Rational(0,2); Rational z = new Rational(-1,2); Rational one = new Rational(-1,1); assertTrue(x.divides(z).equals(one)); } public void testDivides2(){ Rational x=new Rational(-1073741824,1); Rational z=new Rational(2,1); assertEquals(x,x.plus(x).divides(z)); } public void testAbs(){ Rational x= new Rational(5,0); Rational y = new Rational(-3,0); assertFalse(x.abs().equals(y.abs())); } public void testAbs2(){ Rational x= new Rational(5,0); Rational y = new Rational(-5,0); assertTrue(x.abs().equals(y.abs())); } public void testIsLessThan(){ Rational x= new Rational(0,2); Rational y = new Rational(0,1); assertFalse(x.isLessThan(y)); } public static void main(String args[]) { String[] testCaseName = { RationalTest.class.getName() }; // junit.swingui.TestRunner.main(testCaseName); junit.textui.TestRunner.main(testCaseName); } }
Java
UTF-8
2,149
2.796875
3
[]
no_license
package helpers; import org.openqa.selenium.Cookie; import org.openqa.selenium.WebDriver; import pages.LoginPage; import pages.MainPage; import java.io.*; import java.util.Set; public class Helper { public static void writeCookiesInFile(WebDriver driver, String email) throws IOException { Set<Cookie> cookies = driver.manage().getCookies(); File file = new File("cookies/" + email + "-cookies.txt"); if (file.exists()) { file.delete(); } for (Cookie loadedCookie : cookies) { try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, true))) { bufferedWriter.write(String.format("%s-->%s", loadedCookie.getName(), loadedCookie.getValue()) + "\n"); bufferedWriter.close(); } } } public static void readCookiesFromFile(WebDriver driver, String email) throws IOException { File file = new File("cookies/" + email + "-cookies.txt"); FileReader fileReader = new FileReader(file); try(BufferedReader bufferReader = new BufferedReader(fileReader)){ String line = bufferReader.readLine(); while (line != null) { String[] parts = line.split("-->", 20); Cookie cookie = new Cookie(parts[0], parts[1]); driver.manage().addCookie(cookie); line = bufferReader.readLine(); } } } public static void openBrowserWithURL(String url, WebDriver driver) { driver.get(url); driver.manage().window().maximize(); } public static void login(WebDriver driver, String email, String password) throws IOException { File cookiesFile = new File("cookies/" + email + "-cookies.txt"); if (!cookiesFile.exists()) { MainPage mainPage = new MainPage(driver); LoginPage loginPage = mainPage.openLogInPage(); loginPage.login(email, password); writeCookiesInFile(driver, email); } else { readCookiesFromFile(driver, email); driver.navigate().refresh(); } } }
Java
UTF-8
617
3.609375
4
[]
no_license
package sorting_searching; import java.util.Arrays; /* * https://leetcode.com/problems/meeting-rooms/ * * Meeting Rooms: * Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] * (si < ei), determine if a person could attend all meetings. */ public class MeetingRooms { public boolean canAttendMeetings(int[][] intervals) { Arrays.sort(intervals, (x, y)->(x[0]==y[0]?x[1]-y[1]:x[0]-y[0])); for(int i=0;i<intervals.length-1;i++){ int curr[]=intervals[i]; int next[]=intervals[i+1]; if(curr[1]>next[0]){ return false; } } return true; } }
PHP
UTF-8
638
2.75
3
[]
no_license
<?php class Company extends ActiveRecord\Model{ static $table_name = 'companies'; static $before_save = ['dup_check']; public function dup_check(){ if($this->id) $check = static::find(['conditions' => ['ticker LIKE ? AND id <> ?', $this->ticker, $this->id]]); else $check = static::find(['conditions' => ['ticker LIKE ?', $this->ticker]]); return ($check ? FALSE : TRUE); } public static function filldrop(){ $html = ''; foreach(Company::all() as $comp) $html .= "<option value='" . $comp->id . "'>" . $comp->ticker . "</option>"; return $html; } }
Java
UTF-8
235
1.601563
2
[]
no_license
package com.iiitb.services; import org.springframework.data.jpa.repository.JpaRepository; import com.iiitb.modal.user; public interface userlogindao extends JpaRepository<user, Integer> { user findByUname(String uname); }
JavaScript
UTF-8
2,337
3.59375
4
[]
no_license
// function to calculate the result of the survey $(document).ready( (score = () => { let adventurescore = 0; let comfortscore = 0; let countryscore = 0; // get a list of the radio inputs on the page let choices = document.getElementsByTagName("input"); // loop through all the radio inputs for (i = 0; i < choices.length; i++) { // if the radio is checked.. if (choices[i].checked) { // add 1 to that choice's score if (choices[i].value == "ad1") { adventurescore = adventurescore + 1; } if (choices[i].value == "com2") { comfortscore = comfortscore + 1; } if (choices[i].value == "coun3") { countryscore = countryscore + 1; } } } // Find out which choice got the highest score. let maxscore = Math.max(adventurescore, comfortscore, countryscore); // Display answer corresponding to that choice let answerbox1 = document.getElementById("answer"); if (adventurescore == maxscore) { // If user chooses the first choice the most, this outcome will be displayed. answerbox1.innerHTML = "You are an adventure seeker... why not look at our Adventure package"; } if (comfortscore == maxscore) { // If user chooses the second choice the most, this outcome will be displayed. answerbox1.innerHTML = "Looking for a relaxing getaway? Enjoy a week away in our Comfort package"; } if (countryscore == maxscore) { // If user chooses the third choice the most, this outcome will be displayed. answerbox1.innerHTML = "You seek the Country life... enjoying nature, local towns... why not explore our Country packages"; } if(countryscore == maxscore && comfortscore == maxscore && adventurescore == maxscore) { answerbox1.innerHTML = "Fill in the above for your choice!"; } }) ); // program the reset button $(resetAnswer = () => { let answerbox = document.getElementById("answer"); answerbox.innerHTML = "Your result will show up here!"; });
Java
UTF-8
346
1.789063
2
[]
no_license
package com.enterprise.resource.dao.redis; import java.util.List; public interface PurchaseItemDao<PurchaseItem> { public List<PurchaseItem> addItem(PurchaseItem item, String user); public List<PurchaseItem> removeItem(String user, Integer... itemIds); public void removeAll(String user); public List<PurchaseItem> getItems(String user); }
Markdown
UTF-8
3,813
2.71875
3
[ "MIT" ]
permissive
##Config This page describes all of the options available in the kymera_config.yaml. The options are grouped by their relation to each of the different Kymera components. The config file can be manipulated by in two different ways, either directly by changing the contents of the kymera_config.yaml or programatically using the the Kymera::Config class. More on its usuage can be found [here](config_class.md) ###Client The client needs to know where to send the test requests and where to listen for the results. ####Broker Address The broker address is where the client will connect to send subsequent test run requests. The address as 3 components to is, the protocol, the ip address and the port number. The protocol for the address will always be tcp. The ip should be the ip address of the computer that the broker will reside on and the port number will be the port that the broker will be listening on for communication. An example of this would be: 'tcp://192.168.0.12:5000' ####Results Bus Address The results bus address is the address the client should connect to in order to receive real time results as well as run completion notification. As with the broker address it has 3 components as well. The protocol, the ip address and the port number. An example of this would be: 'tcp://192.168.0.12:5000' ###Broker The broker has 4 configuration options. The client listening port, the worker listening port, the internal worker port and the number of connections ####Client Listening Port The client listening port is the port that the broker is listening on for connections from the clients. This port number should be the port that the client is using in the broker address ####Worker Listening Port The worker listening port is the port that the broker is listening on for connections from the workers. This port number should be the port tat the workers are using when specifying the broker address ####Internal Worker Port The part of the broker that is responsible for managing the test queue needs to have its own port for connections. This port is used only within the broker and is not needed by any other component ####Number of Connections Currently, the broker has two queues that it uses for managing tests. When the broker is started, it spawn a number of threads based on number of connections config option. It then uses those threads as the queue for sending tests to workers. ###Worker ####Broker address This is the address of the broker that the client will get its test run requests from. Like the others, it has a protocol, an ip address and a port number ####Results Collector Address This is the address where the worker will send its final results for a completed test. Like the others, it has a protocol, an ip address and a port number ####Results Bus Collector This is the address where the worker will send its realtime output. ###Result Collector ####Incoming Listening Port This is the port that the results collector will listen on for incoming results from workers ####Results Bus Address This is the address that the results collector will send the completion signal to the client ####Send Mongo Results This config options tells the collector whether or not to send the results to a mongo database ####Mongo DB Address The location of the mongo database that the collector will send the full runs results to ####Mongo DB Port The port number the mongo database is listening on ####Mongo Database Name The name of the datbase that the results will be written to ####Mongo Collection Name The name of the collection that the results will belong to ###Result Bus ####Publish Port The port that workers and collectors will publish messages to ####Subscribe Port The port that clients will subscribe to in order to get results
Markdown
UTF-8
485
2.796875
3
[]
no_license
# churn-modelling A basic ANN model that predicts whether a person is gonna leave bank in future or not. Model is based on present condition of a individual like his salary, time with bank, etc., and predicts his/her future actions towards bank. As I trained it on 100 epochs, where we can see that while training after 40 to 50 epochs, accuracy almost remain constant for futher epochs. This mean that our model based on given parameters has stopped learning much from training data.
PHP
UTF-8
1,517
2.640625
3
[ "MIT" ]
permissive
<?php App::uses('CakeCSFixerTest', 'CakeCSFixer.Test/Case/Lib/Fixer'); App::uses('PhpCloseTagFixer', 'CakeCSFixer.Lib/Fixer'); class PhpCloseTagFixerTest extends CakeCSFixerTest { public function setUp() { parent::setUp(); } public function testCloseTag() { $fixer = new PhpCloseTagFixer(); $wrong = <<<TEST <?php class TestingController extends AppController { public function index() { } } ?> TEST; $correct = <<<TEST <?php class TestingController extends AppController { public function index() { } } TEST; $this->assertEqual($correct, $fixer->fix($wrong)); $wrong = <<<TEST <?php class TestingController extends AppController { public function index() { } } class Test { } ?> TEST; $correct = <<<TEST <?php class TestingController extends AppController { public function index() { } } class Test { } TEST; $this->assertEqual($correct, $fixer->fix($wrong)); $correct = <<<TEST SOME TEXT BEFORE <?php echo 'yes'; ?> TEST; $this->assertEqual($correct, $fixer->fix($correct)); $correct = <<<TEST <?php class MyModel extends OtherModel { public function getCloseTag() { return '?>' } } TEST; $this->assertEqual($correct, $fixer->fix($correct)); $wrong = <<<TEST <?php class MyModel extends OtherModel { public function getCloseTag() { return '?>' } } ?> TEST; $correct = <<<TEST <?php class MyModel extends OtherModel { public function getCloseTag() { return '?>' } } TEST; $this->assertEqual($correct, $fixer->fix($wrong)); } }
C++
UTF-8
7,460
2.59375
3
[]
no_license
#include "stdafx.h" #include "hslUtilities.h" #include <algorithm> #include "ColorPin.h" #include "ColorContrast.h" namespace DxColor { namespace { RgbPart GetMaxComponent(ColorArgb rgb, bite minVal, bite maxVal) { if (maxVal == minVal) return RgbPart::total; if (rgb.R == maxVal) return RgbPart::red; if (rgb.G == maxVal) return RgbPart::green; if (rgb.B == maxVal) return RgbPart::blue; return RgbPart::blue; } double GetHue(ColorArgb rgb, bite minVal, bite maxVal, RgbPart maxComponent) { if (maxComponent == RgbPart::total) { if (maxVal == 255) return MAX_HUE; return 0.0; } int C = maxVal - minVal; double hue = 0.0; if (C == 0) return hue; int r = rgb.R; int g = rgb.G; int b = rgb.B; if (maxComponent == RgbPart::red) { double h = static_cast<double>(g - b) / C; if (h < 0) h += 6; hue = 60.0 * h; } if (maxComponent == RgbPart::green) { double h = static_cast<double>(b - r) / C + 2.0; hue = 60.0 * h; } if (maxComponent == RgbPart::blue) { double h = static_cast<double>(r - g) / C + 4.0; hue = 60.0 * h; } while (hue < 0.0) hue += 360.0; return hue; } double GetLightness(bite maxVal, bite minVal) { double dMax = maxVal / 255.0; double dMin = minVal / 255.0; return (dMin + dMax) / 2; } double GetSaturation(bite maxVal, bite minVal, double l) { if (minVal == maxVal) return 0.0; double dMax = maxVal / 255.0; double dMin = minVal / 255.0; if (l <= 0.5) { return (dMax - dMin) / (2 * l); } return (dMax - dMin) / (2.0 - 2 * l); } } HSL ToHsl(ColorArgb rgb) { HSL hsl; bite max = std::max(std::max(rgb.R, rgb.G), rgb.B); bite min = std::min(std::min(rgb.R, rgb.G), rgb.B); RgbPart maxComponent = GetMaxComponent(rgb, min, max); hsl.H = GetHue(rgb, min, max, maxComponent); hsl.L = GetLightness(max, min); hsl.S = GetSaturation(max, min, hsl.L); return hsl; } ColorArgb Rgb::ToColorArgb(bite a) { bite r = std::max((bite)0, std::min((bite)(_r * 255 + 0.5), (bite)255)); bite g = std::max((bite)0, std::min((bite)(_g * 255 + 0.5), (bite)255)); bite b = std::max((bite)0, std::min((bite)(_b * 255 + 0.5), (bite)255)); ColorArgb color; color.A = a; color.R = r; color.G = g; color.B = b; return color; } ColorArgb ToRgb(HSL hsl, bite a) { double c = (1 - fabs(2 * hsl.L - 1)) * hsl.S; double h = hsl.H / 60.0; double x = c * (1.0 - fabs(fmod(h, 2.0) - 1)); double r = 0, g = 0, b = 0; if (h >= 0 && h < 1.0) { r = c; g = x; b = 0.0; } else if (h >= 1.0 && h < 2.0) { r = x; g = c; b = 0.0; } else if (h >= 2.0 && h < 3.0) { r = 0.0; g = c; b = x; } else if (h >= 3.0 && h < 4.0) { r = 0.0; g = x; b = c; } else if (h >= 4.0 && h < 5.0) { r = x; g = 0.0; b = c; } else if (h >= 5.0 && h < 6.0) { r = c; g = 0.0; b = x; } else { r = 0.0; g = 0.0; b = 0.0; } double m = hsl.L - 0.5 * c; Rgb rgb(r + m, g + m, b + m); return rgb.ToColorArgb(a); } HslPair GetMinMaxHue(const PinPalette& palette) { HslPair huePair; huePair.maxValue = 0.0; huePair.minValue = 360.0; bool bBandLast = false; int nPins = static_cast<int>(palette.Pins.size()); for(int iPin = 0; iPin < nPins; ++iPin) { const ColorPin& pin = palette.Pins.at(iPin); auto pinColor = pin.Color1; HSL hsl = ToHsl(pinColor); huePair.minValue = std::min(huePair.minValue, hsl.H); huePair.maxValue = std::max(huePair.maxValue, hsl.H); // we don't need the last color2 if there is no next color and it's not used for the last cycle bool bandNow = (pin.CurveType == ColorCurveType::DoubleBand) && iPin < nPins-1; if (bandNow || bBandLast) { auto pinColor2 = pin.Color2; HSL hsl2 = ToHsl(pinColor); huePair.minValue = std::min(huePair.minValue, hsl2.H); huePair.maxValue = std::max(huePair.maxValue, hsl2.H); } bBandLast = bandNow; } return huePair; } HslPair GetMinMaxLightness(const PinPalette& palette) { HslPair lightPair; lightPair.maxValue = 0.0; lightPair.minValue = 1.0; bool bBandLast = false; int nPins = static_cast<int>(palette.Pins.size()); for (int iPin = 0; iPin < nPins; ++iPin) { const ColorPin& pin = palette.Pins.at(iPin); auto pinColor = pin.Color1; HSL hsl = ToHsl(pinColor); lightPair.minValue = std::min(lightPair.minValue, hsl.L); lightPair.maxValue = std::max(lightPair.maxValue, hsl.L); // we don't need the last color2 if there is no next color and it's not used for the last cycle bool bandNow = (pin.CurveType == ColorCurveType::DoubleBand) && iPin < nPins - 1; if (bandNow || bBandLast) { auto pinColor2 = pin.Color2; HSL hsl2 = ToHsl(pinColor); lightPair.minValue = std::min(lightPair.minValue, hsl2.L); lightPair.maxValue = std::max(lightPair.maxValue, hsl2.L); } bBandLast = bandNow; } return lightPair; } HslPair GetMinMaxSaturation(const PinPalette& palette) { HslPair satPair; satPair.maxValue = 0.0; satPair.minValue = 1.0; bool bBandLast = false; int nPins = static_cast<int>(palette.Pins.size()); for (int iPin = 0; iPin < nPins; ++iPin) { const ColorPin& pin = palette.Pins.at(iPin); auto pinColor = pin.Color1; HSL hsl = ToHsl(pinColor); satPair.minValue = std::min(satPair.minValue, hsl.S); satPair.maxValue = std::max(satPair.maxValue, hsl.S); // we don't need the last color2 if there is no next color and it's not used for the last cycle bool bandNow = (pin.CurveType == ColorCurveType::DoubleBand) && iPin < nPins - 1; if (bandNow || bBandLast) { auto pinColor2 = pin.Color2; HSL hsl2 = ToHsl(pinColor); satPair.minValue = std::min(satPair.minValue, hsl2.S); satPair.maxValue = std::max(satPair.maxValue, hsl2.S); } bBandLast = bandNow; } return satPair; } HslScaleParams CalculateScaleParams(const PinPalette& palette, const ColorContrast& contrast) { HslScaleParams scales; scales.HuePair = GetMinMaxHue(palette); scales.LightPair = GetMinMaxLightness(palette); scales.SatPair = GetMinMaxSaturation(palette); scales.HueScale = 1.0; if (scales.HuePair.maxValue > scales.HuePair.minValue) scales.HueScale = (contrast.MaxHue - contrast.MinHue) / (scales.HuePair.maxValue - scales.HuePair.minValue); scales.LightScale = 1.0; if (scales.LightPair.maxValue > scales.LightPair.minValue) scales.LightScale = (contrast.MaxLightness - contrast.MinLightness) / (scales.LightPair.maxValue - scales.LightPair.minValue); scales.SatScale = 1.0; if (scales.SatPair.maxValue > scales.SatPair.minValue) scales.SatScale = (contrast.MaxSaturation - contrast.MinSaturation) / (scales.SatPair.maxValue - scales.SatPair.minValue); return scales; } ColorArgb StretchHslColor(ColorArgb color, const HslScaleParams& scaleParams, const ColorContrast& contrast) { HSL hsl = ToHsl(color); double newSat = contrast.MinSaturation + (hsl.S - scaleParams.SatPair.minValue) * scaleParams.SatScale; hsl.S = newSat; double newLight = contrast.MinLightness + (hsl.L - scaleParams.LightPair.minValue) * scaleParams.LightScale; hsl.L = newLight; double newHue = contrast.MinHue + (hsl.H - scaleParams.HuePair.minValue) * scaleParams.HueScale; hsl.H = newHue; return ToRgb(hsl, color.A); } }
Java
UTF-8
1,897
2.109375
2
[]
no_license
package usr.localcontroller.command; import java.io.IOException; import java.io.PrintStream; import java.util.List; import org.simpleframework.http.Request; import org.simpleframework.http.Response; import us.monoid.json.JSONException; import us.monoid.json.JSONObject; import usr.logging.Logger; import usr.logging.USR; import usr.protocol.MCRP; /** * The RequestRouterStatsCommand command. */ public class RequestRouterStatsCommand extends LocalCommand { // the original request String request; /** * Construct a RequestRouterStatsCommand. */ public RequestRouterStatsCommand() { super(MCRP.REQUEST_ROUTER_STATS.CMD); } /** * Evaluate the Command. */ @Override public boolean evaluate(Request request, Response response) { try { PrintStream out = response.getPrintStream(); if (controller.getGlobalControllerInteractor() == null) { response.setCode(302); JSONObject jsobj = new JSONObject(); jsobj.put("error", "RequestRouterStatsCommand: No global controller present"); out.println(jsobj.toString()); response.close(); return false; } else { List<String> list = controller.getRouterStats(); controller.sendRouterStats(list); JSONObject jsobj = new JSONObject(); jsobj.put("msg", "REQUEST FOR STATS RECEIVED"); out.println(jsobj.toString()); response.close(); return true; } } catch (IOException ioe) { Logger.getLogger("log").logln(USR.ERROR, leadin() + ioe.getMessage()); } catch (JSONException jex) { Logger.getLogger("log").logln(USR.ERROR, leadin() + jex.getMessage()); } return false; } }
Markdown
UTF-8
2,723
2.546875
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: イマーシブ リーダーを起動して HTML コンテンツを表示する titleSuffix: Azure Cognitive Services description: この記事では、イマーシブ リーダーを起動して HTML コンテンツを表示する方法について説明します。 author: metanMSFT manager: guillasi ms.service: cognitive-services ms.subservice: immersive-reader ms.topic: conceptual ms.date: 01/14/2020 ms.author: metan ms.openlocfilehash: bc7ab46113e1b819fc71a9f6e8a18400f8acfbef ms.sourcegitcommit: 2ec4b3d0bad7dc0071400c2a2264399e4fe34897 ms.translationtype: HT ms.contentlocale: ja-JP ms.lasthandoff: 03/28/2020 ms.locfileid: "75946078" --- # <a name="how-to-launch-the-immersive-reader-with-html-content"></a>イマーシブ リーダーを起動して HTML コンテンツを表示する方法 この記事では、イマーシブ リーダーを起動して HTML コンテンツを表示する方法について説明します。 ## <a name="prepare-the-html-content"></a>HTML コンテンツを準備する イマーシブ リーダーでレンダリングしたいコンテンツをコンテナー要素内に配置します。 コンテナー要素に一意の `id` があることを確認してください。 イマーシブ リーダーは、基本的な HTML 要素をサポートします。詳細については、[リファレンス](./reference.md#html-support)を参照してください。 ```html <div id='immersive-reader-content'> <b>Bold</b> <i>Italic</i> <u>Underline</u> <strike>Strikethrough</strike> <code>Code</code> <sup>Superscript</sup> <sub>Subscript</sub> <ul><li>Unordered lists</li></ul> <ol><li>Ordered lists</li></ol> </div> ``` ## <a name="get-the-html-content-in-javascript"></a>JavaScript で HTML コンテンツを取得する JavaScript コードで HTML コンテンツを取得するには、コンテナー要素の `id` を使用します。 ```javascript const htmlContent = document.getElementById('immersive-reader-content').innerHTML; ``` ## <a name="launch-the-immersive-reader-with-your-html-content"></a>イマーシブ リーダーを起動して HTML コンテンツを表示する `ImmersiveReader.launchAsync` を呼び出すときに、チャンクの `mimeType` プロパティを `text/html` に設定すると、HTML のレンダリングが有効になります。 ```javascript const data = { chunks: [{ content: htmlContent, mimeType: 'text/html' }] }; ImmersiveReader.launchAsync(YOUR_TOKEN, YOUR_SUBDOMAIN, data, YOUR_OPTIONS); ``` ## <a name="next-steps"></a>次のステップ * [イマーシブ リーダー SDK リファレンス](./reference.md)を参照する
Java
UTF-8
2,720
2.25
2
[]
no_license
package com.example.controller; import com.example.model.Article; import com.example.model.Comment; import com.example.model.Pressman; import com.example.repository.ArticleRepo; import com.example.repository.CommentsRepo; import com.example.repository.SketchRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @Controller public class ArticleController { @Autowired private ArticleRepo articleRepo; @Autowired private SketchRepo sketchRepo; @Autowired private CommentsRepo commentsRepo; @GetMapping("/articleReadMore/{user}/{articleId}") public String getArticle(Model model, @PathVariable String user,@PathVariable Long articleId){ Article searchArticle = articleRepo.findByUsernameAndId(user, articleId); if (searchArticle!=null){ model.addAttribute("article",searchArticle); }else{ model.addAttribute("message","Article Not found"); } Article article = new Article(); article.setId(articleId); List<Comment> comments = commentsRepo.findByArticle(article); if(comments!=null){ model.addAttribute("comments",comments); } return "viewArticle"; } @PostMapping public String sendComment(@AuthenticationPrincipal Pressman pressman, @RequestParam Long articleId, @RequestParam String name, @RequestParam String textComment, Model model){ Comment comment = new Comment(); Article article = articleRepo.findTopById(articleId); comment.setArticle(article); comment.setAuthor(name); comment.setText(textComment); commentsRepo.save(comment); if(article.getComments().isEmpty()) { article.setComments(Collections.singletonList(comment)); articleRepo.save(article); }else{ article.getComments().add(comment); } model.addAttribute("article",article); return String.format("redirect:/articleReadMore/%s/%s",name,articleId); } }
C#
UTF-8
1,152
2.734375
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; using System.Xml; using VPleckaitis.Mobile.Warframe.Helpers; namespace VPleckaitis.Mobile.Warframe.Models.External { public static class RssFeedMapper { public static Alert Map<T>(this RssFeedModel entity) where T : Alert { return new Alert() { Id = entity.guid, Type = entity.author, Description = entity.title, Start = DateTime.Parse(entity.pubDate) }; } public static List<RssFeedModel> Map<T>(this string data) where T : List<RssFeedModel> { List<RssFeedModel> list = new List<RssFeedModel>(); XmlDocument dataXml = new XmlDocument(); dataXml.LoadXml(data); if(dataXml.SelectSingleNode("rss/channel")!= null) { foreach(XmlNode node in dataXml.SelectNodes("rss/channel/item")) { list.Add(XmlSerialiserHelper.ConvertNode<RssFeedModel>(node)); } } return list; } } }
Java
UTF-8
617
1.695313
2
[]
no_license
package com.bestnet.hf; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) //启动一个服务注册中心提供给其他应用进行对话 @EnableEurekaServer public class HfHqbEurakaApplication { public static void main(String[] args) { SpringApplication.run(HfHqbEurakaApplication.class, args); } }
Java
UTF-8
1,067
2.59375
3
[]
no_license
package com.park; import com.park.entity.Ticket; import com.park.entity.Vehicle; import com.park.service.ParkingService; import com.park.service.ParkingServiceImpl; public class App { public static void main(String[] args) { ParkingService parkingService = new ParkingServiceImpl(); parkingService.init(100); Vehicle maruti_alto = new Vehicle("white", "MH01-23-4566"); Vehicle maruti_ciaz = new Vehicle("black", "MH02-23-4566"); Vehicle maruti_ciaz2 = new Vehicle("white", "MH01-23-4664"); Ticket t1 = parkingService.park(maruti_alto); Ticket t2 = parkingService.park(maruti_ciaz); Ticket t3 = parkingService.park(maruti_ciaz2); System.out.println(t1.getTicketNo()); System.out.println(t2.getTicketNo()); System.out.println(t3.getTicketNo()); System.out.println(parkingService.getByColor("White")); System.out.println(parkingService.getBySlot(1)); System.out.println(parkingService.getByVehicleID("MH01-23-4664")); parkingService.unPark(t3); System.out.println(parkingService.getByVehicleID("MH01-23-4664")); } }
C#
UTF-8
475
2.921875
3
[]
no_license
using NUnit.Framework; namespace AlgoSolving.Task0560_Subarray_Sum_Equals_K { public class Tests { [Test] public void AcceptanceTest1() { Assert.That(new Solution().SubarraySum(new[] { 1, 1, 1 }, 2), Is.EqualTo(2)); } [Test] public void Last_element_equaled_to_sum_should_be_counted() { Assert.That(new Solution().SubarraySum(new[] { 1, 2, 3 }, 3), Is.EqualTo(2)); } } }
Swift
UTF-8
541
2.984375
3
[]
no_license
// // DateExtensions.swift // JustAHabit // // Created by Jaeson Booker on 11/16/18. // Copyright © 2018 Jaeson Booker. All rights reserved. // import Foundation extension Date { var stringValue: String { return DateFormatter.localizedString(from: self, dateStyle: .medium, timeStyle: .none) } var isToday: Bool { let calender = Calendar.current return calender.isDateInToday(self) } var isYesterday: Bool { let calender = Calendar.current return calender.isDateInYesterday(self) } }
Markdown
UTF-8
21,292
3.859375
4
[]
no_license
## 第9章 类和模块 ### 1. 类和原型 + 在JavaScript中,类的所有实例对象都从同一个原型对象上继承属性,因此原型对象是类的核心。 ### 2. 类和构造函数 + 调用构造函数的一个重要特征是:构造函数的prototype属性都被用作新对象的原型,这意味着通过同一个构造函数创建的所有对象都继承自一个相同对象,因此他们是同一个类的成员。 (1)构造函数和类的标识 + 原型对象是类的唯一标识,当且晋档两个对象继承自同一个原型对象时,它们才属于同一个类的实例。 (2)constructor属性 + 任何JavaScript函数都可以用作构造函数,并且调用构造函数是需要用到一个prototype属性的,因此每个JavaScript函数都拥有一个prototype属性,这个属性是一个对象,这个对象包含唯一一个不可枚举的属性constructor。constructor的值是一个函数对象。 + 使用构造函数创建一个Animal类: ```javascript function Animal(name) { this.name = name; } Animal.prototype = { sayName: function() { console.log(this.name); } } var animal = new Animal("cat"); animal.sayName();//cat console.log(Animal.prototype.constructor === Animal);//false ``` 输出false。这是因为Animal类使用它自身的一个新对象重写预定义的Animal.prototype对象,这个新定义的原型对象不含有constructor属性。我们可以通过不就措施类弥补这个问题: ```javascript function Animal(name) { this.name = name; } Animal.prototype = { constructor: Animal,//显示设置构造函数反向引用 sayName: function() { console.log(this.name); } } var animal = new Animal("cat"); animal.sayName();//cat console.log(Animal.prototype.constructor === Animal);//true ``` 另一种方法是使用预定义的原型对象,预定义的原型对象包含constructor属性,然后一次给该原型对象添加方法: ```javascript function Animal(name) { this.name = name; } Animal.prototype.sayName = function() { console.log(this.name); } var animal = new Animal("cat"); animal.sayName();//cat console.log(Animal.prototype.constructor === Animal);//true console.log(animal.constructor === Animal);//true ``` #### 3. javascript中的Java式的继承 (1)在JavaScript中定义类的步骤: + 先定义一个构造函数并设置初始化新对象的实例属性。 + 给构造函数的prototype对象定义实例的方法。 + 给构造函数定义类字段和类属性。 (2)java中有很多重要特性在JavaScript类中时无法模拟的。 #### 4. 类的扩充 + JavaScript中基于原型的继承机制是动态的:对象从其原型继承属性,如果创建对象之后原型的属性发生改变,也会影响到继承这个原型链的所有实例对象。这意味着我们可以通过给原型添加新方法来扩充JavaScript类。 + 可以给Object.prototype添加方法,从而使所有对象都可以直接调用这些方法,但是并不推荐,因为在ES5之前,Object.prototype添加的属性是可以被for/in循环遍历到的。 #### 5. 类和类型 (1)instanceof运算符 + 尽管instanceof运算符右操作数是构造函数,但计算过程实际上是检测了对象的继承关系,而不是检测创建对象的构造函数。 + instanceof和isPrototypeOf()方法的缺点是: + 无法通过对象来获得类名,只能检测对象是否属于指定的类名。 + 在客户端多窗口多框架子页面的web应用中兼容性不佳,每个窗口和框架子页面都具有单独的执行上下文,每个上下文都包含独有的全局变量和一组构造函数。在两个不同框架页面中创建的两个数组继承自两个相同但互相独立的原型对象,其中一个框架页面中的数组不是另一个框架页面的Array()构造函数的实例,instanceof运算结果是false。 (2)constructor属性: + 可以识别对象是否属于某个类。 + 缺点是:在客户端多窗口多框架子页面的web应用中兼容性不佳,一个框架页面中的数组不是另一个框架页面的Array()构造函数的实例,instanceof运算结果是false。 (3)构造函数的名称 + 鉴于instanceof运算符和constructor属性的缺点,可以使用构造函数的名字而不是构造函数本身作为类标识符。但是也存在不足:并不是所有对象都有constructor属性,并不是多有函数都由名字。 (4)鸭式辩型 + 不要关注“对象的类是什么”,而是管制“对象能做什么”。 + “像鸭子一样走路、游泳并且嘎嘎叫的鸟就是鸭子!” + 利用鸭式辩型实现的函数,quacks()函数用以检查一个对象(第一个实参)是否实现了剩下的参数所表示的方法。对于除了第一个参数外的每个参数,如果字符串的话则直接检查是否存在以他命名的方法,如果是对象的话则检查第一个对象中的方法是否在这个对象中也具有同名的方法,如果参数是函数,则嘉定他是构造函数,函数检查顶一个对象实现的方法是否在构造函数的原型对象中也具有同名的方法。 ```javascript //如果o实现了除了第一个参数之外的参数所表示的方法,则返回true function quacks(o /* ,...*/) { for(var i = 1;i < arguments.length;i++) { var arg = arguments[i]; switch(typeof arg) { case 'string': if(typeof o[arg] !== 'function') return false; continue; case 'function': arg = arg.prototype; case 'object': for(var m in arg) { if(typeof arg[m] !== 'function') continue; if(typeog o[m] !== 'function') return false; } } } return true; } ``` 但是不能通过quacks(o, Array)检测o是否实现了Array中国所有同名的方法,原因是内置类的方法都是不可枚举的,通过for/in循环无法遍历到。但是ES5中可以使用Object.getOwnPropertyNames()获得对象的自由属性(包括可枚举和不可枚举的属性)。 #### 6. JavaScript中的面向对象技术 ##### (1)实现集合类的例子 ```javascript function Set() { this.values = {};//结合数据都保存在对象的属性里 this.n = 0;//集合中值的个数 this.add.apply(this,arguments);//把所有参数添加到集合里面 } //将每个参数添加到集合里面 Set.prototype.add = function() { arguments.forEach(function(item) { var str = Set._v2s(item);//转换为字符串 if(!this.values.hasOwnProperty(str)) { this.values[str] = item; this.n++; } }) return this;//支持方法链式调用 } //从集合删除元素,这些元素由参数指定 Set.prototype.remove = function() { arguments.array.forEach(element => { var str = Set._v2s(element); if(this.values.hasOwnProperty(str)){ delete this.values[str]; this.n--; } }); return this; } //如果集合中包含这个值,返回true,否则返回false Set.prototype.contains = function(value) { return this.values.hasOwnProperty(Set._v2s(value)); } //返回集合大小 Set.prototype.size = function () { return this.n; } //遍历集合中的所有元素,在指定的上下文中调用f Set.prototype.foreach = function(f, context) { for(var item in this.values) { if(this.values.hasOwnProperty(s)) {//忽略继承的属性 f.call(context, this.values[item]); } } } //内部函数,将任意JavaScript值和唯一的字符串对应起来 Set._v2s = function(val) { switch(val) { case undefined: return 'u'; case null: return 'n'; case true: return 't'; case false: return 'f'; default: switch (typeof val) { case 'number': return '#' + val; case 'string': return '\'\'' + val; default: return '@' + objectId(val); } } function objectId(o) { var prop = "|**objectid**|";//私有属性,用来存放id if(!o.hasOwnProperty(prop))//如果对象没有id o[prop] = Set._v2s.next++;//将下一个值赋给它 return o[prop];//返回这个id } }; Set._v2s.next = 100;//设置初始id的值。 ``` ##### (2)实现枚举类型的例子 + 这个函数创建一个新的枚举类型,实参对象表示类的每个实例的名字和值 + 返回值是一个构造函数,它标识这个新类 + 注意:这个构造函数也会抛出异常,不能使用它来创建该类型的新实例 + 返回的构造函数包含名/值对的映射表 + 包括由值组成的数组,以及一个forEach()迭代器函数 ```javascript function enumeration(namesToValues) { //这个虚构的构造函数时返回值 var enumeration = function() { throw "can not instantiate enumerations"; } //枚举值继承自这个对象 var proto = enumeration.prototype = { constructor: enumeration,//标识类型 toString: function () {return this.name;},//返回名字 valueOf: function () {return this.value},//返回值 toJSON: function () {return this.name;}//转换为JSON }; enumeration.values = [];//用以存放枚举对象的数组 //现在创建新类型的实例 for(name in namesToValues) { var e = inherit(proto);//创建一个代表它的对象 e.name = name;//给它一个名字 e.value = namesToValues[name];//给它一个值 enumeration[name] = e;//将它设置为构造函数的属性 enumeration.values.push(e);//将它存储在数组中 } //一个类方法,用来对类的实例进行迭代 enumeration.foreach = function(f, c) { values.foreach(function(item) { f.call(c, this.values[i]) }) }; //返回标识这个新类型的构造函数 return enumeration; } //创建一个新的枚举类 var Coin = enumeration({Penny: 1, Nickel: 5, Dime: 10, Quarter: 25}); var c = Coin.Dime;//这是新类的实例 c instanceof Coin;//true c.constructor == Coin;//true ``` ##### (3)标准转换方法 + toString() + toLocaleString() + valueOf() + toJSON + 下面这个例子将这些方法添加到Set类的原型中 ```javascript function extend(o, p){ for(var prop in p){ o[prop] = p[prop]; } return o; } extend(Set.prototype,{ //将集合转换为字符串 toString: function() { var s = '{',i = 0; this.foreach(function(v) { s += ((i++>0)?", ": "") + v; }); return s + "}"; }, toLocaleString: function() { var s = "{",i = 0; this.foreach(function(v){ if(i++>0) s+=", "; if(v == null) s += v;//null和undefined else s+= v.toLocaleString();//其它情况 }); return s + "}"; }, toArray: function() { var a = []; this.foreach(function(v) {a.push(v);}); return a; } }) ``` ##### (4)比较方法 + 下面这个例子给Set添加一个equals()方法,这个方法只能接收一个实参,如果这个实参和调用此方法的对象相等的话则返回true ```javascript Set.prototype.equals = function (that) { if(this === that) return true; if(!(that instanceof Set)) return false; if(this.size() !== that.size()) return false; try{ this.foreach(function(v) { if(!that.contains(v)) throw false; }) } catch(x) { if(x === false) return false; throw x; } } ``` + compareTo()方法只能接收一个参数,这个方法将这个参数和调用它的对象进行比较。如果this对象小于参数对象,compareTo()应当返回比0小的值,相等返回0,否则,返回大于0的值。给Range()类添加一个compareTo方法: ```javascript Range.prototypef.compareTo = function(that) { if(!(that instanceof Range)) throw "error"; var diff = this.from - that.from;//比较下边界 if(diff == 0) diff = this.to - that.to; reutrn diff; } ``` ##### (5)方法借用 + 把一个类中的方法用到其他的类中。类似于其他语言中的“多重继承”。 ```javascript //不适合实例太复杂的类 Range.prototype.equals = generic.equals; ``` ##### (6)私有状态 + 可以通过将变量(或参数)闭包在一个构造函数内来模拟实现私有实例字段,调用构造函数会创建一个实例。为了做到这一点,需要: + 在构造函数内部定义一个函数(因此这个函数可以访问构造函数内部的参数和变量) + 将这个函数赋值给新创建对象的属性 ```javascript function Range(form, to) { this.form = form; this.to = to; } function Range(form, to) { this.form = function() {return form;} this.to = function(){return to;} } ``` ```javascript var r = new Range(1, 5) console.log(r.form());//1 ``` 第一种方法一旦实例化一个新的对象r,就不能修改了; 第二种可以通过方法替换它。 ```javascript r.form = function() {return 0;} ``` ##### (7)构造函数的重载和工厂方法 + 重载:根据传入的参数不同执行不同的方法 ```javascript function Set () { this.value = {}; this.n = 0; if(arguments.length === 0 && isArrayLike(arguments[0])) { this.add.call(this,arguments[0]); } if(arguments.length > 0) { this.add.apply(this,arguments); } } ``` + 工厂模式 + 工厂接口是工厂方法模式的核心,与调用者直接交互用来提供产品。 + 工厂实现决定如何实例化产品,是实现扩展的途径,需要有多少种产品,就需要有多少个具体的工厂实现。 ### 七、子类 #### 1. 定义子类 ```javascript B.prototype = inherit(A.prototype);//子类派生来自父类 B.prototype.constructor = B;//重载继承来的constructor属性 ``` + 创建一个圆形对象,这个原型对象继承自Set的原型 ```javascript SingleletSet.prototype = inherit(Set.prototype); extend(SingleletSet.prototype, { constructor: SingleletSet,//设置合适的constructor属性 add: function () {throw "read-only set"}, remove: function () {return "read-only set"} }); //这里的singleletSet类从父类中继承了toString()、equals()等方法,同时也有add()、remove()自有方法。 ``` #### 2. 构造函数和方法连链 + 类工厂和方法链 ```javascript //这个函数返回Set类的子类 //并重写该类的add()方法用以对添加的元素做特殊的过滤 function filteredSetSubClass (superclass, filter) { var constructor = function () { superclass.apply(this, arguments);//调用父类的构造函数 } constructor.prototype = inherit(superClass.prototype); constructor.prototype.constructor = constructor; prop.add = function () { //在添加任何成员之前首先使用过滤器将所有参数进行过滤 for(var i = 0; i < arguments.length; i++) { var v = arguments[i]; if(!filter(v)) throw("value" + v + "rejected by filter"); } //调用父类的add()方法 superclass.prototype.add.apply(this, arguments); } return constructor; } ``` 上面这个例子用一个函数将创建子类的代码包装起来,这样就可以在构造函数和方法链中使用父类的参数,而不是通过写死某个父类的名字来使用它的参数。也就是说如果想修改父类,只需要修改一处代码即可,而不需要对每个用到父类类名的地方都做修改。 #### 3. 组合vs子类 + “组合由于继承” ```javascript /* *实现一个FilteredSet,它包装某个指定的集合对象 *并对传入add()方法的值应用了某种过滤器 *“范围”类中其他所有的和新方法延续到包装后的实例中 */ var FilteredSet = Set.extend( function FilteredSet(set, filter) { this.set = set; this.filter = filter; }, { //实例方法 add: function() { //如果已有过滤器,直接使用它 if(this.filter) { for (var i = 0;i < arguments.length;i++) { var v = arguments[i]; if(!filter(v)) throw("value" + v + "rejected by filter"); } } //调用set中的add方法 this.set.add.apply(this.set, arguments); return this; }, //剩下的方法保持不变 remove: function () { this.set.remove.apply(this.set, arguments); return this; } /*,....其他方法..*/ } ) //创建一个实例 var s = new FilteredSet(new Set(), function(x) {return x !== null}); ``` 上面这个例子中使用组合的好处是:只需创建一个单独的FilteredSe t子类即可。可以利用这个类的实例来创建任意带有成员限制的集合实例。 #### 4. 类的层次结构和抽象类 + 从实现中抽离接口,定义一个抽象类,某些实现方法不同的的方法在这个类中不做实现,在具体的子类上做这些方法的具体实现。 + 使用extend()实现子类方法的扩展 #### 8. ES5中的类 + ES5增加了方法支持 + getter + setter + 可枚举性 + 可写性 + 可配置性 + ES5增加了对象扩展的限制 ##### (1)让属性不可枚举 + 使用Object.defindProperty(obj,prop,{ value: value, writable: boolean, enumerable: boolean, configurable: boolean, }),将enumerable的值设置为false ##### (2)定义不可变的类 + 使用Object.defindProperty(obj,prop,{ value: value, writable: boolean, enumerable: boolean, configurable: boolean, }),将writable和configurable的值设置为false。 + Object.defineProperty(obj,prop,{ value: value, writable: boolean, enumerable: boolean, configurable: boolean, })和Object.defineProperties()可以用来创建新属性 ##### (3)封装对象状态 + 在ES5中,可以通过定义属性getter和setter方法将状态变量更健壮的封装起来,这两个方法是无法删除的。 ```javascript function Range(from, to) { function getFrom() {return from;} function getTo() {return to;} function setFrom(value) {from = value;} function setTo(value) {to = value;} Object.defineProperties(this,{ from: { get: getFrom, set: setFrom, enumerable: true, configurable: false }, to: { get: getTo, set: setTo, enumerable: true, configurable: false } }) } var r = new Range(2, 5); console.log(r.from);//2 ``` 使用这种方法,实例方法可以像读取普通的属性一样读取from和to。 ##### (4)防止类的扩展 + 使用Object.preventExtensions()可以将对象设置为不可扩展的; + Object.seal()可以将对象设置为不可扩展、不可配置的(依然可写); + Object.freeze()可以执行冻结操作,不能给对象添加新的实例,已有的实例也无法删除或者修改。 ##### (5)子类和ES5 + 使用Object.create()创建子类 ##### (6)属性描述符 + 通过Object.defineProperty()给对象设置属性 #### 9. 模块 + 模块化的目标:支持大规模的程序开发,处理分散源中代码的组装。实现代码重用。 + 模块:是一个独立的JavaScript文件,模块文件可以包含一个类定义、一组相关的类、一个实用函数数据库或者是一些待执行的代码。 + 不同的模块必须避免修改全局执行上下文,尽可能的减少定义全局变量 (1)用做命名空间的对象: + 避免污染全局变量 + 模块的文件名应该和命名空间匹配 + 最顶层的命名空间用来标识创建模块的作者或者组织 (2)作为私有命名空间的函数:模块内的某些函数并不需要外界可见。 + 方法一: ```javascript var collections; if(!collections) collections = {}; collections.sets = (function namespace () { /*省略部分代码*/ //通过返回命名空间对象将API导出 return { AbstractSet: AbstractSet, NoSet: NoSet, SingleTonSet: SingleTonSet, ArraySet: ArraySet }; }()); ``` + 方法二:将模块函数当做构造函数 ```javascript var collections; if(!collections) collections = {}; collections.sets = (new function namespace() { function Console() { console.log("123455") } function AbstractSet() { } function SingleTonSet() { } //将API导出到this对象 this.AbstractSet = AbstractSet; this.Console = Console; this.SingleTonSet = SingleTonSet; //这里没有返回值 }()); collections.sets.Console();//123455 ``` + 方法三: ```javascript var collections; if(!collections) collections = {}; collections.sets = {}; (function namespace() { /*省略部分代码*/ //将API导出到this对象 collections.sets.AbstractSet = AbstractSet; collections.sets.SingleTonSet = SingleTonSet; //这里没有返回值 }()); ```
Python
UTF-8
473
3.609375
4
[]
no_license
def rec_preorder(node, result): if node: result.append(node.val) rec_preorder(node.left, result) rec_preorder(node.right, result) #Basically a DFS def iter_preorder(root): if not root: return result = [] stack = [root] while stack: node = stack.pop() result.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) #Done second so it gets popped off first return result
PHP
UTF-8
1,224
2.65625
3
[]
no_license
<?php class modelPagamento { private $id; private $pedido; private $pag; private $tPag; private $vPag; private $card; private $CNPJ; private $tBand; private $cAut; public function getId(){ return $this->id; } public function setId($id){ $this->id = $id; } public function getPedido(){ return $this->pedido; } public function setPedido($pedido){ $this->pedido = $pedido; } public function getPag(){ return $this->pag; } public function setPag($pag){ $this->pag = $pag; } public function getTPag(){ return $this->tPag; } public function setTPag($tPag){ $this->tPag = $tPag; } public function getVPag(){ return $this->vPag; } public function setVPag($vPag){ $this->vPag = $vPag; } public function getCard(){ return $this->card; } public function setCard($card){ $this->card = $card; } public function getCNPJ(){ return $this->CNPJ; } public function setCNPJ($CNPJ){ $this->CNPJ = $CNPJ; } public function getTBand(){ return $this->tBand; } public function setTBand($tBand){ $this->tBand = $tBand; } public function getCAut(){ return $this->cAut; } public function setCAut($cAut){ $this->cAut = $cAut; } }
C#
UTF-8
2,699
2.921875
3
[ "Apache-2.0" ]
permissive
using System.Globalization; namespace EFIngresProvider.SqlGen { /// <summary> /// TopClause represents the a TOP expression in a SqlSelectStatement. /// It has a count property, which indicates how many TOP rows should be selected and a /// boolen WithTies property. /// </summary> class TopClause : ISqlFragment { /// <summary> /// How many top rows should be selected. /// </summary> internal ISqlFragment TopCount { get; set; } /// <summary> /// How many top rows should be skipped. /// </summary> internal ISqlFragment SkipCount { get; set; } internal bool IsEmpty { get { return (TopCount == null) && (SkipCount == null); } } /// <summary> /// Creates a TopClause with the given topCount and withTies. /// </summary> /// <param name="topCount"></param> /// <param name="withTies"></param> internal TopClause() { } internal void Clear() { TopCount = null; SkipCount = null; } internal void SetTopClause(TopClause topClause) { TopCount = topClause.TopCount; SkipCount = topClause.SkipCount; } internal void SetTopCount(int topCount) { TopCount = new SqlBuilder(topCount.ToString(CultureInfo.InvariantCulture)); } internal void SetSkipCount(int skipCount) { SkipCount = new SqlBuilder(skipCount.ToString(CultureInfo.InvariantCulture)); } #region ISqlFragment Members /// <summary> /// Write out the TOP part of sql select statement /// It basically writes TOP (X) [WITH TIES]. /// </summary> /// <param name="writer"></param> /// <param name="sqlGenerator"></param> public void WriteSql(SqlWriter writer, SqlGenerator sqlGenerator) { if (SkipCount != null) { writer.WriteLine(); writer.Write("offset "); writer.Write(SkipCount.GetInt(sqlGenerator) + 1); writer.Write(" "); } if (TopCount != null) { writer.WriteLine(); writer.Write("fetch "); if (SkipCount != null) { writer.Write("next "); } else { writer.Write("first "); } writer.Write(TopCount.GetInt(sqlGenerator)); writer.Write(" rows only "); } } #endregion } }
C++
UTF-8
1,829
3.015625
3
[ "MIT" ]
permissive
#include "box.h" float Box::surface_area(){ return 2.*(side_length[0]*side_length[1] + side_length[1]*side_length[2] + side_length[2]*side_length[0] ); } Collision Box::next_collision_with(Particle* ptcl){ // record the collision event Collision collision; collision.collision_pos = ptcl->get_pos(); // calculate what happens after the collision collision.new_vel1 = ptcl->get_vel(); int face_to_collide_with = 0; float time_to_collision = 1.0/0.0; // !! better define inf // loop through each wall, find time to collision for (unsigned int dir=0;dir<3;dir++){ // x,y,z for (unsigned int plus=0;plus<2;plus++){ // -,+ direction float distance_to_wall = 0; // [position of wall - position of particle] in given direction if (plus){ distance_to_wall = side_length[dir]-ptcl->get_pos()[dir]; } else { distance_to_wall = 0.0 - ptcl->get_pos()[dir]; } float time = time_to_collision; if (distance_to_wall!=0){ time = distance_to_wall/ptcl->get_vel()[dir]; } // if time is properly calculated this part is fine // assign nexy collision if (time >0 && time < time_to_collision){ // enumerate faces (-x,+x,-y,+y,-z,+z) -> (0,1,2,3,4,5) face_to_collide_with = dir*2+plus; time_to_collision = time; } } } collision.time_to_collision = time_to_collision; for (unsigned int dir=0;dir<3;dir++){ // x,y,z for (unsigned int plus=0;plus<2;plus++){ // -,+ direction if (dir*2+plus==face_to_collide_with){ collision.new_vel1[dir] = -1.*ptcl->get_vel()[dir]; } } } return collision; }
Java
UTF-8
1,184
2.078125
2
[]
no_license
package com.Dao; import com.pojo.Comment; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface CommentDao extends JpaRepository<Comment,Long> { List<Comment> findAllByUsername(String username); List<Comment> findAllByUsernameAndAndIsRead(String username,int isRead); List<Comment> findAllByBlogId(long blogId); @Query(value = "update comment set likes = likes - 1 where blog_id = #{blogId} and id = #{commentId}",nativeQuery = true) void updDesCommIsLikes(Long blogId, Long commentId); @Query(value = "update comment set likes = likes + 1 where blog_id = #{blogId} and id = #{commentId}",nativeQuery = true) void updInsCommIsLikes( Long blogId, Long commentId); @Query(value = "update comment set is_read = 0 where id = #{arg0}",nativeQuery = true) void updOneBlogNotComm(Long id); @Query(value = "update commentlikes set is_read = 0 where id = #{arg0}",nativeQuery = true) void updOneBlogNotLikes(Long id); }
Java
UTF-8
5,778
2.1875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package shapefileloader; import dao.GeoDao; import database.DBUtils; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import org.geotools.data.FeatureSource; import org.geotools.data.FileDataStore; import org.geotools.data.FileDataStoreFinder; import org.geotools.feature.FeatureCollection; import org.geotools.feature.FeatureIterator; import org.opengis.feature.Feature; import sdnis.wb.util.ShapeFileUtils; import sdnis.wb.util.ShapeWrapper; /** * * @author wb385924 */ public class ArgentineProvinceReader { private static final Logger log = Logger.getLogger(ArgentineProvinceReader.class.getName()); public void readBoundaryData(String path) { FeatureIterator fi = null; Connection con = null; try { con = null;//DBUtils.get("city_risk").getConnection(); FileDataStore store = FileDataStoreFinder.getDataStore(new File(path)); FeatureSource featureSource = store.getFeatureSource(); FeatureCollection fc = featureSource.getFeatures(); List<String> propNames = new ArrayList<String>(); propNames.add("NAME_1"); ShapeFileUtils shapeUtil = new ShapeFileUtils( null, propNames); fi = fc.features(); int count = 0; while (fi.hasNext()) { Feature f = fi.next(); ShapeWrapper wrapper = shapeUtil.extractFeatureProperties(f); String name = wrapper.getPropertyMap().get("NAME_1"); int id = GeoDao.storeGeometry(con, "province", "shape", wrapper.getShapeString()); if(id != -1){ GeoDao.storeEntitySinglePropertyById(con, "province", "name", name, id); } log.log(Level.INFO, "feature {0} geom is {1}", wrapper.getShapeString()); count++; } log.log(Level.INFO, "total features is {0}", count); } catch (FileNotFoundException ex) { log.severe(ex.getMessage()); } catch (IOException ex) { log.severe(ex.getMessage()); } finally { fi.close(); DBUtils.close(con); } } /**public void loadData(String path) { FeatureIterator fi = null; Connection con = null; try { FileDataStore store = FileDataStoreFinder.getDataStore(new File(path)); FeatureSource featureSource = store.getFeatureSource(); FeatureCollection fc = featureSource.getFeatures(); List<String> propNames = new ArrayList<String>(); propNames.add("Grid_ID"); ShapeFileUtils shapeUtil = new ShapeFileUtils(fc, "M\\d{1,2}y\\d{4}", propNames); fi = fc.features(); int count = 0; while (fi.hasNext()) { Feature f = fi.next(); ShapeWrappers wrapper = shapeUtil.extractFeatureProperties(f); int cellId = Integer.parseInt(wrapper.getPropertyMap().get("Grid_ID")); String shapeString = wrapper.getShapeString(); log.log(Level.INFO, "grid id is {0}", cellId); //int id = GeoDao.getEntityId(con, "country", "iso_3", isoCode); log.log(Level.INFO, "feature {0} geom is {1}", shapeString); if(!doesCellIdExist(cellId)){ int returnId = insertGeometry(shapeString); if(returnId != -1){ updateCell(cellId, returnId); } } count++; } log.log(Level.INFO, "total features is {0}", count); } catch (FileNotFoundException ex) { log.severe(ex.getMessage()); } catch (IOException ex) { log.severe(ex.getMessage()); } finally { fi.close(); DBUtils.get().close(con); } }**/ private int insertGeometry(String shapeString){ DBUtils db = null;//DBUtils.get("city_risk"); Connection c = db.getConnection(); int returnId = GeoDao.storeGeometry(c, "grid_cell","bounds", shapeString); db.close(c); return returnId; } private boolean doesCellIdExist(int id){ DBUtils db =null;// DBUtils.get("city_risk"); Connection c = db.getConnection(); int returnId = GeoDao.getEntityId(c, "grid_cell", "id", id); db.close(c); return returnId != -1; } private void updateCell(int id, int assignedId){ DBUtils db =null;// DBUtils.get("city_risk"); Connection c = db.getConnection(); TreeMap<String,Integer> dataMap = new TreeMap<String,Integer>(); dataMap.put("assigned_id", assignedId); TreeMap<String,Integer> whereMap = new TreeMap<String,Integer>(); whereMap.put("id", id); GeoDao.updateEntityData(c, "grid_cell", dataMap, whereMap); db.close(c); } public static void main(String[] args) { //File f = new File("somefile"); new ArgentineProvinceReader().readBoundaryData("C:\\Users\\wb385924\\Documents\\Volcano\\Provinces_affected.shp"); // new ReadBoundaryData().readAllBoundaries(new File("C:\\climate data\\countries"));nb2010_me_people.shp DBUtils.closeAll(); } }
TypeScript
UTF-8
1,632
2.875
3
[ "MIT" ]
permissive
import { Action } from '@ngrx/store'; import { ActionType } from './action-type.enum'; export const displayableTypes = ['string', 'number', 'boolean', 'object']; export type MessageValueTypes = 'string' | 'number' | 'boolean' | 'object' | 'null' | 'array'; const MAX_MESSAGES = 500; export interface IAction extends Action { type: ActionType; payload?: any; } export class State { messages: {}[]; selected: string[]; hidden: string[]; } export const reducers = { messages: (messages: {}[], action: IAction) => { switch (action.type) { case ActionType.APPEND_MESSAGE: const msgs = messages.slice(0, MAX_MESSAGES); msgs.unshift(action.payload); return msgs; case ActionType.CLEAR_MESSAGES: return []; default: return messages; } }, selected: (selected: string[], action: IAction) => { switch (action.type) { case ActionType.SELECT_PROPERTY: return [ ...selected, action.payload ]; case ActionType.DESELECT_PROPERTY: return selected.filter(x => x !== action.payload); default: return selected; } }, hidden: (hidden: string[], action: IAction) => { switch (action.type) { case ActionType.HIDE_PROPERTY: return [ ...hidden, action.payload ]; case ActionType.UNHIDE_PROPERTY: return hidden.filter(x => x !== action.payload); default: return hidden; } }, };
C
UTF-8
2,034
3.046875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #define ALLOC_MEM_SIZE (100 * 1024 * 1024) unsigned long *buf, *curr_pos; unsigned long func_call = 0; /* ackermann function */ unsigned long ack(unsigned long m, unsigned long n) { unsigned long val; unsigned long random_num = rand(); if (m == 0) { val = n + 1; } else if (n == 0) { val = ack(m - 1, 1); } else { val = ack(m - 1, ack(m, n - 1)); } if (func_call < (ALLOC_MEM_SIZE / sizeof(unsigned long))) { /* memory write */ *curr_pos = val; curr_pos++; } func_call++; return val; } int main(int argc, char** argv) { /* ackermann fucntion argument */ unsigned long m = 4, n = 1; unsigned long sum = 0, randnum, ackres, caltime; int i; struct timeval tv1, tv2; /* init random */ srand((unsigned)time(NULL)); randnum = rand() % 10; /* memory allocation */ buf = (unsigned long *)calloc((ALLOC_MEM_SIZE / sizeof(unsigned long)), sizeof(unsigned long)); if (!buf) { fprintf(stderr, "Memory allcation error.\n"); return -1; } curr_pos = buf; /* get time */ if (gettimeofday(&tv1, NULL) < 0) { fprintf(stderr, "error : gettimeofday()\n"); return -1; } /* call ackermann and calculation(plus operation) */ ackres = ack(m, n); /* memory read */ curr_pos = buf; for (i = 0; i < (ALLOC_MEM_SIZE / sizeof(unsigned long)); i++) { sum += (*curr_pos % (randnum + 3)); curr_pos++; } /* get time */ if (gettimeofday(&tv2, NULL) < 0) { fprintf(stderr, "error : gettimeofday()\n"); return -1; } /* calculate time */ if (tv1.tv_usec <= tv2.tv_usec) { caltime = (tv2.tv_sec - tv1.tv_sec) * 1000000 + (tv2.tv_usec - tv1.tv_usec); } else { caltime = (tv2.tv_sec - tv1.tv_sec) * 1000000 + (1000000 + tv2.tv_usec - tv1.tv_usec); } printf("ackermann result=%ld\n", ackres); printf("time=%ld[usec]\n", caltime); //printf("func_call=%ld\n", func_call); //printf("random value=%ld\n", randnum); //printf("sum=%ld\n", sum); /* release memory */ free((void *)buf); return 0; }
PHP
UTF-8
506
3.859375
4
[]
no_license
<?php $isOk = false; ?> <!DOCTYPE html> <html lang="fr" dir="ltr"> <head> <meta charset="utf-8" /> <title>Exercice 8 partie 2 php</title> </head> <body> <p>Traduire ce code avec des if et des else :</p> <p>< ? php</p> <p>echo ($isOk) ? 'c'est ok !!' : 'c'est pas bon !!!';</p> <p>?></p> <!-- même exo que le 7 mais on voit que nous n'avons pas besoin de mettre == true --> <?php if ($isOk){ ?> <p>C'est ok !!'</p> <?php } else { ?> <p>Ce n'est pas bon !!!</p> <?php } ?> </body> </html>
Markdown
UTF-8
1,365
3.890625
4
[]
no_license
# BIG O Notation Big O notation is used in Computer Science to describe the performance or complexity of an algorithm. ## Common Notations O(1) describes an algorithm that will always execute in the same time (or space) regardless of the size of the input data set. A process that doesn't involve a calculation being performed on any piece of data in the data set. O(N) describes an algorithm whose performance will grow linearly and in direct proportion to the size of the input data set. A function that does an operation on each piece of data in the data set. O(N^2) represents an algorithm whose performance is directly proportional to the square of the size of the input data set. A function that does on operation using 2 data points for every data position. O(2^N) denotes an algorithm whose growth doubles with each additon to the input data set. This is a function where each additional data point means each calculation for the function must be done 1 more time. A good example is a fibonacci sequence. O(log N) is slightly trickier to explain.Doubling the size of the input data set has little effect on its growth as after a single iteration of the algorithm the data set will be halved and therefore on a par with an input data set half the size. This makes algorithms like binary search extremely efficient when dealing with large data sets.
C++
UTF-8
4,907
3.171875
3
[]
no_license
#pragma once #include <vector> #include <memory> #include <functional> #include <algorithm> #include <cassert> namespace tgvoiprate { class VectorOfColumns { public: using Iterator = std::vector<double>::iterator; VectorOfColumns(const std::vector<double>& data, size_t rowsCount) : mRowsCount{rowsCount} , mData(data) {} VectorOfColumns(Iterator begin, Iterator end, size_t rowsCount) : mRowsCount{rowsCount} , mData(begin, end) {} VectorOfColumns(size_t rowsCount, size_t length = 0) : mRowsCount{rowsCount} , mData(rowsCount * length) {} double& At(int column, int row) { return mData[column * RowsCount() + row]; }; size_t RowsCount() const { return mRowsCount; } size_t Length() const { return (mData.size()) / RowsCount(); } double Accumulate(double startValue, std::function<double(double, double)> accFunction) const { double result = startValue; for (double x: mData) { result = accFunction(result, x); } return result; } double Min() const { return *std::min_element(mData.begin(), mData.end()); } double Max() const { return *std::max_element(mData.begin(), mData.end()); } double Mean() const { return Accumulate(0, [this](double result, double value){ return result + value / mData.size(); }); } VectorOfColumns& ForEach(std::function<void(double&)> func) { for (double& x: mData) { func(x); } return *this; } VectorOfColumns& ForEachIndexed(std::function<void(int, int, double&)> func) { for (size_t i = 0; i < mData.size(); ++i) { func(i / RowsCount(), i % RowsCount(), mData[i]); } return *this; } void ForEachFrame(int frameLength, int step, std::function<void(int, VectorOfColumns&)> func) { for (int i = 0; i + frameLength <= Length(); i += step) { VectorOfColumns frame = SubCopy(i, frameLength); func(i, frame); } } VectorOfColumns& CombineWith(VectorOfColumns& another, std::function<double(double, double)> op) { assert(another.Length() == Length()); assert(another.RowsCount() == RowsCount()); return ForEachIndexed([&another, op](int column, int row, double& value) { value = op(value, another.At(column, row)); }); } VectorOfColumns operator*(VectorOfColumns& another) { return SubCopy().CombineWith(another, [](double a, double b){ return a * b; }); } VectorOfColumns operator/(VectorOfColumns& another) { return SubCopy().CombineWith(another, [](double a, double b){ return a / b; }); } VectorOfColumns operator+(VectorOfColumns& another) { return SubCopy().CombineWith(another, [](double a, double b){ return a + b; }); } VectorOfColumns operator-(VectorOfColumns& another) { return SubCopy().CombineWith(another, [](double a, double b){ return a - b; }); } VectorOfColumns Convolve(VectorOfColumns& window) { assert(window.RowsCount() <= RowsCount()); assert(window.Length() <= Length()); assert(window.RowsCount() % 2 == 1); assert(window.Length() % 2 == 1); VectorOfColumns result{RowsCount() - window.RowsCount() - 1, Length() - window.Length() - 1}; ForEachIndexed([&](int column, int row, double& value){ int dstColumn = column - window.Length() / 2; int dstRow = row - window.RowsCount() / 2; if (dstColumn < 0 || dstColumn >= result.Length()) { return; } if (dstRow < 0 || dstRow >= result.RowsCount()) { return; } window.ForEachIndexed([&](int wnd_column, int wnd_row, double& wnd_value) { int srcColumn = column + wnd_column - window.Length() / 2; int srcRow = row + wnd_row - window.RowsCount() / 2; result.At(dstColumn, dstRow) += wnd_value * this->At(srcColumn, srcRow); }); }); return result; } void Append(const std::vector<double>& column) { assert(column.size() == RowsCount()); mData.insert(mData.end(), column.begin(), column.end()); } VectorOfColumns SubCopy(size_t startColumn = 0, size_t length = 0) { assert(startColumn + length <= Length()); if (length == 0) { length = Length() - startColumn; } return VectorOfColumns { mData.begin() + startColumn * RowsCount(), mData.begin() + (startColumn + length) * RowsCount(), RowsCount() }; } private: size_t mRowsCount; std::vector<double> mData; }; }
Markdown
UTF-8
700
2.578125
3
[ "MIT" ]
permissive
# ハンズオン: 相談員とAI、あなたはどちら このハンズオンでは、前のハンズオンで作成したフローをもとに __お悩み相談__ を変更し発信者の入力をもとにフローを分岐させる方法を学習します。 ## ハンズオンのゴール - 相談者の入力を取得する方法を学習する - フローを分岐する方法を学習する ## 手順 1. [相談者の入力を取得し、フローを分岐させる](01-Gather-Split-Flow.md) 2. [分岐したフローをそれぞれ設定する](02-Setting-Wdigets.md) ## 次のハンズオン [ハンズオン: 高度な機能の活用](/docs/03-Studio-Advanced-Features/00-Overview.md)
Markdown
UTF-8
738
3.34375
3
[ "CC-BY-4.0" ]
permissive
# sys.setrecursionlimit Published: 23 June 2020, 18:00 Python doesn't support [tail recursion](https://t.me/pythonetc/239). Hence, it's easy to face `RecursionError` when implementing recursive algorithms. You can get and change maximum recursion depth with [sys.getrecursionlimit](https://docs.python.org/3/library/sys.html#sys.getrecursionlimit) and [sys.setrecursionlimit](https://docs.python.org/3/library/sys.html#sys.setrecursionlimit) functions: ```python sys.getrecursionlimit() # 3000 sys.setrecursionlimit(4000) sys.getrecursionlimit() # 4000 ``` However, it's a dangerous practice, especially because every new frame on the call stack is quite expensive. Luckily, any recursive algorithm can be rewritten with iterations.
Markdown
UTF-8
4,822
2.515625
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: Using Azure Stack HCI on a single server description: This article describes Azure Stack HCI OS on a single server author: ronmiab ms.author: robess ms.topic: overview ms.reviewer: kimlam ms.lastreviewed: 01/17/2023 ms.date: 01/17/2023 --- # Using Azure Stack HCI on a single server [!INCLUDE [applies-to](../../includes/hci-applies-to-22h2-21h2.md)] This article provides an overview of running Azure Stack HCI on a single server, also known as a single-node cluster. Using a single server minimizes hardware and software costs in locations that can tolerate lower resiliency. A single server can also allow for a smaller initial deployment that you can add servers to later (scaling out). Along with the benefits mentioned, there are some initial limitations to recognize. - You must use PowerShell to create the single-node cluster and enable Storage Spaces Direct. - Single servers must use only a single drive type: Non-volatile Memory Express (NVMe) or Solid-State (SSD) drives. - Stretched (dual-site) clusters aren't supported with individual servers (stretched clusters require a minimum of two servers in each site). - To install updates for single-node clusters, see [Updating single-node clusters](../deploy/single-server.md#updating-single-node-clusters). For solution updates (such as driver and firmware updates), see your solution vendor. - Operating system or other updates requiring a restart cause downtime to running virtual machines (VMs) because there isn't another running cluster node to move the VMs to. We recommend manually shutting down the VMs before restarting to ensure that the VMs have enough time to shut down prior to the restart. ## Prerequisites - A server from the [Azure Stack HCI Catalog](https://hcicatalog.azurewebsites.net/#/catalog) that's certified for use as a single-node cluster and configured with all NVMe or all SSD drives. - An [Azure Subscription](https://azure.microsoft.com/). For hardware, software, and network requirements see [What you need for Azure Stack HCI](/azure-stack/hci/overview#what-you-need-for-azure-stack-hci). ## Comparing single-node and multi-node clusters The following table compares attributes of a single-node cluster to multi-node clusters. |Attributes | Single-node | Multi-node | |----------|-----------|-----------| |Full software-defined data center (SDDC) stack (hypervisor, storage, networking) | Yes | Yes| |Storage Spaces Direct support | Yes | Yes | |Software Defined Networking (SDN) support | Yes | Yes | |Native Azure Arc integration | Yes | Yes | |Managed through Windows Admin Center and Azure portal | Yes | Yes | |Azure billing/registration | Yes | Yes | |Charged per physical core| Yes | Yes | |Support through Azure | Yes | Yes | |Connectivity (intermittent or connected) | Yes | Yes | |[Azure benefits](../manage/azure-benefits.md) on Azure Stack HCI | Yes | Yes | |[Activate Windows Server Subscriptions](../manage/vm-activate.md) | Yes | Yes | |[Azure Defender and Secured-core](/shows/inside-azure-for-it/securing-azure-stack-hci-with-azure-defender-and-secured-core) | Yes | Yes | |[Azure Kubernetes Service (AKS) hybrid](/azure-stack/aks-hci/) | Yes | Yes | |[Azure Virtual Desktop](/azure/virtual-desktop/overview) | Yes | Yes | |[Azure Site Recovery](../manage/azure-site-recovery.md) | Yes | Yes | |[Azure Stack HCI: Stretch cluster support](../concepts/stretched-clusters.md) | No | Yes | |[Use Graphics Processing Units (GPUs) with clustered VMs](../manage/use-gpu-with-clustered-vm.md) | Yes | Yes | ## Known issues The following table describes currently known issues for single-node clusters. This list is subject to change as other items are identified, check back for updates. |Issue | Notes| |-----------|---------------| |SBL cache isn't supported in single-node clusters. | All-flash, flat configuration with Non-volatile Memory Express (NVMe) or Solid-State Drives (SSD) must be used. | |Windows Admin Center doesn't support creating single-node clusters. | [Deploy single server with PowerShell](../deploy/create-cluster-powershell.md). | |Windows Admin Center cosmetic user interface (UI) changes needed. | Doesn't limit Live Migration within the same cluster; allows affinity rules to be created, etc. Actions will fail without any harm. | |Windows Admin Center pause server fails since it tries to drain the server. | Utilize PowerShell to pause (suspend the server). | |Cluster Aware Updating (CAU) doesn't support single-node clusters in 21H2. You'll need to update to 22H2. | Update using Windows Admin Center (through server manager), PowerShell, or the Server Configuration tool (SConfig). [Learn more](../deploy/single-server.md#updating-single-node-clusters) | ## Next steps > [!div class="nextstepaction"] > [Deploy on a single server](../deploy/single-server.md)
Java
UTF-8
1,991
2.40625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.walmart.ticketservice.service; import com.walmart.ticketservice.data.Seat; import java.util.Optional; import java.util.stream.Collectors; import com.walmart.ticketservice.data.SeatHold; import com.walmart.ticketservice.data.SeatHoldImpl; import com.walmart.ticketservice.data.TicketServiceManager; import java.util.Comparator; import java.util.List; /** * * @author Getaneh Kassahun */ public class TicketServiceImpl implements TicketService { @Override public int numSeatsAvailable(Optional<Integer> venueLevel) { return (int) TicketServiceManager.getInstance().getAllSeats().stream() .filter(s -> (!venueLevel.isPresent() || s.getLevelId() == venueLevel.get()) && s.isAvailable()).count(); } @Override public SeatHold findAndHoldSeats(int numSeats, Optional<Integer> minLevel, Optional<Integer> maxLevel, String customerEmail) { List<Seat> seats = TicketServiceManager.getInstance().getAllSeats().stream() .filter(s -> s.isAvailable() && (!minLevel.isPresent() || s.getLevelId() >= minLevel.get()) && (!maxLevel.isPresent() || s.getLevelId() <= maxLevel.get()) ) .sorted(Comparator.comparing(s -> s.getLevelId())) .limit(numSeats) .collect(Collectors.toList()); SeatHold seatHold = new SeatHoldImpl(customerEmail); seatHold.addSeats(seats); TicketServiceManager.getInstance().addSeatHold(seatHold); return seatHold; } @Override public String reserveSeats(int seatHoldId, String customerEmail) { SeatHold seatHold = TicketServiceManager.getInstance().getSeatHold(seatHoldId); seatHold.reserve(); return seatHold.getResearvationCode(); } }
Ruby
UTF-8
1,858
2.796875
3
[]
no_license
require 'sqlite3' require_relative 'questions_db' require_relative 'like' require_relative 'user' require_relative 'follow' require_relative 'question' class Reply attr_accessor :author_id, :parent_id, :id, :body def initialize(input = {}) @author_id = input['author_id'] @parent_id = input['parent_id'] @id = input['id'] @body = input['body'] @question_id = input['question_id'] end def self.find_by_user_id(user_id) results = QuestionsDatabase.instance.execute(<<-SQL, user_id) SELECT * FROM replies WHERE replies.author_id = ? SQL results.map { |result| Reply.new(result) } end def self.find_by_question_id(question_id) results = QuestionsDatabase.instance.execute(<<-SQL, question_id) SELECT * FROM replies WHERE replies.question_id = ? SQL results.map { |result| Reply.new(result) } end def author result = QuestionsDatabase.instance.execute(<<-SQL, @author_id) SELECT users.* FROM users WHERE users.id = ? SQL User.new(result.first) end def question result = QuestionsDatabase.instance.execute(<<-SQL, @question_id) SELECT questions.* FROM questions WHERE questions.id = ? SQL Question.new(result.first) end def child_replies results = QuestionsDatabase.instance.execute(<<-SQL, @id) SELECT replies.* FROM replies WHERE replies.parent_id = ? SQL results.map { |result| Reply.new(result) } end def parent_reply result = QuestionsDatabase.instance.execute(<<-SQL, @parent_id) SELECT replies.* FROM replies WHERE replies.id = ? SQL Reply.new(result.first) end end
JavaScript
UTF-8
531
4.3125
4
[]
no_license
const basket = ["apples", "oranges", "grapes"]; //for for (let i = 0; i < basket.length; i++) { console.log(basket[i], " for"); } //forEach basket.forEach((item) => console.log(item, "forEach")); //for of for (item of basket) { console.log(item, "for of"); } // iterating -> we are able to go 1 by 1 through an array //for in //works with objects // we enumerating here , becuase its for objects const detailedbasket = { apples: 5, oranges: 10, grapes: 100, }; for (item in detailedbasket) { console.log(item); }
C++
UTF-8
2,294
2.609375
3
[]
no_license
#ifndef URLLINEEDIT_H #define URLLINEEDIT_H #include <QtCore/QUrl> #include <QtWidgets/QLineEdit> #include <QtWidgets/QAbstractButton> #include <QtWidgets/QPushButton> class QLineEdit; class WebView; class BrowserMainWindow; /* * Search icon on the left hand side of the search widget * When a menu is set a down arrow appears */ class SearchButton : public QAbstractButton { Q_OBJECT public: SearchButton(QWidget* parent = 0, int _size = 16); void paintEvent(QPaintEvent* event); QSize sizeHint() const; QMenu* menu; protected: void mousePressEvent(QMouseEvent* event); int size; }; /* * Clear Buuton on the right hand side of the BrowserLineEdit. * Hidden by Default * "A circle with an X in it" */ class ClearButton : public QAbstractButton { Q_OBJECT public: ClearButton(QWidget* parent = 0, int _size = 16); void paintEvent(QPaintEvent* event); QSize sizeHint() const; public slots: void TextChanged(const QString& text); protected: int size; }; class BrowserLineEdit : public QWidget { Q_OBJECT signals: void textChanged(const QString&); public: BrowserLineEdit(QWidget* parent = 0); inline void SetOwnerBrowserMainWindow(BrowserMainWindow* ownerMainWindow) { ownerBrowserMainWindow = ownerMainWindow; } inline QLineEdit* GetLineEdit() const { return lineEdit; } inline QWidget* GetLeftWidget() const { return leftWidget; } inline void SetLeftWidget(QWidget* widget) { leftWidget = widget; } QSize sizeHint() const; QVariant inputMethodQuery(Qt::InputMethodQuery property) const; inline BrowserMainWindow* GetOwnerBrowserMainWindow() const { return ownerBrowserMainWindow; } int heightOfLineEdit; protected: void focusInEvent(QFocusEvent* event); void focusOutEvent(QFocusEvent* event); void keyPressEvent(QKeyEvent* event); void resizeEvent(QResizeEvent* event); void inputMethodEvent(QInputMethodEvent* event); QWidget* leftWidget; QLineEdit* lineEdit; ClearButton* clearButton; BrowserMainWindow* ownerBrowserMainWindow; }; class UrlLineEdit : public BrowserLineEdit { Q_OBJECT public: UrlLineEdit(QWidget *parent); void SetWebView(WebView* _webView); protected: void focusOutEvent(QFocusEvent* event); private slots: void WebViewUrlChanged(const QUrl& url); private: WebView* webView; }; #endif // URLLINEEDIT_H
Java
UTF-8
1,989
2.046875
2
[]
no_license
package com.yq.xcode.common.bean; import java.util.List; public class ContractFunctionView { /** * 第几个函数 */ private Integer ind; /** * functionCode = eleNumber */ private Long functionId; private String functionCode; /** * functionName = eleName */ private String functionName; private String description; private String parameters; private String paramsCn; private String termsTitle; private List<ContractParamsView> paramList; public ContractFunctionView() { } public ContractFunctionView(String functionCode, String functionName) { this.functionCode = functionCode; this.functionName = functionName; this.description = "当前尚未选择函数"; } public String getParamsCn() { return paramsCn; } public void setParamsCn(String paramsCn) { this.paramsCn = paramsCn; } public String getFunctionName() { return functionName; } public void setFunctionName(String functionName) { this.functionName = functionName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getFunctionCode() { return functionCode; } public void setFunctionCode(String functionCode) { this.functionCode = functionCode; } public String getParameters() { return parameters; } public void setParameters(String parameters) { this.parameters = parameters; } public List<ContractParamsView> getParamList() { return paramList; } public void setParamList(List<ContractParamsView> paramList) { this.paramList = paramList; } public Integer getInd() { return ind; } public void setInd(Integer ind) { this.ind = ind; } public Long getFunctionId() { return functionId; } public void setFunctionId(Long functionId) { this.functionId = functionId; } public String getTermsTitle() { return termsTitle; } public void setTermsTitle(String termsTitle) { this.termsTitle = termsTitle; } }
Markdown
UTF-8
9,510
3.046875
3
[ "MIT" ]
permissive
--- layout: post title: "Following my SPA into the DOM Living Standard docs" date: 2020-09-21 13:50:32 -0400 permalink: following_my_spa_into_the_dom_living_standard_docs --- At the point that I imagined, wireframed and built the API and frontend for Writing Place, I had been in Flatiron’s Fullstack program long enough to have created the first version of this project using jquery. It had been an app for Soup Kitchens, where users could leave yelp-like feedback on soup kitchens and food pantries they’d visited. The idea came from a project I’d done at Code for Philly, and then, from conversations I’d had with the Dept of Health. I coded most of that project, and then ran into a problem using data-id and event bubbling. My work life heated up, too, and I had a new book to promote, so I took many months before I returned to this project. By then, happily, the curriculum had changed. JQuery was out, and SPA design patterns were in, using a vanilla JS frontend with a Rails API. Instead of retooling the old app, I created [Writing Place](https://github.com/MiriamPeskowitz/underground_frontend) The concept: Writing Place provides spaces and places as a prompt for writing. You choose a topic, and use each of it’s eight sites as a writing prompt. Then (and this is still a stretch feature), you can see all your notes together, and edit and stitch them together into a longer piece. The app nurtures you into new kinds of writing, and I imagine it might be useful for education, or for adults who want to write and journal but need some structure for doing it, and an element of surprise. ![](https://res.cloudinary.com/tech-stories/image/upload/v1600710049/Screen_Shot_2020-09-21_at_1.39.51_PM_or4uju.png) Building the Rails API was fairly straightforward, but since I’d been thinking in JavaScript for many months, I had to relearn Rails and RESTful conventions. What was new was working with serialization so that my data could move back and forth from Ruby and JSON, and I chose to work with the fast_jsonapi gem, after spending some time with tutorials, and understanding the specific ways that it nests data. The JS front end had two big challenges. The first was coding in Object-Oriented JS. This, I found, was an act of imagination. Even when I copied suggested syntax and “got it right,” I found that it wasn’t enough; it still didn’t feel familiar. To get there, I had to sit and close my eyes and follow the data through its flow, seeing it start in the database, watch it as JSON, see it come into the front end through the fetch function, and only then did it make sense that my JS class constructors were organizing the JSON to use as a coherent class, or grouping, on my front end. This act of imagination felt like a step forward. You can actually get a lot done on an app without actually understanding what’s happening, but I wanted to not feel like any line in my app, or any relationship between code and files was a mystery. The second challenge, again, was using data-id, and then when I cleared that up, the challenge was in understanding and using eventListeners with dynamically-created elements. Because of its async character, eventListeners become a problem in JS when the elements they’re attached to aren’t available, and in an SPA app, this happens all the time. The result is a click that won’t work, or a situation where the first of a series of data will click open, but the rest won’t. In my SPA, I need to capture the data-id specific to a single site in a dynamically-generated list. ![](https://res.cloudinary.com/tech-stories/image/upload/v1600710029/Screen_Shot_2020-09-21_at_1.40.18_PM_k7g3wl.png) The solution to the problem of eventListeners with dynamic JS is to attach the eventListener not to the specific element, but to a parent that will always be present. Then of course, one’s left with the problem of locating the exact location of the click, so that the code related to that specific click in a single location can trigger the intended reaction. This is done by using event.target to find the location of the click, and making sure that it corresponds to the correct id, class or element. Here are some examples of attaching the eventListener not to a specific element but to a parent, like document, and then using e.target to only run the function if the click equals a specific className, in this case the “see-sites-button.” ![](https://res.cloudinary.com/tech-stories/image/upload/v1600709799/Screen_Shot_2020-09-21_at_12.42.40_PM_kmjyl5.png) Similarly here. The addEventListener function is attached to document, and runs only if event.target.id is the “show-writing-button.” ![](https://res.cloudinary.com/tech-stories/image/upload/v1600709805/Screen_Shot_2020-09-21_at_12.42.30_PM_mqrx88.png) And here, the eventListener is on`document. The location is grabbed by using event.target, this time finding not the id or the className, but the dataset id, the particular id attached to a list of rendered items. The specific data-id is nabbed, then used to locate the object’s data using a findById method built into the object-oriented JS design. ![](https://res.cloudinary.com/tech-stories/image/upload/v1600709809/Screen_Shot_2020-09-21_at_12.42.09_PM_vhjhbj.png) At this point, the click will attach to the correct element on a list. One of the topics in Writing Place is Underground Sites in Philadelphia. Click on that topic and you’ll see a list of 8 sites, each with a photo and description. A user can click on any of these and a form will come up to reflect and write, based on this site. The way to make this click work for all members of the list is to attach the click to the parent, and then tell the browser to use event.target to find the data-id number, and use that to find the correct site. To figure this out, I ended up doing a deep dive into event listeners, which became a deep dive into the target property, the Event interface (and all the things we get with a browser that we don’t have to add code for; the browser itself is a living object), EventTarget, and event delegation. All of this is beyond the scope of this blog post, and I’m leaving some resource links below. But here are a few things to remember. First, the browser. The browser has events, and the three most common are window, document and element. It’s the document event that we’re attaching our event listeners to, in lieu of attaching to a specific element, through we could attach it to the window as well, or to a specific parent element that we know will be present throughout the life of the SPA. When something is confusing, I recommend searching the MDN docs and other resources to deepen your understanding of the browser. It really is the environment that we full stack developers live in, and it’s worth getting to know how it really works. Often the MDN docs include a link to the source code for that topic in the LS, or Living Standards, published by the WHATWG community. When I understood the surface level of “attach the event listener to the parent element” and “then use e.target”, it still just felt like magic until I tracked through MDN and found the DOM Living Standards and started to understand the code behind the DOM. Second, event.target works because “an EventTarget object represents a target to which an event can be dispatched when something has occurred.” A primary use of the target property is to “implement event delegation.” Event delegation is one of those HTML topics that you cover quickly, and it returns in JS with a vengeance, and I found that if you don’t take the time to imagine what’s happening, to slow down and see the movie of your code, the way data moves through it and events move through it, then you’ll feel like you’re faking it. The classic article is this: https://davidwalsh.name/event-delegate. It’s a huge topic but here’s the short form. HTML elements are nested in the browser, and an event attached to an element will propagate, or move around. It can “bubble” up, going from child to parent, inner to outer element. This is the default. Event propagation can be coded to “capture,” or move from parent to child, or outermost element to innermost element; you’d do this by adding an optional 3d argument to your event listener. Here’s the HTML. I’ve underlined various parent elements that I could have attached an event listener to, though I chose document instead. A click on the button with a data-id of 3 would have bubbled up to all of them, and beyond, to the document event that’s part of the browser. ![](https://res.cloudinary.com/tech-stories/image/upload/c_scale,w_493/v1600709789/Screen_Shot_2020-09-21_at_1.17.10_PM_pieqfz.png) At various points in learning JS, HTML becomes really important, and this is one of them. It’s all about knowing, really knowing, the stack of events that will be fired through the HTML elements in the browser, and how JS expands this and works with it. As promised, resources: https://davidwalsh.name/event-delegate https://developer.mozilla.org/en-US/docs/Web/API/Event https://developer.mozilla.org/en-US/docs/Web/API/Event/target https://dom.spec.whatwg.org/#interface-eventtarget https://dom.spec.whatwg.org/#interface-event https://dom.spec.whatwg.org/#event-target https://whatwg.org/ https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation)
JavaScript
UTF-8
1,437
2.890625
3
[]
no_license
(function(){ var stickyContent; var posStickyContent; var scrollY; function stickyOnscroll() { stickyContent = document.querySelector('.js-sticky'); scrollY = window.pageYOffset; if(stickyContent) { posStickyContent = stickyContent.getBoundingClientRect().top + scrollY; setWidth(); toggleSticky(); window.addEventListener('scroll', function() { toggleSticky(); }); window.addEventListener('resize', function() { setWidth(); }); } } function toggleSticky() { scrollY = window.pageYOffset; posStickyContent < scrollY ? stickyContent.classList.add("sticky") : stickyContent.classList.remove("sticky"); if(stickyContent.classList.contains("sticky")) { document.querySelector('.wrapper').style.marginTop = stickyContent.offsetHeight + parseInt(parentMarginContainer().marginTop, 10) + 'px'; } else { document.querySelector('.wrapper').removeAttribute("style"); } } function setWidth() { var widthSticky = stickyContent.parentNode.clientWidth; stickyContent.style.maxWidth = widthSticky + 'px'; } function parentMarginContainer() { var parentContainer = stickyContent.parentNode; var styleMarginTop = parentContainer.currentStyle || window.getComputedStyle(parentContainer); return styleMarginTop; } window.addEventListener('load', function() { stickyOnscroll(); }); })();
Markdown
UTF-8
781
2.625
3
[ "MIT" ]
permissive
# Web应用防火墙拦截上传文件的请求 {#concept_j4m_kfl_q2b .concept} ## 问题描述 {#section_qpw_kfl_q2b .section} 在浏览器中调用POST方法上传文件时,会有一定的概率出现405错误,提示被Web应用防火墙拦截。 ## 问题原因 {#section_rpw_kfl_q2b .section} 因为POST方法上传文件时,文件本身的内容也会被转码放到POST请求的body中一起上传,并且同样会被Web应用防火墙检测到。当转码后的文件中出现一些关键字时,就会被Web应用防火墙误认为含有恶意代码,从而拦截。 ## 解决方案 {#section_spw_kfl_q2b .section} 由于是文件转码后的误命中,暂时没有主动的解决办法,将以您将该地址加入精准访问控制的放行规则里。
Shell
UTF-8
2,351
3.296875
3
[]
no_license
#!/bin/sh #author: minus42 version="Version: 0.4" if [[ $1 ]] then if [ $1 = "-v" ] then echo $version exit else echo "only -v or no parameter allowed" exit fi fi echo "Generating dump, please hold the line!" now1=$(date +"%d.%m.%Y") now2=$(date +"%H:%M") sys=`uname -s` if [ x$sys = xDarwin ] ; then name=$(networksetup -getcomputername) interface=$(networksetup -listallhardwareports | cut -d : -f2 -s | grep -A 1 Wi-Fi | sed -n 2p | sed s/\ //g) own_mac=$(ipconfig getpacket $interface | sed -n 12p | cut -c 10-27) ssid=$(exec /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport --getinfo | grep " SSID:" | awk '{print $2}') bssid=$(exec /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport --getinfo | grep " BSSID:" | awk '{print $2}') tx_rate=$(exec /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport --getinfo | grep " lastTxRate:" | awk '{print $2}') channel=$(exec /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport --getinfo | grep " channel:" | awk '{print $2}' | awk -F ',' '{print $1}') fi if [ x$sys = xLinux ]; then name=$(hostname) interface=$(iw dev | grep Interface | awk '{print $2}') own_mac=$(iw dev $interface info | grep addr | awk '{print $2}') ssid=$(iw dev $interface link | grep SSID | awk '{for (i=2; i<NF; i++) printf $i " "; print $NF}') bssid=$(iw dev $interface link | grep 'Connected to' | awk '{print $3}') tx_rate=$(iw dev $interface link | grep 'tx bitrate' | awk '{print $3}') channel=$(iw dev $interface info | grep channel | awk '{print $2}') fi iperf=$(exec iperf3 -c linux.uni-koblenz.de 2> /tmp/wifidump_error.txt | grep " receiver" | awk '{print $7 " " $8}') iperf_error=$(</tmp/wifidump_error.txt) if [ -n "$iperf_error" ]; then iperf=$(</tmp/wifidump_error.txt) fi rm /tmp/wifidump_error.txt if [ $channel -lt 36 ] then frequency="2,4 GHz" else frequency="5 GHz" fi echo echo "# Timestamp #" echo Date: $now1 echo Time: $now2 echo echo "# Device #" echo Name: $name echo MAC: $own_mac echo echo "# Access Point #" echo BSSID: $bssid echo SSID: $ssid echo Frequency: $frequency echo Channel: $channel echo TxRate: $tx_rate MBit/s echo echo "# iperf #" echo Performance: $iperf echo echo proudly presented by minus42
Java
UTF-8
7,669
2
2
[]
no_license
package com.aumaid.bochihhott.PartnerModule; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.webkit.MimeTypeMap; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.Toast; import com.aumaid.bochihhott.Adapters.UniversalImageLoader; import com.aumaid.bochihhott.DAO.FoodItemDao; import com.aumaid.bochihhott.Models.Model; import com.aumaid.bochihhott.R; import com.aumaid.bochihhott.Utils.FirebaseMethods; import com.bumptech.glide.Glide; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; public class PartnerHomeActivity extends AppCompatActivity { private static final String TAG = "PartnerHomeActivity"; private StorageReference mSReference; private ImageView mProductImage; private Button mAddProductBtn; private Uri imageUri; private Context mContext; /** * declaring firebase stuff*/ private FirebaseMethods firebaseMethods; private FirebaseAuth.AuthStateListener mAuthListener; private FirebaseAuth mAuth; private FirebaseDatabase mFirebaseDatabase; private DatabaseReference myRef; /*Newly added stuff*/ //vars private DatabaseReference root = FirebaseDatabase.getInstance().getReference("photos/food_image_photos/"); private StorageReference reference = FirebaseStorage.getInstance().getReference(); /*Declaring Widgets*/ private EditText mProductName; private EditText mProductPrice; private Spinner mProductCategory; private EditText mProductDescription; private ImageView mBackButton; /*Variables*/ /** * This array stores food categories*/ private String[] foodCategories = { "Pizzas", "Burgers", "Soups", "Chicken", "Noodles", "Rolls", "Biryani", "Fries", "Dals", "Waazwaan"}; private String selectedCategory; private double mPhotoUploadProgress = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_partner_home); //Hooking all the widgets bindViews(); //Setting up Firebase setUpFireBaseAuth(); //Selecting Image by clicking on the Image View mProductImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { filechooser(); } }); //Uploading the Product by Clicking on the button mAddProductBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(mContext, "Attempting to upload the food item", Toast.LENGTH_SHORT).show(); String productName = mProductName.getText().toString().trim(); float productPrice = Float.parseFloat(mProductPrice.getText().toString().trim()); String productDescription = mProductDescription.getText().toString().trim(); Log.d(TAG, "onClick: "+selectedCategory); if(imageUri != null) { FoodItemDao dao = new FoodItemDao(mContext); dao.uploadToFirebase(true,selectedCategory.toLowerCase(),productDescription,productName,imageUri,4.5f,productPrice); }else{ Toast.makeText(mContext, "Please Select Image", Toast.LENGTH_SHORT).show(); } } }); //Assigning functionality to the Back Button mBackButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } /** * This method is used to hook all the widgets*/ private void bindViews(){ mContext = PartnerHomeActivity.this; firebaseMethods = new FirebaseMethods(mContext); mProductName = findViewById(R.id.productName); mProductPrice = findViewById(R.id.productPrice); mProductCategory = findViewById(R.id.productCategory); mProductDescription = findViewById(R.id.productDescription); mProductImage = findViewById(R.id.productPhoto); mAddProductBtn = findViewById(R.id.addProductButton); mBackButton = findViewById(R.id.back_btn); // Creating adapter for spinner ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, foodCategories); adapter.setDropDownViewResource(R.layout.simple_dropdown_spinner_layout); //Getting the instance of Spinner and applying OnItemSelectedListener on it mProductCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { selectedCategory = foodCategories[position]; } @Override public void onNothingSelected(AdapterView<?> parent) { } }); mProductCategory.setAdapter(adapter); } /** * This method opens up the image type intent * and then is used to store the uri of the image that is choosen*/ private void filechooser(){ Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent,1); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==1 && resultCode==RESULT_OK && data!=null && data.getData() !=null){ imageUri = data.getData(); mProductImage.setImageURI(imageUri); } } /*** * This section contains all the firebase related Methods*/ private void setUpFireBaseAuth(){ mAuth = FirebaseAuth.getInstance(); mFirebaseDatabase = FirebaseDatabase.getInstance(); myRef = mFirebaseDatabase.getReference(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { } }; myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } }
C++
WINDOWS-1252
1,729
2.71875
3
[]
no_license
/* * Config.h * * Author: JochenAlt */ #ifndef __ACTUATOR_CONFIG_H_ #define __ACTUATOR_CONFIG_H_ #include "Arduino.h" #include "core.h" #include "HerkuleX.h" #define NUMBER_OF_LEGS 5 // total number of legs #define HERKULEX_BAUD_RATE_DEFAULT 115200 // baud rate for connection to herkulex servos #define HERKULEX_BAUD_RATE_HIGH 115200 // incrreased baud rate for connection to herkulex servos #define I2C_BUS_RATE I2C_RATE_300 // frequency of i2c bus (1MHz KHz) #define I2C_BUS_TYPE I2C_OP_MODE_ISR // I2C library is using interrupts #define SENSOR_HERKULEX_SERVO_ID 200 #define SENSOR_CMD_REQUEST_DISTANCE 200 #define SENSOR_CMD_SEND_DISTANCE 201 enum LimbIdentifier {HIP=0 , THIGH=1, KNEE=2, FOOT=3 }; void logLimbName(LimbIdentifier id); void logLegName(int id); class LimbConfigType { public: int leg; LimbIdentifier id; uint8_t herkulexMotorId; ServoType type; bool clockwise; float nullAngle; // [] float maxAngle; // [] float minAngle; // [] float gearRatio; // void print(); void println(); void set(int legId, LimbIdentifier limbId, ServoType newType, int newHerkulexId, bool newClockwise, float newNullAngle, float newMinAngle, float newMaxAngle, float newGearRatio ) { leg = legId; id = limbId; herkulexMotorId = newHerkulexId; type = newType; clockwise = newClockwise; nullAngle = newNullAngle; maxAngle = newMaxAngle; minAngle = newMinAngle; gearRatio = newGearRatio; } float direction() { return clockwise?1:-1; } }; class LegConfigType { public: static void setDefaults(); void print(); int legId; LimbConfigType limbs[NumberOfLimbs]; int serialId; int nullDistance; }; const float servoAngleLimitOffset = 4; // [] #endif
PHP
UTF-8
492
2.578125
3
[ "MIT" ]
permissive
<?php /** * Hours per week fieldset * * @author Alex Peshkov <alex.peshkov@valtech.co.uk> * @author Rob Caiger <rob@clocal.co.uk> */ namespace Common\Form\Elements\Types; use Laminas\Form\Fieldset; /** * Hours per week fieldset * * @author Alex Peshkov <alex.peshkov@valtech.co.uk> * @author Rob Caiger <rob@clocal.co.uk> */ class HoursPerWeek extends Fieldset { public function setMessages($messages) { $this->messages = $messages; } public function getMessages($elementName = null) { return $this->messages; } }
Python
UTF-8
990
3.28125
3
[]
no_license
import requests from bs4 import BeautifulSoup # scrape list of 100 space facts from: url = 'https://www.thefactsite.com/2012/01/100-random-facts-about-space.html' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'} def get_facts(soup): ol = soup.find('ol') lis = [li for li in soup.find('ol').find_all('li')] # some list items have <script> tags embedded after text # contents[0] just to get text # som items are just an <a> tag -> ignore these facts = [li.contents[0] for li in lis if not li.find('a')] return facts facts = [] # facts are paginated, simply with a '/<page_number>' appended to url for i in range(5): if i == 0: page_url = url else: page_url = f'{url}/{i}' r = requests.get(page_url, headers=headers) soup = BeautifulSoup('\n'.join(r.text.splitlines()), 'html.parser') facts += get_facts(soup) print(facts)
Python
UTF-8
4,481
2.78125
3
[]
no_license
import sys,os import curses import math import redis ''' Init Redis ''' r = redis.StrictRedis(host='redis.hwanmoo.kr', port=6379, db=1) class Screen: def __init__(self): self.k = 0 self.cursor_x = 0 self.cursor_y = 0 def init_menu(stdscr): # Clear and refresh the screen for a blank canvas stdscr.clear() stdscr.refresh() # Start colors in curses curses.start_color() curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE) # Loop where k is the last character pressed # while (k != ord('q')): return stdscr self.stdscr = curses.wrapper(init_menu) def get_pos(self, num, flag, max_height, max_width, _str): _w = 30 _h = 15 _empty_str = "" for i in range(_w): _empty_str += " " if flag == 'worker_header': x = 0 y = 1 elif flag == 'print': x = 0 y = 2 elif flag == 'episode': x = 0 y = 3 elif flag == 'step': x = 0 y = 4 elif flag == 'distance': x = 0 y = 6 elif flag == 'd': x = 0 y = 7 elif flag == 'cos_a': x = 0 y = 8 elif flag == 'reward': x = 0 y = 10 elif flag == 'reset_amt': x = 0 y = 11 elif flag == 'reset_cnt': x = 0 y = 12 _raw_x = x + _w*(num) y = y + _h*(math.floor(_raw_x/max_width)) x = _raw_x - max_width*(math.floor(_raw_x / max_width)) - (_raw_x % max_width) % _w self.stdscr.addstr(y, x, _empty_str[:max_width-1], curses.color_pair(1)) return [y + 20, x, _str[:_w-2]] def clear(self, num, max_height, max_width): _w = 30 _h = 15 for x in range(20): for y in range(2,30): _raw_x = x + _w*(num) y = y + _h*(math.floor(_raw_x/max_width)) x = _raw_x - max_width*(math.floor(_raw_x / max_width)) - (_raw_x % max_width) % _w self.stdscr.delch(y+20,x) def update(self, _str, num, flag): r.hset('log-'+str(num),flag,_str) _str = str(_str) # Initialization # self.stdscr.clear() height, width = self.stdscr.getmaxyx() # self.clear(num, height, width) self.stdscr.refresh() if self.k == curses.KEY_DOWN: self.cursor_y = self.cursor_y + 1 elif self.k == curses.KEY_UP: self.cursor_y = self.cursor_y - 1 elif self.k == curses.KEY_RIGHT: self.cursor_x = self.cursor_x + 1 elif self.k == curses.KEY_LEFT: self.cursor_x = self.cursor_x - 1 self.cursor_x = max(0, self.cursor_x) self.cursor_x = min(width-1, self.cursor_x) self.cursor_y = max(0, self.cursor_y) self.cursor_y = min(height-1, self.cursor_y) # Declaration of strings statusbarstr = "STATUS BAR | Pos: {}, {}".format(self.cursor_x, self.cursor_y) # Rendering some text pos = self.get_pos(num, flag, height, width, _str) self.stdscr.addstr(pos[0], pos[1], pos[2], curses.color_pair(1)) # Render status bar self.stdscr.attron(curses.color_pair(3)) self.stdscr.addstr(height-1, 0, statusbarstr) self.stdscr.addstr(height-1, len(statusbarstr), " " * (width - len(statusbarstr) - 1)) self.stdscr.attroff(curses.color_pair(3)) # # Turning on attributes for title # self.stdscr.attron(curses.color_pair(2)) # self.stdscr.attron(curses.A_BOLD) # # Rendering title # self.stdscr.addstr(start_y, start_x_title, title) # # Turning off attributes for title # self.stdscr.attroff(curses.color_pair(2)) # self.stdscr.attroff(curses.A_BOLD) # Print rest of text self.stdscr.move(self.cursor_y, self.cursor_x) # Refresh the screen self.stdscr.refresh() # Wait for next input # self.k = self.stdscr.getch() def main(): curses.wrapper(draw_menu) if __name__ == "__main__": main()
JavaScript
UTF-8
925
2.84375
3
[]
no_license
import React from 'react'; function PokeList({cards, visibilityFilter, handleClick}) { console.log(`The visibility filter is: ${visibilityFilter}`); let filteredCards = cards; if (visibilityFilter === 'caught') { console.log('Caught Filter'); filteredCards = filteredCards.filter(card => card.isCaught); } else if (visibilityFilter === 'uncaught') { console.log('Uncaught Filter'); filteredCards = filteredCards.filter(card => !card.isCaught); } else { console.log('No Filter'); } console.log(filteredCards); const cardItems = filteredCards.map((card) => { return <li onClick={() => { handleClick(card.id); }} key={card.id}><img className="pokeImg" src={card.imageUrl} alt="poke"/><br/>{card.name}</li> }); return ( <ul> {cardItems} </ul> ); } export default PokeList;
PHP
UTF-8
1,279
2.71875
3
[]
no_license
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="keywords" content="CIS Restaurant, Lunch Menu"> <meta name="description" content="CIS Restaurant: Lunch Menu"> <title>CIS Restaurant Menu</title> <link rel="stylesheet" type="text/css" href="../style.css"> <link rel="stylesheet" type="text/css" href="./report.css"> </head> <body> <div id="container"> <h3 class="blue center">Total Sales by Month/Year</h3> <?php // database login credentials include('../config.php'); $rownum = 0; try { $DBH = new PDO("mysql:host=$_SQL_ADDRESS;dbname=$_SQL_DATABASE", $_SQL_USERNAME, $_SQL_PASSWORD); } catch (PDOException $e) { echo $e->getMessage(); } $query = "SELECT MONTHNAME(orderdate) AS MONTH, YEAR(orderdate) AS YEAR, sum(total) AS TOTAL FROM payment GROUP BY YEAR(orderdate), MONTH(orderdate)"; $stmt = $DBH->prepare($query); $stmt->execute(); $result = $stmt->fetchAll(); echo "<table class=\"table2 tablectr\">"; echo "<tr><th>Month</th><th>Total Sales</th></tr>"; foreach ($result as $row) { echo '<tr">'; echo "<td>" . $row['MONTH'] . " " . $row['YEAR'] . "</td><td>$" . $row['TOTAL'] . "</td>"; echo "</tr>"; $rownum++; } echo "</table>"; $DBH = null; ?> <br> </div> </body> </html>