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
Java
UTF-8
1,863
2.46875
2
[]
no_license
package com.pro_rate.HelthCare; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import java.util.List; @Path("hospitals") public class HospitalResource { HospitalDataModel hosRepo = new HospitalDataModel(); @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public List<Hospital> GetHospital() { System.out.println("Hospital Get API Called"); return hosRepo.getHospital(); } @GET @Path("hospitals/{registerId}") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Hospital GetHospital(@PathParam("registerId") String registerId) { System.out.println("Hospitals 1 Get API Called"); return hosRepo.getHospital(registerId); } @POST @Path("register") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Hospital CreateHospital(Hospital hos1) { System.out.println("Hospital create API Called"); System.out.println(hos1); hosRepo.createHospital(hos1); return hos1; } @PUT @Path("update") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Hospital Upadte(Hospital hos1) { System.out.println("Hospital Update API Called"); hosRepo.updateHospital(hos1); return hos1; } @DELETE @Path("hospitals/{reisterId}") public Hospital deleteHospital(@PathParam("registerId") String registerId) { System.out.println("Hospital Delete API Called"); Hospital del_hos = hosRepo.getHospital(registerId); if (del_hos.getRegisterId() != "0") { hosRepo.deleteHospital(registerId); } return del_hos; } }
Python
UTF-8
914
2.71875
3
[ "Apache-2.0" ]
permissive
#!python2 import sys import re from bs4 import BeautifulSoup files = sys.argv[1:] for file in files: print "Cleaning up %s" % file with open(file, 'r') as content_file: content = content_file.read() soup = BeautifulSoup(content, 'html.parser') for toc in soup.select('#toc'): toc.extract() for body in soup.find_all('body'): body_class = body['class'] try: body_class.remove('toc2') except Exception as e: pass try: body_class.remove('toc-left') except Exception as e: pass body['class'] = body_class for anchor in soup.find_all('a'): text = re.sub(r'\s+', ' ', ' '.join(list(anchor.stripped_strings)), flags=re.UNICODE) anchor.string = text with open(file, 'w') as content_file: content_file.write(soup.prettify(formatter="html").encode('utf-8'))
Java
UTF-8
1,531
2.234375
2
[]
no_license
/* * put your module comment here * formatted with JxBeauty (c) johann.langhofer@nextra.at */ package com.ga.cs.swing.model; import java.util.ResourceBundle; import com.chelseasystems.cr.currency.ArmCurrency; import com.ga.cs.swing.report.mediareport.MediaReportApplet; /** * TableModel for Media Report * @author fbulah * */ public class MediaReportModel extends BaseReportModel { public static final String[] MEDIA_REPORT_COLNAMES = MediaReportApplet.MEDIA_REPORT_COL_HEADINGS; /** */ public MediaReportModel() { ResourceBundle res = com.chelseasystems.cr.util.ResourceManager.getResourceBundle(); this.setColumnIdentifiers(new String[] {res.getString("Media Type") , res.getString("Media Count"), res.getString("Gross Amount") , res.getString("Credit/Return"), res.getString("Net Amount") }); } /** * @param colhdgs */ public MediaReportModel(String[] colhdgs) { super(colhdgs); } /** */ public MediaReportModel(ResourceBundle res) { this.setColumnIdentifiers(new String[] {res.getString("Media Type") , res.getString("Media Count"), res.getString("Gross Amount") , res.getString("Credit/Return"), res.getString("Net Amount") }); } // /* (non-Javadoc) // * @see javax.swing.table.TableModel#getColumnClass(int) // */ // public Class getColumnClass(int columnIndex) { // return getValueAt(0, columnIndex).getClass(); // } /** * @return */ public int getColumnCount() { return MEDIA_REPORT_COLNAMES.length; } }
Markdown
UTF-8
1,092
2.625
3
[]
no_license
--- layout: post title: 'Catching Up on Family News' category: uncategorized --- Seems that there is something in the water down in Memphis because my family has recently gone baby crazy. Congratulations to John and Lisa for the arrival of Elizabeth Marie. Congratulations to Bill and Melissa for the arrival of Matthew Cole. Congratulations to Michael and Kimberly for the arrival of Gracen Brooke, and sorry for the misspelling. I didn't receive an official announcement e-mail with the correct name spelling. I'm not even sure I know the name of Rip's offspring.<br /><br />And for the really big announcement, congratulations to Tommy and Renay (my little sis). The two are expecting a new homo sapiens arrival of their own. It will be interesting to see how the baby blends in with the personal zoo they have. Will the baby sleep in the same room as the frogs, snakes, rats, bats, and giraffes? Will he or she crawl around with the 12 dogs and 18 cats? Seriously, Melanie and I are both very excited for you guys.<br /><br />And congratulations to all, and to all a good night. <br /><br /><br />
Python
UTF-8
1,321
2.84375
3
[]
no_license
# Title: Vectorizer # Author: Andrew Bossie # Description: Wrapper class and helper functions for word2vec integration from gensim.models import Word2Vec from gensim.test.utils import datapath # import logging # logging.basicConfig(format=โ€™%(asctime)s : %(levelname)s : %(message)sโ€™, level=logging.INFO) class Vectorizer(): def __init__(self): pass @staticmethod def vectorize(corpus_list, file_name=None): # New Model if not file_name: v_model = Word2Vec(corpus_list, min_count=3, vector_size=1000, workers=4, window=5, epochs=40, sg=1) # 2 / 1000 / 5 / 500 / sg print(f"Created tensor with shape: {v_model.wv.vectors.shape}") print("Saving model...") v_model.save("../saved_models/v_model.w2v") else: # Load Saved Model v_model = Word2Vec.load(file_name) print("Done.") # print(v_model.wv.most_similar('president')) # print("----------------") # print(v_model.wv.most_similar('attack')) # print("----------------") # print(v_model.wv.most_similar('corruption')) # print("----------------") # print(v_model.wv.most_similar('investigation')) # print("----------------") return v_model
C++
UTF-8
383
3.1875
3
[]
no_license
#include <stdio.h> struct weapon{ int price; int atk; struct weapon * next; }; int main() { struct weapon a,b,c, *head; a.price=100; a.atk=100; b.price=200; b.atk=200; c.price=300; c.atk=300; head = &a; a.next = &b; b.next = &c; c.next = NULL; struct weapon *p; p = head; while(p!=NULL) { printf("%d ,%d\n",p->atk,p->price); p=p->next; } return 0; }
Java
UTF-8
294
1.734375
2
[]
no_license
package com.hieudn.mta.repository; import com.hieudn.mta.domain.Authority; import org.springframework.data.jpa.repository.JpaRepository; /** * Spring Data JPA repository for the {@link Authority} entity. */ public interface AuthorityRepository extends JpaRepository<Authority, String> { }
C++
UTF-8
2,768
4.21875
4
[ "MIT" ]
permissive
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; // Arrange given numbers to form the biggest number | Set 1 // Reference Link: https://www.geeksforgeeks.org/given-an-array-of-numbers-arrange-the-numbers-to-form-the-biggest-number/ // http://www.cplusplus.com/reference/algorithm/sort/ // Given an array of numbers, arrange them in a way that yields the largest // value. For example, if the given numbers are {54, 546, 548, 60}, the // arrangement 6054854654 gives the largest value. And if the given numbers are // {1, 34, 3, 98, 9, 76, 45, 4}, then the arrangement 998764543431 gives the largest value. // The idea is to use any comparison based sorting algorithm. In the used // sorting algorithm, instead of using the default comparison, write a // comparison function myCompare() and use it to sort numbers. Given two // numbers X and Y, how should myCompare() decide which number to put first โ€“ // we compare two numbers XY (Y appended at the end of X) and YX (X appended at // the end of Y). If XY is larger, then X should come before Y in output, else // Y should come before. For example, let X and Y be 542 and 60. To compare X // and Y, we compare 54260 and 60542. Since 60542 is greater than 54260, we put // Y first. // A comparison function which is used by sort() in printLargest() int myCompare(string x, string y) { // first append Y at the end of X string xy = x.append(y); // then append X at the end of Y string yx = y.append(x); // Now see which of the two formed numbers is greater return xy.compare(yx) > 0 ? 1 : 0; } // The main function that prints the arrangement with the largest value. // The function accepts a vector of strings void printLargest(vector<string> arr) { // Sort the numbers using library sort funtion. The function uses // our comparison function myCompare() to compare two strings. // See http://www.cplusplus.com/reference/algorithm/sort/ for details sort(arr.begin(), arr.end(), myCompare); for (int i = 0; i < arr.size(); i++) cout << arr[i]; cout << endl; } // driver program to test above functions int main() { vector<string> arr; //output should be 6054854654 arr.push_back("54"); arr.push_back("546"); arr.push_back("548"); arr.push_back("60"); printLargest(arr); vector<string> arr2; // output should be 777776 arr2.push_back("7"); arr2.push_back("776"); arr2.push_back("7"); arr2.push_back("7"); printLargest(arr2); vector<string> arr3; //output should be 998764543431 arr3.push_back("1"); arr3.push_back("34"); arr3.push_back("3"); arr3.push_back("98"); arr3.push_back("9"); arr3.push_back("76"); arr3.push_back("45"); arr3.push_back("4"); printLargest(arr3); return 0; }
Markdown
UTF-8
1,566
2.53125
3
[ "CC0-1.0" ]
permissive
# Dataset language **Purpose**: If the type of the resource is dataset or series, a resource language must be given. **Prerequisites** * [Hierarchy](./hierarchy) **Test method** This test case only applies to records with a [hierarchyLevel](#hierarchyLevel) value 'dataset' or 'series'. The test first checks if a [gmd:LanguageCode](#langcode) object is given and contains a codeList and codeListValue attribute. It is then checked if the codeListValue attribute contains a valid 3-letter language code (one of the values of enumeration type `languageISO6392B` in http://inspire.ec.europa.eu/schemas/common/1.0/common.xsd). **Reference(s)** * [TG MD](./README.md#ref_TG_MD), 2.2.7, Req 8 & 9 * ISO 639-2 **Test type**: Automated **Notes** The ETS does not check if a gmd:LanguageCode contains a codeList attribute, since that is required by the schema. The depencency to [Hierarchy](./hierarchy) has not been implemented in the ETS as it still seems reasonable to test the available dataset (series) metadata records. ##Contextual XPath references The namespace prefixes used as described in [README.md](./README.md#namespaces). Abbreviation | XPath expression (relative to gmd:MD_Metadata) -----------------------------------------------| ------------------------------------------------------------------------- <a name="hierarchyLevel"></a> hierarchyLevel | gmd:hierarchyLevel/gmd:MD_ScopeCode/@codeListValue <a name="langcode"></a> LanguageCode | gmd:identificationInfo[1]/\*/gmd:language/gmd:LanguageCode
Java
UTF-8
4,069
2.609375
3
[]
no_license
package com.shinwootns.common.mq.client; import java.util.ArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.rabbitmq.client.AMQP.Exchange; import com.rabbitmq.client.QueueingConsumer.Delivery; import com.rabbitmq.client.Channel; import com.rabbitmq.client.QueueingConsumer; public class PublishClient extends BaseClient { private final Logger _logger = LoggerFactory.getLogger(getClass()); private String _queueName = null; //region Constructor public PublishClient(Channel channel) { super(channel); } //endregion // Publish Mode //========================================================== // X(Fanout)์— ์˜ํ•ด, ์—ฌ๋Ÿฌ ํ์— ๋ชจ๋‘ ๋™์ผํ•œ ๋ฉ”์‹œ์ง€๊ฐ€ ์‚ฝ์ž… // C1, C2๊ฐ€ ๋ชจ๋‘ ๋™์ผํ•œ ๋ฉ”์‹œ์ง€๋ฅผ ๋ฐ›์ง€๋งŒ, ํ•˜๋Š” ์ผ์€ ๋‹ค๋ฆ„ // // (type=fanout) // [P] ------[X]----[Q1]--- [C1] // | // +-----[Q2]--- [C2] // //region Declare Exchange public boolean DeclareExchange(String exchangeName, boolean durable) { if (_channel == null) return false; try { // durable : exchanges survive broker restart. // autoDelete : exchanges is deleted when all queues have finished using it. // Declare Exchange Exchange.DeclareOk result = _channel.exchangeDeclare(exchangeName, "fanout", durable); return true; } catch(Exception ex) { _logger.error(ex.getMessage(), ex); } return false; } //endregion //region DeclareQueue - Publish Mode public boolean DeclareQueue_PublishMode(String exchangeName) { try { //super.DeclareExchange(exchangeName, "fanout", durable) // Declare Exchange Exchange.DeclareOk exchangeRusult = _channel.exchangeDeclare(exchangeName, "fanout"); // Declare Queue this._queueName = _channel.queueDeclare().getQueue(); // Bind Exchange & Queue _channel.queueBind(_queueName, exchangeName, ""); return true; } catch(Exception ex) { _logger.error(ex.getMessage(), ex); } return false; } //endregion //region get QueueName public String getQueueName() { return this._queueName; } //endregion //region Send Data public boolean SendData(String exchangeName, byte[] bytes) { if (_channel == null) return false; try { _channel.basicPublish(exchangeName, "", null, bytes); return true; } catch(Exception ex) { _logger.error(ex.getMessage(), ex); } return false; } //endregion //region Receive Data public ArrayList<String> ReceiveData(boolean autoAck, int timeout_ms, int popCount, String charset ) { if (_channel == null) return null; if (_consumer == null) _consumer = new QueueingConsumer(_channel); ArrayList<String> listData = new ArrayList<String>(); try { _channel.basicConsume(this._queueName, autoAck, _consumer); long startTime = System.currentTimeMillis(); long estimatedTime = startTime; Delivery delivery; while(true) { // Get Data delivery = _consumer.nextDelivery(timeout_ms); if (delivery != null) { // To String String message = new String(delivery.getBody(), charset); // Add to list listData.add(message); if (autoAck == false) { // Send Ack boolean multiple = false; _channel.basicAck(delivery.getEnvelope().getDeliveryTag(), multiple); } } else { Thread.sleep(100); } estimatedTime = System.currentTimeMillis() - startTime; // Check Pop Count if (popCount > 0 && listData.size() >= popCount) break; // Check Timeout else if (timeout_ms < estimatedTime) break; } } catch(Exception ex) { _logger.error(ex.getMessage(), ex); } return listData; } //endregion }
Python
UTF-8
5,684
2.546875
3
[ "Apache-2.0" ]
permissive
import boto3 import json from datetime import datetime, timedelta from boto3.dynamodb.conditions import Key, Attr # Get the service resource. dynamodb = boto3.resource('dynamodb') #Get Table Objects Child_Table = dynamodb.Table('Child_Tasks') Parent_Table = dynamodb.Table('Parent_Tasks') #Scans Parent Table def AltViewHistory(params): #Get Param daysBack = int(params['DaysBack']) #Denote variables items = [] missed = 0 complete = 0 #Calculate days yest = (datetime.now()-timedelta(days=1)).strftime('%Y%m%d') past = (datetime.now()-timedelta(days=daysBack)).strftime('%Y%m%d') #Scan Parent Table parents = Parent_Table.scan( FilterExpression=Attr('Active').eq(1) )['Items'] #Iterate through Parent Ids for p in parents: #Query Child Table children = Child_Table.query( IndexName= "Parent_Index", KeyConditionExpression= Key('Parent_Id').eq(p['Parent_Id']) & Key('Due_Date').between(past, yest), FilterExpression=Attr('Active').eq(1) )['Items'] #Iterate through children for child in children: #Calculate Date Completed if child['Completed']: completed_on = datetime.fromtimestamp( float(child['Completed_DateTime']) ).strftime('%c') else: completed_on = '' #Determine Task Status if child['Completed'] and child['Late']: status = 'Late' elif child['Completed']: status = 'Complete' complete += 1 else: status = 'Missed' missed += 1 #Add additional fields child['Completed_On'] = completed_on child['Status'] = status #Remove Fields del child['Active'] del child['Late'] del child['Completed'] del child['Completed_DateTime'] #Add task to list items.append(child) #Build result object result = { 'Items': items, 'Missed': missed, 'Complete': complete } return result #Dear Future Capstone Student - Use this if Alt View History # becomes slow. This doesn't rely on scan, so the size of # the database will not affect latency. Speed is only # affected by how many queries you run. I.e the more DaysBack # the more queries will be run. def ViewHistory(params): #Get Param days = int(params['DaysBack']) #Denote variables items = [] missed = 0 complete = 0 #Iterate through tasks for daysBack in range(1, days+1): #Calculate key for due date dueDate = (datetime.now()-timedelta(days=daysBack)).strftime('%Y%m%d') #Get tasks due for calculated due date children = Child_Table.query( KeyConditionExpression= Key('Due_Date').eq(dueDate), FilterExpression=Attr('Active').eq(1) )['Items'] #Iterate through children for child in children: #Calculate Date Completed if child['Completed']: completed_on = datetime.fromtimestamp( float(child['Completed_DateTime']) ).strftime('%c') else: completed_on = '' #Determine Task Status if child['Completed'] and child['Late']: status = 'Late' elif child['Completed']: status = 'Complete' complete += 1 else: status = 'Missed' missed += 1 #Add additional fields child['Completed_On'] = completed_on child['Status'] = status #Remove Fields del child['Active'] del child['Late'] del child['Completed'] del child['Completed_DateTime'] items.append(child) #Build result object result = { 'Items': items, 'Missed': missed, 'Complete': complete } return result def ViewHistoryHandler(event, context): reqParams = ['DaysBack'] #Get Query Params paramVals = event["queryStringParameters"] #Return client error if no string params if (paramVals is None): return{ 'statusCode': 400, 'headers':{ 'Content-Type': 'text/plain' }, 'body': json.dumps({ 'Message' : 'Failed to provide query string parameters.' }) } #Check for each parameter we need for name in reqParams: if (name not in paramVals): return { 'statusCode': 400, 'headers':{ 'Content-Type': 'text/plain' }, 'body': json.dumps({ 'Message' : 'Failed to provide parameter: ' + name }) } try: #Call function result = AltViewHistory(paramVals) #Send Response return { 'statusCode': 200, 'headers':{ 'Content-Type': 'text/plain' }, 'body': json.dumps(result) } except Exception as e: #Return exception with response return { 'statusCode': 500, 'headers':{ 'Content-Type': 'text/plain' }, 'body': json.dumps({ 'Message' : str(e) }) }
Python
UTF-8
1,458
2.703125
3
[]
no_license
#This file for download DisGeNET database with API #build by XiaoyingLv at 2020.9.8 import requests import json import csv import datetime import argparse #get paramter from the external environment def get_parser(): """ Parameters Parser """ parser = argparse.ArgumentParser(description="Using the URL API to store output to csv file") parser.add_argument('-url',type=str,default='&&',help='input your URL') parser.add_argument('-out',type=str,default='test',help='output result to csv file') args = parser.parse_args() return parser def main(args): #disease_name=input("Please input the disease name and We will obtain the UMLS CUI string.") #url='https://www.disgenet.org/api/gda/disease/C2751492?source=ALL&type=disease' #======URL========= url='%s'%args.url #print(url) resp = requests.get(url) data = json.loads(resp.text) #print(data[0]) #=====extract data==== uniprotid_list = [] gene_symbol_list = [] for i in range(len(data)): uniprotid_list.append(data[i].get('uniprotid')) gene_symbol_list.append(data[i].get('gene_symbol')) #==write the time to file name== time = datetime.datetime.now().strftime('%Y_%m_%d') csvfile = open('%s_%s.csv'%(args.out,time),'w') #csvfile = open('test_%s.csv'%time,'w') writer = csv.writer(csvfile) writer.writerows(zip(uniprotid_list,gene_symbol_list)) csvfile.close() if __name__ == '__main__': argparser = get_parser() args = argparser.parse_args() main(args)
C++
UTF-8
332
2.765625
3
[]
no_license
#include"array.h" //Constructor DynamArr::DynamArr(int numOfEntries){ m_numOfEntries = numOfEntries; m_dynArr = new int[m_numOfEntries]; } //Copy Constructor DynamArr::DynamArr(DynamArr &dynamArr){ m_dynArr = new int[m_numOfEntries]; *m_dynArr = *dynamArr.m_dynArr; } //Destructor DynamArr::~DynamArr(){ delete[] m_dynArr; }
Java
UTF-8
1,663
2.75
3
[]
no_license
package com.neo.datamanager; import java.io.*; import java.util.Properties; public class Test { /** * ่ฏปๅ–jarๅŒ…ๅ†…็š„้…็ฝฎๆ–‡ไปถ * @return */ private static Properties getConfigInfoIn() { InputStream is = Test.class.getResourceAsStream("/config2.properties"); Properties prop = new Properties(); try { prop.load(is); } catch (IOException e) { e.printStackTrace(); } return prop; } /** * ่ฏปๅ–jarๅŒ…ๅค–็š„้…็ฝฎๆ–‡ไปถ * @return */ private static Properties getConfigInfoOut() { String filePath = System.getProperty("user.dir") + "\\config3.properties"; System.out.println(filePath); InputStream is = null; Properties prop = new Properties(); try { is = new FileInputStream(filePath); prop.load(is); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return prop; } public void getPath(){ String path = System.getProperty("java.class.path"); int firstIndex = path.lastIndexOf(System.getProperty("path.separator")) + 1; int lastIndex = path.lastIndexOf(File.separator) + 1; path = path.substring(firstIndex, lastIndex); System.out.println(path); } public static void main(String[] args) { // Properties prop = getConfigInfoOut(); // System.out.println(prop.getProperty("user")); // System.out.println(getConfigInfoIn().getProperty("xx")); new Test().getPath(); } }
C#
UTF-8
659
3.046875
3
[]
no_license
๏ปฟusing Curs20.AbstractFactory; using System.Collections.Generic; namespace Curs20.Builder { /// <summary> /// The 'Builder' abstract class /// First version /// </summary> public abstract class AbstractOptionBuilder { protected Car car; protected List<Option> options = new List<Option>(); public abstract void AddSpoiler(); public abstract void AddXenon(); public abstract void AddParkingSensors(); public Car Build() { foreach (var option in options) { car.AddOption(option); } return car; } } }
JavaScript
UTF-8
951
2.796875
3
[]
no_license
$(document).ready(()=>{ setInterval(()=>{ $.get("http://localhost/smartconnect/?reqType=1&reqDevId=1&reqStatusData=0", function(data, status){ if(status === "success"){ showStatus(data); } }); },800); }); function showStatus(readObj){ var bulbObj = '<div class="card"><center><img class="bulb_img" src="img/bulb_off.png" alt="bulb" ><hr /><h3>Socket <span class="sockId"></span></h3></center></div>'; if($(".bulb_img").length> readObj.sockStatus.length) { $(".card").remove(); } for( var i = 0; $(".bulb_img").length < readObj.sockStatus.length; i++) $("#myBlock").append(bulbObj); var bulbs = document.getElementsByClassName("bulb_img"); var socks = document.getElementsByClassName("sockId"); var i=0; readObj.sockStatus.forEach((status)=>{ var myImg = 'img/bulb_off.png'; if(status == 1) myImg = 'img/bulb_on.png'; socks[i].innerText = i+1; bulbs[i++].src= myImg; }); }
Java
UTF-8
758
2.90625
3
[]
no_license
package com.pekey.framework.observer_method.subject; import com.pekey.framework.observer_method.sbserver.Observer; import java.util.Enumeration; import java.util.Vector; public class AbstractSubject implements Subject { private Vector vector = new Vector(); @Override public void add(Observer observer) { vector.add(observer); } @Override public void del(Observer observer) { vector.remove(observer); } @Override public void notifyObservers() { Enumeration enumo = vector.elements(); while(enumo.hasMoreElements()){ Observer observer = (Observer) enumo.nextElement(); observer.update(); } } @Override public void operation() { } }
PHP
UTF-8
15,313
2.53125
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Jtl\Connector\Core\Model; use JMS\Serializer\Annotation as Serializer; /** * A config Item that is displayed in a config Group. * Config item can reference to a specific productId to inherit price, name and description. * * @access public * @package Jtl\Connector\Core\Model * @subpackage Product * @Serializer\AccessType("public_method") */ class ConfigItem extends AbstractIdentity { /** * @var Identity Reference to configGroup * @Serializer\Type("Jtl\Connector\Core\Model\Identity") * @Serializer\SerializedName("configGroupId") * @Serializer\Accessor(getter="getConfigGroupId",setter="setConfigGroupId") */ protected Identity $configGroupId; /** * @var Identity Optional reference to product * @Serializer\Type("Jtl\Connector\Core\Model\Identity") * @Serializer\SerializedName("productId") * @Serializer\Accessor(getter="getProductId",setter="setProductId") */ protected Identity $productId; /** * @var integer Optional:Ignore multiplier. * If true, quantity of config item will not be increased if product quantity is increased * @Serializer\Type("integer") * @Serializer\SerializedName("ignoreMultiplier") * @Serializer\Accessor(getter="getIgnoreMultiplier",setter="setIgnoreMultiplier") */ protected int $ignoreMultiplier = 0; /** * @var boolean Optional: Inherit product name and description if productId is set. * If true, configItem name will be received from referenced * product and configItemI18n name will be ignored. * @Serializer\Type("boolean") * @Serializer\SerializedName("inheritProductName") * @Serializer\Accessor(getter="getInheritProductName",setter="setInheritProductName") */ protected bool $inheritProductName = false; /** * @var boolean Optional: Inherit product price of referenced productId. * If true, configItem price will be the same as referenced product price. * @Serializer\Type("boolean") * @Serializer\SerializedName("inheritProductPrice") * @Serializer\Accessor(getter="getInheritProductPrice",setter="setInheritProductPrice") */ protected bool $inheritProductPrice = false; /** * @var double Optional initial / predefined quantity. Default is one (1) quantity piece. * @Serializer\Type("double") * @Serializer\SerializedName("initialQuantity") * @Serializer\Accessor(getter="getInitialQuantity",setter="setInitialQuantity") */ protected float $initialQuantity = 0.0; /** * @var boolean Optional: Preselect configItem. If true, configItem will be preselected or prechecked. * @Serializer\Type("boolean") * @Serializer\SerializedName("isPreSelected") * @Serializer\Accessor(getter="getIsPreSelected",setter="setIsPreSelected") */ protected bool $isPreSelected = false; /** * @var boolean Optional: Highlight or recommend config item. If true, configItem will be recommended/highlighted. * @Serializer\Type("boolean") * @Serializer\SerializedName("isRecommended") * @Serializer\Accessor(getter="getIsRecommended",setter="setIsRecommended") */ protected bool $isRecommended = false; /** * @var double Maximum allowed quantity. Default 0 for no maximum limit. * @Serializer\Type("double") * @Serializer\SerializedName("maxQuantity") * @Serializer\Accessor(getter="getMaxQuantity",setter="setMaxQuantity") */ protected float $maxQuantity = 0.0; /** * @var double Optional minimum quantity required to add configItem. Default 0 for no minimum quantity. * @Serializer\Type("double") * @Serializer\SerializedName("minQuantity") * @Serializer\Accessor(getter="getMinQuantity",setter="setMinQuantity") */ protected float $minQuantity = 0.0; /** * @var boolean Optional: Show discount compared to productId price. * If true, the discount compared to referenct product price will be shown. * @Serializer\Type("boolean") * @Serializer\SerializedName("showDiscount") * @Serializer\Accessor(getter="getShowDiscount",setter="setShowDiscount") */ protected bool $showDiscount = false; /** * @var boolean Optional: Show surcharge compared to productId price. * @Serializer\Type("boolean") * @Serializer\SerializedName("showSurcharge") * @Serializer\Accessor(getter="getShowSurcharge",setter="setShowSurcharge") */ protected bool $showSurcharge = false; /** * @var integer Optional sort order number * @Serializer\Type("integer") * @Serializer\SerializedName("sort") * @Serializer\Accessor(getter="getSort",setter="setSort") */ protected int $sort = 0; /** * @var integer Config item type. 0: Product, 1: Special * @Serializer\Type("integer") * @Serializer\SerializedName("type") * @Serializer\Accessor(getter="getType",setter="setType") */ protected int $type = 0; /** * @var ConfigItemI18n[] * @Serializer\Type("array<Jtl\Connector\Core\Model\ConfigItemI18n>") * @Serializer\SerializedName("i18ns") * @Serializer\AccessType("reflection") */ protected array $i18ns = []; /** * @var ConfigItemPrice[] * @Serializer\Type("array<Jtl\Connector\Core\Model\ConfigItemPrice>") * @Serializer\SerializedName("prices") * @Serializer\AccessType("reflection") */ protected array $prices = []; /** * Constructor. * * @param string $endpoint * @param int $host */ public function __construct(string $endpoint = '', int $host = 0) { parent::__construct($endpoint, $host); $this->configGroupId = new Identity(); $this->productId = new Identity(); } /** * @return Identity Reference to configGroup */ public function getConfigGroupId(): Identity { return $this->configGroupId; } /** * @param Identity $configGroupId Reference to configGroup * * @return ConfigItem */ public function setConfigGroupId(Identity $configGroupId): ConfigItem { $this->configGroupId = $configGroupId; return $this; } /** * @return Identity Optional reference to product */ public function getProductId(): Identity { return $this->productId; } /** * @param Identity $productId Optional reference to product * * @return ConfigItem */ public function setProductId(Identity $productId): ConfigItem { $this->productId = $productId; return $this; } /** * @return integer Optional:Ignore multiplier. * If true, quantity of config item will not be increased if product quantity is increased */ public function getIgnoreMultiplier(): int { return $this->ignoreMultiplier; } /** * @param integer $ignoreMultiplier Optional:Ignore multiplier. * If true, quantity of config item will not be increased * if product quantity is increased * * @return ConfigItem */ public function setIgnoreMultiplier(int $ignoreMultiplier): ConfigItem { $this->ignoreMultiplier = $ignoreMultiplier; return $this; } /** * @return boolean Optional: Inherit product name and description if productId is set. * If true, configItem name will be received from referenced product * and configItemI18n name will be ignored. */ public function getInheritProductName(): bool { return $this->inheritProductName; } /** * @param boolean $inheritProductName Optional: Inherit product name and description if productId is set. * If true, configItem name will be received from referenced product and * configItemI18n name will be ignored. * * @return ConfigItem */ public function setInheritProductName(bool $inheritProductName): ConfigItem { $this->inheritProductName = $inheritProductName; return $this; } /** * @return boolean Optional: Inherit product price of referenced productId. * If true, configItem price will be the same as referenced product price. */ public function getInheritProductPrice(): bool { return $this->inheritProductPrice; } /** * @param boolean $inheritProductPrice Optional: Inherit product price of referenced productId. * If true, configItem price will be the same as referenced product price. * * @return ConfigItem */ public function setInheritProductPrice(bool $inheritProductPrice): ConfigItem { $this->inheritProductPrice = $inheritProductPrice; return $this; } /** * @return double Optional initial / predefined quantity. Default is one (1) quantity piece. */ public function getInitialQuantity(): float { return $this->initialQuantity; } /** * @param double $initialQuantity Optional initial / predefined quantity. Default is one (1) quantity piece. * * @return ConfigItem */ public function setInitialQuantity(float $initialQuantity): ConfigItem { $this->initialQuantity = $initialQuantity; return $this; } /** * @return boolean Optional: Preselect configItem. If true, configItem will be preselected or prechecked. */ public function getIsPreSelected(): bool { return $this->isPreSelected; } /** * @param boolean $isPreSelected Optional: Preselect configItem. * If true, configItem will be preselected or prechecked. * * @return ConfigItem */ public function setIsPreSelected(bool $isPreSelected): ConfigItem { $this->isPreSelected = $isPreSelected; return $this; } /** * @return boolean Optional: Highlight or recommend config item. * If true, configItem will be recommended/highlighted. */ public function getIsRecommended(): bool { return $this->isRecommended; } /** * @param boolean $isRecommended Optional: Highlight or recommend config item. * If true, configItem will be recommended/highlighted. * * @return ConfigItem */ public function setIsRecommended(bool $isRecommended): ConfigItem { $this->isRecommended = $isRecommended; return $this; } /** * @return double Maximum allowed quantity. Default 0 for no maximum limit. */ public function getMaxQuantity(): float { return $this->maxQuantity; } /** * @param double $maxQuantity Maximum allowed quantity. Default 0 for no maximum limit. * * @return ConfigItem */ public function setMaxQuantity(float $maxQuantity): ConfigItem { $this->maxQuantity = $maxQuantity; return $this; } /** * @return double Optional minimum quantity required to add configItem. Default 0 for no minimum quantity. */ public function getMinQuantity(): float { return $this->minQuantity; } /** * @param double $minQuantity Optional minimum quantity required to add configItem. * Default 0 for no minimum quantity. * * @return ConfigItem */ public function setMinQuantity(float $minQuantity): ConfigItem { $this->minQuantity = $minQuantity; return $this; } /** * @return boolean Optional: Show discount compared to productId price. * If true, the discount compared to referenct product price will be shown. */ public function getShowDiscount(): bool { return $this->showDiscount; } /** * @param boolean $showDiscount Optional: Show discount compared to productId price. * If true, the discount compared to referenct product price will be shown. * * @return ConfigItem */ public function setShowDiscount(bool $showDiscount): ConfigItem { $this->showDiscount = $showDiscount; return $this; } /** * @return boolean Optional: Show surcharge compared to productId price. */ public function getShowSurcharge(): bool { return $this->showSurcharge; } /** * @param boolean $showSurcharge Optional: Show surcharge compared to productId price. * * @return ConfigItem */ public function setShowSurcharge(bool $showSurcharge): ConfigItem { $this->showSurcharge = $showSurcharge; return $this; } /** * @return integer Optional sort order number */ public function getSort(): int { return $this->sort; } /** * @param integer $sort Optional sort order number * * @return ConfigItem */ public function setSort(int $sort): ConfigItem { $this->sort = $sort; return $this; } /** * @return integer Config item type. 0: Product, 1: Special */ public function getType(): int { return $this->type; } /** * @param integer $type Config item type. 0: Product, 1: Special * * @return ConfigItem */ public function setType(int $type): ConfigItem { $this->type = $type; return $this; } /** * @param ConfigItemI18n $i18n * * @return ConfigItem */ public function addI18n(ConfigItemI18n $i18n): ConfigItem { $this->i18ns[] = $i18n; return $this; } /** * @return ConfigItemI18n[] */ public function getI18ns(): array { return $this->i18ns; } /** * @param ConfigItemI18n ...$i18ns * * @return ConfigItem */ public function setI18ns(ConfigItemI18n ...$i18ns): ConfigItem { $this->i18ns = $i18ns; return $this; } /** * @return ConfigItem */ public function clearI18ns(): ConfigItem { $this->i18ns = []; return $this; } /** * @param ConfigItemPrice $price * * @return ConfigItem */ public function addPrice(ConfigItemPrice $price): ConfigItem { $this->prices[] = $price; return $this; } /** * @return ConfigItemPrice[] */ public function getPrices(): array { return $this->prices; } /** * @param ConfigItemPrice ...$prices * * @return ConfigItem */ public function setPrices(ConfigItemPrice ...$prices): ConfigItem { $this->prices = $prices; return $this; } /** * @return ConfigItem */ public function clearPrices(): ConfigItem { $this->prices = []; return $this; } }
JavaScript
UTF-8
779
2.546875
3
[]
no_license
import {actionTypes} from '../ActionTypes/registration'; export const initialState = { pending: false, info: {}, error: null } export function registrationReducer(state = initialState, action) { switch(action.type) { case actionTypes.REGISTRATION_PENDING: return { ...state, pending: true } case actionTypes.REGISTRATION_SUCCESS: return { ...state, pending: false, info: action.payload } case actionTypes.REGISTRATION_ERROR: return { ...state, pending: false, error: action.payload } default: return state; } }
Java
UTF-8
3,767
2.5625
3
[ "MIT" ]
permissive
package main.java.expr; import java.util.HashMap; import java.util.Objects; import main.java.data.D_Binding; import main.java.data.D_List; import main.java.data.D_Set; import main.java.data.Obj; import main.java.evaluator.Evaluator; import main.java.evaluator.TypeCheck; import main.java.expr.contin.C_ApplyInfixOp; import main.java.show.Show; public class E_InfixExpr extends Obj { // Static variables =============================================== private static E_Identifier _DOUBLECOLON = E_Identifier.create("::"); private static HashMap<String, Integer> _PREC = new HashMap<>(); static { _PREC.put(".", 5); _PREC.put(":", 5); _PREC.put("^", 4); _PREC.put("*", 3); _PREC.put("/", 3); _PREC.put("%", 3); _PREC.put("+", 2); _PREC.put("-", 2); _PREC.put("::", 2); _PREC.put(":>", 2); _PREC.put(":?", 2); _PREC.put("++", 2); //_PREC.put("+++", 2); _PREC.put("..", 2); _PREC.put(":=", 1); _PREC.put("=~", 1); _PREC.put("==", 1); _PREC.put("!=", 1); _PREC.put("<", 1); _PREC.put(">", 1); _PREC.put("<=", 1); _PREC.put(">=", 1); //_PREC.put("##", 1); _PREC.put("//", 1); _PREC.put("in", 1); _PREC.put("is", 1); _PREC.put("isnot", 1); _PREC.put("and", 1); _PREC.put("or", 1); _PREC.put("xor", 1); } // Instance variables ============================================= private Obj _lhs, _rhs; private E_Identifier _oper; // Static methods ================================================= public static E_InfixExpr create(Obj lhs, E_Identifier oper, Obj rhs) { return new E_InfixExpr(lhs, oper, rhs); } // Constructors =================================================== private E_InfixExpr(Obj lhs, E_Identifier oper, Obj rhs) { _lhs = lhs; _oper = oper; _rhs = rhs; } // Instance methods =============================================== @Override public void eval(Evaluator etor) { etor.pushExpr(new C_ApplyInfixOp(_lhs, _rhs)); etor.pushExpr(_oper); } @Override public void freeVars(D_Set vars) { _lhs.freeVars(vars); _oper.freeVars(vars); _rhs.freeVars(vars); } public Obj getLhs() { return _lhs; } public E_Identifier getOper() { return _oper; } public Obj getRhs() { return _rhs; } @Override public int hashCode() { return Objects.hash(E_InfixExpr.class, _lhs, _oper, _rhs); } /** * This is used during checking of a typed function parameter. */ @Override public D_List match(Obj obj, D_List bindings) { if(_oper == _DOUBLECOLON) { if(TypeCheck.hasType(obj, _rhs)) { D_Binding binding = D_Binding.create(_lhs, obj); return D_List.create(binding, bindings); } } return null; } @Override public void show(StringBuilder sb) { if(_lhs instanceof E_InfixExpr) { E_InfixExpr lhsOper = (E_InfixExpr)_lhs; int thisPrecedence = _PREC.get(_oper.toString()); int lhsPrecedence = _PREC.get(lhsOper._oper.toString()); if(lhsPrecedence <= thisPrecedence) Show.show(sb, '(', _lhs, ')'); else Show.show(sb, _lhs); } else Show.show(sb, _lhs); String operStr = _oper.toString(); if(operStr.equals(".") || operStr.equals(":")) Show.show(sb, operStr); else Show.show(sb, ' ', operStr, ' '); if(_rhs instanceof E_InfixExpr) { E_InfixExpr rhsOper = (E_InfixExpr)_rhs; int thisPrecedence = _PREC.get(_oper.toString()); int rhsPrecedence = _PREC.get(rhsOper._oper.toString()); if(rhsPrecedence <= thisPrecedence) Show.show(sb, '(', _rhs, ')'); else Show.show(sb, _rhs); } else Show.show(sb, _rhs); } }
JavaScript
UTF-8
3,200
2.984375
3
[ "Unlicense" ]
permissive
// TODO: // 1. Handle depths // 2. Handle areafill // 3. Handle all types and subtypes // 4. Handle penstyle // 5. Handle style // 6. Handle diffs // 7. Build display list sorted by depth var scale = 0.2; var x1 = 0; var y1 = 0; var display_list = []; function trans_x(p) { return (p - x1) * scale; } function trans_y(p) { return (p - y1) * scale; } function render_compound(ctx, obj) { render_element_list(ctx, obj.objects); } function render_polyline(ctx, obj) { ctx.lineWidth = obj.thickness; ctx.lineJoin = obj.joinstyle; ctx.lineCap = obj.capstyle; if (obj.subtype === "box") { obj_x = trans_x(obj.points[0][0]); obj_y = trans_y(obj.points[0][1]); obj_w = trans_x(obj.points[2][0]) - obj_x; obj_h = trans_y(obj.points[2][1]) - obj_y; if (obj.areafill == 20) { ctx.fillStyle = obj.fillcolor; ctx.fillRect(obj_x, obj_y, obj_w, obj_h); } if (obj.penstyle === -1) { ctx.strokeStyle = obj.pencolor; ctx.strokeRect(obj_x, obj_y, obj_w, obj_h); } } else if (obj.subtype === "polyline") { for (i in obj.points) { if (i == 0) { ctx.moveTo(trans_x(obj.points[i][0]), trans_y(obj.points[i][1])); } else { ctx.lineTo(trans_x(obj.points[i][0]), trans_y(obj.points[i][1])); } } if (obj.areafill == 20) { ctx.fillStyle = obj.fillcolor; ctx.fill(); } if (obj.penstyle === -1) { ctx.strokeStyle = obj.pencolor; ctx.stroke(); } } else if (obj.subtype === "arc-box") { obj_x = trans_x(obj.points[0][0]); obj_y = trans_y(obj.points[0][1]); obj_w = trans_x(obj.points[2][0]) - obj_x; obj_h = trans_y(obj.points[2][1]) - obj_y; ctx.beginPath(); ctx.moveTo(obj_x - obj.radius, obj_y); ctx.lineTo(obj_x + obj.radius + obj_w + obj.radius, obj_y); // ctx.arcTo(obj_x + obj.radius + obj_w ctx.closePath(); if (obj.areafill == 20) { ctx.fillStyle = obj.fillcolor; ctx.fill(); } if (obj.penstyle === -1) { ctx.strokeStyle = obj.pencolor; ctx.stroke(); } } else { } } function render_element_list(ctx, l) { l1 = create_display_list(l); for (i in l1) { obj = l1[i]; if (obj.type === "compound") { render_compound(ctx, obj); } else if (obj.type === "polyline") { render_polyline(ctx, obj); } else { } } } function flatten_element_list(l) { if (l.length == 0) { return []; } else if (l.length == 1) { if (l[0].type === "compound") { return flatten_element_list(l[0].objects); } else { return [l[0]]; } } else { if (l[0].type === "compound") { return flatten_element_list(l[0].objects).concat( flatten_element_list(l.slice(1))); } else { return [l[0]].concat(flatten_element_list(l.slice(1))); } } } function create_display_list(l) { l1 = flatten_element_list(l); l1.sort(function(a, b) { return b.depth - a.depth; }); return l1; } window.onload = function() { var canvas = document.getElementById("machine_canvas"); var ctx = canvas.getContext("2d"); x1 = machine.x1; y1 = machine.y1; canvas.width = (machine.x2 - x1) * scale; canvas.height = (machine.y2 - y1) * scale; render_element_list(ctx, machine.objects); }
Python
UTF-8
9,266
3.046875
3
[ "MIT" ]
permissive
"""Analog log report object.""" from __future__ import (absolute_import, division, print_function, unicode_literals) from collections import Counter, defaultdict, OrderedDict import time from analog.renderers import Renderer from analog.utils import PrefixMatchingCounter try: from statistics import mean, median except ImportError: from analog.statistics import mean, median from analog import LOG class ListStats(object): """Statistic analysis of a list of values. Provides the mean, median and 90th, 75th and 25th percentiles. """ def __init__(self, elements): """Calculate some stats from list of values. :param elements: list of values. :type elements: ``list`` """ self.mean = mean(elements) if elements else None self.median = median(elements) if elements else None class Report(object): """Log analysis report object. Provides these statistical metrics: * Number for requests. * Response request method (HTTP verb) distribution. * Response status code distribution. * Requests per path. * Response time statistics (mean, median). * Response upstream time statistics (mean, median). * Response body size in bytes statistics (mean, median). * Per path request method (HTTP verb) distribution. * Per path response status code distribution. * Per path response time statistics (mean, median). * Per path response upstream time statistics (mean, median). * Per path response body size in bytes statistics (mean, median). """ def __init__(self, verbs, status_codes): """Create new log report object. Use ``add()`` method to add log entries to be analyzed. :param verbs: HTTP verbs to be tracked. :type verbs: ``list`` :param status_codes: status_codes to be tracked. May be prefixes, e.g. ["100", "2", "3", "4", "404" ] :type status_codes: ``list`` :returns: Report analysis object :rtype: :py:class:`analog.report.Report` """ def verb_counter(): return Counter({verb: 0 for verb in verbs}) def status_counter(): return PrefixMatchingCounter( {str(code): 0 for code in status_codes}) self._start_time = time.clock() self.execution_time = None self.requests = 0 self._verbs = verb_counter() self._status = status_counter() self._times = [] self._upstream_times = [] self._body_bytes = [] self._path_requests = Counter() self._path_verbs = defaultdict(verb_counter) self._path_status = defaultdict(status_counter) self._path_times = defaultdict(list) self._path_upstream_times = defaultdict(list) self._path_body_bytes = defaultdict(list) def finish(self): """Stop execution timer.""" end_time = time.clock() self.execution_time = end_time - self._start_time def add(self, path, verb, status, time, upstream_time, body_bytes): """Add a log entry to the report. Any request with ``verb`` not matching any of ``self._verbs`` or ``status`` not matching any of ``self._status`` is ignored. :param path: monitored request path. :type path: ``str`` :param verb: HTTP method (GET, POST, ...) :type verb: ``str`` :param status: response status code. :type status: ``int`` :param time: response time in seconds. :type time: ``float`` :param upstream_time: upstream response time in seconds. :type upstream_time: ``float`` :param body_bytes: response body size in bytes. :type body_bytes: ``float`` """ # Only keep entries with verbs/status codes that are being tracked if verb not in self._verbs or self._status.match(status) is None: LOG.debug("Ignoring log entry for non-tracked verb ({verb}) or " "status code ({status!s}).".format(verb=verb, status=status)) return self.requests += 1 self._verbs[verb] += 1 self._status.inc(str(status)) self._times.append(time) self._upstream_times.append(upstream_time) self._body_bytes.append(body_bytes) self._path_requests[path] += 1 self._path_verbs[path][verb] += 1 self._path_status[path].inc(status) self._path_times[path].append(time) self._path_upstream_times[path].append(upstream_time) self._path_body_bytes[path].append(body_bytes) @property def verbs(self): """List request methods of all matched requests, ordered by frequency. :returns: tuples of HTTP verb and occurrency count. :rtype: ``list`` of ``tuple`` """ return self._verbs.most_common() @property def status(self): """List status codes of all matched requests, ordered by frequency. :returns: tuples of status code and occurrency count. :rtype: ``list`` of ``tuple`` """ return self._status.most_common() @property def times(self): """Response time statistics of all matched requests. :returns: response time statistics. :rtype: :py:class:`analog.report.ListStats` """ return ListStats(self._times) @property def upstream_times(self): """Response upstream time statistics of all matched requests. :returns: response upstream time statistics. :rtype: :py:class:`analog.report.ListStats` """ return ListStats(self._upstream_times) @property def body_bytes(self): """Response body size in bytes of all matched requests. :returns: response body size statistics. :rtype: :py:class:`analog.report.ListStats` """ return ListStats(self._body_bytes) @property def path_requests(self): """List paths of all matched requests, ordered by frequency. :returns: tuples of path and occurrency count. :rtype: ``list`` of ``tuple`` """ return self._path_requests.most_common() @property def path_verbs(self): """List request methods (HTTP verbs) of all matched requests per path. Verbs are grouped by path and ordered by frequency. :returns: path mapping of tuples of verb and occurrency count. :rtype: ``dict`` of ``list`` of ``tuple`` """ return OrderedDict( sorted(((path, counter.most_common()) for path, counter in self._path_verbs.items()), key=lambda item: item[0])) @property def path_status(self): """List status codes of all matched requests per path. Status codes are grouped by path and ordered by frequency. :returns: path mapping of tuples of status code and occurrency count. :rtype: ``dict`` of ``list`` of ``tuple`` """ return OrderedDict( sorted(((path, counter.most_common()) for path, counter in self._path_status.items()), key=lambda item: item[0])) @property def path_times(self): """Response time statistics of all matched requests per path. :returns: path mapping of response time statistics. :rtype: ``dict`` of :py:class:`analog.report.ListStats` """ return OrderedDict( sorted(((path, ListStats(values)) for path, values in self._path_times.items()), key=lambda item: item[0])) @property def path_upstream_times(self): """Response upstream time statistics of all matched requests per path. :returns: path mapping of response upstream time statistics. :rtype: ``dict`` of :py:class:`analog.report.ListStats` """ return OrderedDict( sorted(((path, ListStats(values)) for path, values in self._path_upstream_times.items()), key=lambda item: item[0])) @property def path_body_bytes(self): """Response body size in bytes of all matched requests per path. :returns: path mapping of body size statistics. :rtype: ``dict`` of :py:class:`analog.report.ListStats` """ return OrderedDict( sorted(((path, ListStats(values)) for path, values in self._path_body_bytes.items()), key=lambda item: item[0])) def render(self, path_stats, output_format): """Render report data into ``output_format``. :param path_stats: include per path statistics in output. :type path_stats: ``bool`` :param output_format: name of report renderer. :type output_format: ``str`` :raises: :py:class:`analog.exceptions.UnknownRendererError` or unknown ``output_format`` identifiers. :returns: rendered report data. :rtype: ``str`` """ renderer = Renderer.by_name(name=output_format) return renderer.render(self, path_stats=path_stats)
C#
UTF-8
1,062
3.984375
4
[]
no_license
๏ปฟusing System; namespace MathLibrary { public class MathRoutines { public static decimal Add(decimal num1, decimal num2) { return Math.Round((num1 + num2), 2); } public static decimal Subtract(decimal num1, decimal num2) { return Math.Round((num1 - num2), 2); } public static decimal Multiply(decimal num1, decimal num2) { return Math.Round((num1 * num2), 2); } public static decimal Divide(decimal num1, decimal num2) { return Math.Round((num1 / num2), 2); } public static double Power(double num1, double num2) { return Math.Round((Math.Pow(num1, num2)), 2); } public static decimal Ceiling(decimal num1) { return Math.Round((Math.Ceiling(num1)), 2); } public static decimal Floor(decimal num1) { return Math.Round((Math.Floor(num1)), 2); } } }
TypeScript
UTF-8
202
2.53125
3
[ "MIT" ]
permissive
๏ปฟexport abstract class VirtualComponent { protected _root: HTMLElement; get root() { return this._root; } constructor(root?: HTMLElement) { this._root = root; } }
Python
UTF-8
3,521
2.96875
3
[ "MIT" ]
permissive
import constants as c import utils.misc as misc from utils.misc import log_print def build_semantic_graphs(dependency_graphs, disambiguations): """ Transform each pair of dependency parsed sentence-disambiguated sentence into a syntactis-semantic graph. :param dependency_graphs: a spaCy dependency parsed sentence :param disambiguations: a list of Disambiguation objects :return: """ semantic_graphs = [] for Gd, Sd in zip(dependency_graphs, disambiguations): cur_semantic_graph, _= build_one_semantic_graph(Gd, Sd) semantic_graphs.append(cur_semantic_graph) return dependency_graphs def build_one_semantic_graph(Gd, Sd): """ :param Gd: Dependency parsed sentence (through spaCy). The method does side-effect on this variable. :param Sd: list of Disambiguation objects, one per word. :return: A tuple of two elements: 0 - the same dependency parsed sentence, but with the nodes merged by following the disambiguations 1 - a mapping from indexes of the tags in the new parsed sentence to concepts. """ cur_Gd = Gd tokenIndex2concept_mapping = {} temp = cur_Gd.root sentence = list(Gd) if len(sentence)!=len(Sd): merge_unfolded_nodes_from_tokenization(Gd, Sd) assert(len(list(Gd))==len(Sd)) # misc.to_nltk_tree(Gd.root).pretty_print() lost_positions = 0 tot_lost_positions = 0 cur_index=0 # merge nodes that belongs to the same super-concept # through the spaCy API (the "merge" function) for i, disambiguation in enumerate(Sd): if (lost_positions>0): lost_positions-=1 continue word = disambiguation.word concept = disambiguation.concept cur_index = i-tot_lost_positions tokenIndex2concept_mapping[cur_index] = concept concept_mention = concept.mention concept_mention_length = len(concept_mention.split()) cur_span = Gd[cur_index: cur_index + concept_mention_length] if not concept.isNullConcept(): # If there is some subject or object in the element of the merge, # Preserve it in the final merged node if any(t.dep_ in c.SPECIAL_DEP_TAGS for t in cur_span): if any(t.dep_ in c.SUBJ_DEPTAGS for t in cur_span): cur_dep_ = c.NSUBJ_DEPTAG elif any(t.dep_ in c.OBJ_DEPTAGS for t in cur_span): cur_dep_ = c.POBJ_DEPTAG else: Exception("Misconfiguration: SPECIAL_DEP_TAGS is either in SUBJ_DEPTAGS or in OBJ_DEPTAGS") cur_span.merge(ent_id_=concept.babelNetID, dep_=cur_dep_) # Otherwise, let spaCy do the job of choose the appropriate dependency tag else: cur_span.merge(ent_id_=concept.babelNetID) lost_positions = concept_mention_length-1 tot_lost_positions += lost_positions else: Gd[cur_index].ent_id_ = concept.babelNetID return Gd, tokenIndex2concept_mapping def merge_unfolded_nodes_from_tokenization(Gd, Sd): """ Fix some misalignment between the syntactic graph (Gd) and the disambiguation mapping (Sd) (a list of Disambiguation) for example: words as "mother-in-law" are parsed differently between the spaCY parser and the format provided by the corpus. """ cur_index = 0 lost_positions = 0 tot_lost_positions = 0 cur_word = "" for i in range(len(Gd)): cur_token = Gd[i-tot_lost_positions] cur_word += cur_token.text cur_mapped_word = Sd[cur_index].word if cur_word == cur_mapped_word: merged_node = Gd[cur_index: cur_index+1+lost_positions] if len(merged_node)!=1: merged_node.merge() tot_lost_positions+=lost_positions lost_positions = 0 cur_index += 1 cur_word = "" else: lost_positions += 1 assert cur_word == ""
C++
UTF-8
718
2.96875
3
[]
no_license
#include <iostream> #include <cstdio> #include <stdlib.h> #include <algorithm> using namespace std; typedef struct Activity { int begin_; int end_; bool operator <( const Activity b) const { return end_ < b.end_; } }; int main() { int n,len,ans,temp; Activity activities[1001]; cin >> n; len = n; ans = 1; while(n--) { cin >> activities[n].begin_ >> activities[n].end_; } sort(activities, activities + len); temp = activities[0].end_; for(int i = 1; i < len; i++) { if(activities[i].begin_ >= temp) { ans++; temp = activities[i].end_; } } cout << ans << endl; return 0; }
JavaScript
UTF-8
1,190
2.5625
3
[]
no_license
import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import MyButton from './component/myButton' import List from './component/List' import Input from './component/Input' export default class App extends React.Component { state = { myState: 'Lorem ipsum dolor sit amet' } updateState = () => { this.setState({ myState: 'The state is updated' }) } render() { return ( <View style={styles.container}> <View style={styles.redbox} /> <View style={styles.bluebox} /> <View style={styles.blackbox} /> <MyButton myState={this.state.myState} updateState={this.updateState} /> <List /> <View style={styles.container}> <Input /> </View> </View> ); } } const styles = StyleSheet.create({ container: { flexDirection: 'column', justifyContent: 'center', alignItems: 'center', backgroundColor: 'grey', }, redbox: { width: 100, height: 100, backgroundColor: 'red' }, bluebox: { width: 100, height: 100, backgroundColor: 'blue' }, blackbox: { width: 100, height: 100, backgroundColor: 'black' }, });
Java
UTF-8
757
2.890625
3
[]
no_license
package org.crazystudios.input; import org.crazystudios.graphics.Images; import org.crazystudios.graphics.Screen; public class Button { private final transient Images imageb; private final transient Images simageb; public transient int x, y; public transient boolean hovered; public Button(final Images imageb, final Images simageb , final int x, final int y) { this.imageb = imageb; this.simageb = simageb; this.x = x; this.y = y; this.hovered = false; } public boolean pressed (final Keyboard keyboard) { return keyboard.select && hovered ? true : false; } public void render(final Screen screen) { if (hovered) { screen.blit(simageb, this.x, this.y); } else { screen.blit(imageb, this.x, this.y); } } }
Python
UTF-8
169
3.625
4
[]
no_license
import datetime d1 = datetime.date.today() print(d1) # ๆ˜จๅคฉ d2 = d1 - datetime.timedelta(days=1) print(d2) # 7ๅคฉๅŽ d3 = d1 + datetime.timedelta(days=7) print(d3)
Markdown
UTF-8
5,611
2.65625
3
[ "MIT" ]
permissive
--- layout: page title: Welcome to CrossVillage image: feature: abstract-5.jpg comments: false --- > CrossVillage is a side event of CrossCTF 2018 where we invited three speakers to give talks on **17th June 2018**. More details on the talks can be found below. --- ## Overview **Anyone** is welcomed to register for CrossVillage. You can register here: <a href="https://goo.gl/forms/20k5mPlGrlH9eBU03" target="_blank">https://goo.gl/forms/20k5mPlGrlH9eBU03</a> <br/><br/> Here are a list of the topics for the talks. More information can be found below. - E2EE Fuzzing for Mobile Applications - Introduction to Lockpicking - Mobile App Analysis <br/> <table> <tr> <td><b>Information</b></td> <td>&nbsp;</td> </tr> <tr> <td>Date/Time:</td> <td>17th June 2018, 9am - 4.30pm</td> </tr> <tr> <td>Location:</td> <td>#03-01, 79 Ayer Rajah Crescent, Singapore 139955 (Please take LIFT 3 to go up)<br/>SgInnovateโ€™s BASH @ One-north</td> </tr> </table> <br/> <img src="../images/map.png"/> <br/> There will be attractive prizes to be won from the **lucky draw** at the end of CrossVillage. <br/> **Pizzas** will be provided for lunch and below is the schedule for CrossVillage on the day. <br/> <table> <tr> <td>Time</td> <td>Event</td> </tr> <tr> <td>9:00am</td> <td>Registration/Sign in</td> </tr> <tr> <td>10:00am</td> <td>Talk 1</td> </tr> <tr> <td>11:00am</td> <td>Talk 2</td> </tr> <tr> <td>12:00pm</td> <td>Break for lunch</td> </tr> <tr> <td>1:30pm</td> <td>Mid-day keynote speech</td> </tr> <tr> <td>2:00pm</td> <td>Talk 3</td> </tr> <tr> <td>3:00pm</td> <td>Closing keynote speech</td> </tr> <tr> <td>3:30pm</td> <td>Award Ceremony for Crossctf 2018 / Lucky draw ceremony</td> </tr> <tr> <td>4:30pm</td> <td>End of event/Tea break/Networking</td> </tr> </table> <br/><br/> Here are a list of the topics for the talks. More information can be found below. - E2EE Fuzzing for Mobile Applications - Introduction to Lockpicking - Mobile App Analysis <br><br> --- ### Talk 1: E2EE Fuzzing for Mobile Applications <table> <tr> <td>Speaker Name:<br/><br/></td> <td valign="top" >Sayed Hamzah</td> </tr> <tr> <td valign="top" >Speaker Bio:</td> <td>Currently working as a Security Consultant in Centurion Information Security, Hamzah has a vast amount experience in the areas of penetration testing for mobile/web applications and enterprise network infrastructures. His skillset is further complimented with his acquisition of Offensive Security certifications (OSCP, OSCE) and CREST Registered Tester (CRT) certifications. In addition, Hamzah has been actively involved in the establishment of the Offensive Cyber Security Club in Nanyang Technological University, providing training for club members who have a keen interest in vulnerability assessment and penetration testing as a career in the future.<br/><br/></td> </tr> <tr> <td valign="top" >Company:</td> <td><img src="/images/Centurion_logo.png" height="400" width="400" /><br/><br/></td> </tr> <tr> <td valign="top" >Description:</td> <td>End-to-end encryption, or E2EE in short, involves encrypting data on the mobile application before it gets sent to the application server. This is mainly to prevent any attackers to tamper or inject malicious payloads while the data is in transit, in the event of a man-in-the-middle attack. However, that does not mean that the application server is safe from such attacks even if E2EE is implemented.</td> </tr> </table> --- ### Talk 2: Introduction to Lockpicking <table> <tr> <td>Speaker Name:<br/><br/></td> <td valign="top" >Fazli Sapuan</td> </tr> <tr> <td valign="top" >Speaker Bio:</td> <td>Locksmiths hate him. Check out this one weird trick he once saw someone on YouTube use to defeat a lock 9 out of 10 experts thought was adequately secure.<br/><br/></td> </tr> <tr> <td valign="top" >Company:</td> <td>N/A<br/><br/></td> </tr> <tr> <td valign="top" >Description:</td> <td>Physical locks are an important aspect of operations security that is often overlooked. In order to properly assess the amount of security a particular lock would provide, it would be helpful to learn its mechanism and the tried and tested methods of defeating them. (Or, you know, just just pick up the skill for fun)</td> </tr> </table> --- ### Talk 3: Mobile App Analysis <table> <tr> <td>Speaker Name:<br/><br/></td> <td valign="top" >Tan Shu Ren</td> </tr> <tr> <td valign="top" >Speaker Bio:</td> <td>Shu Ren had been working at CSIT for the past 4 years as a mobile researcher. His area of work includes investigating threats on mobile OS, performing security assessments on mobile app through code audit and reverse engineering as well as to profile and evaluate security of mobile devices. <br/><br/> Prior to joining CSIT, Shu Ren studied Computer Science in USA, and work at Oracle Corporation for a while.<br/><br/></td> </tr> <tr> <td valign="top" >Company:</td> <td><img src="/images/csit-logo.png" /><br/><br/></td> </tr> <tr> <td valign="top" >Description:</td> <td>This year marks the 10 years in which Apple App Store and Google Play Store have been in business. Downloading, installing and using of mobile applications from these stores have become an integral part of our daily interactions with our mobile devices. However, do the users (us) really know what these mobile app offered us? Does the mobile app only offer the features that are stated upfront or are there any hidden "features" that the users (us) do not know about?</td> </tr> </table> ---
SQL
UTF-8
811
3.625
4
[]
no_license
/* Users: -id: serial -username: character varying(55) -passwordHash: character varying(255) Items: -id: serial -name: character varying(55) -userId: int -key: int -own: boolean */ CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, username CHARACTER VARYING(55) NOT NULL, passwordHash CHARACTER VARYING(255) NOT NULL ); CREATE TABLE IF NOT EXISTS items ( id SERIAL PRIMARY KEY, name CHARACTER VARYING(55), userId INT REFERENCES users, key INT, isOwned BOOLEAN ); create table IF NOT EXISTS usersession ( SessionKey text primary key, UserID int not null REFERENCES users, LoginTime timestamp not null, LastSeenTime timestamp not null ) INSERT INTO users (username, passwordHash) VALUES ('tindell', '6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090'); INSERT INTO items (name, userId, key) VALUES ('Cilantro', 1, 97);
TypeScript
UTF-8
1,092
2.765625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
import {MediaAudio, VoiceContentType} from "../../src"; import {expect} from "chai"; const chai = require('chai'), chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); describe("MediaAudio", () => { it("sets constructor values properly", () => { const mediaAudio = new MediaAudio('id1234'); expect(mediaAudio.mediaId).to.equal('id1234'); }); it("detects invalid property values", () => { const mediaAudio = new MediaAudio('id1234'); expect(() => { // @ts-ignore mediaAudio.mediaId = undefined; }).to.throw(); }); it('sets values properly', () => { const mediaAudio = new MediaAudio('id1234'); expect(mediaAudio.type).to.equal(VoiceContentType.MEDIA); expect(mediaAudio.mediaId).to.equal('id1234'); }); it("toJSON returns properties correctly", () => { const mediaAudio = new MediaAudio('id1234'); expect(mediaAudio.toJSON()).to.deep.equal({ "mediaId": "id1234", "type": "MEDIA" }); }); });
Java
UTF-8
154
2.171875
2
[ "CC-BY-4.0", "MIT" ]
permissive
package lljvm.io; public interface StandardHandleFactory { FileHandle createStdin(); FileHandle createStdout(); FileHandle createStderr(); }
Shell
UTF-8
292
2.671875
3
[ "MIT" ]
permissive
#!/bin/bash num=$1 zero=0 for((integer=1; integer<=12; integer++)) do { condition=`expr $integer % 1` if [ "$condition" == 0 ] then ./console.py sendtx ExchangeV2 0xa72db07ffb5befe9c9e8264c2224a8b3b7d4e8f4 transfer ${integer} 0x692a70D2e424a56D2C6C27aA97D1a86395877b3A fi }& done
C
UTF-8
907
2.859375
3
[]
no_license
#include <stdio.h> int main() { int i,j,stepen; int paskalovTrougao[100][102]; paskalovTrougao[0][0]=0;paskalovTrougao[0][1]=1;paskalovTrougao[0][2]=0; for(i=1;i<100;i++) { paskalovTrougao[i][0]=0;paskalovTrougao[i][i+2]=0; for(j=1;j<i+2;j++) { paskalovTrougao[i][j]=paskalovTrougao[i-1][j-1]+paskalovTrougao[i-1][j]; } } printf("Unesite stepen binoma(od 1 do 100):"); scanf("%d",&stepen); printf("(a+b)^%d=\n",stepen); for(j=0;j<stepen+1;j++) { if(j==0) printf("a^%d",stepen); else if(j==stepen) printf("b^%d",stepen); else if(j==1) printf("%d * a^%d * b",paskalovTrougao[stepen][2],stepen-1); else if(j==stepen-1) printf("%d * a * b^%d",paskalovTrougao[stepen][2],stepen-1); else printf("%d * a^%d * b^%d",paskalovTrougao[stepen][j+1],stepen-j,j); if(j<stepen) printf(" + "); } scanf("%d",&i); return 0; }
C
UTF-8
986
2.640625
3
[]
no_license
#include <gdt.h> #define GDT_LENGTH 5 gdt_entry_t gdt_entries[GDT_LENGTH]; gdt_ptr_t gdtr; void init_gdt() { gdtr.limit = sizeof(gdt_entry_t) * GDT_LENGTH - 1; gdtr.base = (uint32_t)&gdt_entries; gdt_set_gate(0, 0, 0, 0, 0); // null seg gdt_set_gate(1, 0, 0xffffffff, 0x9a, 0xcf); // code seg gdt_set_gate(2, 0, 0xffffffff, 0x92, 0xcf); // data seg gdt_set_gate(3, 0, 0xffffffff, 0xfa, 0xcf); // user code seg gdt_set_gate(4, 0, 0xffffffff, 0xf2, 0xcf); // user data seg gdt_flush((uint32_t)&gdtr); } static void gdt_set_gate(int32_t num, uint32_t base, uint32_t limit, uint8_t access, uint8_t other) { num = num % GDT_LENGTH; gdt_entries[num].base_low = base & 0xffff; gdt_entries[num].base_mid = (base >> 16) & 0xff; gdt_entries[num].base_high = (base >> 24) & 0xff; gdt_entries[num].limit_low = limit & 0xffff; gdt_entries[num].other = ((limit >> 16) & 0xf) | other; gdt_entries[num].access = access; }
Python
UTF-8
936
3.046875
3
[]
no_license
import numpy as np from keras.models import Sequential from keras.layers import Dense import numpy # fix random seed for reproducibility numpy.random.seed(0) # Input array # Example: 5 groups of data. Each group of data has 4 input features. X = np.array([[1,0,1,0],[1,0,1,1],[0,1,0,1],[0,0,1,1],[1,1,1,1]]) # Output array # Example: 5 groups of data. Each group of data has 1 output. #y = np.array([[1,0],[1,1],[0,0],[0,1],[1,1]]) y = np.array([1,1,0,0,1]) # create model model = Sequential() model.add(Dense(2, input_dim=4, activation='relu')) model.add(Dense(2, activation='relu')) model.add(Dense(1, activation='linear')) # Compile model model.compile(loss='mse', optimizer='adam', metrics=['accuracy']) # Fit the model model.fit(X, y, epochs=2000, batch_size=3, verbose=0) w = model.get_weights() print (w) # evaluate the model scores = model.evaluate(X, y) print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
Java
UTF-8
502
2.75
3
[]
no_license
package com.izhaoyan.util; import java.awt.*; /** * Created by Rockyan on 2016/5/7. */ public class UiUtils { public static void placeToCenter(Container container) { Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); int x = (int) (dimension.getWidth() - container.getWidth()) / 2; int y = (int) (dimension.getHeight() - container.getHeight()) / 2; container.setBounds(x, y, container.getWidth(), container.getHeight()); } }
Java
UTF-8
640
1.515625
2
[]
no_license
package com.zoovisitors; import android.support.v7.app.AppCompatActivity; import com.zoovisitors.bl.BusinessLayer; import com.zoovisitors.pl.BaseActivity; /** * Created by aviv on 10-Jan-18. */ public class GlobalVariables { public static boolean DEBUG = false; public static String ServerAddress = "negevzoo.sytes.net:50" + (DEBUG ? "555/" : "000/"); public static String LOG_TAG = "zoovisitors"; public static int language; public static AppCompatActivity appCompatActivity; public static BusinessLayer bl; public static String firebaseToken; public static boolean notifications = true; }
Java
UTF-8
988
2.84375
3
[]
no_license
package codejams; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; public class Main { // debug switch public static final boolean debug = false; // target filename - will read fname.in, and output to fname.out public static final String fname = "files\\competition\\C-large"; public static void main(String[] args) { // program Object, change class for relevant program Mines2 prog = new Mines2(); try (BufferedReader br = new BufferedReader(new FileReader(fname+".in"))) { PrintWriter pw = new PrintWriter(fname+".out"); int testCases = Integer.parseInt(br.readLine()); for (int i = 1;i <= testCases;i++) { pw.print("Case #"+i+": "); if (debug) System.out.println("====Test case "+i+"===="); prog.testCase(br,pw); pw.print("\n"); pw.flush(); } } catch (Exception e) { e.printStackTrace(); } System.out.println("Done!"); } }
C++
UTF-8
2,961
2.515625
3
[ "MIT" ]
permissive
#include "../../gi.h" #include "../../util.h" #include "rectangle.h" using namespace v8; namespace GNodeJS { namespace Cairo { Nan::Persistent<FunctionTemplate> Rectangle::constructorTemplate; Nan::Persistent<Function> Rectangle::constructor; /* * Initialize Rectangle. */ void Rectangle::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { Nan::HandleScope scope; // Constructor auto tpl = Nan::New<FunctionTemplate>(Rectangle::New); constructorTemplate.Reset(tpl); tpl->InstanceTemplate()->SetInternalFieldCount(1); tpl->SetClassName(Nan::New("CairoRectangle").ToLocalChecked()); // Prototype Local<ObjectTemplate> proto = tpl->PrototypeTemplate(); SetProtoAccessor(proto, UTF8("x"), GetX, SetX, tpl); SetProtoAccessor(proto, UTF8("y"), GetY, SetY, tpl); SetProtoAccessor(proto, UTF8("width"), GetWidth, SetWidth, tpl); SetProtoAccessor(proto, UTF8("height"), GetHeight, SetHeight, tpl); auto ctor = Nan::GetFunction (tpl).ToLocalChecked(); constructor.Reset(ctor); Nan::Set(target, Nan::New("Rectangle").ToLocalChecked(), ctor); } /* * Initialize a Rectangle with the given width and height. */ NAN_METHOD(Rectangle::New) { if (!info.IsConstructCall()) { return Nan::ThrowTypeError("Class constructors cannot be invoked without 'new'"); } cairo_rectangle_t* data = NULL; if (info[0]->IsExternal()) { data = (cairo_rectangle_t*) External::Cast (*info[0])->Value (); } else { data = new cairo_rectangle_t(); if (info.Length() == 4) { data->x = Nan::To<double>(info[0].As<Number>()).ToChecked(); data->y = Nan::To<double>(info[1].As<Number>()).ToChecked(); data->width = Nan::To<double>(info[2].As<Number>()).ToChecked(); data->height = Nan::To<double>(info[3].As<Number>()).ToChecked(); } } Rectangle* rectangle = new Rectangle(data); rectangle->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } /* * Initialize text extent. */ Rectangle::Rectangle(cairo_rectangle_t* data) : ObjectWrap() { _data = data; } /* * Destroy text extent.. */ Rectangle::~Rectangle() { if (_data != NULL) { delete _data; } } /* * Getter/setters */ #define DEFINE_ACCESSORS(prop, getterName, setterName) \ NAN_GETTER(Rectangle::getterName) { \ Rectangle *rectangle = Nan::ObjectWrap::Unwrap<Rectangle>(info.This()); \ info.GetReturnValue().Set(Nan::New<Number>(rectangle->_data->prop)); \ } \ \ NAN_SETTER(Rectangle::setterName) { \ if (value->IsNumber()) { \ Rectangle *rectangle = Nan::ObjectWrap::Unwrap<Rectangle>(info.This()); \ rectangle->_data->prop = Nan::To<double> (value).ToChecked(); \ } \ } DEFINE_ACCESSORS(x, GetX, SetX) DEFINE_ACCESSORS(y, GetY, SetY) DEFINE_ACCESSORS(width, GetWidth, SetWidth) DEFINE_ACCESSORS(height, GetHeight, SetHeight) #undef DEFINE_ACCESSORS }; // Cairo }; // GNodeJS
Markdown
UTF-8
84,353
2.5625
3
[]
no_license
* * * * * **Council Bill Number: [](#h0)[](#h2)116146** **Ordinance Number: 122643** * * * * * AN ORDINANCE relating to the Seattle Department of Parks and Recreation; authorizing the Superintendent of Parks and Recreation to enter into a Lease Agreement with the Victory Heights Cooperative Preschool to provide preschool education and recreation programs for children and adults at the Victory Heights Shelterhouse. **Status:** Passed **Date passed by Full Council:** March 17, 2008 **Vote:** 9-0 **Date filed with the City Clerk:** March 24, 2008 **Date of Mayor's signature:** March 21, 2008 [(about the signature date)](/~public/approvaldate.htm) **Date introduced/referred to committee:** March 3, 2008 **Committee:** Parks and Seattle Center **Sponsor:** RASMUSSEN **Index Terms:** DEPARTMENT-OF-PARKS-AND-RECREATION, LEASES, CHILD-CARE, VICTORY-HEIGHTS, LAKE-CITY **Fiscal Note:** [Fiscal Note to Council Bill](http://clerk.seattle.gov/~public/fnote/116146.htm)[](#h1)[](#h3)116146 **Electronic Copy: ** [PDF scan of Ordinance No. 122643](/~archives/Ordinances/Ord_122643.pdf) * * * * * **Text** ORDINANCE _________________ AN ORDINANCE relating to the Seattle Department of Parks and Recreation; authorizing the Superintendent of Parks and Recreation to enter into a Lease Agreement with the Victory Heights Cooperative Preschool to provide preschool education and recreation programs for children and adults at the Victory Heights Shelterhouse. WHEREAS, preschool education for children and adults with a recreational component are an important service for Seattle citizens and the Department of Parks and Recreation ("DPR") has provided facilities for such services for 28 years; and WHEREAS, Victory Heights Cooperative Preschool has provided and successfully implemented preschool education classes and recreation programs that serve the public, including diverse communities that normally do not have access to these programs, at the City's Victory Heights Shelterhouse facility for the last 28 years; and WHEREAS, DPR wishes to continue this relationship with the Victory Heights Cooperative Preschool to maintain the delivery of such services to the public at this public building; NOW, THEREFORE, BE IT ORDAINED BY THE CITY OF SEATTLE AS FOLLOWS: Section 1. The Superintendent of Parks and Recreation ("Superintendent"), or his or her designee, is authorized to execute, for and on behalf of the City of Seattle ("City"), a Lease Agreement with Victory Heights Cooperative Preschool in substantially the form attached hereto as Attachment 1, with such minor additions, modifications, or deletions as the Mayor or said Superintendent deems to be in the best interest of the City. Section 2. This ordinance shall take effect and be in force thirty (30) days from and after its approval by the Mayor, but if not approved and returned by the Mayor within ten (10) days after presentation, it shall take effect as provided by Municipal Code Section 1.04.020. Passed by the City Council the ____ day of _________, 2008, and signed by me in open session in authentication of its passage this _____ day of __________, 2008. _________________________________ President __________of the City Council Approved by me this ____ day of ___________, 2008. _________________________________ Gregory J. Nickels, Mayor Filed by me this ____ day of _____________, 2008. ____________________________________ City Clerk (Seal) Attachment 1: Victory Heights Cooperative Preschool Lease Agreement between the City of Seattle and the Victory Heights Cooperative Preschool Exhibit A to Attachment 1: Legal Description Rita Hollomon DPR Victory Heights Co-op Lease ORD 1/30/08 Version #3 VICTORY HEIGHTS COOPERATIVE PRESCHOOL LEASE AGREEMENT BETWEEN THE CITY OF SEATTLE AND THE VICTORY HEIGHTS COOPERATIVE PRESCHOOL THIS LEASE ("Lease") is entered into this ____ day of ______________, 20__, by and between THE CITY OF SEATTLE ("City"), a city of the first class of the State of Washington, acting by and through its Department of Parks and Recreation ("DPR") and the Superintendent thereof ("Superintendent"), and Victory Heights Cooperative Preschool ("Lessee") a Washington not-for-profit corporation organized under the laws of the State of Washington. AGREEMENT IN CONSIDERATION of the mutual covenants contained herein, City and Lessee covenant and agree as follows: 1. Lease Data; Exhibits. The following terms shall have the following meanings, except as otherwise specifically modified in this Lease: 1.1 Premises. The "Premises" are defined for purposes of this Agreement as the interior spaces of the Victory Heights Shelterhouse located at 1747 NE 106th Street, Seattle, WA 98125, situated on real property described in Exhibit A. 1.2 Commencement Date. Upon execution by the Superintendent. 1.3 Expiration Date. March 1, 2013, unless extended under Subsection 3.2. 1.4 Rent and Additional Charges. 1.4.1 Rent: Lessee shall pay a monthly base rent of $1,555 to the City for each calendar month when school is in session (September 1st through June 30th each year) except as may be adjusted pursuant to Section 4. 1.4.2 Additional Charges: Whether or not so designated, all other sums due from Lessee under this Lease shall constitute Additional Charges, payable when specified in this Lease. 1.5 Notice Addresses. To City: City of Seattle Department of Parks and Recreation Magnuson Park & Business Resources Attention: Concessions Coordinator 6310 NE 74th Street, #109E Seattle, WA 98115 To Lessee: Victory Heights Co-op Preschool 1747 NE 106th Street Seattle, WA 98125 1.6 Exhibits. The following exhibits are made a part of this Lease: Exhibit A - Legal Description 2. Premises. 2.1 Grant. City hereby leases to Lessee and Lessee hereby leases from City those certain premises referenced in Section 1 (the "Premises"), which are located on the real property described on Exhibit A ("Property"). The Lessee shall have use of the Premises during the months of September through June during each calendar year in the Lease Term, and during the hours specified in Section 35. The City reserves to itself the right to license the use of the Premises as a place for public voting on election days, and on election days, Lessee's use will be non-exclusive. The City also reserves to itself the right to license the use of the Premises during the months of July and August when school is not in session, and during hours that do not conflict with Lessee's hours of use specified in Section 35. 2.2 Condition. City leases the Premises and Lessee accepts the Premises in their "as is" condition. 2.3 Permitted Use. Lessee shall use the Premises for operating a cooperative preschool and all necessary and related administrative activities. Lessee shall not use the Premises for any purpose whatsoever other than the uses specifically permitted herein (collectively, the "Permitted Use"). 2.4 Common Areas. During the Term, Lessee and its licensees, invitees and customers shall have the non-exclusive right to use the adjacent playground and other public areas of the Property (the "Common Areas") in common with the general public. City shall at all times have exclusive control and management of the Common Areas and no diminution thereof shall be deemed a constructive or actual eviction or entitle Lessee to compensation or a reduction or abatement of rent. 2.5 Alterations. City, in its discretion, may increase, decrease or change the number, locations and dimensions of any hallways, lobby areas, Common Areas and other improvements shown on the Property that are not within the Premises. Such increase, decrease, or change shall not materially interfere with Lessee's business as permitted in Subsection 2.3. Permitted Use. City reserves the right from time to time (i) to install, use, maintain, repair, relocate and replace pipes, ducts, conduits, wires and appurtenant meters and equipment for service to the Premises, or to other parts of the Building/Property where the Premises are located in areas above the suspended ceiling surfaces, below the floor surfaces, within the walls and elsewhere in the Building; (ii) to alter or expand the Building/Property; and (iii) to alter, relocate or substitute any of the Common Areas. In performing any work described in (i), (ii), and (iii) of this subsection, City shall make every reasonable effort to work with Lessee in order to minimize any interruption or adverse affect on Lessee's use of the Premises. 3. Lease Term. 3.1 Initial Term. This Lease shall be for a term ("Lease Term" or "Term") beginning on the Commencement Date specified in Subsection 1.2 and ending on the Expiration Date specified in Subsection 1.3, unless the Lease Term is terminated earlier in accordance with the provisions of this Lease or extended as provided in Subsection 3.2 below. It is agreed that Lessee will only occupy the premises 10 months of each year. Lessee will not occupy or use the building during the months of July and August. 3.2 Extended Terms. City shall have the option to offer Lessee an extension of this Lease for up to one (1) successive individual extended term of five (5) years, hereafter called "the Extended Term," on the same terms and conditions set forth herein. City may extend the Lease Term to include any Extended Term by giving Lessee written notice of its willingness to do so at least ninety (90) days prior to the Expiration Date specified in Subsection 1.3. Lessee shall provide City with written notice of its acceptance of the Extended Term no later than 45 days prior to the Expiration Date specified in Subsection 1.3. As used in this Lease, the "Lease Term" means the original term commencing on the Commencement Date and ending on the Expiration Date specified in Subsection 1.3, and any and all Extended Term(s) established by City hereunder. 4. Rent. 4.1 Rent Commencement Date. Commencing March 10, 2008 ("Rent Commencement Date") Lessee shall pay to City at the address and to the account specified by City, without notice or demand or any setoff or deduction whatsoever, in lawful money of the United States (a) the monthly amount of Rent specified in Subsection 1.4.1 in advance on the tenth day of each month; and (b) Additional Charges as and when specified elsewhere in this Lease, but if not specified, then within ten (10) days after written demand. Rent and, if appropriate, as reasonably determined by City, Additional Charges shall be prorated on a daily basis for any partial month within the Lease Term, and for any partial initial month in the Lease Term shall be paid on the first day of the Lease Term. 4.2 Additional Utility Charge. Commencing on the Rent Commencement Date, Lessee shall pay to City a monthly Additional Utility Charge of $150 for Lessee's use of utilities at the Premises, including but not limited to: electricity, water and sewer services and data and telecommunications services. The Additional Utility Charge is payable at the same time and in the same manner as Rent. 4.3 Adjustments to Rent and Additional Utility Charge During Extended Term. In the event that the Term is extended under Section 3.2, beginning on the first day when rent is due under the Extended Term and every year thereafter until the expiration or termination of this Agreement (each, a "Rent Adjustment Date"), Rent and the Additional Utility Charge shall be adjusted upward only to reflect increases in the total noncompounded percentage change in the Consumer Price Index for All Urban Consumers (All Items) in the Seattle-Tacoma-Bremerton region (1982-84 = 100) ("CPI"), published by the Bureau of Labor Statistics, United States Department of Labor between the first and last years being adjusted, provided, however, that in no event shall Rent and the Additional Utility Charge increase by more than four percent (4%) per year. The City shall notify Lessee in writing at least three (3) months prior to each Rent Adjustment Date of the new monthly Rent and Additional Utility Charge amount that will be due starting on such Rent Adjustment Date. By way of example only, if the CPI on the commencement date of this Agreement is 100 and the CPI most recently issued prior to the first Rent Adjustment Date is 110 and the annual Rent due under this Agreement is $60,000, then the total CPI adjustment would be no more than 4% and annual Rent under this Agreement would increase to $62,400 effective as of the Rent Adjustment Date. In no event shall the Rent, as adjusted for any period, be less than Rent payable during the immediately preceding period. In the event the CPI is discontinued, the parties shall agree upon another similar index to be used to calculate the contemplated adjustment and, in the event of an inability to agree, the parties shall request the American Arbitration Association or its successor to appoint a qualified arbitrator to establish an appropriate adjustment standard to measure inflation. 4.4 Public Benefit Offset. By March 15 annually, Lessee may request a Public Benefit Offset against Rent to reflect expenditures made to provide benefits to the public (such as scholarship programs or public classes). Lessee may identify the amount of Public Benefit Offset it is requesting for the subsequent school year and the justification for the request. The Superintendent will act reasonably in reviewing the request and will respond within 30 days stating the amount, if any, of the Public Benefit Offset allowed for the upcoming school year. The amount of the Public Benefit Offset for a given year shall rest in the Superintendent's sole discretion. Any Public Benefit Offset shall be credited against the Rent only in monthly installments, in such amounts as the Superintendent determines. With each monthly payment, Lessee shall report to the DPR Finance Director the amount of Public Benefit Offset being applied to Rent. In no instance shall the monthly rent adjustment be lower than that specified in Section 4.5 below. 4.5 Limitation on Offsets. Notwithstanding anything in this Agreement to the contrary, in no event shall Lessee's monthly Rent be less than $600. 4.6 Taxes. Lessee shall pay to DPR monthly whatever leasehold excise tax is assessed pursuant to Chapter 82.29A RCW as a consequence of Lessee' use and occupancy of the Premises under this Agreement. In addition, Lessee shall pay before their delinquency, all other taxes that may be due and payable with respect to property owned by and the activities of Lessee on the Premises to the extent failure to do so could result in a lien against the Premises. 4.7 Offset Inapplicable to Taxes. The reduction and offsetting of any Rent pursuant to Section 4.4 hereof shall have no effect on the amount of any leasehold excise tax due and payable to the City or any other tax obligation of Lessee. Unless Lessee is exempt from the payment of leasehold excise taxes, all such taxes shall be payable only in cash or cash equivalents. The City shall not contest any application by Lessee for an exemption from the leasehold excise tax. 4.8 Rent, Additional Utility Charge, and Leasehold Excise Tax Payment Date and Address. Rent, Additional Utility Charge and leasehold excise tax due and payable under this Agreement shall be remitted on the tenth (10th) calendar day of each month during the term of this Agreement to the City at the address shown in Section 1.5 hereof, or to such other place as DPR may hereafter designate. 4.9 Late Charge; Interest. If Lessee fails to pay the City any sum when due, such amount shall bear interest at the rate of 12% per annum from the date due until the date paid. In addition, Lessee shall pay the City a Twenty Dollar ($20.00) charge for each check refused payment for insufficient funds or any other reason. 5. Lessee 's Operations. 5.1 Use of Premises. Lessee shall use the Premises only for the Permitted Use. As City's willingness to enter into this Lease with Lessee was predicated, in part, on the nature of Lessee 's business, and the compatibility of such business with the use of the Building, Lessee shall not use or permit the use of the Premises for any other business, or purpose, or under any other name, without City's prior written consent. Lessee shall promptly comply, at its sole cost and expense, with such reasonable rules and regulations relating to the use of the Premises and Common Areas, as City, from time to time, may promulgate. Any newly promulgated rules and regulations shall not materially interfere with Lessee's business for the Permitted Use. In the event of any conflict between the rules and regulations promulgated by City and the terms of this Lease, the terms of this Lease shall prevail. Lessee shall maintain the Premises in a clean, orderly and neat fashion and to a standard established for other similar DPR properties, permitting no objectionable odors to be emitted from the Premises and shall neither commit waste nor permit any waste to be committed thereon. Lessee shall not permit any accumulation of trash on or about the Premises. Lessee shall not create or contribute to the creation of a nuisance in either the Premises and Lessee shall not engage in or permit any action that will disturb the quiet enjoyment of any other occupant in the Building. 5.2 Compliance with Laws; Nondiscrimination. 5.2.1 General Obligation. Lessee shall not use or permit the Premises or any part thereof to be used for any purpose in violation of any municipal, county, state or federal law, ordinance or regulation, or for any purpose offensive to the standards of the community. Lessee shall promptly comply, at its sole cost and expense, with all laws, ordinances and regulations now in force or hereafter adopted relating to or affecting the condition, use or occupancy of the Premises. 5.2.2 Nondiscrimination. Without limiting the generality of Subsection 5.2.1, Lessee agrees to and shall comply with all applicable equal employment opportunity and nondiscrimination laws of the United States, the State of Washington, and The City of Seattle, including but not limited to Chapters 14.04, 14.10 and 20.42 of the Seattle Municipal Code, as they may be amended from time to time, and rules, regulations, orders and directives of the associated administrative agencies and their officers. 5.3 Liens and Encumbrances. Lessee shall keep the Premises free and clear of, and shall indemnify, defend and hold City harmless from, any and all, liens and encumbrances arising or growing out of any act or omission, or breach of this Lease or its use, improvement or occupancy of the Premises by Lessee or any of its principals, officers, employees or agents or subtenants. Lessee shall inform the City in writing of any lien filed against the Premises within ten (10) days of the filing date of the lien. If any lien is so filed against the Premises, Lessee shall either cause the same to be fully discharged and released of record within ten (10) days after City's written demand therefor or, within such period, provide City with cash or other security acceptable to City in an amount equal to one and one-half (11/2) times the amount of the claimed lien as security for its prompt removal. City shall have the right to disburse such security to cause the removal of the lien if City deems such necessary, in City's sole discretion. 5.4 Hazardous Substances. Lessee shall not, without City's prior written consent, keep on or about the Premises any substance designated as, or containing any component now or hereafter designated as hazardous, dangerous, toxic or harmful and/or subject to regulation under any federal, state or local law, regulation or ordinance ("Hazardous Substances"), except customary office, kitchen, cleaning and other related supplies in normal quantities handled in compliance with applicable laws. With respect to any Hazardous Substances stored with City's consent, Lessee shall promptly, timely and completely comply with all governmental requirements for reporting and record keeping; submit to City true and correct copies of all reports, manifests and identification numbers at the same time as they are required to be and/or are submitted to the appropriate governmental authorities; within five (5) days after City's request therefor, provide evidence satisfactory to City of Lessee's compliance with all applicable governmental rules, regulations and requirements; and comply with all governmental rules, regulations and requirements regarding the proper and lawful use, sale, transportation, generation, treatment and disposal of Hazardous Substances. Any and all costs incurred by City and associated with City's inspections of the Premises and City's monitoring of Lessee's compliance with this Subsection 5.4, including City's attorneys' fees and costs, shall be Additional Charges and shall be due and payable to City within ten (10) days after City's demand therefor, if Lessee's violation of this Subsection 5.4 is discovered as a result of such inspection or monitoring. Lessee shall be fully and completely liable to City for any and all cleanup costs and expenses and any and all other charges, expenses, fees, fines, penalties (both, civil and criminal) and costs imposed with respect to Lessee's use, disposal, transportation, generation and/or sale of Hazardous Substances in or about the Premises. Lessee shall indemnify, defend and hold City harmless from any and all of the costs, fees, penalties, charges and expenses assessed against, or imposed, upon City (as well as City's attorneys' fees and costs) as a result of Lessee's use, disposal, transportation, generation and/or sale of Hazardous Substances on or about the Premises. The indemnification obligation of this subsection shall survive the expiration or earlier termination of this Lease. 6. Utilities. 6.1 General. Lessee shall pay a monthly fee as stated in subsection 4.2 to DPR for their use of utilities at the Premises, including but not limited to, electricity, water and sewer services and data and telecommunications services. 6.2 Refuse Collection; Recycling of Waste Materials. Lessee shall provide all necessary housekeeping and janitorial services for the Premises to a level consistent with other similar DPR facilities and operations and to the Superintendent's reasonable satisfaction. Lessee shall be responsible for proper storage and removal of trash, litter pickup and recycling consistent with City standards. 6.3 Interruption. City shall not be liable for any loss, injury or damage to person or property caused by or resulting from any variation, interruption or failure of services due to any cause whatsoever, including, but not limited to, electrical surges, or from failure to make any repairs or perform any maintenance. No temporary interruption or failure of such services incident to the making of repairs, alterations or improvements or due to accident, strike or conditions or events beyond City's reasonable control shall be deemed an eviction of Lessee or to relieve Lessee from any of Lessee's obligations hereunder or to give Lessee a right of action against City for damages. Lessee acknowledges its understanding that there may be City-planned utility outages affecting the Premises and that such outages may interfere, from time to time, with Lessee's use of the Premises. City shall provide Lessee with not less than 48 hours' prior written notice of any City-planned electricity outage in the Premises. City has no obligation to provide emergency or backup power to Lessee. The provision of emergency or backup power to the Premises or to enable the equipment therein to properly function shall be the sole responsibility of Lessee. If utilities are interrupted at the Premises so as to render them unfit for their permitted uses, then the Rent for the year shall be abated for the duration of the disruption in the proportion that the number of days of the disruption bears to the number of days of the year. 7. Licenses and Taxes. Without any deduction or offset whatsoever, Lessee shall be liable for, and shall pay prior to delinquency, all taxes, license and excise fees and occupation taxes covering the business conducted on the Premises and all personal property taxes and other impositions levied with respect to all personal property located at the Premises; Lessee shall be responsible for, and shall pay prior to delinquency, all fees, charges, or costs, for any governmental inspections or examinations relating to Lessee's use and occupancy of the Premises, and pay all taxes on the leasehold interest created by this Lease (e.g., leasehold excise taxes). 7.1 Contests. Lessee shall have the right to contest the amount and validity of any taxes by appropriate legal proceedings, but this shall not be deemed or construed in any way as relieving Lessee of its covenant to pay any such taxes. City shall not be subjected to any liability or for the payment of any costs or expenses in connection with any such proceeding brought by Lessee, and Lessee hereby covenants to indemnify and hold City harmless from any such costs or expenses. The indemnification obligation of this subsection shall survive the expiration or earlier termination of this Lease. 8. Alterations by Lessee. Lessee shall not make any alterations, additions or improvements in or to the Premises without first submitting to City professionally-prepared plans and specifications for such work and obtaining City's prior written approval thereof. Lessee covenants that it will cause all alterations, additions and improvements to the Premises to be completed at Lessee's sole cost and expense by a contractor approved by City and in a manner that (a) is consistent with the City-approved plans and specifications and any conditions imposed by City in connection therewith; (b) is in conformity with first-class, commercial standards; (c) includes acceptable insurance coverage for City's benefit; (d) does not affect the structural integrity of the Premises or any of the Premises' systems;(e) does not disrupt the use of the Premises by any third party City licenses or leases the Premises to for use during the months or hours when Lessee does not use and occupy the Premises; and (f) does not invalidate or otherwise affect the construction or any system warranty then in effect with respect to the Premises. Lessee shall secure all governmental permits and approvals required for the work; shall comply with all other applicable governmental requirements and restrictions; and reimburse City for any and all expenses incurred in connection therewith. Except as provided in Section 12 with regard to concurrent negligence, Lessee shall indemnify, defend and hold City harmless from and against all losses, liabilities, damages, liens, costs, penalties and expenses (including attorneys' fees, but without waiver of the duty to hold harmless) arising from or out of Lessee's performance of such alterations, additions and improvements, including, but not limited to, all which arise from or out of Lessee's breach of its obligations under terms of this Section 8. All alterations, additions and improvements (expressly including all light fixtures; heating and ventilation units; floor, window and wall coverings; and electrical wiring), except Lessee's moveable trade fixtures and appliances and equipment not affixed to the Premises (including without limitation furniture, computers, point of sale systems and registers) shall become the property of City at the expiration or termination of this Lease without any obligation on its part to pay for any of the same. At City's request, Lessee shall execute a deed or bill of sale in favor of City with respect to such alterations and/or improvements. Notwithstanding the foregoing, Lessee shall remove all or any portion of such alterations and/or improvements on the expiration or termination of this Lease if City specifically so directs, in writing, at the time of City's issuance of its approval thereof. Within ninety (90) days after the completion of any alteration, addition or improvement to the Premises, Lessee shall deliver to City a full set of "as-built" plans of the Premises showing the details of all alterations, additions and improvements made to the Premises by Lessee. 9. Care of Premises. 9.1 General Obligation. Lessee shall take good care of the Premises and shall reimburse City for all damage done to the Premises that results from any act or omission of Lessee or any of Lessee's officers, contractors, agents, invitees, licensees or employees, including, but not limited to, cracking or breaking of glass. 9.2 Custodial Service for Premises. Lessee shall at its own expense, at all times, keep the Premises and areas immediately adjacent thereto in a neat, clean, safe, and sanitary condition; and keep the glass of all windows and doors serving such areas clean and presentable. Lessee shall furnish all cleaning supplies and materials needed to operate such areas in the manner prescribed in this Lease; Lessee shall provide all necessary janitorial service to adequately maintain the inside of such areas using a company reasonably approved by City. Lessee shall be responsible for keeping the areas immediately adjacent to the perimeter of such areas free of litter and clean of spills resulting from Lessee's operations. If, after City provides written notice to Lessee of Lessee's failure to comply with this Section, Lessee fails to take good care of such areas, City, at its option, may do so, and in such event, upon receipt of written statements from City, Lessee shall promptly pay the entire actual and reasonable cost thereof as an Additional Charge. City shall have the right to enter the Premises for such purposes. City shall not be liable for interference with light, air or view. 9.3 City Maintenance Obligations. All normal repairs necessary to maintain the Premises (including the structural aspects and exterior of the Premises), the Common Areas, and the heating, ventilation, utility, electric and plumbing and other systems and equipment serving the Premises in a reasonably good operating condition, as determined by City, shall be performed by City at its expense. The foregoing sentence does not extend to maintenance occasioned by an act or omission of Lessee or its officers, agents, employees, or contractors. Except in the event of City's gross negligence or intentional misconduct, there shall be no abatement or reduction of rent arising by reason of City's making of repairs, alterations or improvements. 9.4 Prohibition Against Installation or Integration of Any Work of Visual Art on Premises Without City's Consent. City reserves to and for itself the right to approve or disapprove of the installation or integration on or in the Premises of any "work of visual art," as that term is defined in the Visual Artists Rights Act of 1990, as now existing or as later amended, and to approve or disapprove of each and every agreement regarding any such installation or integration. Lessee shall not install on or integrate into, or permit any other person or entity to install on or integrate into, the Premises any such work of visual art without City's prior, express, written consent. City's consent to the installation of any such art work may be granted, granted upon one or more conditions, or withheld in City's discretion. 9.5 Lessee's Indemnification of City Against Liability under Visual Artists Rights Act of 1990. Lessee shall protect, defend, and hold City harmless from and against any and all claims, suits, actions or causes of action, damages and expenses (including attorneys' fees and costs) arising as a consequence of (a) the installation or integration of any work of visual art on or into the Premises; or (b) the destruction, distortion, mutilation or other modification of the art work that results by reason of its removal; or (c) any breach of Subsection 9.4 of this Lease; or (d) any violation of the Visual Artists Rights Act of 1990, as now existing or hereafter amended; by Lessee or any of its officers, employees or agents. This indemnification obligation shall exist regardless of whether City or any other person employed by City has knowledge of such installation, integration, or removal or has consented to any such action or is not required to give prior consent to any such action. The indemnification obligation of this subsection shall survive the expiration or earlier termination of this Lease. 10. Signs and Advertising. 10.1 Signs, Generally. Lessee shall not inscribe, post, place, or in any manner display any sign, notice, picture, poster, or any advertising matter whatsoever anywhere in or about the Premises, without the Superintendent's prior written consent. Lessee shall remove all signage at the expiration or earlier termination of this Lease and repair any damage or injury to the Premises. 10.2 On-Premises Signs. Lessee may install approved permanent exterior signage. Temporary signs or banners not more than 24 square feet in size may be displayed on or about the Premises to advertise a special event beginning two weeks immediately before the event advertised, through the conclusion of such event. Exterior signage shall include the Premises' name, Lessee's name and the DPR logo and shall be constructed in a style and size consistent with the DPR sign policy. 10.3 Recognition. On materials printed after the date this Lease becomes effective, Lessee shall include a statement and the DPR logo in its printed materials stating, in effect, that: "We would like to thank Seattle Parks and Recreation for providing a location for Victory Heights Cooperative Preschool." 11. Surrender of Premises. 11.1 General Matters. At the expiration or sooner termination of the Lease Term, Lessee shall return the Premises to City in the same condition in which received on the Commencement Date (or, if altered, then the Premises shall be returned in such altered condition unless otherwise directed by City pursuant to Section 8), reasonable wear and tear, casualty and condemnation damages not resulting from or contributed to by negligence of Lessee, excepted. Prior to such return, Lessee shall remove its moveable trade fixtures and appliances and equipment that have not been attached to the Premises, and shall repair any damage resulting from their removal. In no event shall Lessee remove floor coverings; heating or ventilating equipment; lighting equipment or fixtures; or floor, window or wall coverings unless otherwise specifically directed by City, in writing, at the time when City's approval of their installation is issued. Lessee's obligations under this Section 11 shall survive the expiration or termination of this Lease. Lessee shall indemnify City for all damages and losses suffered as a result of Lessee's failure to remove voice and data cables, wiring and communication lines and moveable trade fixtures and appliances and to redeliver the Premises on a timely basis. 11.2 Cable and Wiring. Notwithstanding any provision to the contrary in this Lease and if the City so directs, on or by the Expiration Date, or if this Lease is terminated before the Expiration Date, within fifteen (15) days after the effective termination date, whichever is earlier, Lessee shall remove all voice and data communication and transmission cables and wiring installed by or for Lessee to serve any telephone, computer or other equipment located in that portion of the Premises. Cables and wiring shall include all of the same located within the interior and exterior walls and through or above the ceiling or through or below the floor of such portion of the Premises or located in any Building equipment room, vertical or horizontal riser, raceway, conduit, channel, or opening connecting to the portion of the Premises to be vacated and surrendered to City as of such Expiration Date or earlier termination date. Lessee shall leave the mud rings, face plates and floor boxes in place. 12. Waiver; Indemnification. 12.1 Lessee's Indemnification. Except as otherwise provided in this section, Lessee shall indemnify, defend (using legal counsel reasonably acceptable to City) and save City, City's officers, agents, employees and contractors, and other occupants of the Building harmless from all claims, suits, losses, damages, fines, penalties, liabilities and expenses (including City's actual and reasonable personnel and overhead costs and attorneys' fees and other costs incurred in connection with claims, regardless of whether such claims involve litigation) resulting from any actual or alleged injury (including death) of any person or from any actual or alleged loss of or damage to, any property arising out of or in connection with (i) Lessee's occupation, use or improvement of the Premises, or that of any of its employees, agents or contractors, (ii) Lessee's breach of its obligations hereunder, or (iii) any act or omission of Lessee or any subtenant, licensee, assignee or concessionaire of Lessee, or of any officer, agent, employee, guest or invitee of any of the same in or about the Premises/Building; provided that Lessee shall not be required to indemnify the City for damages resulting from the sole negligence of the City, its officers, agents, employees and contractors. Lessee agrees that the foregoing indemnity specifically covers actions brought by its own employees. This indemnity with respect to acts or omissions during the Lease Term shall survive termination or expiration of this Lease. The foregoing indemnity is specifically and expressly intended to, constitute a waiver of Lessee's immunity under Washington's Industrial Insurance Act, RCW Title 51, to the extent necessary to provide City with a full and complete indemnity from claims made by Lessee and its employees, to the extent of their negligence. Lessee shall promptly notify City of casualties or accidents occurring in or about the Premises. CITY AND LESSEE ACKNOWLEDGE THAT THEY SPECIFICALLY NEGOTIATED AND AGREED UPON THE INDEMNIFICATION PROVISIONS OF THIS SECTION 12. 12.2 Lessee's Release of Claims. Lessee hereby fully and completely waives and releases all claims against City to the extent a loss or damage is covered by insurance for any losses or other damages sustained by Lessee or any person claiming through Lessee resulting from any accident or occurrence in or upon the Premises, including but not limited to any defect in or failure of equipment; any failure to make repairs; any defect, failure, surge in, or interruption of facilities or services; (any defect in or failure of Common Areas); broken glass; water leakage; the collapse of any component; or any act, omission or negligence of co-tenants, licensees or any other persons or occupants of the Premises. 12.3 Limitation of Lessee's Indemnification. In compliance with RCW 4.24.115 as in effect on the date of this Lease, all provisions of this Lease pursuant to which City or Lessee (the "Indemnitor") agrees to indemnify the other (the "Indemnitee") against liability for damages arising out of bodily injury to persons or damage to property relative to the construction, alteration, repair, addition to, subtraction from, improvement to, or maintenance of, any building, road, or other structure, project, development, or improvement attached to real estate, including the Premises, (i) shall not apply to damages caused by or resulting from the sole negligence of the Indemnitee, its agents or employees, and (ii) to the extent caused by or resulting from the concurrent negligence of (a) the Indemnitee or the Indemnitee's agents or employees, and (b) the Indemnitor or the Indemnitor's agents or employees, shall apply only to the extent of the Indemnitor's negligence; PROVIDED, HOWEVER, the limitations on indemnity set forth in this section shall automatically and without further act by either City or Lessee be deemed amended so as to remove any of the restrictions contained in this section no longer required by then applicable law. 12.4 City's Release of Claims. City hereby fully and completely waives and releases all claims against Lessee to the extent a loss or damage is caused by City's negligence, willful misconduct or breach of this Lease. 13. Insurance. 13.1 Lessee Furnished Insurance. Lessee shall maintain, or cause its Subtenant(s), if any, to maintain at no expense to City throughout the entire Lease Term minimum levels of insurance coverages and limits of liability as specified below: 13.1.1 Commercial General Liability (CGL) insurance including: - Premises/Operations - Products/Completed Operations - Personal/Advertising Injury - Contractual - Stop Gap - Host Liquor - Tenant/Fire Legal. Such insurance must provide a minimum limit of liability of $1,000,000 each occurrence combined single limit bodily injury and property damage except: - $1,000,000 each offense Personal/Advertising Injury - $ 100,000 each occurrence Tenant/Fire Legal Liability - $1,000,000 each Accident/ Disease/Employee Stop Gap (alternatively, may be evidenced as Employer's Liability insurance under Part B of a Workers Compensation insurance policy). The limits of liability described above are minimum limits of liability only. They shall neither (1) be intended to establish a maximum limit of liability to be maintained by Lessee as respects this Agreement, including additional limits of liability conferred by the Lessor's placement of excess and/or umbrella liability insurance policies, nor (2) be construed as limiting the liability of any of Lessee's insurers, which must continue to be governed by the stated limits of liability of the relevant insurance policies. 13.1.2 Property insurance under which the Lessee's furniture, equipment, inventory and trade fixtures, excluding tenant improvements ("Business Personal Property") are insured for "all risks" of physical loss or damage with an amount of insurance not less than the replacement cost thereof and not subject to any coinsurance clause. 13.2 City Furnished Property Insurance. The City shall maintain throughout the entire Lease Term minimum levels of property insurance and/or self-insurance providing "all risks" of physical loss or damage in an amount of insurance not less than the replacement cost of the Victory Heights Shelter House at 1747 NE 106th Street, Seattle, WA 98125 ("Building"). The City furnished coverage shall include the Premises, including tenant improvements, but exclude Lessee's Business Personal Property. Any premium charge to the Lessee for such City furnished property insurance shall be stated in the Lease. 13.3 General Requirements Regarding Lessee and City Furnished Property Insurance. 13.3.1 The City and the Lessee shall mutually waive their respective property insurers' rights of subrogation in favor of the other. 13.3.2 The City and the Lessee shall mutually waive their respective rights of recovery for property insurance deductibles in favor of the other except to the extent that (1) Lessee is responsible for the damage to or destruction of the Premises and, (2) Lessee's Tenant/Fire Legal Liability applies to the resultant claim. 13.3.3 Lessee shall be responsible for reviewing and adjusting as necessary upon each insurance renewal of Lessee's Property insurance the adequacy of the replacement values of Lessee's Business Personal Property. 13.4 General Requirements Regarding Lessee's CGL and other Liability Insurance. The CGL insurance and, in addition, any and all Excess and/or Umbrella liability insurance, if any, shall include the City of Seattle as an additional insured for primary and non- contributory limits of liability for the total available limits of liability of each policy. The term "insurance" in this paragraph shall include insurance, self-insurance (whether funded or unfunded), alternative risk transfer techniques, capital market solutions or any other form of risk financing. 13.5 General Requirements for Lessee's Property and CGL Insurance. 13.5.1 Coverage shall not be cancelled without thirty (30) day written notice of such cancellation, except ten (10) day written notice as respects cancellation for non-payment of premium, to the City at its notice address except as may otherwise be specified in Revised Code of Washington (RCW) 48.18.290 (Cancellation by insurer.). The City and the Lessee mutually agree that for the purpose of RCW 48.18.290 (1) (b), for both liability and property insurance the City is deemed to be a "mortgagee, pledge, or other person shown by (the required insurance policies) to have an interest in any loss which may occur thereunder." 13.5.2 Each insurance policy required hereunder shall be (1) subject to reasonable approval by City that it conforms with the requirements of this Section, and (2) be issued by an insurer rated A-:VII or higher in the then-current A. M. Best's Key Rating Guide and licensed to do business in the State of Washington unless procured under the provisions of chapter 48.15 RCW (Unauthorized insurers). 13.5.3 Any deductible or self-insured retention ("S.I.R.") must be disclosed to, and shall be subject to reasonable approval by, the City. Lessee shall cooperate to provide such information as the City may reasonably deem to be necessary to assess the risk bearing capacity of the Lessee to sustain such deductible or S.I.R. The cost of any claim falling within a deductible or S.I.R. shall be the responsibility of Lessee. If a deductible or S.I.R. for CGL or equivalent insurance is not "fronted" by an insurer but is funded and/or administered by Lessee or a contracted third party claims administrator, Lessee agrees to defend and indemnify the City to the same extent as the City would be protected as an additional insured for primary and non-contributory limits of liability as required herein by an insurer. 13.5.4 The City shall have the right to periodically review the adequacy of property and liability insurance coverages and limits of liability in view of inflation, changing industry conditions and/or similar considerations and to require an adjustment in such coverage or limits upon ninety (90) day prior written notice. 13.6 Evidence of Insurance. On or before the Commencement Date, and thereafter not later than the last business day prior to the expiration date of each such policy, the following documents must be delivered to City at its notice address as evidence of the insurance coverage required to be maintained by Lessee: 13.6.1 A copy of the CGL and Property insurance policy's declarations pages; 13.6.2 A copy of the CGL insurance policy provision(s) documenting that the City of Seattle is an additional insured on a primary and non-contributory basis; 13.6.3 A copy of the CGL and Property insurance policy provisions that document that coverage shall not be cancelled without thirty (30) day written notice of such cancellation, except ten (10) day written notice as respects cancellation for non-payment of premium, unless otherwise specified in Revised Code of Washington (RCW) 48.18.290 (Cancellation by insurer.); and, 13.6.4 If the insurance policy documentation as otherwise required herein is not available because policies have not been issued, received and/or reviewed, binders of insurance that otherwise evidence compliance with this Section may be substituted until such copies of policy declarations pages, additional insured and cancellation provisions are reasonably available. A certificate of insurance form alone will not satisfy the requirements for documentation specified in this Subsection. 13.7 Damage or Destruction. If the Premises are rendered partially or wholly untenantable by fire or other casualty: 13.7.1 The City shall proceed with reasonable diligence as soon as sufficient insurance, self-insurance and/or other funds are available therefor, to prepare plans and specifications for, and thereafter to carry out, all work necessary to repair or replace the Premises or any portions thereof that were damaged or destroyed by a fire or other casualty. However, the City retains the sole option to not repair or replace the Premises for any reason, in which case the City shall advise Lessee of City's election to terminate this Lease by giving at least a thirty (30) day notice to Lessee. 13.7.2 If the City elects to repair or replace the Premises, Lessee shall proceed with reasonable diligence as soon as sufficient insurance, self-insurance and/or other proceeds and other funds are available therefor (in any event, within twenty-four (24) months from the date of the occurrence of a fire or other casualty), to repair or replace Business Personal Property that has been damaged or destroyed. 13.7.3 Rent and Additional Charges shall be abated in the proportion that the untenantable portion of the Premises bears to the whole Premises, in the City's sole determination, for the period from the date of the fire or other casualty until either the completion of the repairs and restoration or the termination of this lease at the City's option as provided herein. 13.7.4 If the Premises cannot be repaired or replaced within twenty-four (24) months from the date of the occurrence of the fire or other casualty, or if thirty percent (30%) or more of the Premise's interior area is damaged or destroyed Lessee may terminate this Lease upon sixty (60) days' written notice to the City. 13.7.5 Except in the event of City's gross negligence, intentional misconduct or breach of this Lease, City shall not be liable to Lessee for damages, compensation or other sums for inconvenience, loss of business or disruption arising from any repairs to or restoration of any portion of the Building or Premises or to the termination of this Lease as provided herein. 13.8 Assumption of Property Risk. The placement and storage of Lessee's Business Personal Property in or about the Premises shall be the responsibility, and at the sole risk, of Lessee. 14. Assignment or Sublease. Lessee shall not sublet or encumber the whole or any part of the Premises, nor shall this Lease or any interest thereunder be assignable or transferable by operation of law or by any process or proceeding of any court or otherwise without the prior written consent of City, whose consent shall be given or withheld in its sole discretion. The granting of consent to a given transfer shall not constitute a waiver of the consent requirement as to future transfers. Any assignment or sublease, without City's prior written consent, at City's option, shall be void. No assignment or sublease shall release Lessee from primary liability hereunder. Each assignment and sublease shall be by an instrument in writing in form satisfactory to City. If Lessee is a corporation, then any transfer of this Lease by merger, consolidation or liquidation, or any direct or indirect change, in the ownership of, or power to vote the majority of, Lessee's outstanding voting stock, shall constitute an assignment for the purposes of this Lease. If Lessee is a partnership, then a change in general partners in or voting or decision-making control of the partnership shall also constitute an assignment. 15. Assignment by City. If City sells or otherwise transfers the Premises, or if City assigns its interest in this Lease, such purchaser, transferee, or assignee thereof shall be deemed to have assumed City's obligations under this Lease arising after the date of such transfer, and City shall thereupon be relieved of all liabilities under this Lease arising thereafter, but this Lease shall otherwise remain in full force and effect. Lessee shall attorn to City's successor, which assumes and agrees to perform all of City's obligations under this Lease. 16. Eminent Domain. 16.1 Taking. If all of the Premises are taken by Eminent Domain, this Lease shall terminate as of the date Lessee is required to vacate the Premises and all Rent and Additional Charges shall be paid to that date. The term "Eminent Domain" shall include the taking or damaging of property by, through or under any governmental or statutory authority, and any purchase or acquisition in lieu thereof, whether the damaging or taking is by government or any other person. If a taking of any part of the Premises by Eminent Domain renders the remainder thereof unusable for the business of Lessee, in the reasonable judgment of City, the Lease may, at the option of either party, be terminated by written notice given to the other party not more than thirty (30) days after City gives Lessee written notice of the taking, and such termination shall be effective as of the date when Lessee is required to vacate the portion of the Premises so taken. If this Lease is so terminated, all Rent and Additional Charges shall be paid to the date of termination. Whenever any portion of the Premises is taken by Eminent Domain and this Lease is not terminated, City, at its expense, shall proceed with all reasonable dispatch to restore, to the extent of available proceeds and to the extent it is reasonably prudent to do so, the remainder of the Premises to the condition they were in immediately prior to such taking, and Lessee, at its expense, shall proceed with all reasonable dispatch to restore its personal property and all improvements made by it to the Premises to the same condition they were in immediately prior to such taking, to the extent award is available therefor. The Rent and Additional Charges payable hereunder shall be reduced from the date Lessee is required to partially vacate the Premises in the same proportion that the Rentable Area taken bears to the total Rentable Area of the Premises prior to taking. 16.2 Award. Except as otherwise provided below, City reserves all right to the entire damage award or payment for any taking by Eminent Domain, and Lessee waives all claim whatsoever against City for damages for termination of its leasehold interest in the Premises or for interference with its business. Lessee hereby grants and assigns to City any right Lessee may now have or hereafter acquire to such damages and agrees to execute and deliver such further instruments of assignment as City, from time to time, may request. Lessee, however, shall have the right to claim from the condemning authority all compensation that may be recoverable by Lessee on account of any loss incurred by Lessee in moving Lessee's merchandise, furniture, trade fixtures and equipment and the cost or restoring its personal property and improvements made by it to the Premises. 17. Default by Lessee. 17.1 Definition. If Lessee violates, breaches, or fails to keep or perform any term, provision, covenant, or any obligation of this Lease; or if Lessee files or is the subject of a petition in bankruptcy, or if a trustee or receiver is appointed for Lessee's assets or if Lessee makes an assignment for the benefit of creditors, or if Lessee is adjudicated insolvent, or becomes subject to any proceeding under any bankruptcy or insolvency law whether domestic or foreign, or liquidated, voluntarily or otherwise; then Lessee shall be deemed in default ("Default"). 17.2 City Remedies. If Lessee has defaulted and such Default continues or has not been remedied to the reasonable satisfaction of the Superintendent within thirty (30) days after written notice thereof has been provided to Lessee, then City shall have the following nonexclusive rights and remedies at its option: (i) to cure such default on Lessee's behalf and at Lessee's sole expense and to charge Lessee for all actual and reasonable costs and expenses incurred by City in effecting such cure as an Additional Charge; (2) to terminate this Lease; provided, however, that if the nature of Lessee's obligation (other than monetary obligations and other than vacation or abandonment of the Premises) is such that more than thirty (30) days is required for performance, then Lessee shall not be in default if it commences performance within such thirty (30) day period and thereafter diligently prosecutes the same to completion. 17.3 Reentry by City Upon Termination. Upon the termination of this Lease, City may reenter the Premises, take possession thereof, and remove all persons therefrom, for which actions Lessee shall have no claim thereon or hereunder. Lessee shall be liable and shall reimburse City upon demand for all actual and reasonable costs and expenses of every kind and nature incurred in retaking possession of the Premises. If City retakes the Premises, City shall have the right, but not the obligation, to remove therefrom all or any part of the personal property located therein and may place the same in storage at any place selected by City, including a public warehouse, at the expense and risk of Lessee. City shall have the right to sell such stored property, after reasonable prior notice to Lessee or such owner(s), after it has been stored for a period of thirty (30) days or more. The proceeds of such sale shall be applied first, to the cost of such sale; second, to the payment of the charges for storage, if any; and third, to the payment of any other sums of money that may be due from Lessee to City; the balance, if any, shall be paid to Lessee. 17.4 Vacation or Abandonment. If Lessee vacates or abandons the Premises in their entirety and fails to reoccupy them within thirty (30) days after City (1) delivers a notice to Lessee's notice address set forth in Section 1.5 above demanding such reoccupancy and (2) mails by certified or registered mail a copy of the notice to any forwarding address given by Lessee to City in writing, Lessee shall be in default under this Lease. 17.5 City's Non-exclusive Remedies upon Termination due to Default of Lessee. Notwithstanding any reentry by City and anything to the contrary in this Lease, in the event of the termination of this Lease due to the Default of Lessee, the liability of Lessee for all sums due under this Lease provided herein shall not be extinguished for the balance of the Term of this Lease. Lessee shall also be liable to City for any other amount (excluding consequential or specific damages) necessary to compensate City for all the detriment proximately caused by Lessee's failure to perform its obligations under this Lease or that in the ordinary course of things would be likely to result therefrom, including but not limited to, any costs or expenses incurred in maintaining or preserving the Premises after such Default, and any costs incurred in authorizing others the use and occupancy of the Premises and in preparing the Premises for such use and occupancy, and such other amounts in addition to or in lieu of the foregoing as may be permitted from time to time by the laws of the State of Washington. In the event of Termination due to Default of the Lessee, City will use reasonable efforts to mitigate its damages, but such efforts shall not be construed to be a waiver of the City's rights to be made whole by Lessee in the event of such Termination. The provisions of this Subsection 17.5 shall survive the expiration or earlier termination of this Lease. 18. City's Remedies Cumulative; Waiver. City's rights and remedies hereunder are not exclusive, but cumulative, and City's exercise of any right or remedy due to a default or breach by Lessee shall not be deemed a waiver of, or alter, affect or prejudice any other right or remedy that City may have under this Lease or by law or in equity. Neither the acceptance of rent nor any other act or omission of City at any time or times after the happening of any event authorizing the cancellation or forfeiture of this Lease shall operate as a waiver of any past or future violation, breach or failure to keep or perform any covenant, agreement, term or condition hereof or to deprive City of its right to cancel or forfeit this Lease, upon the written notice provided for herein, at any time that cause for cancellation or forfeiture may exist, or be construed so as to estop City at any future time from promptly exercising any other option, right or remedy that it may have under any term or provision of this Lease. 19. Default by City. City shall be in default if City fails to perform its obligations under this Lease within thirty (30) days after its receipt of notice of nonperformance from Lessee; provided, that if the default cannot reasonably be cured within the thirty (30) day period, City shall not be in default if City commences the cure within the thirty (30) day period and thereafter diligently pursues such cure to completion. Upon City's default, Lessee may pursue any remedies at law or in equity that may be permitted from time to time by the laws of the State of Washington. 20. Termination for Convenience. Notwithstanding anything else in this Lease to the contrary, the City may, at any time and without liability of any kind to Lessee, terminate this Lease upon One Hundred Twenty (120) days' written notice to Lessee if the City determines that the Premises are required for a different public purpose. 21. Attorneys' Fees. If either party retains the services of an attorney in connection with enforcing the terms of this Lease, each party agrees to bear its own attorneys' fees and costs. 22. Access by City. City and its agents shall have the right to enter the Premises at any reasonable time to examine the same, and to show them to prospective purchasers, lenders or tenants, and to make such repairs, alterations, improvements, additions or improvements to the Premises as City may deem necessary or desirable. If Lessee is not personally present to permit entry and an entry is necessary in an emergency, City may enter the same by master key or may forcibly enter the same, without rendering City liable therefor, except in the event of City's gross negligence or intentional misconduct. Nothing contained herein shall be construed to impose upon City any duty of repair or other obligation not specifically stated in this Lease. Lessee shall change the locks to the Premises only through City and upon paying City for all actual and reasonable costs related thereto. 23. Holding Over. Unless otherwise agreed in writing by the parties hereto, any holding over by Lessee after the expiration of the Lease Term, whether or not consented to by City, shall be construed as a tenancy from month-to-month on the terms and conditions set forth herein. Either party may terminate any holdover tenancy by written notice delivered to the other party not later than twenty (20) days prior to the end of the final month. If Lessee fails to surrender the Premises upon the expiration or termination of this Lease without City's written consent, Lessee shall indemnify, defend and hold harmless City from all losses, damages, liabilities and expenses resulting from such failure, including, without limiting the generality of the foregoing, any claims made by any succeeding tenant arising out of such failure. Lessee's obligations under this paragraph shall survive expiration or termination of this Lease. 24. Notices. Any notice, demand or request required hereunder shall be given in writing to the party's address set forth in Subsection 1.5 hereof by any of the following means: (a) personal service; (b) commercial or legal courier; or (c) registered or certified, first class mail, postage prepaid, return receipt requested. Such addresses may be changed by notice to the other parties given in the same manner as above provided. Notices shall be deemed to have been given upon the earlier of actual receipt, as evidenced by the deliverer's affidavit, the recipient's acknowledgment of receipt, or the courier's receipt, except in the event of attempted delivery during the recipient's normal business hours at the proper address by an agent of a party or by commercial or legal courier or the U.S. Postal Service but refused acceptance, in which case notice shall be deemed to have been given upon the earlier of the day of attempted delivery, as evidenced by the messenger's affidavit of inability to deliver stating the time, date, place and manner in which such delivery was attempted and the manner in which such delivery was refused, or on the day immediately following deposit with such courier or, if sent pursuant to subsection (c), forty-eight (48) hours following deposit in the U.S. mail. 25. Successors or Assigns. All of the terms, conditions, covenants and agreements of this Lease shall extend to and be binding upon City, Lessee and, subject to the terms of Sections 14 and 15, their respective heirs, administrators, executors, successors and permitted assigns, and upon any person or persons coming into ownership or possession of any interest in the Premises by operation of law or otherwise. 26. Authority and Liability. Lessee warrants that this Lease has been duly authorized, executed and delivered by Lessee, and that Lessee has the requisite power and authority to enter into this Lease and perform its obligations hereunder. Lessee covenants to provide City with evidence of its authority and the authorization of this Lease upon request. All persons and entities named as Lessee herein shall be jointly and severally liable for Lessee's liabilities, covenants and agreements under this Lease. 28. Partial Invalidity. If any court determines that any provision of this Lease or the application hereof to any person or circumstance is, to any extent, invalid or unenforceable, the remainder of this Lease, or application of such provision to persons or circumstances other than those as to which it is held invalid or unenforceable, shall not be affected thereby and each other term, covenant or condition of this Lease shall be valid and be enforced to the fullest extent permitted by law. 29. Force Majeure. Neither City nor Lessee shall be deemed in default hereof nor liable for damages arising from its failure to perform its duties or obligations hereunder if such is due to any cause beyond its reasonable control, including, but not limited to an act of Nature, act of civil or military authority, fire, flood, windstorm, earthquake, strike or labor disturbance, civil commotion, delay in transportation, governmental delay, or war; provided, however, that the foregoing shall not excuse Lessee from the timely payment of Rent and Additional Charges due hereunder, when due. 30. Counterparts. The parties may execute this Lease in counterparts, which, taken together, constitute the entire Lease. 31. Headings. The section headings used in this Lease are used for purposes of convenience and do not alter in any manner the content of the sections. 32. Context. Whenever appropriate from the context, the use of any gender shall include any other or all genders, and the singular shall include the plural, and the plural shall include the singular. 33. Execution by City and Lessee; Effective Date. Neither City nor Lessee shall be deemed to have made an offer to the other party by furnishing the other party with a copy of this Lease with particulars inserted. No contractual or other rights shall exist or be created between City and Lessee until all parties hereto have executed this Lease and the appropriate legislative authority approves it. This Lease shall become effective on the date (the "Effective Date") on which this Lease is executed by City and Lessee and approved by the Seattle City Council. City shall have no liability to Lessee and shall have the right to terminate this Lease upon written notice to Lessee if this Lease is legislatively disapproved. 34. Time of Essence; Time Calculation Method. Time is of the essence with respect to this Lease. Except as otherwise specifically provided, any reference in this Lease to the word "day" means a "calendar day"; provided, however, that if the final day for any action required hereunder is a Saturday, Sunday or City holiday, such action shall not be required until the next succeeding day that is not a Saturday, Sunday or City holiday. Any reference in this Lease to the word "month" means "calendar month." 35. Lessee's Hours of Operation. Lessee shall keep the Premises open during the school months and use them to transact business with the public daily during hours as designated below or as otherwise may be designated by the Superintendent. Subject to the Superintendent's prior reasonable approval, Lessee may, upon posting a written notice to the public of not less than one (1) week in duration prior to any approved closure, close the Premises or a portion thereof for a reasonable period for repairs or any approved remodeling, or for taking inventory. Lessee shall close to accommodate reasonable operational requirements of City's business, upon thirty (30) days' prior written notice to Lessee, and Lessee shall immediately close in the case of any emergency as determined by the Superintendent; provided, however, that if Lessee shall close pursuant to this sentence at the direction of City, and if Lessee remains closed at the direction of City for more than three (3) days, then Lessee's Rent and Additional Charges shall be prorated for the duration of the closure in the proportion that the number of days of the closure bears to the number of days of the month. Lessee shall furnish an approved sign at the Premises entrance advising the public of any approved closure, unless closed at the Direction of City. Minimum hours of operation of the business conducted on the Premises are as follows: Monday thru Friday 8:00 am 5:00 pm Saturday (Lessee can come in between these times to perform Cleaning of building) 10:00 am 2:00 pm Sunday (Lessee can come in between these times to perform Cleaning of building) 10:00 am 2:00 pm 36. Standards. Lessee recognizes that, although it is operating its facilities as an independent operator, DPR is organized and exists for the purpose of maintaining park and recreation facilities for the use and enjoyment of the general public. Lessee, its agents and employees, will devote their efforts toward rendering courteous service to the public as though they were employees of the City, with a view of adding to the enjoyment of the patrons of this recreational facility. Lessee shall operate and conduct the facilities on the Premises in a businesslike manner, and will not permit any conduct on the part of Lessee's employees, which would be detrimental to City's operations. 37. City's Control of Premises and Vicinity. All common and other facilities provided by City in or about the Premises are subject to the City's exclusive control and management by City. Accordingly, City may do any and all of the following (among other activities in support of DPR or other municipal objectives), all without incurring any liability whatsoever to Lessee: 37.1 Change of Vicinity. City may increase, reduce, or change in any manner whatsoever the number, dimensions, and locations of the walks, buildings, landscaping, exhibit, service area, and parking areas in the vicinity of the Premises; 37.2 Traffic Regulation. City may regulate all traffic within and adjacent to the Premises, including the operation and parking of vehicles of Lessee and its invitees, employees, and patrons. 37.3 Display of Promotional Materials. City may erect, display, and remove promotional exhibits and materials and permit special events on property adjacent to and nearby the Premises. 37.4 Promulgation of Rules. City may promulgate, from time to time, reasonable rules and regulations regarding the use and occupancy of any Department property including, but not limited to, the Premises. 37.5 Change of Businesses. City may change the size, number, and type and identity of concessions, stores, businesses and operations being conducted or undertaken in the vicinity of the Premises. 38. Miscellaneous. 38.1 Entire Lease; Applicable Law. This Lease and the Exhibits attached hereto, and by this reference incorporated herein, set forth the entire agreement of City and Lessee concerning the Premises, and there are no other agreements or understanding, oral or written, between City and Lessee concerning the Premises. Any subsequent modification or amendment of this Lease shall be binding upon City and Lessee only if reduced to writing and signed by them. This Lease shall be governed by, and construed in accordance with the laws of the State of Washington. 38.2 Negotiated Lease. The parties to this Lease acknowledge that it is a negotiated agreement, that they have had the opportunity to have this Lease reviewed by their respective legal counsel, and that the terms and conditions of this Lease are not to be construed against any party on the basis of such party's draftsmanship thereof. IN WITNESS WHEREOF, the parties hereto have executed this instrument the day and year indicated below. CITY: LESSEE: THE CITY OF SEATTLE VICTORY HEIGHTS COOPERATIVE PRESCHOOL By: ______________________________ By: Print Name:_Timothy A. Gallager______ Print Name: _______________________________ Title: _Superintendent _______________ Title: _____________________________________ Department of Parks and Recreation Victory Heights Cooperative Preschool STATE OF WASHINGTON ) ) ss. (Acknowledgement for City) COUNTY OF KING ) On this _____ day of ______________, 20__, before me, the undersigned, a Notary Public in and for the State of Washington, duly commissioned and sworn personally appeared _______________, known to me to be the ___________________ of the Department of Parks and Recreation of THE CITY OF SEATTLE, the party that executed the foregoing instrument as City, and acknowledged said instrument to be the free and voluntary act and deed of said party, for the purposes therein mentioned, and on oath stated that he/she was authorized to execute said instrument. WITNESS my hand and official seal hereto affixed the day and year in the certificate above written. [Signature] [Printed Name] NOTARY PUBLIC in and for the State of Washington residing at . My commission expires ______________. STATE OF WASHINGTON ) ) ss. (Acknowledgement for ___________) COUNTY OF KING ) On this _____ day of _________________, 20__, before me, a Notary Public in and for the State of Washington, duly commissioned and sworn, personally appeared _____________, to me known to be the __________________of _____________________, the entity that executed the foregoing instrument as ___________; and acknowledged to me that he signed the same as the free and voluntary act and deed of said entity for the uses and purposes therein mentioned and that he was authorized to execute said instrument for said entity. WITNESS my hand and official seal the day and year in this certificate above written. [Signature] [Printed Name] NOTARY PUBLIC in and for the State of Washington residing at . My commission expires ______________. EXHIBIT A Legal Description The Victory Heights Shelter House is located on the following property, legally described as follows: VICTORY HEIGHTS PLAYGROUND Lots 1,2, Block B, Lots 1,2,3,4, Block C, Replat of Blocks 12 and 13 of Victory Heights, together with that portion of vacated Seward Place Northeast adjoining Tax parcel No. 8901500065
C
UTF-8
377
3.1875
3
[]
no_license
#include <stdio.h> int main(){ int kasus, n, b, k, h, v, baris, kolom; scanf("%d", &n); for(kasus=1;kasus<=n;kasus++){ scanf("%d %d %d %d", &b, &k, &h, &v); for(baris=1;baris<=b;baris++){ for(kolom=1;kolom<=k;kolom++){ if(kolom == v || baris == h) printf("ANJING"); else if(kolom<v) printf(" "); } printf("\n"); } if(kasus != n) printf("\n"); } }
Shell
UTF-8
766
2.640625
3
[ "MIT" ]
permissive
#!/bin/bash # pritunl sudo tee /etc/apt/sources.list.d/pritunl.list << EOF deb http://repo.pritunl.com/stable/apt xenial main EOF sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com --recv 7568D9BB55FF9E5287D586017AE645C0CF8E292A # mongodb wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add - sudo apt-get install gnupg wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add - echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list apt-get --assume-yes update apt-get --assume-yes upgrade apt-get --assume-yes install pritunl mongodb-org systemctl start pritunl mongod systemctl enable pritunl mongod
C++
UTF-8
2,130
2.625
3
[]
no_license
#include "Cfg_SDL.h" int Cfg_SDL::initSDL() { if (SDL_Init(SDL_INIT_VIDEO) < 0) { return Cfg_SDL::ERROR_SDL_INIT; } return 0; } int Cfg_SDL::defaults(SDL_Window*& window, SDL_GLContext& context, unsigned int screenWidth, unsigned int screenHeight, unsigned int sMinor, unsigned int sMajor, bool hasAA) { unsigned int engineError; if (engineError = Cfg_SDL::initSDL() > 0) return engineError; if (engineError = Cfg_SDL::setGlAttributes(sMinor, sMajor) > 0) return engineError; if (engineError = Cfg_SDL::initWindow(window, screenWidth, screenHeight) > 0) return engineError; if (engineError = Cfg_SDL::initContext(context, window) > 0) return engineError; if (engineError = Cfg_SDL::initGlew() > 0) return engineError; if (hasAA) bool hasAA = false; Cfg_SDL::initMultisampling(1,4); } int Cfg_SDL::setGlAttributes(unsigned int major, unsigned int minor) { SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minor); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); return 0; } void Cfg_SDL::initMultisampling(int buffers, int sampleSize) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, buffers); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, sampleSize); } int Cfg_SDL::initWindow(SDL_Window*& window, unsigned int width, unsigned int height) { window = SDL_CreateWindow( "Thunderbolt", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE ); if (!window) { return Cfg_SDL::ERROR_CREATE_WINDOW; } return 0; } int Cfg_SDL::initContext(SDL_GLContext& context, SDL_Window*& window) { context = SDL_GL_CreateContext(window); if (!context) { return Cfg_SDL::ERROR_CREATE_CONTEXT; } return 0; } int Cfg_SDL::initGlew() { glewExperimental = GL_TRUE; GLenum err = glewInit(); if (err) { return Cfg_SDL::ERROR_GLEW_INIT; } return 0; } int Cfg_SDL::shutDown(SDL_Window*& window, SDL_GLContext& context) { SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
Java
UTF-8
2,115
1.914063
2
[]
no_license
package toker.panel.config; import org.openid4java.consumer.ConsumerManager; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.boot.web.servlet.MultipartConfigFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpRequest; import org.springframework.http.client.support.HttpRequestWrapper; import org.springframework.security.openid.NullAxFetchListFactory; import org.springframework.security.openid.OpenID4JavaConsumer; import org.springframework.security.openid.OpenIDConsumer; import org.springframework.util.unit.DataSize; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; import javax.servlet.MultipartConfigElement; import java.net.URI; @Configuration public class GeneralBeanConfig { @Bean public OpenIDConsumer openIDConsumer() { ConsumerManager manager = new ConsumerManager(); manager.setMaxAssocAttempts(0); return new OpenID4JavaConsumer(manager, new NullAxFetchListFactory()); } @Bean @Qualifier("steam-api") public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.interceptors((request, body, execution) -> { HttpRequest newRequest = new HttpRequestWrapper(request) { @Override public URI getURI() { return UriComponentsBuilder.fromHttpRequest(request) .queryParam("key", "827E49C8DF4885520BD4559A0BC83F23") .build().toUri(); } }; return execution.execute(newRequest, body); }).build(); } @Bean public MultipartConfigElement multipartConfig() { MultipartConfigFactory factory = new MultipartConfigFactory(); factory.setMaxFileSize(DataSize.ofMegabytes(1280)); factory.setMaxRequestSize(DataSize.ofMegabytes(1280)); return factory.createMultipartConfig(); } }
PHP
UTF-8
1,591
2.859375
3
[]
no_license
<style media="screen"> *{ margin: 0; padding: 0; box-sizing: border-box; } .container { background-color: lightblue; width: 100vw; height: 100vh; display: flex; flex-direction: column; justify-content: space-around; align-items: center; padding: 10px; font-weight: bold; } .pluto { border: 1px solid black; padding: 15px; border-radius: 5px; } </style> <div class="container"> <?php class User { public $name; public $nickname; public $age; public $mail; public $photo; public function __construct($name,$nickname,$age,$mail,$photo = 'photo'){ $this -> name = $name; $this -> nickname = $nickname; $this -> age = $age; $this -> mail = $mail; $this -> photo = $photo; } // public function getDetails(){ // return $this -> name . '<br>'. $this -> nickname . '<br>'. $this -> age . '<br>'. $this -> mail . '<br>'. $this -> photo; // } public function __toString() { return $this -> name . '<br>'. $this -> nickname . '<br>'. $this -> age . '<br>'. $this -> mail . '<br>'. $this -> photo; } } $user1 = new User('Pluto','pippo1',20,"pluto@gmail.com"); $user2 = new User('Topolino','paperino',20,"topolino@gmail.com"); // echo $user1 -> getDetails(); ?> <div class="pluto"> <?php echo $user1; ?> </div> <div class="pluto"> <?php echo $user2; ?> </div> </div>
JavaScript
UTF-8
1,166
2.875
3
[ "MIT" ]
permissive
var socket = io.connect('http://localhost:4000/'); var nickname = undefined; var textcolor = undefined; socket.on('connected', function(name, color) { $('.connecting').slideUp(); $('input').attr('disabled', false); $('#name').text('Hello, '+name); $('#name').addClass(color); nickname = name textcolor = color; }); socket.on('pm', function(data) { writeLine(data.name, data.color, data.line); }); function writeLine(name, color, line) { var $span = $('<span>'); var $li = $('<li>'); $span.addClass('nick').text(name+": "); $li.addClass(color).text(line); $li.prepend($span); $('.chatlines').append($li); }; $(function () { $('form').on('submit', function(ev) { ev.preventDefault(); var chattext = $('#chattext').val(); var firstchar = chattext.split(" ")[0].charAt(0); var to = "All" console.log("firstchar: "+firstchar); if (firstchar == "@") { var atTo = chattext.split(" ")[0] to = atTo.substring(1, atTo.length) } socket.emit('pm', {name: nickname, to: to, color: textcolor, line: chattext}); writeLine(nickname, textcolor, chattext); $('#chattext').val(""); }); });
TypeScript
UTF-8
4,073
2.59375
3
[ "MIT" ]
permissive
import AbstractAdapter from './Adapter/AbstractAdapter'; import InMemoryAdapter from './Adapter/InMemoryAdapter'; import {Counter, Gauge, Histogram, MetricInterface} from './Metric'; import MetricFamilySamples from './MetricFamilySamples'; export default class Registry { public static getDefault(): Registry { if (!Registry.defaultRegistry) { Registry.defaultRegistry = new Registry(new InMemoryAdapter()); } return Registry.defaultRegistry; } private static defaultRegistry: Registry; public readonly storageAdapter: AbstractAdapter; private readonly gauges: Gauge[] = []; private readonly counters: Counter[] = []; private readonly histograms: Histogram[] = []; public constructor(adapter: AbstractAdapter) { this.storageAdapter = adapter; } public async getMetricFamilySamples(): Promise<MetricFamilySamples[]> { return this.storageAdapter.collect(); } public registerCounter(config: Partial<MetricInterface>): Counter { const metricIdentifier = this.metricIdentifier(config.namespace, config.name); if (this.counters[metricIdentifier] !== undefined) { throw new Error('Metric already registered'); } this.counters[metricIdentifier] = new Counter(this.storageAdapter, config); return this.counters[metricIdentifier]; } public getCounter(namespace: string, name: string): Counter { const metricIdentifier = this.metricIdentifier(namespace, name); if (this.counters[metricIdentifier] === undefined) { throw new Error('Metric is not registered'); } return this.counters[metricIdentifier]; } public getOrRegisterCounter(config: Partial<MetricInterface>): Counter { try { return this.getCounter(config.namespace, config.name); } catch (e) { return this.registerCounter(config); } } public registerGauge(config: Partial<MetricInterface>): Gauge { const metricIdentifier = this.metricIdentifier(config.namespace, config.name); if (this.gauges[metricIdentifier] !== undefined) { throw new Error('Metric already registered'); } this.gauges[metricIdentifier] = new Gauge(this.storageAdapter, config); return this.gauges[metricIdentifier]; } public getGauge(namespace: string, name: string): Gauge { const metricIdentifier = this.metricIdentifier(namespace, name); if (this.gauges[metricIdentifier] === undefined) { throw new Error('Metric is not registered'); } return this.gauges[metricIdentifier]; } public getOrRegisterGauge(config: Partial<MetricInterface>): Gauge { try { return this.getGauge(config.namespace, config.name); } catch (e) { return this.registerGauge(config); } } public registerHistogram(config: Partial<MetricInterface>): Histogram { const metricIdentifier = this.metricIdentifier(config.namespace, config.name); if (this.histograms[metricIdentifier] !== undefined) { throw new Error('Metric already registered'); } this.histograms[metricIdentifier] = new Histogram(this.storageAdapter, config); return this.histograms[metricIdentifier]; } public getHistogram(namespace: string, name: string): Histogram { const metricIdentifier = this.metricIdentifier(namespace, name); if (this.histograms[metricIdentifier] === undefined) { throw new Error('Metric is not registered'); } return this.histograms[metricIdentifier]; } public getOrRegisterHistogram(config: Partial<MetricInterface>): Histogram { try { return this.getHistogram(config.namespace, config.name); } catch (e) { return this.registerHistogram(config); } } private metricIdentifier(namespace: string, name: string): string { return `${namespace}:${name}`; } }
Java
UTF-8
5,940
2.59375
3
[]
no_license
package pool; import jdbc.servlet.todo.pool.ExpireGenericPool; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.NoSuchElementException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class TestExpireObjectPool { private final String DUMMY_FACTORY_RESULT = "Hello world"; private final int EXPIRATION_TIME = 4000; private final int MAX_OBJECT_POOL_SIZE = 10; ExpireGenericPool<StringWithId> expireGenericPool; @Before public void init() { expireGenericPool = new ExpireGenericPool.Builder<StringWithId>() .setExpireTime(EXPIRATION_TIME) .setFactory(() -> new StringWithId(DUMMY_FACTORY_RESULT)) .setMaxObjectsInPool(MAX_OBJECT_POOL_SIZE) .build(); } @Test(expected = NullPointerException.class) public void testNullFactory() { new ExpireGenericPool.Builder<String>().setFactory(null) .setExpireTime(10) .setMaxObjectsInPool(10) .build(); } @Test(expected = IllegalArgumentException.class) public void testZeroExpirationTime() { new ExpireGenericPool.Builder<String>().setFactory(() -> "") .setExpireTime(0) .setMaxObjectsInPool(10) .build(); } @Test(expected = IllegalArgumentException.class) public void testNegativeExpirationTime() { new ExpireGenericPool.Builder<String>().setFactory(() -> "") .setExpireTime(-1) .setMaxObjectsInPool(10) .build(); } @Test(expected = IllegalArgumentException.class) public void testZeroObjectsSizeInPool() { new ExpireGenericPool.Builder<String>().setFactory(() -> "") .setExpireTime(10) .setMaxObjectsInPool(0) .build(); } @Test(expected = IllegalArgumentException.class) public void testNegativeObjectsSizeInPool() { new ExpireGenericPool.Builder<String>().setFactory(() -> "") .setExpireTime(10) .setMaxObjectsInPool(-1) .build(); } @Test public void testObjectFactoryPoolValue() { StringWithId producedValueByFactory = expireGenericPool.get(); Assert.assertEquals(DUMMY_FACTORY_RESULT, producedValueByFactory.getValue()); } @Test public void testObjectInPoolSize() { testObjectFactoryPoolValue(); Assert.assertEquals(1, expireGenericPool.size()); } @Test public void testBusyObjectPoolSize() { testObjectFactoryPoolValue(); Assert.assertEquals(1, expireGenericPool.busyObjectSize()); } @Test public void testFreeObjectPoolSize() { testObjectFactoryPoolValue(); Assert.assertEquals(0, expireGenericPool.freeObjectSize()); } @Test(expected = NullPointerException.class) public void testIfObjectIsExpiredWithNull() { expireGenericPool.isExpired(null); } @Test(expected = NoSuchElementException.class) public void testIfUnrecognizedObjectIsExpired() { expireGenericPool.isExpired(new StringWithId("UNRECOGNIZED OBJECT")); } @Test(expected = NullPointerException.class) public void testReturnBackForNull() { expireGenericPool.returnBack(null); } @Test(expected = NoSuchElementException.class) public void testReturnBackWithUnrecognizedObject() { expireGenericPool.returnBack(new StringWithId("UNRECOGNIZED OBJECT")); } @Test public void testReturnBackReceivedObject() { StringWithId receivedObj = expireGenericPool.get(); Assert.assertEquals(1, expireGenericPool.busyObjectSize()); Assert.assertEquals(0, expireGenericPool.freeObjectSize()); Assert.assertEquals(1, expireGenericPool.size()); expireGenericPool.returnBack(receivedObj); Assert.assertEquals(0, expireGenericPool.busyObjectSize()); Assert.assertEquals(1, expireGenericPool.freeObjectSize()); Assert.assertEquals(1, expireGenericPool.size()); } @Test public void testObjectValidObjectExpirationTime() throws InterruptedException { StringWithId receivedObj = expireGenericPool.get(); TimeUnit.MILLISECONDS.sleep(EXPIRATION_TIME + 100); Assert.assertTrue(expireGenericPool.isExpired(receivedObj)); } @Test public void testConcurrentObjectCreation() throws InterruptedException { ExecutorService executorService = Executors.newCachedThreadPool(); executorService.execute(() -> { while (expireGenericPool.busyObjectSize() < 5) { expireGenericPool.get(); } }); //Time for value generation TimeUnit.SECONDS.sleep(1); Assert.assertEquals(expireGenericPool.busyObjectSize(), 5); } @Test public void testForceRetrieveObjectsIfTheyAreExpired() throws InterruptedException { ExecutorService executorService = Executors.newCachedThreadPool(); int totalReceivedObjects = MAX_OBJECT_POOL_SIZE / 2; executorService.execute(() -> { while (expireGenericPool.busyObjectSize() < totalReceivedObjects) { expireGenericPool.get(); } }); //for object instantiation TimeUnit.MILLISECONDS.sleep(EXPIRATION_TIME / 5); Assert.assertEquals(totalReceivedObjects, expireGenericPool.size()); Assert.assertEquals(totalReceivedObjects, expireGenericPool.busyObjectSize()); Assert.assertEquals(0, expireGenericPool.freeObjectSize()); TimeUnit.MILLISECONDS.sleep(EXPIRATION_TIME * 2); Assert.assertEquals(totalReceivedObjects, expireGenericPool.freeObjectSize()); Assert.assertEquals(0, expireGenericPool.busyObjectSize()); } }
Java
UTF-8
601
2.375
2
[]
no_license
package AAAAAAPracs.async; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * @author bockey */ @Slf4j @Component public class TaskTest { // ้—ด้š”1็ง’ๆ‰ง่กŒไธ€ๆฌก @Async @Scheduled(cron = "0/1 * * * * ?") public void method1() { log.info("โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”method1 startโ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”"); log.info("โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”method1 endโ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”"); } }
Python
UTF-8
3,388
4
4
[]
no_license
# open๏ผˆโ€˜ๆ–‡ไปถๆ‰€ๅœจไฝ็ฝฎ+ๆ–‡ไปถๅโ€™๏ผŒโ€˜ๅฏนๆ–‡ไปถๅค„็†็š„ๆ–นๅผ๏ผˆr๏ผŒw๏ผŒa๏ผ‰โ€˜ ,encoding = '็ผ–็ ๅฝขๅผ๏ผˆๅฆ‚utf-8๏ผ‰'๏ผ‰ โ€˜rโ€™ๅช่ฏป๏ผŒ'r+'่ฏปๅ†™ๆจกๅผ # f = open('11.text','r',encoding='utf-8') #ๆ‰“ๅผ€ๆ–‡ไปถ็š„็ผ–็ ่ฆไธŽๆ–‡ไปถๆœฌ่บซ็š„็ผ–็ ่ฆไธ€่‡ด # a = f.read() #read๏ผˆ๏ผ‰ๅฐ†ๆ–‡ไปถไธญ็š„ๆ‰€ๆœ‰ๅ†…ๅฎน่ฏปๅ‡บ # print(a) # b = f.readable() #ๅˆคๆ–ญๆ–‡ไปถๆ˜ฏๅฆๅฏไปฅ่ฏปๅ‡บๆฅ๏ผŒ่ฟ”ๅ›žboolๅ€ผ # print(b) # c = f.readline() #ไธ€่กŒไธ€่กŒ็š„่ฏป # print(c) # d = f.readlines() #ๅฐ†ๆ‰€ๆœ‰็š„ๆ–‡ไปถๅ†…ๅฎนๅ…จ้ƒจ่ฏปๅ‡บๆฅ๏ผŒๆฏไธ€่กŒไธบไธ€ไธชๅ…ƒ็ด ๆ”พๅœจๅˆ—่กจไธญ # print(d) # f.close() # # โ€˜wโ€™ๆจกๅผ๏ผŒๅฝ“ๆ–‡ไปถๅไธๅญ˜ๅœจๆ—ถ๏ผŒๅˆ›ๅปบๆ–‡ไปถ๏ผˆๅญ˜ๅœจๆ—ถ๏ผŒ่€…่ฆ†็›–ๅŽŸๆ–‡ไปถ๏ผ‰ # f = open('11.text','w',encoding='utf-8') # f.write('jiang\njiang\njiang') #'w'ๆจกๅผไธ‹ไนŸๆœ‰writeline๏ผˆ๏ผ‰๏ผŒwriteable๏ผˆ๏ผ‰็ญ‰ไฝฟ็”จๆ–นๆณ•๏ผŒไธŽโ€˜rโ€™ๆจกๅผ็›ธไผผ # f.close() # # 'a'ๆจกๅผ๏ผŒๆทปๅŠ ๆจกๅผ๏ผŒๅœจๆ–‡ไปถ็š„ๆœ€ๅŽๆทปๅŠ ๅ†…ๅฎน # f = open('11.text','a',encoding='utf-8') # f.write('jianren\n') #ไปŽๆ–‡ไปถไธญ็š„ๆœ€ๅŽๅค„ๅผ€ๅง‹ๆทปๅŠ  # f.close() # # โ€˜r+โ€™ ่ฏปๅ†™ๆจกๅผ # f = open('11.text','r+',encoding='utf-8') # print(f.read()) # f.write('jiangxiaolong\njiangxiaolong\njiangxiaolong\n') # ๅœจโ€˜r+โ€™ๆจกๅผไธ‹๏ผŒwrite๏ผˆ๏ผ‰ๆ˜ฏ่ฟฝๅŠ ๆ–‡ไปถ # f.writelines(['jiangxiaolong\n','age\n','ttt']) #writelines๏ผˆ๏ผ‰๏ผŒไผ ๅ…ฅๅˆ—่กจ๏ผŒโ€˜\nโ€™,ๅ…ƒ็ด ๆข่กŒ # f.close() # # # # with open('11.text','r+',encoding='utf-8') as f: #ไฝฟ็”จwithๆ›ดๅŠ ๆ–นไพฟ,็œ็•ฅไบ†close๏ผˆ๏ผ‰ # a = f.read() # print(a) # f.write('\nsb\n sb') # # ้™คไบ†'r','a','w'็ญ‰ๆจกๅผๅค–่ฟ˜ๅฏไปฅๅœจ่ฟ™ไบ›ๆจกๅผ็š„ๅŽ้ขๅŠ โ€˜b๏ผˆbytesไบŒ่ฟ›ๅˆถ๏ผ‰โ€™๏ผŒ่กจ็คบไปฅไบŒ่ฟ›ๅˆถ็š„ๆ–นๅผ่ฏปๅ†™ # ้‚ฃไนˆไธบไป€ไนˆ่ฆๆœ‰โ€˜bโ€™ๅ‘ข๏ผŒๅ› ไธบ่ฏปๅ†™ๆ–‡ไปถๆ—ถ๏ผŒๆ–‡ไปถไธๆ˜ฏๅชๆœ‰ๅญ—็ฌฆไธฒไธฒ๏ผŒ่ฟ˜ๆœ‰ๅ›พ็‰‡๏ผŒ่ง†้ข‘็ญ‰ # f = open('11.text','rb+') #ๅœจไบŒ่ฟ›ๅˆถ็š„ๆจกๅผไธ‹๏ผŒไธ่ƒฝๅŠ ๅ…ฅencoding # a = f.read() #ไปฅไบŒ็บงๅˆถ็š„ๅฝขๅผ่ฏปๅ‡บๆ–‡ไปถๅ†…ๅฎน # print(a) # f.write('jiang\nxiao\nlong'.encode('utf-8')) # ่ฆๅœจๅ†™ๅ…ฅ็š„ๅ†…ๅฎนๅŽ้ขไฝฟ็”จencode๏ผˆ๏ผ‰ๆ–นๆณ•๏ผŒ # f.write(bytes('jiang\nxiao\nlong',encoding='utf-8')) #ๅฐ†ๅญ—็ฌฆไธฒ่ฝฌๅŒ–ไธบไบŒ่ฟ›ๅˆถ๏ผŒไนŸๅฏไปฅ็”จbytesๅ‡ฝๆ•ฐ # f.close() # # # ไธ€ไธชๅฐ็ปƒไน ๏ผŒ็ป™ไฝ ไธ€ไธชๆ–‡ไปถๆ€Žไนˆ่ฏปๅ‡บ่ถ…ๅคงๆ–‡ไปถ็š„ๆœ€ๅŽ้ขไธ€่กŒ็š„ไฟกๆฏ # ่ฟ™้‡Œ่ฆไป‹็ป ๅ…‰ๆ ‡๏ผˆ่ฏปๅ–ๅ†™ไปŽไป€ไนˆไฝ็ฝฎๅผ€ๅง‹๏ผˆไปŽๅ…‰ๆ ‡็š„ไฝ็ฝฎๅ‘ๅŽๆ“ไฝœ๏ผ‰็ฑปไผผไบŽ้ผ ๆ ‡ๅœจๆ–‡ไปถไธญ็š„ไฝ็ฝฎ๏ผ‰ # seek๏ผˆoffset: int๏ผ‰ offset่กจ็คบๅ‘ๅŽ็งปๅŠจ็š„ๆ•ฐ้‡๏ผŒintๆœ‰3็ง็ฑปๅž‹ใ€‚1๏ผˆ่กจ็คบไปŽ0็š„ไฝ็ฝฎๅผ€ๅง‹็งปๅŠจ๏ผ‰๏ผŒ2๏ผˆ่กจ็คบไปŽ็›ธๅฏนไฝ็ฝฎๅผ€ๅง‹็งปๅŠจ๏ผ‰๏ผŒ # 3๏ผˆ่กจ็คบไปŽๆ–‡ไปถ็š„ๆœ€ๅŽๅผ€ๅง‹็งปๅŠจ๏ผ‰ # # f = open('11.text','r+',encoding='utf-8') # # f.seek(9,0) #่ฟ™้‡Œ่ฆๆณจๆ„็š„ๆ˜ฏ1ไธญๆ–‡ๅญ—็ฌฆไปฃ่กจ3ไธชๅญ—่Š‚๏ผŒๅœจWindowsไธญๆข่กŒไปฃ่กจ2ไธชๅญ—่Š‚๏ผŒๅ…ถไป–็š„้ƒฝๆ˜ฏไธ€ไธช # # print(f.read()) # # f.close() # ่ฏปๅ–ๆ–‡ไปถ็š„ๆœ€ๅŽไธ€่กŒ # f = open('11.text','rb') # x = -3 # while True: # f.seek(x,2) # print(f.fileno()) #fileno()ๅ‡ฝๆ•ฐ๏ผŒๆŸฅ็œ‹ๅฝ“ๅ‰ๅ…‰ๆ ‡ๆ‰€ๅœจ็š„ไฝ็ฝฎ # date = f.readlines() # if len(date) > 1: # print(date[-1].decode(encoding='utf-8')) #decode()่งฃ็ ๅ‡ฝๆ•ฐ๏ผŒๅฐ†ไบŒ็บงๅˆถ่งฃ็  # break # x = x -3 # f.close()
C++
UTF-8
13,137
2.921875
3
[ "MIT" ]
permissive
#include <Rcpp.h> #include "ColorSpace.h" #include "Comparison.h" #include <memory> using namespace Rcpp; // returns the number of dimensions for a color space type // with a special case for Cmyk template <typename SPACE> inline int dimension(){ return 3 ; } template <> inline int dimension<ColorSpace::Cmyk>(){ return 4 ; } // read a color from a color space in the row, and convert it to rgb template <typename Space> void fill_rgb( NumericMatrix::ConstRow row, ColorSpace::Rgb* rgb){ Space( row[0], row[1], row[2] ).ToRgb(rgb) ; } template <> void fill_rgb<ColorSpace::Cmyk>( NumericMatrix::ConstRow row, ColorSpace::Rgb* rgb){ ColorSpace::Cmyk( row[0], row[1], row[2], row[3] ).ToRgb(rgb) ; } // these grab values from the Space type and use them to fill `row` // unfortunately, given how the `ColorSpace` C++ library is written, // this has to do lots of special casing template <typename Space> void grab( NumericMatrix::Row row, const Space& ) ; template <> void grab<ColorSpace::Rgb>( NumericMatrix::Row row, const ColorSpace::Rgb& color){ row[0] = color.r ; row[1] = color.g ; row[2] = color.b ; } template <> void grab<ColorSpace::Xyz>( NumericMatrix::Row row, const ColorSpace::Xyz& color){ row[0] = color.x ; row[1] = color.y ; row[2] = color.z ; } template <> void grab<ColorSpace::Hsl>( NumericMatrix::Row row, const ColorSpace::Hsl& color){ row[0] = color.h ; row[1] = color.s ; row[2] = color.l ; } template <> void grab<ColorSpace::Lab>( NumericMatrix::Row row, const ColorSpace::Lab& color){ row[0] = color.l ; row[1] = color.a ; row[2] = color.b ; } template <> void grab<ColorSpace::Lch>( NumericMatrix::Row row, const ColorSpace::Lch& color){ row[0] = color.l ; row[1] = color.c ; row[2] = color.h ; } template <> void grab<ColorSpace::Luv>( NumericMatrix::Row row, const ColorSpace::Luv& color){ row[0] = color.l ; row[1] = color.u ; row[2] = color.v ; } template <> void grab<ColorSpace::Yxy>( NumericMatrix::Row row, const ColorSpace::Yxy& color){ row[0] = color.y1 ; row[1] = color.x ; row[2] = color.y2 ; } template <> void grab<ColorSpace::Cmy>( NumericMatrix::Row row, const ColorSpace::Cmy& color){ row[0] = color.c ; row[1] = color.m ; row[2] = color.y ; } template <> void grab<ColorSpace::Cmyk>( NumericMatrix::Row row, const ColorSpace::Cmyk& color){ row[0] = color.c ; row[1] = color.m ; row[2] = color.y ; row[3] = color.k ; } template <> void grab<ColorSpace::Hsv>( NumericMatrix::Row row, const ColorSpace::Hsv& color){ row[0] = color.h ; row[1] = color.s ; row[2] = color.v ; } template <> void grab<ColorSpace::Hsb>( NumericMatrix::Row row, const ColorSpace::Hsb& color){ row[0] = color.h ; row[1] = color.s ; row[2] = color.b ; } template <> void grab<ColorSpace::HunterLab>( NumericMatrix::Row row, const ColorSpace::HunterLab& color){ row[0] = color.l ; row[1] = color.a ; row[2] = color.b ; } // this is where the real work happens, // the template parameters Space_From and Space_To give us the types of the // from and to colours. template <typename Space_From, typename Space_To> NumericMatrix convert_dispatch_impl( const NumericMatrix& colour, const NumericVector& white_from, const NumericVector& white_to ){ // check that the dimensions of the input match the colour space if( dimension<Space_From>() != colour.ncol() ){ stop("colourspace requires %d values", dimension<Space_From>() ) ; } // make the result matrix int n = colour.nrow() ; NumericMatrix out(n, dimension<Space_To>() ) ; ColorSpace::Rgb rgb ; Space_To to ; for( int i=0; i<n; i++){ // fill `rgb` based on the input color in the `from` color space ColorSpace::XyzConverter::whiteReference = {white_from[0], white_from[1], white_from[2]}; fill_rgb<Space_From>( colour(i,_), &rgb) ; // ... convert the color to the `to` color space ColorSpace::XyzConverter::whiteReference = {white_to[0], white_to[1], white_to[2]}; ColorSpace::IConverter<Space_To>::ToColorSpace(&rgb, &to) ; // ... and move it to the row of the `out` matrix grab<Space_To>( out(i,_), to ) ; } return out ; } // these are used below in the dispatcher functions // this is one-based in the same order as the `colourspaces` // vector define in aaa.R #define CMY 1 #define CMYK 2 #define HSL 3 #define HSB 4 #define HSV 5 #define LAB 6 #define HUNTERLAB 7 #define LCH 8 #define LUV 9 #define RGB 10 #define XYZ 11 #define YXY 12 // this is a trick to do a runtime fake compile time dispatch // the idea is to call the right instantiation of the convert_dispatch_impl template // where the real work happens, based on `to` template <typename From> NumericMatrix convert_dispatch_to( const NumericMatrix& colour, int to, const NumericVector& white_from, const NumericVector& white_to ){ switch(to){ case CMY: return convert_dispatch_impl<From, ColorSpace::Cmy>( colour, white_from, white_to ) ; case CMYK: return convert_dispatch_impl<From, ColorSpace::Cmyk>( colour, white_from, white_to ) ; case HSL: return convert_dispatch_impl<From, ColorSpace::Hsl>( colour, white_from, white_to ) ; case HSB: return convert_dispatch_impl<From, ColorSpace::Hsb>( colour, white_from, white_to ) ; case HSV: return convert_dispatch_impl<From, ColorSpace::Hsv>( colour, white_from, white_to ) ; case LAB: return convert_dispatch_impl<From, ColorSpace::Lab>( colour, white_from, white_to ) ; case HUNTERLAB: return convert_dispatch_impl<From, ColorSpace::HunterLab>( colour, white_from, white_to ) ; case LCH: return convert_dispatch_impl<From, ColorSpace::Lch>( colour, white_from, white_to ) ; case LUV: return convert_dispatch_impl<From, ColorSpace::Luv>( colour, white_from, white_to ) ; case RGB: return convert_dispatch_impl<From, ColorSpace::Rgb>( colour, white_from, white_to ) ; case XYZ: return convert_dispatch_impl<From, ColorSpace::Xyz>( colour, white_from, white_to ) ; case YXY: return convert_dispatch_impl<From, ColorSpace::Yxy>( colour, white_from, white_to ) ; } // never happens return colour ; } // same trick, but for the `from` NumericMatrix convert_dispatch_from( const NumericMatrix& colour, int from, int to, const NumericVector& white_from, const NumericVector& white_to){ switch(from){ case CMY: return convert_dispatch_to<ColorSpace::Cmy>( colour, to, white_from, white_to ) ; case CMYK: return convert_dispatch_to<ColorSpace::Cmyk>( colour, to, white_from, white_to ) ; case HSL: return convert_dispatch_to<ColorSpace::Hsl>( colour, to, white_from, white_to ) ; case HSB: return convert_dispatch_to<ColorSpace::Hsb>( colour, to, white_from, white_to ) ; case HSV: return convert_dispatch_to<ColorSpace::Hsv>( colour, to, white_from, white_to ) ; case LAB: return convert_dispatch_to<ColorSpace::Lab>( colour, to, white_from, white_to ) ; case HUNTERLAB: return convert_dispatch_to<ColorSpace::HunterLab>( colour, to, white_from, white_to ) ; case LCH: return convert_dispatch_to<ColorSpace::Lch>( colour, to, white_from, white_to ) ; case LUV: return convert_dispatch_to<ColorSpace::Luv>( colour, to, white_from, white_to ) ; case RGB: return convert_dispatch_to<ColorSpace::Rgb>( colour, to, white_from, white_to ) ; case XYZ: return convert_dispatch_to<ColorSpace::Xyz>( colour, to, white_from, white_to ) ; case YXY: return convert_dispatch_to<ColorSpace::Yxy>( colour, to, white_from, white_to ) ; } // never happens so we just return the input to quiet the compiler return colour ; } //[[Rcpp::export]] NumericMatrix convert_c(NumericMatrix colour, int from, int to, NumericVector white_from, NumericVector white_to) { return convert_dispatch_from(colour, from, to, white_from, white_to) ; } #define EUCLIDEAN 1 #define CIE1976 2 #define CIE94 3 #define CIE2000 4 #define CMC 5 double get_colour_dist(ColorSpace::Rgb& from, ColorSpace::Rgb& to, int dist) { switch(dist){ case EUCLIDEAN: return ColorSpace::EuclideanComparison::Compare(&from, &to); case CIE1976: return ColorSpace::Cie1976Comparison::Compare(&from, &to); case CIE94: return ColorSpace::Cie94Comparison::Compare(&from, &to); case CIE2000: return ColorSpace::Cie2000Comparison::Compare(&from, &to); case CMC: return ColorSpace::CmcComparison::Compare(&from, &to); } // Never happens return 0.0; } template <typename Space_From, typename Space_To> NumericMatrix compare_dispatch_impl(const NumericMatrix& from, const NumericMatrix& to, int dist, bool sym, const NumericVector& white_from, const NumericVector& white_to){ // check that the dimensions of the input match the colour space if( dimension<Space_From>() != from.ncol() ){ stop("colourspace requires %d values", dimension<Space_From>() ) ; } if( dimension<Space_To>() != to.ncol() ){ stop("colourspace requires %d values", dimension<Space_From>() ) ; } int n = from.nrow(), m = to.nrow(), i, j; NumericMatrix out(n, m); ColorSpace::Rgb from_rgb, to_rgb; for (i = 0; i < n; ++i) { ColorSpace::XyzConverter::whiteReference = {white_from[0], white_from[1], white_from[2]}; fill_rgb<Space_From>(from(i, _), &from_rgb); ColorSpace::XyzConverter::whiteReference = {white_to[0], white_to[1], white_to[2]}; for (j = sym ? i + 1 : 0; j < m; ++j) { fill_rgb<Space_To>(to(j, _), &to_rgb); out(i, j) = get_colour_dist(from_rgb, to_rgb, dist); } } return out ; } template <typename From> NumericMatrix compare_dispatch_to(const NumericMatrix& from, const NumericMatrix& to, int to_space, int dist, bool sym, const NumericVector& white_from, const NumericVector& white_to) { switch(to_space){ case CMY: return compare_dispatch_impl<From, ColorSpace::Cmy>(from, to, dist, sym, white_from, white_to) ; case CMYK: return compare_dispatch_impl<From, ColorSpace::Cmyk>(from, to, dist, sym, white_from, white_to) ; case HSL: return compare_dispatch_impl<From, ColorSpace::Hsl>(from, to, dist, sym, white_from, white_to) ; case HSB: return compare_dispatch_impl<From, ColorSpace::Hsb>(from, to, dist, sym, white_from, white_to) ; case HSV: return compare_dispatch_impl<From, ColorSpace::Hsv>(from, to, dist, sym, white_from, white_to) ; case LAB: return compare_dispatch_impl<From, ColorSpace::Lab>(from, to, dist, sym, white_from, white_to) ; case HUNTERLAB: return compare_dispatch_impl<From, ColorSpace::HunterLab>(from, to, dist, sym, white_from, white_to) ; case LCH: return compare_dispatch_impl<From, ColorSpace::Lch>(from, to, dist, sym, white_from, white_to) ; case LUV: return compare_dispatch_impl<From, ColorSpace::Luv>(from, to, dist, sym, white_from, white_to) ; case RGB: return compare_dispatch_impl<From, ColorSpace::Rgb>(from, to, dist, sym, white_from, white_to) ; case XYZ: return compare_dispatch_impl<From, ColorSpace::Xyz>(from, to, dist, sym, white_from, white_to) ; case YXY: return compare_dispatch_impl<From, ColorSpace::Yxy>(from, to, dist, sym, white_from, white_to) ; } // never happens return from ; } NumericMatrix compare_dispatch_from(const NumericMatrix& from, const NumericMatrix& to, int from_space, int to_space, int dist, bool sym, const NumericVector& white_from, const NumericVector& white_to) { switch(from_space){ case CMY: return compare_dispatch_to<ColorSpace::Cmy>(from, to, to_space, dist, sym, white_from, white_to) ; case CMYK: return compare_dispatch_to<ColorSpace::Cmyk>(from, to, to_space, dist, sym, white_from, white_to) ; case HSL: return compare_dispatch_to<ColorSpace::Hsl>(from, to, to_space, dist, sym, white_from, white_to) ; case HSB: return compare_dispatch_to<ColorSpace::Hsb>(from, to, to_space, dist, sym, white_from, white_to) ; case HSV: return compare_dispatch_to<ColorSpace::Hsv>(from, to, to_space, dist, sym, white_from, white_to) ; case LAB: return compare_dispatch_to<ColorSpace::Lab>(from, to, to_space, dist, sym, white_from, white_to) ; case HUNTERLAB: return compare_dispatch_to<ColorSpace::HunterLab>(from, to, to_space, dist, sym, white_from, white_to) ; case LCH: return compare_dispatch_to<ColorSpace::Lch>(from, to, to_space, dist, sym, white_from, white_to) ; case LUV: return compare_dispatch_to<ColorSpace::Luv>(from, to, to_space, dist, sym, white_from, white_to) ; case RGB: return compare_dispatch_to<ColorSpace::Rgb>(from, to, to_space, dist, sym, white_from, white_to) ; case XYZ: return compare_dispatch_to<ColorSpace::Xyz>(from, to, to_space, dist, sym, white_from, white_to) ; case YXY: return compare_dispatch_to<ColorSpace::Yxy>(from, to, to_space, dist, sym, white_from, white_to) ; } // never happens so we just return the input to quiet the compiler return from ; } //[[Rcpp::export]] NumericMatrix compare_c(NumericMatrix from, NumericMatrix to, int from_space, int to_space, int dist, bool sym, NumericVector white_from, NumericVector white_to) { return compare_dispatch_from(from, to, from_space, to_space, dist, sym, white_from, white_to); }
Markdown
UTF-8
1,467
2.734375
3
[]
no_license
Projekt zawiera trzy kontenery: php, mysql oraz apache. Kontenery dziaล‚ajฤ… w dwรณch sieciach: backend oraz frontend. Do sieci backend sa podล‚ฤ…czone wszystkie trzy kontenery, natomiast do sieci frontend jest podล‚ฤ…czony tylko kontener apache. Kontener php jest oparty o obraz PHP. Kontener mysql oparty jest o MySQL. Kontener apache oparty jest o PHP-Apache (serwer Apache z zainstalowanym rozszerzeniem PHP). W kontenerze MySQL istnieje baza danych apache_test, ktรณra to zawiera tabele test. Do tabeli tej zostaล‚y dodane trzy rekordy. Po wpisaniu w pole przeglฤ…darki adresu localhost:6666, serwer Apache wykonuje zapytanie do serwera PHP, ktรณry to pobiera dane z bazy danych znajdujฤ…cej siฤ™ w kontenerze mysql. Dane te sฤ… pobieranie przez kontener php, ktรณry nastฤ™pnie odsyล‚a dane do serwera Apache. Serwer apache wyล›wietla nam te dane. W katalogu uruchamiamy nastฤ™pujฤ…ce polecenia: docker-compose build docker-compose up W przeglฤ…darce Firefox moลผe wystฤ…piฤ‡ bล‚ฤ…d odnoล›nie zabronionego portu. Aby obejล›ฤ‡ ten problem naleลผy: 1) W polu adresu przeglฤ…darki wpisaฤ‡ about:config 2) Wyszukaฤ‡ frazฤ™: network.security.ports.banned.override 3) Jeลผeli reguล‚a istnieje to po przecinku dodaฤ‡ nowy numer portu, w tym przypadku 6666. 4) Jeลผeli reguล‚a nie istnieje, to naciskamy plus, a nastฤ™pnie wpisujemy numer portu. Do danych moลผna mieฤ‡ rรณwnieลผ dostฤ™p poprzez uลผycie polecenia curl dostฤ™pnego w systemie linux: curl localhost:6666
Java
UTF-8
1,555
3.140625
3
[]
no_license
package statement.value; import exception.SQLException; import sqlparser.Token; import sqlparser.TokenStream; public class Value { private final String value; private float floatVal; private int intVal; private boolean intLiteral = false; private boolean floatLiteral = false; public Value(TokenStream stream) throws SQLException { Token token = stream.consumeIf(Token.Type.STR); if(token != null) { if(!token.data.equalsIgnoreCase("true") && !token.data.equalsIgnoreCase("false")) { throw new SQLException("ERROR: " + token.data + " must be enclosed in ''"); } value = token.data; } else if((token = stream.consumeIf(Token.Type.STRLITERAL)) != null) { value = token.data.substring(1, token.data.length()-1); } else if((token = stream.consumeIf(Token.Type.INT)) != null) { value = token.data; intVal = Integer.parseInt(value); intLiteral = true; } else if((token = stream.consumeIf(Token.Type.FLOAT)) != null) { value = token.data; floatVal = Float.parseFloat(value); floatLiteral = true; } else throw new SQLException("ERROR: Unexpected token"); } public int getIntVal() { return intVal; } public float getFloatVal() { return floatVal; } public String getValue() { return value; } public boolean isFloatLiteral() { return floatLiteral; } public boolean isIntLiteral() { return intLiteral; } }
Java
UTF-8
470
1.601563
2
[]
no_license
package com.ggs.gulimall.member.service; import com.baomidou.mybatisplus.extension.service.IService; import com.ggs.common.utils.PageUtils; import com.ggs.gulimall.member.entity.MemberCollectSpuEntity; import java.util.Map; /** * ไผšๅ‘˜ๆ”ถ่—็š„ๅ•†ๅ“ * * @author starbug * @email a1285226024@gmail.com * @date 2020-12-14 13:14:17 */ public interface MemberCollectSpuService extends IService<MemberCollectSpuEntity> { PageUtils queryPage(Map<String, Object> params); }
Python
UTF-8
174
3.765625
4
[]
no_license
def fibonacci(num): f0 = 0 f1 = 1 for k in range(num): f2 = f0 + f1 yield f1 f0, f1 = f1, f2 for f in fibonacci(5): print("fib=", f)
Java
UTF-8
13,939
2.140625
2
[]
no_license
package com.danthecodinggui.recipes.model; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.support.annotation.NonNull; import android.text.TextUtils; import android.util.Log; import static com.danthecodinggui.recipes.msc.LogTags.CONTENT_PROVIDER; /** * Content provider for accessing all application data */ public class RecipeProvider extends ContentProvider { //URI codes private static final int RECIPES_TABLE = 100; private static final int RECIPES_ITEM = 101; private static final int METHOD_TABLE = 102; private static final int METHOD_ITEM = 103; private static final int RECIPE_INGREDIENTS_TABLE = 104; private static final int RECIPE_INGREDIENTS_ITEM = 105; private static final UriMatcher uriMatcher; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(ProviderContract.CONTENT_AUTHORITY, ProviderContract.PATH_RECIPES, RECIPES_TABLE); uriMatcher.addURI(ProviderContract.CONTENT_AUTHORITY, ProviderContract.PATH_RECIPES + "/#", RECIPES_ITEM); uriMatcher.addURI(ProviderContract.CONTENT_AUTHORITY, ProviderContract.PATH_METHOD, METHOD_TABLE); uriMatcher.addURI(ProviderContract.CONTENT_AUTHORITY, ProviderContract.PATH_METHOD + "/#", METHOD_ITEM); uriMatcher.addURI(ProviderContract.CONTENT_AUTHORITY, ProviderContract.PATH_RECIPE_INGREDIENTS, RECIPE_INGREDIENTS_TABLE); uriMatcher.addURI(ProviderContract.CONTENT_AUTHORITY, ProviderContract.PATH_RECIPE_INGREDIENTS + "/#", RECIPE_INGREDIENTS_ITEM); uriMatcher.addURI(ProviderContract.CONTENT_AUTHORITY, ProviderContract.PATH_RECIPE_INGREDIENTS, RECIPE_INGREDIENTS_TABLE); uriMatcher.addURI(ProviderContract.CONTENT_AUTHORITY, ProviderContract.PATH_RECIPE_INGREDIENTS + "/#", RECIPE_INGREDIENTS_ITEM); } private DBHelper dbHelper; @Override public boolean onCreate() { dbHelper = new DBHelper(getContext()); return true; } @Override public String getType(@NonNull Uri uri) { if (uri.getLastPathSegment() == null) return "vnd.android.cursor.dir/RecipeProvider.data.text"; else return "vnd.android.cursor.item/RecipeProvider.data.text"; } @Override public Uri insert(@NonNull Uri uri, ContentValues values) { SQLiteDatabase db; String tableName; switch (uriMatcher.match(uri)) { case RECIPES_TABLE: tableName = DBSchema.RecipeEntry.TABLE_NAME; break; case METHOD_TABLE: tableName = DBSchema.MethodStepEntry.TABLE_NAME; break; case RECIPE_INGREDIENTS_TABLE: //Handle 1 provider table -> 2 db tables long recipeId = values.getAsLong(ProviderContract.RecipeIngredientEntry.RECIPE_ID); String ingredient = values.getAsString( ProviderContract.RecipeIngredientEntry.INGREDIENT_NAME); int quantity = values.getAsInteger( ProviderContract.RecipeIngredientEntry.QUANTITY); String measurement = values.getAsString( ProviderContract.RecipeIngredientEntry.MEASUREMENT); long ingredientId = GetIngredientId(ingredient); //Break down old values, reconstruct and insert in RecipeIngredients table values = new ContentValues(); values.put(DBSchema.RecipeIngredientEntry.RECIPE_ID, recipeId); values.put(DBSchema.RecipeIngredientEntry.INGREDIENT_ID, ingredientId); values.put(DBSchema.RecipeIngredientEntry.QUANTITY, quantity); values.put(DBSchema.RecipeIngredientEntry.MEASUREMENT, measurement); tableName = DBSchema.RecipeIngredientEntry.TABLE_NAME; break; default: throw new IllegalArgumentException("Invalid URI for insertion: " + uri); } db = dbHelper.getWritableDatabase(); long id = db.insert(tableName, null, values); Log.i(CONTENT_PROVIDER, "Provider insertion, notifying any listeners..."); getContext().getContentResolver().notifyChange(uri, null); return ContentUris.withAppendedId(uri, id); } /** * Checks to see if ingredient for recipe already exists in ingredients table, * updates if required * @param ingredientName The name of the ingredient to check * @return The primary key of the ingredient */ private long GetIngredientId(String ingredientName) { //Query db to see if ingredient is in table SQLiteDatabase db = dbHelper.getWritableDatabase(); String[] columns = { DBSchema.IngredientEntry._ID }; String selection = DBSchema.IngredientEntry.NAME + " = ?"; String[] selectionArgs = { ingredientName }; Cursor ingredients = db.query( DBSchema.IngredientEntry.TABLE_NAME, columns, selection, selectionArgs, null, null, null ); //Ingredient is not already in table, must add_activity_toolbar it if (ingredients.getCount() <= 0) { ContentValues newIngredient = new ContentValues(); newIngredient.put(DBSchema.IngredientEntry.NAME, ingredientName); return db.insert( DBSchema.IngredientEntry.TABLE_NAME, null, newIngredient ); } //Ingredient is already/now in table, just return it's ID ingredients.moveToFirst(); long id = ingredients.getLong( ingredients.getColumnIndexOrThrow(DBSchema.IngredientEntry._ID)); ingredients.close(); return id; } @Override public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder(); switch (uriMatcher.match(uri)) { case RECIPES_TABLE: qBuilder.setTables(DBSchema.RecipeEntry.TABLE_NAME); break; case RECIPES_ITEM: qBuilder.setTables(DBSchema.RecipeEntry.TABLE_NAME); //Limit query result to one record qBuilder.appendWhere(DBSchema.RecipeEntry._ID + " = " + uri.getLastPathSegment()); break; case METHOD_TABLE: qBuilder.setTables(DBSchema.MethodStepEntry.TABLE_NAME); break; case METHOD_ITEM: qBuilder.setTables(DBSchema.MethodStepEntry.TABLE_NAME); qBuilder.appendWhere(DBSchema.MethodStepEntry._ID + " = " + uri.getLastPathSegment()); break; case RECIPE_INGREDIENTS_TABLE: qBuilder.setTables(DBSchema.INGREDIENTS_JOIN); break; case RECIPE_INGREDIENTS_ITEM: qBuilder.setTables(DBSchema.INGREDIENTS_JOIN); qBuilder.appendWhere(DBSchema.RecipeIngredientEntry._ID + " = " + uri.getLastPathSegment()); break; default: throw new IllegalArgumentException("Invalid URI for query: " + uri); } SQLiteDatabase db = dbHelper.getReadableDatabase(); return qBuilder.query( db, projection, selection, selectionArgs, null, null, sortOrder ); } @Override public int update(@NonNull Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db = dbHelper.getWritableDatabase(); int rowNumUpdated; String id; String where; switch (uriMatcher.match(uri)) { case RECIPES_TABLE: rowNumUpdated = db.update( DBSchema.RecipeEntry.TABLE_NAME, values, selection, selectionArgs ); break; case RECIPES_ITEM: id = uri.getLastPathSegment(); where = DBSchema.RecipeEntry._ID + " = " + id; if (!TextUtils.isEmpty(selection)) { where += " AND " + selection; } rowNumUpdated = db.update( DBSchema.RecipeEntry.TABLE_NAME, values, where, selectionArgs ); break; case METHOD_TABLE: rowNumUpdated = db.update( DBSchema.MethodStepEntry.TABLE_NAME, values, selection, selectionArgs ); break; case METHOD_ITEM: id = uri.getLastPathSegment(); where = DBSchema.MethodStepEntry._ID + " = " + id; if (!TextUtils.isEmpty(selection)) { where += " AND " + selection; } rowNumUpdated = db.update( DBSchema.MethodStepEntry.TABLE_NAME, values, where, selectionArgs ); break; case RECIPE_INGREDIENTS_TABLE: rowNumUpdated = db.update( DBSchema.IngredientEntry.TABLE_NAME, values, selection, selectionArgs ); break; case RECIPE_INGREDIENTS_ITEM: id = uri.getLastPathSegment(); where = DBSchema.RecipeIngredientEntry._ID + " = " + id; if (!TextUtils.isEmpty(selection)) { where += " AND " + selection; } rowNumUpdated = db.update( DBSchema.RecipeIngredientEntry.TABLE_NAME, values, where, selectionArgs ); break; default: throw new IllegalArgumentException("Invalid URI for updating: " + uri); } Log.i(CONTENT_PROVIDER, "Provider update, notifying any listeners..."); getContext().getContentResolver().notifyChange(uri, null); return rowNumUpdated; } @Override public int delete(@NonNull Uri uri, String selection, String[] selectionArgs) { //Same structure as update with changed var names and db methods SQLiteDatabase db = dbHelper.getWritableDatabase(); int rowNumDeleted; String id; String where; switch (uriMatcher.match(uri)) { case RECIPES_TABLE: rowNumDeleted = db.delete( DBSchema.RecipeEntry.TABLE_NAME, selection, selectionArgs ); break; case RECIPES_ITEM: id = uri.getLastPathSegment(); where = DBSchema.RecipeEntry._ID + " = " + id; if (!TextUtils.isEmpty(selection)) { where += " AND " + selection; } rowNumDeleted = db.delete( DBSchema.RecipeEntry.TABLE_NAME, where, selectionArgs ); break; case METHOD_TABLE: rowNumDeleted = db.delete( DBSchema.MethodStepEntry.TABLE_NAME, selection, selectionArgs ); break; case METHOD_ITEM: id = uri.getLastPathSegment(); where = DBSchema.MethodStepEntry._ID + " = " + id; if (!TextUtils.isEmpty(selection)) { where += " AND " + selection; } rowNumDeleted = db.delete( DBSchema.MethodStepEntry.TABLE_NAME, where, selectionArgs ); break; case RECIPE_INGREDIENTS_TABLE: //TODO Maybe in future look for references to a specific ingredient in recipeIngredients, //and delete in ingredients if no refs to it (not a big deal for now) rowNumDeleted = db.delete( DBSchema.RecipeIngredientEntry.TABLE_NAME, selection, selectionArgs ); break; case RECIPE_INGREDIENTS_ITEM: id = uri.getLastPathSegment(); where = DBSchema.RecipeIngredientEntry._ID + " = " + id; if (!TextUtils.isEmpty(selection)) { where += " AND " + selection; } rowNumDeleted = db.delete( DBSchema.RecipeIngredientEntry.TABLE_NAME, where, selectionArgs ); break; default: throw new IllegalArgumentException("Invalid URI for deletion: " + uri); } return rowNumDeleted; } }
Python
UTF-8
351
2.921875
3
[]
no_license
# q2 # from examplepackage.symbols import happy_symbol # print(happy_symbol) #q3 from examplepackage.symbols import * x = all(x in globals() for x in ["happy_symbol", "sad_symbol", "confused_symbol", "all_symbols"]) print(x) print(all_symbols) #q4 import examplepackage y = all(examplepackage.functions.is_symbol(s) for s in all_symbols) print(y)
Java
UTF-8
403
2.40625
2
[]
no_license
package inter; public class P extends Node{ public static P Null = new P(); public Id firstP = null; public Pl pl = null; public P(){} public P(Id p1,Pl pl) { this.firstP = p1; this.pl = pl; } public void gen() { if(this.firstP != null) emit("parm " + firstP.toString()); if(this.pl != null) pl.gen(); } }
Java
UTF-8
610
2.671875
3
[]
no_license
package sorcery.api.spellcasting; import java.util.ArrayList; import sorcery.api.element.ElementStack; public class CastInfo { public ElementStack[] elements = new ElementStack[] {}; public int mojoCost; /** 0 = Right; 1 = Left */ public final int castingHand; public CastInfo(ElementStack[] elements, int mojoCost) { this.elements = elements; this.mojoCost = mojoCost; this.castingHand = 0; } public CastInfo(ElementStack[] elements, int mojoCost, int castingHand) { this.elements = elements; this.mojoCost = mojoCost; this.castingHand = castingHand; } }
Markdown
UTF-8
3,094
3
3
[]
no_license
// Friday, 29 Jan 2021 1. 8 Kyu (https://www.codewars.com/kata/53da3dbb4a5168369a0000fe) Even or Odd 2. 8 Kyu (https://www.codewars.com/kata/54d1c59aba326343c80000e7) Incorrect Division Method 3. 7 Kyu (https://www.codewars.com/kata/54ff3102c1bad923760001f3) Vowel Count 4. 7 Kyu (https://www.codewars.com/kata/586e4c61aa0428f04e000069) Get Decimal Part of the Given Number 5. 6 Kyu (https://www.codewars.com/kata/514b92a657cdc65150000006) Multiples of 3 or 5 6. 6 Kyu (https://www.codewars.com/kata/54da5a58ea159efa38000836) Find the Odd Int 7. 5 Kyu (https://www.codewars.com/kata/525f3eda17c7cd9f9e000b39) Calculating with Functions 8. 5 Kyu (https://www.codewars.com/kata/52597aa56021e91c93000cb0) Moving Zeros To The End // Saturday, 30 Jan 2021 1. 8 Kyu (https://www.codewars.com/kata/596c6eb85b0f515834000049) FIXME: Replace all dots 2. 7 Kyu (https://www.codewars.com/kata/57d2807295497e652b000139) Averages of numbers 3. 6 Kyu (https://www.codewars.com/kata/5ce399e0047a45001c853c2b) Sums of Parts 4. 5 Kyu (https://www.codewars.com/kata/52685f7382004e774f0001f7) Human Readable Time // Monday, 01 Feb 2021 1. 8 Kyu (https://www.codewars.com/kata/5715eaedb436cf5606000381) Sum of Positive 2. 8 Kyu (https://www.codewars.com/kata/56dec885c54a926dcd001095) Opposite Number 3. 8 Kyu (https://www.codewars.com/kata/56bc28ad5bdaeb48760009b0) Remove First and Last Character 4. 8 Kyu (https://www.codewars.com/kata/55685cd7ad70877c23000102) Return Negative 5. 8 Kyu (https://www.codewars.com/kata/57a0e5c372292dd76d000d7e) String Repeat 6. 7 Kyu (https://www.codewars.com/kata/5667e8f4e3f572a8f2000039) Mumbling 7. 7 Kyu (https://www.codewars.com/kata/554b4ac871d6813a03000035) Highest and Lowest 8. 7 Kyu (https://www.codewars.com/kata/546e2562b03326a88e000020) Square Every Digit 9. 7 Kyu (https://www.codewars.com/kata/56747fd5cb988479af000028) Get the Middle Character 10. 7 Kyu (https://www.codewars.com/kata/52fba66badcd10859f00097e) Disemvowel Trolls 11. 6 Kyu (https://www.codewars.com/kata/541c8630095125aba6000c00) Sum of Digits / Digital Root 12. 6 Kyu (https://www.codewars.com/kata/55bf01e5a717a0d57e0000ec) Persistent Bugger 13. 6 Kyu (https://www.codewars.com/kata/5264d2b162488dc400000001) Stop gninnipS My sdroW! 14. 6 Kyu (https://www.codewars.com/kata/5266876b8f4bf2da9b000362) Who Likes it ? 15. 6 Kyu (https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1) Counting Duplicates 16. 5 Kyu (https://www.codewars.com/kata/54521e9ec8e60bc4de000d6c) Maximum Subarray Sum 17. 5 Kyu (https://www.codewars.com/kata/55c6126177c9441a570000cc) Weight for Weight 18. 5 Kyu (https://www.codewars.com/kata/523a86aa4230ebb5420001e1) Where my Anagrams at ? 19. 5 Kyu (https://www.codewars.com/kata/530e15517bc88ac656000716) Rot13 20. 5 Kyu (https://www.codewars.com/kata/550f22f4d758534c1100025a) Direction Reduction // Tuesday, 02 Feb 2021 1. 4 Kyu (https://www.codewars.com/kata/52742f58faf5485cae000b9a) Human Readable Duration Format
C#
UTF-8
826
2.515625
3
[ "MIT" ]
permissive
// Copyright ยฉ John Gietzen. All Rights Reserved. This source is subject to the MIT license. Please see license.md for more information. namespace MediaLibrary.Views { using System.Windows.Forms; public partial class NameInputForm : Form { public NameInputForm() { this.InitializeComponent(); } public string SelectedName { get => this.name.Text; set => this.name.Text = value; } private void CancelButton_Click(object sender, System.EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Hide(); } private void FinishButton_Click(object sender, System.EventArgs e) { this.DialogResult = DialogResult.OK; this.Hide(); } } }
Java
UTF-8
1,945
2.3125
2
[]
no_license
package atlantis.com.atlantis.fragments; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import atlantis.com.atlantis.R; /** * Fragment for showing creating notebook progress */ public class CreatingNotebookFragment extends Fragment { public CreatingNotebookFragment() { // Required empty public constructor } public interface OnCancelNotebookListener { void onCancelConversation(); } OnCancelNotebookListener mListener; @Override public void onAttach(Activity activity) { super.onAttach(activity); try{ mListener = (OnCancelNotebookListener)activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + "must implement OnCancelNotebookListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_creating_notebook, container, false); Button cancelButton = (Button) rootView.findViewById(R.id.cancel_button); cancelButton.setOnClickListener(mCancelButtonListener); // Inflate the layout for this fragment return rootView; } private CreatingNotebookFragment mSelfFragment = this; private View.OnClickListener mCancelButtonListener = new View.OnClickListener() { @Override public void onClick(View v) { mListener.onCancelConversation(); Toast.makeText(mSelfFragment.getActivity(), R.string.cancelled_text, Toast.LENGTH_SHORT).show(); } }; }
Java
UTF-8
1,987
2.140625
2
[]
no_license
package com.hanweb.jmp.cms.entity.infos; import com.hanweb.common.annotation.Column; import com.hanweb.common.annotation.ColumnType; import com.hanweb.common.annotation.Id; import com.hanweb.common.annotation.Table; import com.hanweb.common.annotation.Index; import com.hanweb.common.annotation.Indexes; import com.hanweb.jmp.constant.Tables; @Table(name = Tables.INFO_COUNT) @Indexes({ @Index(fieldNames={"titleid"}, indexName="infocount_idx_001") }) public class InfoCount { /** * ไธป้”ฎid */ @Id @Column(type = ColumnType.INT) private Integer iid; /** * ไฟกๆฏid */ @Column(type = ColumnType.INT) private Integer titleId; /** * ่ฎฟ้—ฎๆฌกๆ•ฐ */ @Column(type = ColumnType.INT) private Integer visitCount = 0; /** * ่ฏ„่ฎบๆ•ฐ */ @Column(type = ColumnType.INT) private Integer commentCount = 0; /** * ็‚น่ตžๆ•ฐ */ @Column(type = ColumnType.INT) private Integer goodCount = 0; /** * ็ฑปๅž‹ 1ๆ˜ฏไฟกๆฏ 2ๆ˜ฏๆŠฅๆ–™ */ @Column(type = ColumnType.INT) private Integer type = 1; /** * ๆ˜ฏๅฆ่ขซ็‚น่ตž */ private Integer isGood = 0; public Integer getIid() { return iid; } public void setIid(Integer iid) { this.iid = iid; } public Integer getTitleId() { return titleId; } public void setTitleId(Integer titleId) { this.titleId = titleId; } public Integer getVisitCount() { return visitCount; } public void setVisitCount(Integer visitCount) { this.visitCount = visitCount; } public Integer getCommentCount() { return commentCount; } public void setCommentCount(Integer commentCount) { this.commentCount = commentCount; } public Integer getGoodCount() { return goodCount; } public void setGoodCount(Integer goodCount) { this.goodCount = goodCount; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getIsGood() { return isGood; } public void setIsGood(Integer isGood) { this.isGood = isGood; } }
C++
UTF-8
3,672
2.515625
3
[]
no_license
int irin = 2; int green = 11; int red = 12; int led = 13; int Pin1 = 5; int Pin2 = 6; int Pin3 = 9; int Pin4 = 10; int bitsize = 4; int timeout = 200; int count_unit = 100; int one = 16; int zero = 0; int flag_receive=0; volatile int enableMortor=0; volatile int enableMelody=0; void setup(){ pinMode(irin, INPUT); pinMode(Pin1, OUTPUT); pinMode(Pin2, OUTPUT); pinMode(Pin3, OUTPUT); pinMode(Pin4, OUTPUT); pinMode(green, OUTPUT); pinMode(red, OUTPUT); attachInterrupt(0, IR_Receive,FALLING); Serial.begin(57600); Serial.println("Ready"); } void loop(){ digitalWrite(led,LOW); LED_Change(); delay(10); } int receiveData[4]; // int receiveRawData[6]; void IR_Receive(){ if(flag_receive==0){ for(volatile int i = zero; i<bitsize;i++) { volatile int count = zero; while(digitalRead(irin) == LOW); // LEDใŒๆถˆ็ฏใ™ใ‚‹ใพใงๅพ…ใค while(digitalRead(irin) == HIGH) { // LEDใŒ็‚น็ฏใ™ใ‚‹ใพใงใฎๆ™‚้–“ใ‚’่จˆใ‚‹ count++; delayMicroseconds(count_unit);// 100ฮผ็ง’ๅ˜ไฝใง่จˆใ‚‹ใ€‚ใใฎใใ‚‰ใ„ๅคง้›‘ๆŠŠใงๅ•้กŒใชใ„ใ€‚ if (count > timeout) break; // ใ‚ใพใ‚Š้•ทใ„ๆ™‚้–“็‚น็ฏใ—ใชใ„ๅ ดๅˆใฏใ‚จใƒฉใƒผใ€‚ } if (count > timeout) break; //receiveRawData[i] = count; receiveData[i] = (count > one); //1.6ms(1600ฮผ็ง’)ใ‚ˆใ‚Š้•ทใ‘ใ‚Œใฐ1 } for(int i=0;i<bitsize;i++){ Serial.print(receiveData[i]); Serial.print(","); } Serial.println("END"); delay(10); flag_receive=1; IR_RC_Bridge(); } } void IR_RC_Bridge(){ flag_receive=0; if(receiveData[0] == 0 && receiveData[1] == 0 && receiveData[2] == 0 && receiveData[3] == 1){ RC_Control(1); Serial.println("Go Straight"); } else if(receiveData[0] == 0 && receiveData[1] == 1 && receiveData[2] == 0 && receiveData[3] == 0){ RC_Control(2); Serial.println("Turn Left"); } else if(receiveData[0] == 0 && receiveData[1] == 0 && receiveData[2] == 1 && receiveData[3] == 1){ RC_Control(3); Serial.println("Turn Right"); } else if(receiveData[0] == 1 && receiveData[1] == 0 && receiveData[2] == 0 && receiveData[3] == 0){ RC_Control(4); Serial.println("Go Back"); } else if(receiveData[0] == 1 && receiveData[1] == 1 && receiveData[2] == 1 && receiveData[3] == 1){ RC_Control(5); Serial.println("Brake"); } delay(250); } void RC_Control(int command){ //1:Go 2:Left 3:Right 4:Back 5:Brake defalut:Stop switch (command){ case 1: enableMortor=1; digitalWrite(Pin1,HIGH); digitalWrite(Pin2,LOW); digitalWrite(Pin3,HIGH); digitalWrite(Pin4,LOW); break; case 2: enableMortor=1; digitalWrite(Pin1,HIGH); digitalWrite(Pin2,LOW); digitalWrite(Pin3,LOW); digitalWrite(Pin4,HIGH); break; case 3: enableMortor=1; digitalWrite(Pin1,LOW); digitalWrite(Pin2,HIGH); digitalWrite(Pin3,HIGH); digitalWrite(Pin4,LOW); break; case 4: enableMortor=1; digitalWrite(Pin1,LOW); digitalWrite(Pin2,HIGH); digitalWrite(Pin3,LOW); digitalWrite(Pin4,HIGH); break; case 5: enableMortor=0; enableMelody=0; digitalWrite(Pin1,HIGH); digitalWrite(Pin2,HIGH); digitalWrite(Pin3,HIGH); digitalWrite(Pin4,HIGH); break; default: enableMortor=0; enableMelody=0; digitalWrite(Pin1,LOW); digitalWrite(Pin2,LOW); digitalWrite(Pin3,LOW); digitalWrite(Pin4,LOW); break; } } void LED_Change(){ if(enableMortor==0){ digitalWrite(green,LOW); digitalWrite(red,HIGH); } else{ digitalWrite(green,HIGH); digitalWrite(red,LOW); } }
Java
UTF-8
1,890
2.625
3
[ "MIT" ]
permissive
package mage.cards.t; import java.util.UUID; import mage.MageInt; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.condition.common.SurgedCondition; import mage.abilities.decorator.ConditionalInterveningIfTriggeredAbility; import mage.abilities.effects.common.DamageTargetEffect; import mage.abilities.keyword.FlyingAbility; import mage.abilities.keyword.SurgeAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.target.common.TargetAnyTarget; /** * * @author fireshoes */ public final class TyrantOfValakut extends CardImpl { public TyrantOfValakut(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{5}{R}{R}"); this.subtype.add(SubType.DRAGON); this.power = new MageInt(5); this.toughness = new MageInt(4); // Surge {3}{R}{R} (You may cast this spell for its surge cost if you or a teammate has cast another spell this turn) addAbility(new SurgeAbility(this, "{3}{R}{R}")); // Flying this.addAbility(FlyingAbility.getInstance()); // When Tyrant of Valakut enters the battlefield, if its surge cost was paid, it deals 3 damage to any target. EntersBattlefieldTriggeredAbility ability = new EntersBattlefieldTriggeredAbility(new DamageTargetEffect(3), false); ability.addTarget(new TargetAnyTarget()); this.addAbility(new ConditionalInterveningIfTriggeredAbility(ability, SurgedCondition.instance, "When {this} enters the battlefield, if its surge cost was paid, it deals 3 damage to any target.")); } private TyrantOfValakut(final TyrantOfValakut card) { super(card); } @Override public TyrantOfValakut copy() { return new TyrantOfValakut(this); } }
Python
UTF-8
399
2.6875
3
[]
no_license
import os,random, time pullData = open("sampleText.txt","w") def _writin_(): start = time.time() while True: i = random.randint(0,69) y = random.randint(0,69) pullData.write(str(i)+","+str(y)+os.linesep) try: end = time.time() delta = end-start if delta>10: return _writin_() _writin_()
Java
UTF-8
1,247
2.71875
3
[ "Apache-2.0" ]
permissive
package pc; import java.io.File; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicLong; /** * Intended to hold shared state between Consumers * */ public class Context { public ConcurrentHashMap<String, AtomicLong> map; public Report report; public Producer producer; // the reader public List<Consumer> consumers; // the writers public File sourceFile; public File targetDir; // where we write to public ThreadPoolExecutor threadPool; public int threads; // the number of threads in the pool public int reportEveryMS; // delay between reporting in millis public int maxQ; // maximum size a queu can be before we wait to write to it public long timeStarted = System.currentTimeMillis(); public long timeLastSplit = System.currentTimeMillis(); public long timeThisSplit = System.currentTimeMillis(); public Context() { map = new ConcurrentHashMap<String, AtomicLong>(); } public List<Consumer> getConsumers() { return consumers; } public File getSourceFile() { return sourceFile; } public int getMaxQ() { return maxQ; } public void setMaxQ(int maxq) { this.maxQ = maxq; } }
Java
UTF-8
408
1.5625
2
[]
no_license
package com.yyt.service.company.impl; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.yyt.dao.BaseDaoImpl; import com.yyt.orm.company.ServicePrice; import com.yyt.service.company.ServicePriceService; @Service @Transactional public class ServicePriceServiceImpl extends BaseDaoImpl<ServicePrice> implements ServicePriceService{ }
Java
UTF-8
2,670
3.875
4
[ "Apache-2.0" ]
permissive
package com.sauzny.jkitchen_note.thread; import java.util.concurrent.locks.LockSupport; public class WaitParkSleep { private final String anyTHing = ""; public void foo01(){ // ็บฟ็จ‹1 wait Thread thread1 = new Thread(() ->{ try { // ๅฟ…้กป่Žทๅพ—ๅฏน่ฑกไธŠ็š„้”ๅŽ๏ผŒๆ‰ๅฏไปฅๆ‰ง่กŒ่ฏฅๅฏน่ฑก็š„waitๆ–นๆณ•ใ€‚ๅฆๅˆ™็จ‹ๅบไผšๅœจ่ฟ่กŒๆ—ถๆŠ›ๅ‡บIllegalMonitorStateExceptionๅผ‚ๅธธใ€‚ synchronized (anyTHing){ // ็บฟ็จ‹็š„็Šถๆ€ๆ˜ฏWAITING็Šถๆ€ // ่ฐƒ็”จwait()ๆ–นๆณ•ๅŽ๏ผŒ็บฟ็จ‹่ฟ›ๅ…ฅไผ‘็œ ็š„ๅŒๆ—ถ๏ผŒไผš้‡Šๆ”พๆŒๆœ‰็š„่ฏฅๅฏน่ฑก็š„้”๏ผŒ่ฟ™ๆ ทๅ…ถไป–็บฟ็จ‹ๅฐฑ่ƒฝๅœจ่ฟ™ๆœŸ้—ด่Žทๅ–ๅˆฐ้”ไบ†ใ€‚ anyTHing.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } }); // ็บฟ็จ‹2 notify Thread thread2 = new Thread(() ->{ synchronized (anyTHing) { // ่ฐƒ็”จObjectๅฏน่ฑก็š„notify()ๆˆ–่€…notifyAll()ๆ–นๆณ•ๅฏไปฅๅ”ค้†’ๅ› ไธบwait()่€Œ่ฟ›ๅ…ฅ็ญ‰ๅพ…็š„็บฟ็จ‹ใ€‚ // notifyๆ˜ฏ้šๆœบๅ”ค้†’ไธ€ไธช่ขซ้˜ปๅกž็š„็บฟ็จ‹ // notifyAllๆ˜ฏๅ”ค้†’ๆ‰€ๆœ‰็บฟ็จ‹ //anyTHing.notify(); anyTHing.notifyAll(); } }); thread1.start(); thread2.start(); } public void foo02(){ // ็บฟ็จ‹1 park // ็บฟ็จ‹็Šถๆ€ไธบWAITING // parkๆ–นๆณ•ไธไผšๆŠ›ๅ‡บInterruptedException๏ผŒไฝ†ๆ˜ฏๅฎƒไนŸไผšๅ“ๅบ”ไธญๆ–ญ // ๅนถไธ”ๅฏไปฅๆ‰‹ๅŠจ้€š่ฟ‡Thread.currentThread().isInterrupted()่Žทๅ–ๅˆฐไธญๆ–ญไฝ Thread thread1 = new Thread(() -> { System.out.println("park begin"); //็ญ‰ๅพ…่Žทๅ–่ฎธๅฏ LockSupport.park(); //่พ“ๅ‡บthread over.true System.out.println("thread over." + Thread.currentThread().isInterrupted()); }); // ็บฟ็จ‹2 unpark ็บฟ็จ‹1 Thread thread2 = new Thread(() -> LockSupport.unpark(thread1)); thread1.start(); // ไธญๆ–ญ็บฟ็จ‹ // thread1ไผšๅ“ๅบ”่ฟ™ไธชไธญๆ–ญ // thread1.interrupt(); thread2.start(); } public void foo03(){ try { // ็Šถๆ€ๅบ”่ฏฅๆ˜ฏTIMED_WAITING๏ผŒ่กจ็คบไผ‘็œ ไธ€ๆฎตๆ—ถ้—ด // ่ฏฅๆ–นๆณ•ไผšๆŠ›ๅ‡บInterruptedExceptionๅผ‚ๅธธ๏ผŒ่ฟ™ๆ˜ฏๅ—ๆฃ€ๆŸฅๅผ‚ๅธธ๏ผŒ่ฐƒ็”จ่€…ๅฟ…้กปๅค„็† // ้€š่ฟ‡sleepๆ–นๆณ•่ฟ›ๅ…ฅไผ‘็œ ็š„็บฟ็จ‹ไธไผš้‡Šๆ”พๆŒๆœ‰็š„้”๏ผŒๅ› ๆญค๏ผŒๅœจๆŒๆœ‰้”็š„ๆ—ถๅ€™่ฐƒ็”จ่ฏฅๆ–นๆณ•้œ€่ฆ่ฐจๆ…Ž Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } }
Java
UTF-8
502
2.40625
2
[]
no_license
/* * Created on Mar 14, 2005 * * */ package com.fsrin.menumine.core.crosstab; /** * @author Nick * * */ public class CrossTabulationCellTotal { private int count = 0; public void incrementCount() { count++; } public Double getColumnPercentage() { return new Double(100.00); } public Double getRowPercentage() { return new Double(100.00); } public int getCount() { return count; } }
PHP
UTF-8
1,250
3.046875
3
[]
no_license
<?php declare(strict_types=1); namespace CultuurNet\UDB3\Search\Offer; use CultuurNet\UDB3\Search\UnsupportedParameterValue; final class Status { private const AVAILABLE = 'Available'; private const UNAVAILABLE = 'Unavailable'; private const TEMPORARILY_UNAVAILABLE = 'TemporarilyUnavailable'; private const ALLOWED_VALUES = [ self::AVAILABLE, self::UNAVAILABLE, self::TEMPORARILY_UNAVAILABLE, ]; /** * @var string */ private $status; public function __construct(string $status) { if (!in_array($status, self::ALLOWED_VALUES)) { throw new UnsupportedParameterValue( 'Invalid Status: ' . $status . '. Should be one of ' . implode(', ', self::ALLOWED_VALUES) ); } $this->status = $status; } public static function available(): self { return new self(self::AVAILABLE); } public static function unavailable(): self { return new self(self::UNAVAILABLE); } public static function temporarilyUnavailable(): self { return new self(self::TEMPORARILY_UNAVAILABLE); } public function toString(): string { return $this->status; } }
JavaScript
UTF-8
535
2.546875
3
[ "MIT" ]
permissive
/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */ var x = S$.symbol("X", ''); //The lack of anchors ^ and $ means that this program can throw errors if (/a|b|c/.test(x)) { if (/a/.test(x)) { S$.assert(!/c/.test(x)); S$.assert(!/b/.test(x)); } if (/b/.test(x)) { S$.assert(!/a/.test(x)); S$.assert(!/c/.test(x)); } if (/c/.test(x)) { S$.assert(!/a/.test(x)); S$.assert(!/b/.test(x)); } }
Markdown
UTF-8
2,488
3.65625
4
[]
no_license
# JavaScriptๅŸบ็ก€Day02_Mathๅฏน่ฑก_ๆ•ฐๆฎ็ฑปๅž‹่ฝฌๆข_้€ป่พ‘่ฟ็ฎ—็ฌฆ_็ญ‰ๅท้€—ๅท่ฟ็ฎ—็ฌฆ_ๅˆ†ๆ”ฏ็ป“ๆž„_ๆกไปถ่กจ่พพๅผ [TOC] ## Math ๅฏน่ฑก ๆ–นๆณ• | ่ฏดๆ˜Ž ----|---- abs(x) | ็ปๅฏนๅ€ผ ceil(x) | ๅ‘ไธŠๅ–ๆ•ด(ๅคฉ่Šฑๆฟๅ‡ฝๆ•ฐ) floor(x) | ๅ‘ไธ‹ๅ–ๆ•ด(ๅœฐๆฟๅ‡ฝๆ•ฐ) round(x) | ๅ››่ˆไบ”ๅ…ฅๅ€ผ max(x,y) | ่ฟ”ๅ›žx ๅ’Œ y ไธญ็š„ๆœ€ๅคงๅ€ผ min(x,y) | ่ฟ”ๅ›žx ๅ’Œ y ไธญ็š„ๆœ€ๅฐๅ€ผ pow(x,y) | ่ฟ”ๅ›žx ็š„ y ๆฌกๅน‚ random() | ่ฟ”ๅ›ž 0-1 ไน‹้—ด็š„้šๆœบๆ•ฐ ๆฒกๆœ‰0ๅ’Œ1 ###ๅ†™ๆณ• ```JavaScript var n1 = Math.ceil(2.333) //ๅ‘ไธŠๅ–ๆ•ด ``` ##ๆ•ฐๆฎ็ฑปๅž‹่ฝฌๆข ###้šๅผ่ฝฌๆข * ็จ‹ๅบๅœจๅ‚ไธŽ่ฟ็ฎ—็š„่ฟ‡็จ‹ไธญ ๅ‘้€็š„ๆ•ฐๆฎ็ฑปๅž‹่ฝฌๆข ###ๆ˜พ็คบ่ฝฌๆข(ๅผบๅˆถ่ฝฌๆข) * ๆŒ‡ๅฎš็š„ๅ…ทไฝ“ๆ•ฐๆฎ็ฑปๅž‹ ####่ฝฌๆขString ๆ–นๆณ•ๅ | ่ฏดๆ˜Ž | ่ฟ”ๅ›žๅ€ผ ----- | ----- | ----- ๅ˜้‡.toString() | ๅฐ†ๆ•ฐๅญ—็ฑปๅž‹่ฝฌๆขไธบๅญ—็ฌฆไธฒ็ฑปๅž‹ | string String(x) | ็›ดๆŽฅ่ฝฌๆขไธบๅญ—็ฌฆไธฒ็ฑปๅž‹ | string ------ ####่ฝฌๆขNamber ๆ–นๆณ•ๅ | ่ฏดๆ˜Ž | ่ฟ”ๅ›žๅ€ผ ----- | ----- | ----- Number(x) | ้€š่ฟ‡Number็š„ๆž„้€ ่ฝฌๆขๆ•ฐๅญ—็ฑปๅž‹ไฟ็•™ๅŽŸๅ€ผ | Number ๅฆ‚ๆžœไผ ๅ…ฅๅญ—ๆฏๅ€ผไธบNaN parseInt(x) | ่ฝฌๆขไธบๆ•ดๆ•ฐ ๅ–ๆ•ดๆ•ˆๆžœ ๆŒ‰็…งๆฏไธ€ไฝๆ•ฐ่ฟ›่กŒ่ฝฌๆข็š„ | int Number ๅชไฟ็•™ๆ•ฐๅญ—้ƒจๅˆ† parseFloat(x) | ่ฝฌๆขไธบๆตฎ็‚นๅž‹ ๆŒ‰็…งๆฏไธ€ไฝๆ•ฐ่ฟ›่กŒ่ฝฌๆข็š„ | float Number ๅชไฟ็•™ๆ•ฐๅญ—้ƒจๅˆ† ------ ####่ฝฌๆขBoolean ๆ–นๆณ•ๅ | ่ฏดๆ˜Ž | ่ฟ”ๅ›žๅ€ผ ----- | ----- | ----- Boolean(x) | ่ฝฌๆขๅธƒๅฐ”็ฑปๅž‹ | ไผ 0 ็ฉบๅญ—็ฌฆ null undefined NaN ไธบfalse ------ ###ๆกˆไพ‹ * ่พ“ๅ…ฅไธ€ไธชไธ‰ไฝๆ•ฐ ๆฑ‚ๅค„ไธ‰ไธชไฝๆ•ฐ็š„ๅ’Œ ```JavaScript /*ๆ–นๅผ1*/ var n1 = prompt("่พ“ๅ…ฅ3ไฝๆ•ฐ"); var n2 = parseInt(n1/100); var n3 = parseInt((n1 - n2*100) / 10); var n4 = parseInt((n1 - n2*100 -n3*10)); alert(n2 + n3 + n4); ``` ```JavaScript /*ๆ–นๅผ2*/ var bw = Math.floor(n1/100); var sw = Math.floor(n1%100/10); var gw = n1%10; ``` ##้€ป่พ‘่ฟ็ฎ—็ฌฆ * ๆˆ–่ฟ็ฎ— || ้‡trueๅˆ™true * ไธŽ(ไธ”)่ฟ็ฎ— && ้‡falesๅˆ™false * ้ž่ฟ็ฎ— ! ้‡falseไธบtrue ้‡trueไธบfalse ##็ญ‰ๅท้€—ๅท่ฟ็ฎ—็ฌฆ ็ฌฆๅท | ่ฏดๆ˜Ž --- | ---- = | ่ต‹ๅ€ผ == | ็›ธ็ญ‰ ๅชๅˆคๆ–ญๅ€ผ ไธๅˆคๆ–ญๆ•ฐๆฎ็ฑปๅž‹ === | ๅ…จ็ญ‰ ๅŒๆ—ถๆฏ”่พƒๅ€ผๅ’Œๆ•ฐๆฎ็ฑปๅž‹ != | ไธ็›ธ็ญ‰ ###้€—ๅท่ฟ็ฎ—็ฌฆ ```JavaScript var n1 = 1, n2 = 2, n3 = 3; ``` ##ๅˆ†ๆ”ฏ็ป“ๆž„(ๆกไปถๅˆคๆ–ญ) ๆกไปถ็ป“ๆž„ๅตŒๅฅ— ```JavaScript if (ๆกไปถ่กจ่พพๅผ) { } if else(ๆกไปถ่กจ่พพๅผ) { } ``` ##ๆกไปถ่กจ่พพๅผ ```JavaScript ๆกไปถ่กจ่พพๅผ ? ไปฃ็ 1 : ไปฃ็ 2; ```
Ruby
UTF-8
726
2.875
3
[ "MIT" ]
permissive
require_relative "york/student_info" class MarkingSystem def add_marks(module_code, year, marks) registry = York::StudentInfo.instance mod = registry.find_module(module_code, true) assessment = registry.create_assessment(mod, year) marks.each do |student_number, mark| registry.add_mark(assessment, student_number, mark) end registry.finalise_assessment(assessment) end def summarise_marks(module_code, year) registry = York::StudentInfo.instance mod = registry.find_module(module_code, false) return "" if mod.nil? marks = mod.assessments.find { |ass| ass.year == year }.marks marks.map { |student_number, mark| "#{student_number}: #{mark}" }.join("\n") end end
SQL
UTF-8
635
2.578125
3
[]
no_license
SELECT * FROM SYS.DBA_OBJECTS WHERE OWNER IN ('USER๋ช…') AND OBJECT_TYPE = 'TABLE' AND LAST_DDL_TIME >= TO_DATE('20190101', 'yyyymmdd') ORDER BY LAST_DDL_TIME DESC; /* OBJECT_TYPE 1 INDEX 2 TABLE SUBPARTITION 3 TYPE BODY 4 JAVA CLASS 5 PROCEDURE 6 INDEX SUBPARTITION 7 JAVA RESOURCE 8 TABLE PARTITION 9 JAVA SOURCE 10 TABLE 11 VIEW 12 TYPE 13 FUNCTION 14 TRIGGER 15 MATERIALIZED VIEW 16 DATABASE LINK 17 PACKAGE BODY 18 SYNONYM 19 RULE SET 20 QUEUE 21 EVALUATION CONTEXT 22 PACKAGE 23 SEQUENCE 24 LOB 25 LOB SUBPARTITION 26 LOB PARTITION 27 INDEX PARTITION 28 JOB */
Python
UTF-8
1,634
2.75
3
[]
no_license
import os from flask import Flask, request, render_template from flask_pymongo import PyMongo app = Flask(__name__) app.config['MONGO_DBNAME'] = 'first_databse' # name of your database app.config['MONGO_URI'] = os.getenv('MONGO_URI', 'mongodb+srv://marta_korts_laur:AstelV88l@cluster0-utrzr.mongodb.net/test?retryWrites=true&w=majority') # URI (see above) mongo = PyMongo(app) @app.route("/") def home(): city_01 = { "name" : "Tallinn", "descr" : "Capital", "bio" : "Tallinn is a great city!" } city_02 = { "name" : "Tartu", "descr" : "University city", "bio" : "Tartu is a small city." } cities = [city_01, city_02] return render_template('index.html', cities=cities) @app.route('/playing_around_with_databases') def playing_around_with_databases(): movies = mongo.db.movies.find() return "This is where we will be playing around with databases" @app.route("/europe") def europe(): return render_template("index.html") @app.route("/estonia") def estonia(): city_01 = { "name" : "Tallinn", "descr" : "Capital" } city_02 = { "name" : "Tartu", "descr" : "University city" } cities = [city_01, city_02] return render_template("country.html", cities=cities) @app.route("/north-america") def america(): return "This is the north american home page" @app.route("/asia") def asia(): return "This is the asian home page" if __name__ == '__main__': app.run(host=os.environ.get('IP', '0.0.0.0'), port=int(os.environ.get('PORT', '5000')), debug=True)
Java
UTF-8
153
1.640625
2
[]
no_license
package com.vas.aos.core.application.service; import java.util.UUID; public interface RequestOrderPaymentService { void requestPayment(UUID id); }
Java
UTF-8
1,507
1.9375
2
[]
no_license
package com.example.tinymall.entity; import java.time.LocalDateTime; import javax.persistence.*; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString @Table(name = "tinymall_ad") public class TinymallAd { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; /** * ๅนฟๅ‘Šๆ ‡้ข˜ */ @Column(name = "name") private String name; /** * ๆ‰€ๅนฟๅ‘Š็š„ๅ•†ๅ“้กต้ขๆˆ–่€…ๆดปๅŠจ้กต้ข้“พๆŽฅๅœฐๅ€ */ @Column(name = "link") private String link; /** * ๅนฟๅ‘Šๅฎฃไผ ๅ›พ็‰‡ */ @Column(name = "url") private String url; /** * ๅนฟๅ‘Šไฝ็ฝฎ๏ผš1ๅˆ™ๆ˜ฏ้ฆ–้กต */ @Column(name = "position") private Byte position; /** * ๆดปๅŠจๅ†…ๅฎน */ @Column(name = "content") private String content; /** * ๅนฟๅ‘Šๅผ€ๅง‹ๆ—ถ้—ด */ @Column(name = "start_time") private LocalDateTime startTime; /** * ๅนฟๅ‘Š็ป“ๆŸๆ—ถ้—ด */ @Column(name = "end_time") private LocalDateTime endTime; /** * ๆ˜ฏๅฆๅฏๅŠจ */ @Column(name = "enabled") private Boolean enabled; /** * ๅˆ›ๅปบๆ—ถ้—ด */ @Column(name = "add_time") private LocalDateTime addTime; /** * ๆ›ดๆ–ฐๆ—ถ้—ด */ @Column(name = "update_time") private LocalDateTime updateTime; /** * ้€ป่พ‘ๅˆ ้™ค */ @Column(name = "deleted") private Boolean deleted; }
Python
UTF-8
501
3.875
4
[]
no_license
def mode(nums): """Return most-common number in list. For this function, there will always be a single-most-common value; you do not need to worry about handling cases where more than one item occurs the same number of times. >>> mode([1, 2, 1]) 1 >>> mode([2, 2, 3, 3, 2]) 2 """ num_count_dict = {nums.count(x):x for x in nums} num_counts = list(num_count_dict.keys()) num_counts.sort() return num_count_dict.get(num_counts[-1])
PHP
UTF-8
1,296
3.953125
4
[]
no_license
<?php abstract class Animal { static $id = 1; public $idAnimal; public abstract function getProduct(); public function getClass() { return static::class; } } class Cow extends Animal { function __construct() { $this->idAnimal=parent::$id++; } public function getProduct() { return rand(8 , 12); } } class Chicken extends Animal { function __construct() { $this->idAnimal=parent::$id++; } public function getProduct() { return rand(0 , 1); } } class CreateFactory { public function getCow() { return new Cow(); } public function getChicken() { return new Chicken(); } } $factory = new createFactory(); $arr = []; for ($i = 0 ; $i < 7 ; $i++) { $arr[] = $factory->getCow(); } for ($y = 0; $y < 15 ; $y++) { $arr[] = $factory->getChicken(); } $milk = 0; $egg = 0; foreach ($arr as $value) { switch ($value->getClass()) { case("Cow"): $milk += $value->getProduct(); break; case ("Chicken"): $egg += $value->getProduct(); } } echo "ะšะพะปะธั‡ะตัั‚ะฒะพ ัะธั† - " . $egg . " ัˆั‚ัƒะบ" . "\n" . "ะšะพะปะธั‡ะตัั‚ะฒะพ ะผะพะปะพะบะฐ - " . $milk . " ะปะธั‚ั€ะพะฒ.";
Java
UTF-8
2,462
2.546875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DAL; /** * * @author Admin */ import java.util.List; import BLL.Puntori; import javax.persistence.Query; public class PuntoriRepository extends EMClass implements PuntoriInterface{ @Override public void create(Puntori p) throws CFormException { try{ em.getTransaction().begin(); em.persist(p); em.getTransaction().commit(); }catch(Exception e){ throw new CFormException("Msg \n" + e.getMessage()); } } @Override public void edit(Puntori p) throws CFormException { try{ em.getTransaction().begin(); em.merge(p); em.getTransaction().commit(); }catch(Exception e){ throw new CFormException("Msg \n" + e.getMessage()); } } @Override public void delete(Puntori p) throws CFormException { try{ em.getTransaction().begin(); em.remove(p); em.getTransaction().commit(); }catch(Exception e){ throw new CFormException("Msg \n" + e.getMessage()); } } @Override public List<Puntori> findAll() throws CFormException { try{ return em.createNamedQuery("Puntori.findAll").getResultList(); }catch(Exception e){ throw new CFormException("Msg \n" + e.getMessage()); } } @Override public Puntori findById(Integer ID) throws CFormException { try { Query query = em.createQuery("SELECT p from Puntori p where p.ID = :abc"); query.setParameter("abc", ID); return (Puntori) query.getSingleResult(); }catch(Exception e) { throw new CFormException(e.getMessage()); } } @Override public Puntori loginByUsernameAndPassword(String u, String psw) throws CFormException { try { Query query = em.createQuery("SELECT p from Puntori p where p.username = :user and p.password = :pw"); query.setParameter("user",u ); query.setParameter("pw",psw ); return (Puntori) query.getSingleResult(); }catch(Exception e) { throw new CFormException(e.getMessage()); } } }
Swift
UTF-8
2,127
2.859375
3
[]
no_license
// // MovieService.swift // moviePicker // // Created by Ajay Kumar on 12/18/15. // Copyright ยฉ 2015 NexGen. All rights reserved. // import Foundation protocol MovieServiceDelegate { func setMovie(movie: Movie) } class MovieService { var delegate: MovieServiceDelegate? func getMovie(movieTitle: String) { //request movie data //..wait // process data let movieEscaped = movieTitle.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet()) let path = "http://api.themoviedb.org/3/search/movie?api_key=c79b9571d2ab98df56637922cb4e93d5&query=\(movieEscaped!)" let url = NSURL(string: path) let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url!) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in //print(">>>> \(data)") let json = JSON(data: data!) let rating = json["results"][0]["vote_average"].double let movieTitle = json["results"][0]["original_title"].string let releaseDate = json["results"][0]["release_date"].string let movie = Movie(movieName: movieTitle!, rating: rating!, year: releaseDate!) // print("\(movieTitle)") // print("\n\(rating)") // print("\n\(releaseDate)") //let movie = Movie(movieName: "Test") if self.delegate != nil { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.delegate?.setMovie(movie) }) } // print(" Movie: \(movieTitle!) \n Rating: \(rating!) \n Release Date: \(releaseDate!)") //self.movieService.getMovie(DeepaksMovie) } task.resume() // let movie = Movie(movieName: movieTitle, rating: 8.1, year: 2002) // // if delegate != nil { // delegate?.setMovie(movie) // } } }
JavaScript
UTF-8
698
3.171875
3
[]
no_license
// const btn = document.getElementById('btn'); // let seter = true; // btn.onclick = function () { // if(seter){ // window.localStorage.setItem('key', JSON.stringify({name: 'Stiv'})); // seter = false; // } else { // console.log(JSON.parse(window.localStorage.getItem('key'))) // window.localStorage.removeItem('key') // seter = true; // } // } const btn = document.getElementById('btn'); let seter = true; btn.onclick = function () { if(seter){ window.sessionStorage.setItem('key', JSON.stringify({name: 'Stiv'})); seter = false; } else { console.log(JSON.parse(window.sessionStorage.getItem('key'))) window.sessionStorage.removeItem('key') seter = true; } }
Java
UTF-8
4,269
2.109375
2
[]
no_license
/* * Copyright (c) 2014 ReasonDev * All rights reserved. */ package net.avonmc.dungeons.dungeon; import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.bukkit.selections.Selection; import net.avonmc.dungeons.Dungeons; import net.avonmc.dungeons.util.Configuration; import net.avonmc.dungeons.util.Messaging; import net.avonmc.dungeons.util.Settings; import net.avonmc.dungeons.util.StringUtil; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.Map; import java.util.TreeMap; public class DungeonHandler { private static YamlConfiguration dungeonC = Configuration.getConfig("dungeons"); private static Map<String, Dungeon> loadedDungeons = new TreeMap<String, Dungeon>(String.CASE_INSENSITIVE_ORDER); public static void loadDungeons() { for(String dungeonID : dungeonC.getKeys(false)) loadDungeon(dungeonID); Messaging.printInfo("Dungeons successfully loaded!"); } private static void loadDungeon(String dungeonID) { loadedDungeons.put(dungeonID, Dungeon.deserialize(dungeonC.getConfigurationSection(dungeonID))); Dungeon dungeon = loadedDungeons.get(dungeonID); ConfigurationSection stageS = dungeonC.getConfigurationSection(dungeonID + ".stages"); for(int i = 0; i < stageS.getKeys(false).size(); i++) dungeon.addStage(Stage.deserialize(dungeon, stageS.getConfigurationSection(String.valueOf(i)))); if(dungeon.getLoadedStages().size() == 0) Messaging.printErr("Error! " + dungeonID + " has no Stages loaded! Errors may occur!"); } public static void saveDungeons() { for(String dungeonID : loadedDungeons.keySet()) dungeonC.set(dungeonID, loadedDungeons.get(dungeonID).serialize()); Messaging.printInfo("Dungeons successfully saved!"); } public static String getDungeonID(Dungeon dungeon) { for(String dungeonID : loadedDungeons.keySet()) if(loadedDungeons.get(dungeonID) == dungeon) return dungeonID; return null; } public static Map<String, Dungeon> getDungeons() { return loadedDungeons; } public static boolean dungeonExists(String dungeonID) { return loadedDungeons.containsKey(dungeonID); } public static Dungeon getDungeon(String dungeonID) { return loadedDungeons.get(dungeonID); } public static Dungeon getRandomDungeon(boolean isVIP) { for(Dungeon dungeon : loadedDungeons.values()) if(dungeon.getActiveLobby() != null) continue; else if(isVIP != dungeon.isVIP()) continue; else return dungeon; return null; } public static void createDungeon(String dungeonID, String displayName, boolean isVIP) { loadedDungeons.put(dungeonID, new Dungeon(displayName, isVIP, new ArrayList<Stage>())); } public static void removeDungeon(String dungeonID) { dungeonC.set(dungeonID, null); loadedDungeons.remove(dungeonID); } public static Dungeon dungeonFromMobSpawn(Location mobSpawn) { for(Dungeon dungeon : loadedDungeons.values()) if(dungeon.stageFromMobSpawn(mobSpawn) != null) return dungeon; return null; } public static void addMobSpawns(Player sender, Stage stage) { Selection sel = Dungeons.getWorldEdit().getSelection(sender); if (sel == null) { Messaging.send(sender, "&cYou have not made a WorldEdit selection!"); return; } Vector min = sel.getNativeMinimumPoint(); Vector max = sel.getNativeMaximumPoint(); for (int x = min.getBlockX(); x < max.getBlockX(); x++) for (int y = min.getBlockY(); y < max.getBlockY(); y++) for (int z = min.getBlockZ(); z < max.getBlockZ(); z++) { Block block = sel.getWorld().getBlockAt(x, y, z); if (block.getType() != Settings.MOB_SPAWN_MARKER) continue; stage.addMobSpawn(block.getLocation()); Messaging.send(sender, "&aSuccessfully added mob spawn at &b" + StringUtil.parseLoc(block.getLocation())); } } }
Python
UTF-8
533
3.9375
4
[]
no_license
# The provided code stub will read in a dictionary containing key/value pairs of name:[marks] for a list of students. # Print the average of the marks array for the student name provided, showing 2 places after the decimal. if __name__ == '__main__': n = 3 inputs = [['Krishna',67,68,69],['Arjun',70,98,63],['Malika',52,56,60]] query_name = 'Malika' for i in range(n): if (inputs[i][0] == query_name): del inputs[i][0] result = '%0.2f' % float(sum(inputs[i]) / 3) print(result)
C#
UTF-8
9,704
2.5625
3
[]
no_license
๏ปฟusing Dapper; using Domain; using Domain.Model; using Domain.Statuses; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; namespace DataAccess { public class OrderRepository : IOrderRepository { private readonly ISqlDataAccess _sqlDataAccess; public OrderRepository(ISqlDataAccess sqlDataAccess) { _sqlDataAccess = sqlDataAccess; } public void SaveOrder(string buyer, string buyerNotification, double summaryOrderValue, List<OrderLineModelDto> list) { using (IDbConnection cnn = new SqlConnection(_sqlDataAccess.GetConnectionString())) { cnn.Open(); using (var transaction = cnn.BeginTransaction()) { string sqlHeader = $"INSERT INTO OrderHeader (Number, BuyerId, Status, BuyerNotification, SummaryValue) " + $"VALUES ((select dbo.GetOrderNumber()), @BuyerId, @Status, @BuyerNotification, @SummaryValue);" + $"SELECT CAST(SCOPE_IDENTITY() as int)"; var result = cnn.ExecuteScalar(sqlHeader, new { BuyerId = buyer , Status = Const.StatusesList.Where(x => x.Status == StatusEnum.Submitted).FirstOrDefault().StatusId , BuyerNotification = buyerNotification , SummaryValue = summaryOrderValue }, transaction: transaction); int OrderHeaderId = Convert.ToInt32(result); foreach (var line in list) { string sqlLine = $"INSERT INTO OrderLine ([OrderHeaderId], [ItemId], [ItemName], [PriceNet], [PriceGross], [Tax], [SubmittedQty]) " + $"VALUES (@OrderHeaderId, @ItemId, @ItemName, @PriceNet, @PriceGross, @Tax, @SubmittedQty)"; cnn.Execute(sqlLine, new { OrderHeaderId, line.ItemId, line.ItemName, line.PriceNet, line.PriceGross, line.Tax, line.SubmittedQty }, transaction: transaction); } transaction.Commit(); } } } public List<OrderHeaderModelDto> GetUserOrderList(StatusEnum[] statuses, string buyer = null, string seller = null, int id = 0) { using (IDbConnection cnn = new SqlConnection(_sqlDataAccess.GetConnectionString())) { List<OrderHeaderModelDto> headers = new List<OrderHeaderModelDto>(); foreach (var status in statuses) { //int testStatus = Const.StatusesList.Where(x => x.Status == StatusEnum.Submitted).FirstOrDefault().StatusId; headers.AddRange(cnn.Query<OrderHeaderModelDto>("dbo.OrderHeaderGet" , param: new { BuyerId = buyer , Status = Const.StatusesList.Where(x => x.Status == status).FirstOrDefault().StatusId , SellerId = seller , Id = id } , commandType: CommandType.StoredProcedure).ToList()); foreach (var item in headers) { string sql = "SELECT [Id], [OrderHeaderId], [ItemId], [ItemName], [PriceNet], [PriceGross], [Tax], [SubmittedQty], [AcceptedQty]" + "FROM [Sklepik].[dbo].[OrderLine] WHERE OrderHeaderId = @OrderHeaderId"; item.Items = cnn.Query<OrderLineModelDto>(sql, param: new { OrderHeaderId = item.Id }).ToList(); } } return headers; } } public List<OrderSummaryModel> OrderHeadersInStatusGet(StatusEnum[] statuses) { using (IDbConnection cnn = new SqlConnection(_sqlDataAccess.GetConnectionString())) { string sql = $"SELECT BuyerId, COUNT(Id) Qty, SUM(SummaryValue) SummaryValue FROM [dbo].[OrderHeader] WHERE "; for (int i = 0; i < statuses.Length; i++) { if (i > 0) { sql += " OR "; } sql += $"Status = {Const.StatusesList.Where(x => x.Status == statuses[i]).FirstOrDefault().StatusId}"; } sql += " GROUP BY BuyerId"; List<OrderSummaryModel> headers = cnn.Query<OrderSummaryModel>(sql).ToList(); return headers; } } public void ChangeOrderStatus(OrderHeaderModelDto dtoModel, StatusEnum newStatus) { using (IDbConnection cnn = new SqlConnection(_sqlDataAccess.GetConnectionString())) { string sqlHead = $"UPDATE [dbo].[OrderHeader] SET Status = @Status WHERE Id = @Id"; cnn.Execute(sqlHead, new { Status = Const.StatusesList.Where(x => x.Status == newStatus).FirstOrDefault().StatusId, dtoModel.Id }); } } public void ChangeOrderStatusAsAccepted(OrderHeaderModelDto dtoModel, string SellerId) { using (IDbConnection cnn = new SqlConnection(_sqlDataAccess.GetConnectionString())) { string sqlHead = $"UPDATE [dbo].[OrderHeader] SET Status = @Status, SellerId = @SellerId, " + $"SummaryValue = @SummaryValue, SellerNotification = @SellerNotification WHERE Id = @Id"; cnn.Execute(sqlHead, new { Status = Const.StatusesList.Where(x => x.Status == StatusEnum.Accepted).FirstOrDefault().StatusId, SellerId, dtoModel.SummaryValue, dtoModel.SellerNotification, dtoModel.Id }); foreach (var item in dtoModel.Items) { string sqlLine = $"UPDATE [dbo].[OrderLine] SET AcceptedQty = {item.AcceptedQty} " + $"WHERE Id = {item.Id}"; cnn.Execute(sqlLine); } } } public void ChangeUserOrdersStatus(string BuyerId, StatusEnum fromStatus, StatusEnum intoStatus) { using (IDbConnection cnn = new SqlConnection(_sqlDataAccess.GetConnectionString())) { string sql = $"UPDATE [dbo].[OrderHeader] SET Status = {Const.StatusesList.Where(x => x.Status == intoStatus).FirstOrDefault().StatusId} " + $"WHERE BuyerId = '{BuyerId}' AND Status = {Const.StatusesList.Where(x => x.Status == fromStatus).FirstOrDefault().StatusId}"; cnn.Execute(sql); } } public void Delete(int id) { using (IDbConnection cnn = new SqlConnection(_sqlDataAccess.GetConnectionString())) { string sql = $"DELETE FROM [Sklepik].[dbo].[OrderHeader] WHERE Id = {id}"; cnn.Execute(sql); } } //public List<OrderHeaderModel> GetOrderList(string buyer = null, OrderStatus status = OrderStatus.Submitted, string seller = null, int id = 0) //{ // using (IDbConnection cnn = new SqlConnection(_sqlDataAccess.GetConnectionString())) // { // var orderDictionary = new Dictionary<int, OrderHeaderModel>(); // var result = cnn.Query<OrderHeaderModel, List<OrderLineModel>, OrderHeaderModel>("dbo.OrderHeaderGet", // (header, lines) => // { // OrderHeaderModel orderEntry; // if (!orderDictionary.TryGetValue(header.Id, out orderEntry)) // { // orderEntry = header; // orderEntry.Items = new List<OrderLineModel>(); // orderDictionary.Add(orderEntry.Id, orderEntry); // } // orderEntry.Items.AddRange(lines); // return orderEntry; // } // , splitOn: "Id, OrderHeaderId" // , param: new { BuyerId = buyer, Status = OrderStatusDictionary.GetStatus[status], SellerId = seller, Id = id } // , commandType: CommandType.StoredProcedure); // return null; // } //} //public List<OrderHeaderModel> GetOrderList(string buyer = null, OrderStatus status = OrderStatus.Submitted, string seller = null, int id = 0) //{ // using (IDbConnection cnn = new SqlConnection(_sqlDataAccess.GetConnectionString())) // { // var result = cnn.Query<OrderHeaderModel, List<OrderLineModel>, OrderHeaderModel>("dbo.OrderHeaderGet", // (header, lines) => { header.Items = lines; return header; } // , splitOn: "Id, OrderHeaderId" // , param: new { BuyerId = buyer, Status = OrderStatusDictionary.GetStatus[status], SellerId = seller, Id = id} // , commandType: CommandType.StoredProcedure); // return null; // } //} } }
Python
UTF-8
438
3.375
3
[ "MIT" ]
permissive
# Time: O(n) # Space: O(1) class Solution(object): def numSteps(self, s): """ :type s: str :rtype: int """ result, carry = 0, 0 for i in reversed(xrange(1, len(s))): if int(s[i]) + carry == 1: carry = 1 # once it was set, it would keep carrying forever result += 2 else: result += 1 return result+carry
C++
UTF-8
5,651
3.09375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; class Seat{ private: bool aisle; bool occupied; public: Seat(){ aisle = false; occupied = false; } void set_aisle(bool b){ aisle = b; } bool is_aisle(){ return aisle; } bool is_occupied(){ return occupied; } void set_occupied(bool ans){ occupied = ans; } }; class Screen{ private: string name; int rows; int cols; vector<vector<Seat> > seats; public: Screen(string n, int r, int c, const vector<int> aisle){ name = n; rows = r; cols = c; seats.resize(rows, vector<Seat> (cols)); for(int x=0; x<rows; x++){ for(int y=0; y<cols; y++){ Seat s{}; seats[x][y] = s; } for(auto i: aisle){ int y = i - 1; seats[x][y].set_aisle(true); } } cout << "success\n"; } void print(){ cout << "Screen name: " << name << " "; cout << "Rows: " << rows << " "; cout << "Cols: " << cols << "\n"; cout << "Seat 1: " << "aisle: " << seats[0][0].is_aisle() << " " << "occupied: " << seats[0][0].is_occupied() << "\n"; } bool reserveSeats(int r, const vector<int>& req){ int x = r - 1; for(auto i: req){ int y = i - 1; if(seats[x][y].is_occupied()) return false; } for(auto i: req){ int y = i - 1; seats[x][y].set_occupied(true); } return true; } vector<int> getUnreservedSeats(int r){ vector<int> res; int x = r-1; for(int y=0; y<cols; y++){ if(!seats[x][y].is_occupied()) res.push_back(y+1); } return res; } vector<int> suggestSeats(int no_of_seats, int r, int req_seat_no){ vector<int> res; int x = r-1; int y = req_seat_no - 1; bool left = true, right = true; if(seats[x][y].is_occupied()) return res; if(seats[x][y].is_aisle()){ if(y-1>=0 && seats[x][y-1].is_aisle()) left = false; if(y+1<cols && seats[x][y+1].is_aisle()) right = false; } no_of_seats--; res.push_back(req_seat_no); int i = y-1, j = y+1; while(left && no_of_seats>0 && i>=0){ if(seats[x][i].is_occupied()) break; res.push_back(i+1); no_of_seats--; if(seats[x][i].is_aisle()) break; i--; } while(right && no_of_seats>0 && j<cols){ if(seats[x][j].is_occupied()) break; res.push_back(j+1); no_of_seats--; if(seats[x][j].is_aisle()) break; j++; } if(no_of_seats>0) res.clear(); sort(res.begin(), res.end()); return res; } }; vector<string> getWords(string s){ vector<string> words; string word = ""; for(char c: s){ if(c == ' '){ words.push_back(word); word=""; } word += c; } words.push_back(word); return words; } int main(){ int tests; string input, operation; vector<string> words; map<string, Screen*> mp; getline(cin, input); tests = stoi(input); while(tests--){ getline(cin, input); words = getWords(input); operation = words[0]; if(operation == "add-screen"){ vector<int> aisle_seats; string screen_name = words[1]; int rows = stoi(words[2]); int cols = stoi(words[3]); for(int i=4; i<words.size(); i++) aisle_seats.push_back(stoi(words[i])); mp[screen_name] = new Screen(screen_name, rows, cols, aisle_seats); } else if(operation == "reserve-seat"){ vector<int> req_seats; string screen_name = words[1]; int row = stoi(words[2]); for(int i=3; i<words.size(); i++) req_seats.push_back(stoi(words[i])); bool res = mp[screen_name]->reserveSeats(row, req_seats); if(res) cout << "success\n"; else cout << "failure\n"; } else if(operation == "get-unreserved-seats"){ string screen_name = words[1]; int row = stoi(words[2]); vector<int> unreserved_seats; unreserved_seats = mp[screen_name]->getUnreservedSeats(row); for(auto i: unreserved_seats) cout << i << " "; cout << "\n"; } else if(operation == "suggest-contiguous-seats"){ string screen_name = words[1]; int no_of_seats = stoi(words[2]); int row = stoi(words[3]); int req_seat_no = stoi(words[4]); vector<int> suggested_seats; suggested_seats = mp[screen_name]->suggestSeats(no_of_seats, row, req_seat_no); if(suggested_seats.size() == 0) cout << "none\n"; else { for(auto i: suggested_seats) cout << i << " "; cout << "\n"; } } } return 0; }
C++
UTF-8
1,492
2.5625
3
[ "MIT" ]
permissive
#ifndef HYBRID_HEIGHT_H #define HYBRID_HEIGHT_H #include "compiled_plugin.h" #include "compiled_plugin_base.h" #include <future> namespace himan { namespace plugin { class hybrid_height : public compiled_plugin, private compiled_plugin_base { public: hybrid_height(); virtual ~hybrid_height() = default; hybrid_height(const hybrid_height& other) = delete; hybrid_height& operator=(const hybrid_height& other) = delete; virtual void Process(std::shared_ptr<const plugin_configuration> conf) override; virtual std::string ClassName() const override { return "himan::plugin::hybrid_height"; } virtual HPPluginClass PluginClass() const override { return kCompiled; } void WriteToFile(const std::shared_ptr<info<float>> targetInfo, write_options opts = write_options()) override; private: virtual void Calculate(std::shared_ptr<info<float>> myTargetInfo, unsigned short threadIndex) override; void WriteSingleGridToFile(const std::shared_ptr<info<float>> targetInfo); bool WithHypsometricEquation(std::shared_ptr<info<float>>& myTargetInfo); bool WithGeopotential(std::shared_ptr<info<float>>& myTargetInfo); std::shared_ptr<himan::info<float>> GetSurfacePressure(std::shared_ptr<himan::info<float>>& myTargetInfo); int itsBottomLevel; bool itsUseGeopotential; }; // the class factory extern "C" std::shared_ptr<himan_plugin> create() { return std::make_shared<hybrid_height>(); } } // namespace plugin } // namespace himan #endif /* HYBRID_HEIGHT_H */
Markdown
UTF-8
4,427
2.75
3
[]
no_license
# Version Control System : git with Sourcetree git - MS Windows version - version : 2.92.2 - Homepage : https://www.git-scm.com Sourcetree - Version : 3.4.5 - Homepage : https://www.sourcetreeapp.com ## Setup ### Set-up User **git bash** ``` $ git config --global user.name "<user_name>" $ git config --global user.email "<email_address>" ``` **Sourcetree** 1. In the menubar, `[Tools] - [Options]` 1. Select `[General]` tab. 1. In `Default user information`, provide `Full Name` and `Email address`. ### Set-up Editor **git bash** - gvim ``` $ git config --global core.editor "'C:\Program Files\Vim\vim82\gvim.exe' --nofork '%*'" ``` - Visual Studio Code ``` $ git config --global core.editor "code --wait" ``` ### Check Settings **git bash** ``` $ git config --list ``` ## Create a new repository **git bash** 1. Create the directory for new repository and get into it. 1. Type ``` $ git init ``` **Sourcetree** 1. Click `Create` in the toolbar. 1. Click `Browse` and choose a directory for a new repository. 1. Click `Create` button below. A new hidden subdirectory named as `.git` will be created, which contains the files necessary for the management of git. ## Add New files to be managed by git Create a file. (e.g. `README.md`) **git bash** 1. To check the status, type ``` $ git status ``` 1. `README.md` file can be found in `Untracked Files` section. **Sourcetree** 1. `README.md` file can be found in `Unstaged files` section with a question mark icon. 1. The question mark icon means the file is *not tracked*. *Untracked* or *Not Tracked* means the files are in the repository, but not managed by git yet. ## Start Tracking the Files **git bash** 1. Type ``` $ git add README.md ``` 1. `git status` command now shows that `README.md` file is in the `Changes to be committed` section and indicated as `new file`. **Sourcetree** 1. In the `Unstaged files` section, click the `+` button at the far right of `README.md` file. 1. Now, `README.md` file is in `Staged files` section. Now, the files begin to be tracked by git, but are not accepted as a version yet. In order to be a version, *commit* action is necessary. ## Commit **git bash** 1. Type ``` $ git commit -m '<commit_message>' ``` 1. `git status` command now says "nothing to commit, working tree clean". 1. Commit history can be shown by ``` $ git log ``` **Sourcetree** 1. Click `Commit` in the toolbar. 1. Write `<commit_message>` in the box at the bottom of the window. 1. Commit history is shown by selecting `WORKSPACE - History` at the sidebar ## Stage ## Remote Repository GitHub site will be used. ### Create a Remote Repository Create a new repository on GitHub. - public - empty : no `README`, `.gitignore`, license ### Connect the Local Repository to the Remote Repository **Sourcetree** 1. In the memubar, `[Repository] - [Add Remote...]`. 1. In the `[Remotes]` tab, `[Add]`. 1. Copy HTTPS address from remote repository page, Paste it in `[URL / Path]`. Information in the `[Optional extended integration]` will be changed to reflect GitHub. 1. Check `[Default remote]` checkbox. `[Remote name]` is set to `origin`. 1. `[OK]`. `[OK]`. 1. In the sidebar, `origin` appears under `[Remote]`. origin : a kind of nickname for remote repository to make easy to use(call) ### Push Synchronization, upload **Sourcetree** 1. In the toolbar, `[Push]`. 1. For `[Push to repository]`, select remote name `origin`. 1. In the `[Branches to push]`, select the branches to push to the remote repository using checkbox. 1. `[Push]` 1. Visit and check the remote repository page. ## Reference - https://opentutorials.org ## Memos - Dropbox, Google Drive are integrated with simple VCS. ## To be studied more `?? README.md` `git -rm --cached <file>...` to unstage ## New repository on GitHub - HTTPS : https://github.com/cdsuh3s/ex_git_sourcetree.git - SSH : git@github.com:cdsuh3s/ex_git_sourcetree.git ### Create a new repository on the command line ```git echo "# ex_git_sourcetree" >> README.md git init git add README.md git commit -m "first commit" git branch -M main git remote add origin git@github.com:cdsuh3s/ex_git_sourcetree.git git push -u origin main ``` ### Push an existing repository from the command line ```git git remote add origin git@github.com:cdsuh3s/ex_git_sourcetree.git git branch -M main git push -u origin main ```
Markdown
UTF-8
1,546
3.71875
4
[ "MIT" ]
permissive
--- layout: post --- ES6 introduces a new keyword "let" that sits alongside var as a way to declare variables. The let keyword is different to var in that it attaches the variable declaration to the scope of whatever block (usually pair of { }) its contained within. {% highlight javascript %} (function(){ "use strict"; var foo = true; if (foo) { var bar = foo * 2; let baz = foo * 2; } console.log(bar); // 2 console.log(baz); // "ReferenceError: baz is not defined })(); {% endhighlight %} Using the let keyword is somewhat implicit. It requires close attention to detail to which blocks have vars scoepd to them, and can cause confusion if blocks are moved around, nested etc as code evolves. This is because there may be hidden reliances on variables that are function or globally scoped. One way to combat this is to be more explicit and use explicit blocks for block scoping to make it more obvious... {% highlight javascript %} var foo = true; if (foo) { { // <-- explicit block let baz = foo * 2; } } console.log(baz); // "ReferenceError: baz is not defined {% endhighlight %} Above we create an arbitrary block for the let declaration to bind to by adding the extra { } pair. ## LET AND HOISTING Unlike var, declarations made with let will not hoist to the entire scope of the block they appear in. I.e. these declarations will not exist in the block until the point they are actually declared. {% highlight javascript %} { console.log( bar ); // ReferenceError! let bar = 2; } {% endhighlight %}
Java
UTF-8
2,987
2.375
2
[]
no_license
package baking.example.android.bakingapp; import android.app.IntentService; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import baking.example.android.bakingapp.data.AppDatabase; import baking.example.android.bakingapp.data.Ingredient; import java.util.List; /** * An {@link IntentService} subclass for handling asynchronous task requests in * a service on a separate handler thread. */ public class GetIngredientsService extends IntentService { private AppDatabase mDb; public static final String ACTION_GET_INGREDIENTS = "baking.example.android.bakingapp.action.GET_INGREDIENTS"; public static final String EXTRA_RECIPE_ID = "baking.example.android.bakingapp.extra.RECIPE_ID";; public GetIngredientsService() { super("GetIngredientsService"); } /** * Starts this service to perform GetIngredients action with the given parameters. If * the service is already performing a task this action will be queued. * * @see IntentService */ public static void startActionGetIngredients(Context context, int recipeId) { Intent intent = new Intent(context, GetIngredientsService.class); intent.setAction(ACTION_GET_INGREDIENTS); intent.putExtra(EXTRA_RECIPE_ID, recipeId); context.startService(intent); } /** * @param intent */ @Override protected void onHandleIntent(Intent intent) { if (intent != null) { final String action = intent.getAction(); if (ACTION_GET_INGREDIENTS.equals(action)) { int recipeId = intent.getIntExtra(EXTRA_RECIPE_ID, 1); handleActionGetIngredients(recipeId); } } } /** * Handle action WaterPlant in the provided background thread with the provided * parameters. */ private void handleActionGetIngredients(int recipeId) { mDb = AppDatabase.getInstance(getApplicationContext()); final List<Ingredient> ingredients = mDb.recipeDao().getRecipe(recipeId).getIngredients(); StringBuilder ingredientsList = new StringBuilder(); for (int i = 0; i < ingredients.size(); i++) { String quantity = ingredients.get(i).getQuantity(); String measure = ingredients.get(i).getMeasure(); String ingredient = ingredients.get(i).getIngredient(); String string = "\n" + quantity + " " + measure + " " + ingredient + "\n"; ingredientsList.append(string); } AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(this, BakingWidgetProvider.class)); //Now update all widgets BakingWidgetProvider.updateIngredientWidgets(this, appWidgetManager, appWidgetIds, ingredientsList.toString()); } }
Go
UTF-8
3,399
3.53125
4
[ "Apache-2.0" ]
permissive
package test const ( KeySizeScenario = "increasing-key-size" ValueSizeScenario = "increasing-value-size" ObjectCountScenario = "increasing-objects-count" Put = "put" Get = "get" ) // Evolve represents an evolution logic for a given scenario parameters type Evolve func(scenario *Scenario) bool type evolution struct { next Evolve iteration int } // Config carries the benchmark scenario evolution configuration type Config struct { Num int KeySize int ValueSize int } // Scenario represents a benchmark scenario type Scenario struct { name string evolution Config } // Benchmark creates a new benchmark scenario func Benchmark(next Evolve, num, keySize, valueSize int) *Scenario { return &Scenario{ evolution: evolution{ next: next, }, Config: Config{ Num: num, KeySize: keySize, ValueSize: valueSize, }, } } func (s *Scenario) Name(name string) Scenario { s.name = name return *s } // next evolves the given scenario for one iteration func (s *Scenario) next() bool { return s.evolution.next(s) } // get returns the scenario config func (s *Scenario) get() Config { s.iteration++ return s.Config } // execute executes all the scenarios based on the corresponding configuration func (s *Scenario) execute(exec func(scenario Config)) { for s.next() { exec(s.get()) } } // Builder facilitates the creation of evolution logic for the becnhmark scenarios type Builder []Evolve // Evolution creates a new scenario evolution builder func Evolution() Builder { return make([]Evolve, 0) } // add adds an evolution stage to the builder func (eb Builder) add(stage Evolve) Builder { eb = append(eb, stage) return eb } // create creates a new scenario based on the builder properties func (eb Builder) create() Evolve { if len(eb) == 0 { panic("cannot create evolution scenario without any instructions") } return func(scenario *Scenario) bool { hasNext := true for i := 0; i < len(eb); i++ { next := eb[i](scenario) hasNext = next && hasNext } return hasNext } } // limit specifies the number of evolutions for a given scenario func limit(iteration int) func(scenario *Scenario) bool { return func(scenario *Scenario) bool { return scenario.iteration < iteration } } // num specifies the number of elements as an evolution parameter func num(o op) func(scenario *Scenario) bool { return func(scenario *Scenario) bool { if scenario.iteration > 0 { scenario.Num = o(scenario.Num) } return true } } // key specifies the elements keys size as an evolution parameter func key(o op) func(scenario *Scenario) bool { return func(scenario *Scenario) bool { if scenario.iteration > 0 { scenario.KeySize = o(scenario.KeySize) } return true } } // value specifies the elements values size as an evolution parameter func value(o op) func(scenario *Scenario) bool { return func(scenario *Scenario) bool { if scenario.iteration > 0 { scenario.ValueSize = o(scenario.ValueSize) } return true } } // op identifies an operation on a generic integer type op func(n int) int // add specifies the addition evolution logic for scenario values func add(m int) op { return func(n int) int { return n + m } } // pow specifies the exponential logic for scenario values evolution func pow(m int) op { return func(n int) int { return n * m } }
Python
UTF-8
475
2.65625
3
[]
no_license
import cv2 import numpy as np cap =cv2.VideoCapture(0) while True: ret, frame = cap.read() hsv= cv2.cvtColor(frame,cv2.COLOR_BGR2HSV) rojo_min= np.array([136,87,111]) rojo_max= np.array([180,255,255]) mascara= cv2.inRange(hsv, rojo_min, rojo_max) bits= cv2.bitwise_and(frame, frame, mask =mascara) cv2.imshow('frame',frame) cv2.imshow('Mascara',mascara) cv2.imshow('Bits',bits) if cv2.waitKey(1) & 0xFF == ord('q'): break
TypeScript
UTF-8
1,002
2.609375
3
[]
no_license
import * as fromModels from '../../models'; import * as fromFeaturebar from '../actions/featurebar.action'; export interface FeaturebarState { title: string; back: fromModels.FeaturebarBack; crumbs: fromModels.FeaturebarLink[]; tabs: fromModels.FeaturebarLink[]; } export const initialState: FeaturebarState = { title: '', back: { enabled: false }, crumbs: [], tabs: [], }; export function reducer( state = initialState, action: fromFeaturebar.FeaturebarAction, ): FeaturebarState { switch (action.type) { case fromFeaturebar.SET_FEATURE_TITLE: { const { title } = action.payload; return { ...state, title, }; } } return state; } export const getFeaturebarTitle = (state: FeaturebarState) => state.title; export const getFeaturebarBack = (state: FeaturebarState) => state.back; export const getFeaturebarCrumbs = (state: FeaturebarState) => state.crumbs; export const getFeaturebarTabs = (state: FeaturebarState) => state.tabs;
JavaScript
UTF-8
1,336
2.671875
3
[]
no_license
import React, { Component } from "react"; import { Link } from "react-router-dom"; import "./Posts.css"; import Post from "../../../components/Post/Post"; class Posts extends Component { state = { posts: [], }; async componentDidMount() { // console.log(this.props); try { const res = await fetch("https://jsonplaceholder.typicode.com/posts "); if (!res.ok) throw new Error("Failed to fetch..."); const data = await res.json(); const dataShortened = data.slice(0, 4); const updatedData = dataShortened.map((element) => { return { ...element, author: "Jaenn", }; }); this.setState({ posts: updatedData }); console.log("ASYNC --- FETCHING DATA FROM SERVER ---"); } catch (err) { // this.setState({ error: true }); console.log(err); } } render() { let posts = ( <p style={{ textAlign: "center" }}>FAILED TO FETCH... PLEASE TRY AGAIN</p> ); if (!this.state.error) { posts = this.state.posts.map((post) => { return ( <Link to={`/${post.id}`} key={post.id}> <Post key={post.id} title={post.title} author={post.author} /> </Link> ); }); } return <section className="Posts">{posts}</section>; } } export default Posts;
Ruby
UTF-8
985
3.265625
3
[]
no_license
class Pager attr_reader :post_num def initialize(post_num = 3) @post_num = post_num end def paginate(directory, num_page) page = directory[((num_page - 1) * @post_num)..(num_page * (@post_num - 1))] page.each do |post| case post.sponsored when "no" puts "#{post.title.capitalize} #{post.date}" puts "*************************" puts "#{post.text}\n" puts "-------------------------" when "yes" puts "=======#{post.title.capitalize}======= #{post.date}" puts "*************************" puts "#{post.text}\n" puts "-------------------------" end end end def calculate_page_num(directory) pages = directory.length / @post_num pages += 1 if (directory.length % @post_num) == 1 pages end def select_page(pages) selection = 0 selection = gets.chomp.to_i until (selection > 0) && (selection <= pages) selection end end
Python
UTF-8
2,830
3.078125
3
[ "MIT" ]
permissive
#!/usr/bin/env python import rospy from std_msgs.msg import String class RobotVoiceOperation: #define the constructor of the class def __init__(self): #initialize the ROS node with a name voice_op rospy.init_node('voice_op') # Publish the String message to the audio_conntrol topic self.movement_pub= rospy.Publisher('audio_control', String, queue_size=5) # Subscribe to the /recognizer/output topic to receive voice commands. rospy.Subscriber('/recognizer/output', String, self.voice_command_callback) #create a Rate object to sleep the process at 5 Hz rate = rospy.Rate(5) # Initialize the movement command message we will publish. self.movement_str = '0' # A mapping from keywords or phrases to commands #we consider the following simple commands, which you can extend on your own self.commands = ['forward', 'slight-left', 'slight-right', 'stop', 'rotate-left', 'rotate-right', 'backward', 'voice control', 'twitch control', ] rospy.loginfo("Ready to receive voice commands") # We have to keep publishing the movement_str message if we want the robot to keep moving. while not rospy.is_shutdown(): self.movement_pub.publish(self.movement_str) rate.sleep() def voice_command_callback(self, msg): # Get the motion command from the recognized phrase command = msg.data if (command in self.commands): if command == 'forward': self.movement_str = '1' elif command == 'slight-left': self.movement_str = '2' elif command == 'slight-right': self.movement_str = '3' elif command == 'stop': self.movement_str = '4' elif command == 'rotate-left': self.movement_str = '5' elif command == 'rotate-right': self.movement_str = '6' elif command == 'backward': self.movement_str = '7' elif command == 'voice-control': #TODO elif command == 'twitch-control': #TODO else: #command not found print 'command not found: '+command self.movement_str = '0' print ("command: " + command) if __name__=="__main__": try: RobotVoiceOperation() rospy.spin() except rospy.ROSInterruptException: rospy.loginfo("Voice navigation terminated.")