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
TypeScript
UTF-8
5,764
3.390625
3
[ "MIT" ]
permissive
import { QueryValueError } from './error'; import { isPlainObject, isShallowEqual, isString, isNumber } from '../util/is'; import { clone } from '../util/clone'; /** * Manage filters applied to a query. * @public */ export class QueryFilter { private _filters: Map<string, unknown> = new Map(); /** * Retrieve the value of a filter. * * @param name - Name of the filter. * @returns The value of the filter. * @public */ public get(name: string): unknown { return this._denormalize(this._filters.get(name)); } /** * Set the value of a filter. * * @remarks * * Setting the value of a filter will replace any existing value. * * @param name - Name of the field. * @param value - Value of the filter. * @public */ public set(name: string, value: unknown): void { const normalized = this._normalize(value); if (normalized instanceof Set) { this._filters.set(name, normalized); } else if (isPlainObject(normalized) && Object.entries(normalized).length === 0) { throw new QueryValueError(`plain object filters can't be empty`); } else { this._filters.set(name, clone(normalized)); } } /** * Check whether there's a filter for the provided name or not. * * @param name - Name of the field. * @returns A boolean value. */ public has(name: string): boolean { return this._filters.has(name); } /** * Check whether there's a filter for the provided name and it contains * the provided value or not. * * @param name - Name of the field. * @param value - The value for the filter. * @returns A boolean value. */ public contains(name: string, value: unknown): boolean { return this.has(name) && this._filterContainsOrEqualsValue(name, value, false); } /** * Check whether there's a filter for the provided name and it's * equal to the provided value or not. * * @param name - Name of the field. * @param value - The value for the filter. * @returns A boolean value. */ public equals(name: string, value: unknown): boolean { return this.has(name) && this._filterContainsOrEqualsValue(name, value, true); } /** * Add a value to filter by a field. * * @remarks * * - If the filter does not exist, it is created. * - If the value is an object, the value for the filter is replaced. * - Otherwise is supposed to be a Set of terms / numbers. * * @param name - Name of the filter. * @param value - Value to add to the filter. * @public */ public add(name: string, value: unknown): void { const added: Set<unknown> | unknown = this._normalize(value); const existing: Set<unknown> | unknown = this._filters.get(name); if (existing instanceof Set) { if (added instanceof Set) { this._filters.set(name, new Set([...existing, ...added])); } else { existing.add(added); } } else { this._filters.set(name, added); } } /** * Remove a filter by a field. * * @remarks * * - If the value is not provided, the filter is removed. * - If the value is an object, the filter is removed. * - Otherwise the value is removed from the list of terms. * * @param name - Name of the filter. * @param value - Optional. Value to remove from the filter. * @public */ public remove(name: string, value?: unknown): void { const existing: Set<unknown> | unknown = this._filters.get(name); if (existing instanceof Set && value != null) { const deleted: Set<unknown> | unknown = this._normalize(value); if (deleted instanceof Set) { for (const item of deleted) { existing.delete(item); } } else { existing.delete(deleted); } if (existing.size === 0) { this._filters.delete(name); } } else { this._filters.delete(name); } } /** * Clear all filters. * @public */ public clear(): void { this._filters.clear(); } /** * Set multiple filters at once. * * @param data - An object with all the filters to be set. * @param replace - Boolean value telling whether to replace any * existing filter or not. * * @public */ public setMany(data: Record<string, any>, replace = false): void { if (replace) { this.clear(); } for (const key in data) { this.set(key, data[key]); } } /** * Dump all filters as an object. * @returns An object with fields as keys and filter values as values. * @public */ public dump(): Record<string, any> { const data: Record<string, any> = {}; this._filters.forEach((value, key) => { data[key] = this._denormalize(value); }); if (Object.keys(data).length > 0) { return data; } } private _normalize(value: unknown): Set<unknown> | unknown { if (isString(value) || isNumber(value)) { return new Set([value]); } else if (Array.isArray(value)) { return new Set(value); } else { return value; } } private _denormalize(value: unknown): unknown { return value instanceof Set ? [...value] : value; } private _filterContainsOrEqualsValue(name: string, value: unknown, checkEquality: boolean): boolean { const normalized = this._normalize(value); const filterValue = this._filters.get(name); if (filterValue instanceof Set && normalized instanceof Set) { if (checkEquality && filterValue.size !== normalized.size) { return false; } for (const term of normalized) { if (!filterValue.has(term)) { return false; } } return true; } else { return isShallowEqual(filterValue, normalized); } } }
PHP
UTF-8
833
2.578125
3
[]
no_license
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateSkill extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('skill', function (Blueprint $table) { $table->increments('skill_id'); $table->integer('target_type'); $table->integer('skill_type_id')->unsigned(); $table->string('skill_name','100'); $table->string('skill','255'); $table->timestamps(); $table->string('last_update_user','20'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('skill'); } }
Python
UTF-8
1,256
3.78125
4
[]
no_license
""" 0.就是调用这个又调用那个 1.横向关系用组合,纵向关系用继承 2.类对象在定义类后即产生了 3.方法会被属性替换掉 4.num count 是类属性,x,y是实例属性 5.方法是要绑定实例对象的,printBB 没有绑定 """ class Cntnum(): num = 0 def __init__(self): Cntnum.num += 1 def __del__(self): Cntnum.num -= 1 def getNum(self): return Cntnum.num # a = Cntnum() # b = Cntnum() # c = Cntnum() # print(Cntnum.num) # del a # print(Cntnum.num) # class MyStack(list): # def __init__(self,x): # super().__init__(x) # def isEmpty(self): # if len(self) == 0: # return True # else: # return False # def push(self,x): # self.append(x) # def top(self): # return self[-1] # def bottom(self): # return self[0] # statick1 = MyStack((1,2,3,4)) # print(statick1) # print(statick1.isEmpty()) # statick1.push(7) # print(statick1) # print(statick1.top()) # print(statick1.bottom()) # print(statick1.pop()) # print(statick1) class MyStack(): def __init__(self,start=[]): self.stack = [] for i in start: self.stack.append(i)
Java
UTF-8
2,578
2.96875
3
[]
no_license
package com.example.justingil1748.mobivity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.Stack; /** * Created by justingil1748 on 4/23/17. */ public class Game2 extends AppCompatActivity implements View.OnClickListener { //member variables, coordinates and direction private int currCor1 = 0; private int currCor2 = 0; private int currDir = 0; private Button b_left, b_right, b_move; private TextView t_pos, t_dir; private final String[] values = {"North", "East", "South", "West"}; private int maxActions, targetpos1, targetpos2, tarInitDir; //store actions, 0-M, 1-L, 2-M Stack<Integer> actionStack = new Stack<Integer>(); @Override public void onClick(View v) { //initialize buttons and textViews b_left = (Button) findViewById(R.id.left_b); b_right = (Button) findViewById(R.id.right_b); b_move = (Button) findViewById(R.id.move_b); t_pos = (TextView) findViewById(R.id.pos_t); t_dir = (TextView) findViewById(R.id.dir_t); //receive initial data from MainActivity Intent i = getIntent(); currCor1 = i.getIntExtra("cor1", 1); currCor2 = i.getIntExtra("cor2", 1); currDir = i.getIntExtra("initDir", 0); maxActions = i.getIntExtra("action", 0); targetpos1 = i.getIntExtra("tarCor1", 1); targetpos2 = i.getIntExtra("tarCor2", 1); tarInitDir = i.getIntExtra("tarInitDir", 0); listPossibleList(); } private void listPossibleList() { int horizontalMove = targetpos1 - currCor1; int verticalMove = targetpos2 - currCor2; boolean moveRight = (horizontalMove > 0); //have to change direction to east boolean moveUp = (verticalMove > 0); //have to change direction to north /* I couldn't finish implementation step, but I have an idea. 1) calculate the minimum movement(distance from current to target) 2) Using the minimum movement, implement a tree structure that has three branches(M,L,F) 3) Set height of the tree to the max number of actions. 4) Print all the possible action sequences, using DFS tree traversal Challenging part: I know how to find the shortest path, but if max possible action is greater than the shortest path, there are a lot more possible cases. */ } }
C
UTF-8
1,584
3.546875
4
[]
no_license
#include <stdio.h> #define STACK_SIZE 1000 #define MAX_ROW 5 #define MAX_COL 5 struct path { int x; int y; }; struct path stack[STACK_SIZE]; typedef struct path item_t; int esp = -1; int maze[MAX_ROW][MAX_COL] = { 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, }; void push(item_t i) { stack[++esp] = i; } void pop() { esp --; } item_t top() { return stack[esp]; } void print_buf(int index) { if (index == 3) return; print_buf(index+1); printf("%d\n", index); } void access(item_t node) { int x = node.x; int y = node.y; maze[x][y] = 2; push(node); } int find_next(item_t *next) { item_t curr = top(); int x = curr.x; int y = curr.y; if (y < 4 && maze[x][y+1] == 0){ next->x = x; next->y = y + 1; return 1; } else if (x > 0 && maze[x-1][y] == 0){ next->x = x - 1; next->y = y; return 1; } else if (y > 0 && maze[x][y-1] == 0){ next->x = x; next->y = y - 1; return 1; } else if (x < 4 && maze[x+1][y] == 0){ next->x = x + 1; next->y = y; return 1; } return 0; } void print_stack_reverse() { for (int i = 0; i <= esp; i ++) { item_t *node = stack + i; printf("%d,%d\n", node->x, node->y); } } void print_stack() { while(esp >= 0){ item_t node = top(); printf("%d,%d\n", node.x, node.y); pop(); } } int main() { item_t root = {.x = 0, .y = 0}; access(root); while(1) { item_t next; int found = find_next(&next); if (!found){ pop(); } else{ access(next); if (top().x == 4 && top().y == 4) break; } } print_stack_reverse(); return 0; }
JavaScript
UTF-8
633
2.53125
3
[ "LicenseRef-scancode-public-domain", "CC0-1.0" ]
permissive
import { state } from 'cerebral'; /** * sets the state.showModal to whatever is pass in the factory function * * @param {string } showModal the value to set the modal to * @returns {Function} the primed action */ export const setShowModalFactoryAction = showModal => { /** * sets the state.showModal to whatever was passed in the factory function * * @param {object} providers the providers object * @param {object} providers.store the cerebral store used for setting state.users */ const setShowModalAction = ({ store }) => { store.set(state.showModal, showModal); }; return setShowModalAction; };
Java
UTF-8
484
2.515625
3
[]
no_license
package fr.umontpellier.iut.dominion.cards.common; import fr.umontpellier.iut.dominion.CardType; import fr.umontpellier.iut.dominion.cards.Card; import java.util.List; public abstract class Victory extends Card { public Victory(String name, int cost){ super(name,cost); } @Override public List<CardType> getTypes() { List<CardType> cardTypeList = super.getTypes(); cardTypeList.add(CardType.Victory); return cardTypeList; } }
Java
UTF-8
5,705
2.25
2
[]
no_license
package ekosh; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.PrivateKey; import java.security.Security; import java.security.cert.Certificate; import java.util.Properties; import org.bouncycastle.jce.provider.BouncyCastleProvider; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Image; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfSignatureAppearance; import com.itextpdf.text.pdf.PdfStamper; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.security.BouncyCastleDigest; import com.itextpdf.text.pdf.security.ExternalDigest; import com.itextpdf.text.pdf.security.ExternalSignature; import com.itextpdf.text.pdf.security.MakeSignature; import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard; import com.itextpdf.text.pdf.security.PrivateKeySignature; public class digiSign { public static String temp,source,destination; public static String base = "D:/ishan/workspace/ekosh/WebContent/files/"; /** * A properties file that is PRIVATE. You should make your own properties * file and adapt this line.sms */ public static String PATH = "D:/ishan/workspace/ekosh/key.properties"; /** Some properties used when signing. */ public static Properties properties = new Properties(); /** One of the resources. */ public static final String RESOURCE = "D:/ishan/workspace/ekosh/WebContent/img/sign.PNG"; /* * public void createPdf(String filename) throws IOException, * DocumentException { Document document = new Document(); * PdfWriter.getInstance(document, new FileOutputStream(filename)); * document.open(); document.add(new Paragraph("Hello World!")); * document.close(); } */ /** * Manipulates a PDF file src with the file dest as result * * @param src * the original PDF * @param dest * the resulting PDF * @throws GeneralSecurityException * @throws IOException * @throws DocumentException * @throws FileNotFoundException * @throws KeyStoreException * @throws Exception */ public void signPdfFirstTime(String src, String dest, String alias) throws IOException, DocumentException, GeneralSecurityException { // String path = properties.getProperty("PRIVATE"); String keystore_password = properties.getProperty("PASSWORD");// getting // keystore // passwd String key_password = properties.getProperty(alias);// getting // alias // passwd KeyStore ks = KeyStore.getInstance("pkcs12");// creating keystore // reference FileInputStream fin = new FileInputStream( "D:/ishan/workspace/ekosh/KEYSTORE.p12"); ks.load(fin, keystore_password.toCharArray()); PrivateKey pk = (PrivateKey) ks.getKey(alias, key_password.toCharArray());// getting private key of alias Certificate[] chain = ks.getCertificateChain(alias);// creating cert // using alias // reader and stamper // src=source file path dest=destination PdfReader reader = new PdfReader(src); FileOutputStream os = new FileOutputStream(dest); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0'); // appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setImage(Image.getInstance(RESOURCE)); appearance.setReason("Digital Signature"); appearance.setLocation("Bangalore"); appearance.setVisibleSignature(new Rectangle(480, 20, 580, 70), 1, "first"); // digital signature ExternalSignature es = new PrivateKeySignature(pk, "SHA-1", "BC"); ExternalDigest digest = new BouncyCastleDigest(); String name = es.getEncryptionAlgorithm(); System.out.print(name); MakeSignature.signDetached(appearance, digest, es, chain, null, null, null, 0, CryptoStandard.CMS); } public static void convert() throws IOException, DocumentException, GeneralSecurityException { Document document = new Document(); // .gif and .jpg are ok too! //String output = "C:/Users/Rahul/Desktop/a.pdf"; try { FileOutputStream fos = new FileOutputStream(temp); PdfWriter writer = PdfWriter.getInstance(document, fos); writer.open(); document.open(); if (source.endsWith("pdf")) { temp = source; } else if (source.endsWith("doc") || source.endsWith("docx") || source.endsWith("txt")) { File file = new File(source); document.add(new Paragraph(org.apache.commons.io.FileUtils .readFileToString(file))); document.close(); document.close(); writer.close(); } else { Image i = Image.getInstance(source); i.scaleToFit(595, 842); document.add(i); document.close(); writer.close(); } } catch (Exception e) { e.printStackTrace(); } } /** * Main method. * * @param args * no arguments needed */ public static String convertAndSign(String a,String name) throws IOException, DocumentException, GeneralSecurityException { source = base+"new"+a; String file = a.substring(0, a.indexOf('.')); temp = base +"temp" + file + ".pdf"; destination = base + "final" + file + ".pdf"; convert(); Security.addProvider(new BouncyCastleProvider()); properties.load(new FileInputStream(PATH)); digiSign signatures = new digiSign(); signatures.signPdfFirstTime(temp, destination, name); return destination; } }
Java
UTF-8
8,945
3.109375
3
[]
no_license
package study_DateAndTime; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import basic.Basic; public class SimpleDateFormatTest extends Basic{ public static void main(String[] args){ try{ // test01(); // test011(); // test012(); // test013(); // test02(); // test03(); // testRFC3339(); // testDayMilliseconds(); testGetHourMinute(); }catch(Exception e){ e.printStackTrace(); } } public static void test01(){ try{ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss"); String dateStr01 = "2015-11-25 00:00:00"; String dateStr02 = "2015-11-25"; String dateStr03 = "2015-11-25 08:00:00"; String timeStr01 = "08:00:00"; Date dateObj01 = sdf.parse(dateStr01); Date nowObj = new Date(); String nowStr = sdf.format(nowObj); long dayMiliSeconds = 24*60*60*1000l; long sdf_dateStr01 = sdf.parse(dateStr01).getTime(); // System.out.println(sdf_dateStr01); long rest = sdf_dateStr01%dayMiliSeconds; // System.out.println(new Date(sdf_dateStr01)); // System.out.println(rest); System.out.println(sdfDate.parse(dateStr02)); System.out.println(sdfDate.parse(dateStr02).getTime()); // System.out.println(sdf.parse(dateStr03).getTime()); System.out.println(sdfTime.parse(timeStr01)); System.out.println(sdfTime.parse(timeStr01).getTime()); Calendar c = Calendar.getInstance(); //对于 08:00:00. 不设置时区, 会默认当前时区, 则时间为8点, 设置了GMT时区, 时间则为Epoch //对于 2015-11-25 不设置时区, 则为当前时区的时间, 2015-11-25 00:00:00, 设置GMT时区, 则时间为前一时间的8小时前, 及2015-11-24 16:00:00 c.setTimeZone(TimeZone.getTimeZone("GMT+0")); c.setTime(sdfTime.parse(timeStr01)); System.out.println(c.get(Calendar.YEAR)+"-"+c.get(Calendar.MONTH)+"-"+c.get(Calendar.DAY_OF_MONTH)+" "+c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND)); c.setTime(sdfDate.parse(dateStr02)); System.out.println(c.get(Calendar.YEAR)+"-"+c.get(Calendar.MONTH)+"-"+c.get(Calendar.DAY_OF_MONTH)+" "+c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND)); // System.out.println(sdf.format(sdfTime.parse(timeStr01))); }catch (Exception e){ e.printStackTrace(); }finally{ } } public static void test011(){ try{ SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); SimpleDateFormat sdfFull = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("GMT+0")); sdfFull.setTimeZone(TimeZone.getTimeZone("GMT+0")); String str01 = "01:00:00"; Date dt01 = sdf.parse(str01); System.out.println(sdf.getTimeZone()); long ms01 = dt01.getTime(); System.out.println(dt01+", "+ms01); long now = new Date().getTime(); System.out.println(now); String str02 = sdfFull.format(new Date(now)); Date dt02 = sdfFull.parse(str02); long dayMs = 24*60*60*1000; long hourMs = 60*60*1000; long minuteMs = 60*1000; long secondMs = 1000; System.out.println(now/dayMs+", "+(now%dayMs)/hourMs+", "+((now%dayMs)%hourMs)/minuteMs); }catch(Exception e){ }finally{ } } public static void test012() throws Exception{ SimpleDateFormat sdfFull = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdfFull.setTimeZone(TimeZone.getTimeZone("GMT+0")); sdfDate.setTimeZone(TimeZone.getTimeZone("GMT+0")); sdfTime.setTimeZone(TimeZone.getTimeZone("GMT+0")); String str01 = "1970-01-01 00:00:00"; String str02 = "2015-11-27"; String str03 = "00:30"; String str04 = "01:30"; System.out.println(sdf.format(sdfFull.parse(str01))); System.out.println(sdfDate.parse(str02)); System.out.println(sdfTime.parse(str03)); System.out.println(sdfTime.parse(str04)); } public static void test013() throws Exception{ DateFormat sdfFull = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd"); DateFormat sdfTime = new SimpleDateFormat("HH:mm"); sdfFull.setTimeZone(null); sdfDate.setTimeZone(null); sdfTime.setTimeZone(null); String str01 = "1970-01-01 00:00:00"; String str02 = "2015-11-27"; String str03 = "00:30"; String str04 = "01:30"; System.out.println(sdfFull.parse(str01)); System.out.println(sdfDate.parse(str02)); System.out.println(sdfTime.parse(str03)); System.out.println(sdfTime.parse(str04)); } public static void test02(){ try{ SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d1 = sdf1.parse("2014-08-23T09:20:05Z"); System.out.println(sdf1.getTimeZone().toString()); sdf1.setTimeZone(TimeZone.getTimeZone("UTC")); System.out.println(sdf1.getTimeZone().toString()); Date d3 = sdf1.parse("2014-08-23T09:20:05Z"); Date d2 = sdf2.parse("2014-08-23 09:20:05"); System.out.println("2014-08-23T09:20:05Z" + " , " + d1.toString() + " , "+sdf1.format(d1)); System.out.println("2014-08-23T09:20:05Z" + " , " + d3.toString() + " , "+sdf1.format(d3)); System.out.println("2014-08-23 09:20:05" + " , " + d2.toString() + " , "+sdf2.format(d2)); }catch(Exception e){ e.printStackTrace(); }finally{ } } /** * E 星期 : 3个E或以下, 显示3字母简写weekday; * 4个E或以上, 显示完整拼写weekday * * M 月份 : 1个M, 显示数字月份, 1月为1, 12月为12; * 2个M, 显示数字月份, 1月为01, 12月为12; * 3个M, 显示3字母简写month; * 4个M或以上, 显示完整拼写month */ public static void test03(){ try{ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd:HHmmss"); Date d = new Date(1486004175238l); d = sdf.parse("20170222:130404"); SimpleDateFormat sdf1 = new SimpleDateFormat("EEEE, d MMMM yyyy'T'HH:mm:ss Z"); SimpleDateFormat sdf2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); SimpleDateFormat sdf3 = new SimpleDateFormat("EE, d MM yyyy HH:mm:ss Z"); SimpleDateFormat sdf4 = new SimpleDateFormat("E, d M yyyy HH:mm:ss Z"); SimpleDateFormat sdf5 = new SimpleDateFormat("EEE, d MMMMM yyyy, H:mm a"); SimpleDateFormat sdf6 = new SimpleDateFormat("EEE, d MMMMM yyyy, h:mm a"); System.out.println(sdf1.format(d)); System.out.println(sdf2.format(d)); System.out.println(sdf3.format(d)); System.out.println(sdf4.format(d)); System.out.println(sdf5.format(d)); System.out.println(sdf6.format(d)); }catch(Exception e){ e.printStackTrace(); } } /** * RFC3339 UTC "Zulu" * * */ public static void testRFC3339(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.'000000000Z'"); long now = System.currentTimeMillis(); Date d = new Date(now); pl("2014-10-02T15:01:23.045123456Z"); pl(sdf.format(d)); pl(d); } public static void testDayMilliseconds() throws Exception{ Calendar c = Calendar.getInstance(); Date now = new Date(); c.setTime(now); c.add(Calendar.DATE, 1); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); sdf.setTimeZone(TimeZone.getTimeZone("GMT+7")); long l = sdf.parse(sdf.format(c.getTime())).getTime(); pl(l); String xStr = "2018-04-11,2018-04-11,2018-04-26,2018-04-11,2018-04-14,2018-04-12,2018-04-14,2018-04-11,2018-04-27,2018-04-11"; String yStr = "1523379600000,1523379600000,1524675600000,1523379600000,1523638800000,1523466000000,1523638800000,1523379600000,1524762000000,1523379600000"; String[] xArr = xStr.split(","); String[] yArr = yStr.split(","); for(int i=0;i<xArr.length; i++){ long lo = sdf.parse(xArr[i]).getTime(); pl(xArr[i] + "-" + yArr[i] + "-" + (lo==Long.parseLong(yArr[i]))); } // 1523379600000 // 1523379600000 } public static void testGetHourMinute() throws Exception{ long start = 1523379600000l; long end = 1523638800000l; String timeZone = "GMT+7"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); sdf.setTimeZone(TimeZone.getTimeZone(timeZone)); Calendar c = Calendar.getInstance(); c.setTimeZone(TimeZone.getTimeZone(timeZone)); for(long millis = start; millis <= end; millis += 1800000l){ c.setTimeInMillis(millis); long dayPart = sdf.parse(sdf.format(new Date(millis))).getTime(); long restPart = c.get(Calendar.HOUR_OF_DAY) * 3600000l + c.get(Calendar.MINUTE) * 60000l; p(restPart);pl(millis == (dayPart + restPart)); } } }
Java
UTF-8
967
3.953125
4
[ "MIT" ]
permissive
package OOP_Part_1.Class; //CLASS public class ClassCar { private int wheels; private String color; private String model; private int doors; //Setter methods public void setColor(String color) { this.color = color; } public void setModel(String model){ String modelCheck = model.toLowerCase(); if (modelCheck.equals("porsche")|| modelCheck.equals("audi")){ this.model = model; }else { this.model = "unknown"; } } //Getter methods public String getColor() { return color; } public String getModel(){ return model; } public static void main(String[] args) { ClassCar porsche = new ClassCar(); porsche.setColor("Blue"); porsche.setModel("Audi"); System.out.println(" Model of the car is: "+porsche.getModel()); System.out.println(" Color of the car is: "+porsche.getColor()); } }
Java
UTF-8
1,761
2.34375
2
[]
no_license
package stepDefinitions; import cucumber.api.java.en.Given; import cucumber.api.java.en.When; import cucumber.api.java.en.Then; import cucumber.api.junit.Cucumber; import helper.DriverInitiation; import cucumber.api.java.*; import org.junit.Assert; import org.openqa.selenium.WebDriver; import pageObjects.CreateAccountPage; import pageObjects.HomePage; import pageObjects.LoginPage; public class LoginTests_Steps { WebDriver driver; HomePage homePage; LoginPage loginPage; CreateAccountPage createAccountPage; @Before public void InitialSetup() { driver = DriverInitiation.InitiateDriver(); } @Given("^the user is on home page$") public void the_user_is_on_home_page() { homePage = new HomePage(driver); } @When("^the user clicks on Sign In link$") public void the_user_clicks_on_Sign_In_link() { homePage.clickOnSignIn(); } @When("^the user provides the email-ID as \"([^\"]*)\"$") public void the_user_provides_the_email_ID_as(String emailID) { loginPage = new LoginPage(driver); LoginPage.SetEmailAddress(emailID); LoginPage.ClickOnCreateAnAccount(); } @Then("^the user is directed to create an account$") public void the_user_is_directed_to_create_an_account() { createAccountPage = new CreateAccountPage(driver); } @Then("^an error message is displayed$") public void an_error_message_is_displayed() { loginPage.VerifyErrorMessageDisplayed(); DriverInitiation.CloseAllInstances(); } @After public void CloseScenario() { DriverInitiation.CloseAllInstances(); } }
PHP
UTF-8
500
3
3
[]
no_license
<?php $values = [ "message" => "Hello world!", "count" => 150, "pi" => 3.14, "status" => false, "result" => null ]; $count = 3; $price = 9.99; $data = [$count, $price]; $articles = [ ["title" => "First post", "content" => "This is the first post"], ["title" => "Another post", "content" => "Another post to read here"], ["title" => "Read this!", "content" => "You must read this article!"] ]; var_dump($articles); var_dump($articles[1]["title"]);
C#
UTF-8
4,603
2.890625
3
[]
no_license
using System; using System.ComponentModel; using System.Linq; using System.Windows.Forms; namespace Impresso_Expresso { /// <summary> /// <author>Stefan Tropčić</author> /// </summary> public partial class FrmSkladiste : Form { private enum opcijeSort { ID, AZ, ZA, Najskuplji, Najjeftiniji, Najviše, Najmanje }; public FrmSkladiste() { InitializeComponent(); } /// <summary> /// prikazi sve graficke elemente /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FrmSkladiste_Load(object sender, EventArgs e) { cbOpcijeSort.DataSource = Enum.GetValues(typeof(opcijeSort)); PrikaziArtikle(); } /// <summary> /// Dohvaća listu svih artikala i prikazuje ih u dgv /// </summary> private void PrikaziArtikle() { BindingList<Artikli> listaArtikala = null; using (var db = new Entities()) { listaArtikala = new BindingList<Artikli>(db.Artiklis.ToList()); } artikliBindingSource.DataSource = Sortiraj(listaArtikala); } #region Sort /// <summary> /// ovisno o odabiru sorta mijenja listu podataka /// </summary> /// <param name="listaArtikala"></param> /// <returns></returns> private BindingList<Artikli> Sortiraj(BindingList<Artikli> listaArtikala) { BindingList<Artikli> sortiranaLista = null; opcijeSort izabranaOpcija = (opcijeSort)cbOpcijeSort.SelectedItem; switch(izabranaOpcija) { case opcijeSort.AZ: sortiranaLista = new BindingList<Artikli>(listaArtikala.OrderBy(x => x.Naziv).ToList()); break; case opcijeSort.ZA: sortiranaLista = new BindingList<Artikli>(listaArtikala.OrderByDescending(x => x.Naziv).ToList()); break; case opcijeSort.Najjeftiniji: sortiranaLista = new BindingList<Artikli>(listaArtikala.OrderBy(x => x.Cijena).ToList()); break; case opcijeSort.Najskuplji: sortiranaLista = new BindingList<Artikli>(listaArtikala.OrderByDescending(x => x.Cijena).ToList()); break; case opcijeSort.Najmanje: sortiranaLista = new BindingList<Artikli>(listaArtikala.OrderBy(x => x.StanjeNaSkladistu).ToList()); break; case opcijeSort.Najviše: sortiranaLista = new BindingList<Artikli>(listaArtikala.OrderByDescending(x => x.StanjeNaSkladistu).ToList()); break; default: sortiranaLista = listaArtikala; break; } return sortiranaLista; } /// <summary> /// u slucaju promjene tipa sortiranja prikazi drugacije podatke /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cbOpcijeSort_SelectedIndexChanged(object sender, EventArgs e) { PrikaziArtikle(); } #endregion #region ButtonEvent /// <summary> /// Metoda instancira i poziva formu FrmUpravljanjeArtikla /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnUnosArtikla_Click(object sender, EventArgs e) { FrmUpravljanjeArtiklom formaUpravljanjeArtiklom = new FrmUpravljanjeArtiklom(); formaUpravljanjeArtiklom.ShowDialog(); PrikaziArtikle(); } /// <summary> /// Metoda instancira i poziva formu FrmPrimka /// </summary> private void btnPrimka_Click(object sender, EventArgs e) { FrmPopisPrimki formaPrimka = new FrmPopisPrimki(); formaPrimka.ShowDialog(); PrikaziArtikle(); } #endregion /// <summary> /// hendla otvaranje user manuala /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FrmSkladiste_KeyDown(object sender, KeyEventArgs e) { if (e.KeyData == Keys.F1) { UserManual.Pdf.OtvoriPodrsku(8); } } } }
Python
UTF-8
2,029
4.25
4
[]
no_license
# __call__ dunder method............................................ class Printing: def __init__(self,name): self.name = name def __call__(self): print("enter user name is : ", self.name) p = Printing("Rakib") p() # simple decorator...................................................... def decorator(f): def inner(): str1 = f() return str1.upper() return inner @decorator def greet(): return "good work" print(greet.__name__) # change object referance decorator to function......................... import functools def decorator(f): @functools.wraps(f) def inner(): str1 = f() return str1.upper() return inner @decorator def greet(): return "good work" print(greet.__name__) # use outer decorator inside a class........................... def check_name(method): def inner(name_ref): if name_ref.name == "Rakib": print("Hey my name is also same!!!") else: method(name_ref) return inner class Printing: def __init__(self,name): self.name = name @check_name def print_name(self): print("enter user name is : ", self.name) p = Printing("Rakib") p.print_name() #----------------------------------- class decorator -------------------------- class Decorator: def __init__(self,func): self.func = func def __call__(self): str1 = self.func() return str1.upper() @Decorator def greet(): return "good work" print(greet()) # another example class Check_div: def __init__(self, func): self.func = func def __call__(self, *args): l = [] l = args[1:] for i in l: if i == 0: return "You can't devide use non-zero value " else: self.func(*args) @Check_div def div(a,b): return a/b @Check_div def divv(a,b,c): return a/b/c print(div(10,0)) print(divv(1,0,1))
Java
UTF-8
1,928
2.3125
2
[]
no_license
package az.course.web; import az.course.dao.UserDao; import az.course.dao.UserDaoImpl; import az.course.model.Student; import az.course.service.UserService; import az.course.service.UserServiceImpl; import az.course.util.Security; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; /** * Created with IntelliJ IDEA. * User: fuadp * Date: 4/2/16 * Time: 11:11 AM * To change this template use File | Settings | File Templates. */ public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String address = ""; UserDao userDao = new UserDaoImpl(); UserService userService = new UserServiceImpl(userDao); String username = request.getParameter("username"); String password = request.getParameter("password"); try { if (username != null && password != null) { Student user = userService.login(username, Security.encodeMd5(password)); HttpSession session = request.getSession(true); System.out.println("user = "+user); if (user == null ) { request.setAttribute("msg","Invalid username or password"); address = "login.jsp"; } else { session.setAttribute("user",user); address = "index.jsp"; } } RequestDispatcher requestDispatcher = request.getRequestDispatcher(address); requestDispatcher.forward(request,response); } catch (Exception ex) { ex.printStackTrace(); } } }
Python
UTF-8
4,178
3.328125
3
[ "Apache-2.0" ]
permissive
#! /usr/bin/env python import logging import collections from typing import Dict, List class TrieNode: def __init__(self): self.children: Dict[str, TrieNode] = {} self.is_word: bool = False class Trie: def __init__(self, is_case_sensitive=False): self.root: TrieNode = TrieNode() self.is_case_sensitive: bool = is_case_sensitive self.logger = logging.getLogger(__name__) def is_empty(self): if not self.root.children: return True return False def load_file_contents(self, file_name: str) -> None: with open(file_name, 'r') as fread: for line in fread: word = line.strip() self.add_word(word) def search_phrase(self, phrase: str, max_len_closest_words=5) -> List: """Returns up to max_len_closest_words closest words given a phrase""" phrase = self._sanitize_word(phrase) status, current_trie_node = self._traverse_trie(phrase) if not status: return [] closest_words = [] queue = collections.deque([(current_trie_node, phrase)]) while queue: current_trie_node, word_so_far = queue.popleft() if current_trie_node.is_word: closest_words.append(word_so_far) if len(closest_words) == max_len_closest_words: break for new_char, child_trie_node \ in current_trie_node.children.items(): queue.append((child_trie_node, word_so_far + new_char)) return closest_words def search_word(self, word) -> bool: """Returns bool value indicating word is present in dictionary""" word = self._sanitize_word(word) status, current_trie_node = self._traverse_trie(word) return status and current_trie_node and current_trie_node.is_word def add_word(self, new_word) -> bool: """Add a word back in to the trie""" new_word = self._sanitize_word(new_word) current_trie_node = self.root for char in new_word: if char not in current_trie_node.children: new_trie_node = TrieNode() current_trie_node.children[char] = new_trie_node current_trie_node = current_trie_node.children[char] current_trie_node.is_word = True return True def remove_word(self, remove_word): """Remove word from trie. Additionally deletes the TrieNode if invalid""" remove_word = self._sanitize_word(remove_word) trie_node_iteration_stack = [] status, current_trie_node = self._traverse_trie( remove_word, maintain_stack=True, trie_node_iteration_stack=trie_node_iteration_stack) if not status: return False if not current_trie_node.is_word: return False current_trie_node.is_word = False while (not current_trie_node.children and current_trie_node is not self.root and not current_trie_node.is_word): current_char, previous_trie_node = trie_node_iteration_stack.pop() previous_trie_node.children[current_char] = None del previous_trie_node.children[current_char] current_trie_node = previous_trie_node return True # ##################### # # # HELPER FUNCTIONS # # # ##################### # def _sanitize_word(self, word: str) -> str: word = word.strip() return word if self.is_case_sensitive else word.lower() def _traverse_trie(self, word: str, maintain_stack: bool = False, trie_node_iteration_stack=None): current_trie_node = self.root if maintain_stack: assert isinstance(trie_node_iteration_stack, list) for char in word: if char not in current_trie_node.children: return False, None if maintain_stack: trie_node_iteration_stack.append((char, current_trie_node)) current_trie_node = current_trie_node.children[char] return True, current_trie_node
Python
UTF-8
1,341
2.875
3
[]
no_license
import sys,os class PollObject: def __init__(self, abbr, points): self.points = points self.abbr = abbr # UD = 0, Trump = 1, Biden = 2 self.cand = 0 self.obj = {} states = {} def getAllStates(): all_states = open('states.csv', 'r').readlines() for state in all_states: state_info = state.split(',') states[state_info[1]] = PollObject( state_info[0], int(state_info[2].strip()) ) def getData(): dataset = open("data.csv", "r").readlines() for data in dataset: curData = data.strip().split('\t') curState = curData[0] if curData[3] == 'Biden': states[curState].cand = 2 else: states[curState].cand = 1 def findReplaceID(curSvg, curAbbr, cand): if cand == 1: curSvg = curSvg.replace("id=\"" + curAbbr + "\" fill=\"#d3d3d3\"", "id=\"" + curAbbr + "\" fill=\"#ffcccb\"") elif cand == 2: curSvg = curSvg.replace("id=\"" + curAbbr + "\" fill=\"#d3d3d3\"", "id=\"" + curAbbr + "\" fill=\"#d1edf2\"") return curSvg def editSvg(): curSvg = open("map.svg", "r").read() for key in states: #print(states[key].cand) curSvg = findReplaceID(curSvg, states[key].abbr, states[key].cand) open("newmap.svg", "w").write(curSvg) getAllStates() getData() editSvg()
Python
UTF-8
213
4.09375
4
[]
no_license
s = input("Enter any string: ") #take input from user x = s.split() #use split method to split at whitespaces x.reverse() #reverse all the elements of the string print(' '.join(x)) #concatenate them into a string
Markdown
UTF-8
910
3.046875
3
[]
no_license
--- id: editable-text title: 文本制作规则 --- --- ### 文本相关的制作规则: #### 1. 不可编辑文本建议转换为形状图层做(右键从文字创建形状); 如果使用了非指定的特殊字体,想要保留字体效果也需要转换成形状图层。 <br/> #### 2. 可编辑文本(即文本内容有被替换的需求)用文本图层制作。 <br/> #### 3. 关于换行和缩小————用户输入文本较多时: <br/> - 如果不需要自动换行和缩小,则用点文本制作(并设置想要的对齐方式)。 <br/> - 如果需要自动换行和缩小字号,则用框文本制作,pag会在框内自动换行和缩小字号。 <br/> - 如果只需要换行不需要缩小,则用框文本制作,且将框的宽度设置成你想要的宽度,框的高度设置尽量大一些,这样就不会缩小字号,只会增加行数。 <br/> ---
C++
UTF-8
1,079
3.59375
4
[]
no_license
#include <iostream> using namespace std; int lectura (int n){ if (n==0 or n==1 or n==2 or n==3 or n==4 or n==5 or n==6 or n==7 or n==8 or n==9){ if (n==0) cout << "El numero es : " << "cero" ; if (n==1) cout << "El numero es : " << "uno" ; if (n==2) cout << "El numero es : " << "dos" ; if (n==3) cout << "El numero es : " << "tres" ; if (n==4) cout << "El numero es : " << "cuatro" ; if (n==5) cout << "El numero es : " << "cinco" ; if (n==6) cout << "El numero es : " << "seis" ; if (n==7) cout << "El numero es : " << "siete" ; if (n==8) cout << "El numero es : " << "ocho" ; if (n==9) cout << "El numero es : " << "nueve" ; } else cout << "El numero es invalido"; return 0; } int main() { //5 cout << "Dame un numero : " ; int n; cin >> n ; lectura (n); return 0; }
Markdown
UTF-8
4,379
2.953125
3
[]
no_license
--- description: "Simple Way to Make Perfect Banana ice cream with frozen raspberries" title: "Simple Way to Make Perfect Banana ice cream with frozen raspberries" slug: 137-simple-way-to-make-perfect-banana-ice-cream-with-frozen-raspberries date: 2020-04-15T17:53:01.385Z image: https://img-global.cpcdn.com/recipes/5343413839331328/751x532cq70/banana-ice-cream-with-frozen-raspberries-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/5343413839331328/751x532cq70/banana-ice-cream-with-frozen-raspberries-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/5343413839331328/751x532cq70/banana-ice-cream-with-frozen-raspberries-recipe-main-photo.jpg author: Florence Hill ratingvalue: 5 reviewcount: 15 recipeingredient: - "1 Frozen banana" - "100 grams frozen rasberries" recipeinstructions: - "Cut a banana into coins and freeze them" - "Set banana coins into the blender" - "Pour in the ice cream in a cup and serve with frozen raspberries on top" categories: - Recipe tags: - banana - ice - cream katakunci: banana ice cream nutrition: 230 calories recipecuisine: American preptime: "PT26M" cooktime: "PT45M" recipeyield: "4" recipecategory: Lunch --- ![Banana ice cream with frozen raspberries](https://img-global.cpcdn.com/recipes/5343413839331328/751x532cq70/banana-ice-cream-with-frozen-raspberries-recipe-main-photo.jpg) Hey everyone, it is Drew, welcome to my recipe site. Today, I will show you a way to prepare a special dish, banana ice cream with frozen raspberries. It is one of my favorites food recipes. This time, I'm gonna make it a little bit tasty. This is gonna smell and look delicious. Banana ice cream with frozen raspberries is one of the most favored of current trending foods in the world. It's simple, it is fast, it tastes yummy. It's appreciated by millions daily. They're nice and they look wonderful. Banana ice cream with frozen raspberries is something which I have loved my entire life. Frozen bananas are the secret to this easy ice cream everyone will love! Just blend and you have creamy &#34;nice&#34; cream! What is this one magic ingredient that can be whipped into rich and silky ice cream, with no additional dairy, sweeteners, or ingredients needed whatsoever? To get started with this particular recipe, we have to prepare a few ingredients. You can have banana ice cream with frozen raspberries using 2 ingredients and 3 steps. Here is how you cook it. ##### The ingredients needed to make Banana ice cream with frozen raspberries: 1. Prepare 1 Frozen banana 1. Make ready 100 grams frozen rasberries A delicious dessert made from only bananas (and any additional ingredients you may I always have a stash of frozen bananas in the freezer. They are great for making frozen desserts, for using in smoothies or to simply eat as they are. Blend the frozen banana slices in a high-speed blender until they reach a smooth consistency. Banana nice cream is a frozen dessert made with a frozen banana base. ##### Instructions to make Banana ice cream with frozen raspberries: 1. Cut a banana into coins and freeze them 1. Set banana coins into the blender 1. Pour in the ice cream in a cup and serve with frozen raspberries on top If you have frozen bananas and a little Banana nice cream was first created as a homemade vegan ice cream recipe substitute, but even if Raspberry Chocolate Swirl Banana Soft Serve. Use an ice cream scoop or two large spoons to scoop the banana ice cream into two serving bowls or glasses. Drizzle with Raspberry Mint Sauce and If you don&#39;t have a strong food processor at home, be careful with frozen bananas because they are quite hard to mix. It&#39;s best to leave them out of the. · Make creamy and delicious healthy chocolate banana ice cream using frozen bananas, almond milk, cacao powder and almond butter. in Homemade Raspberry Cheesecake Ice Cream - Lovely Little Kitchen. Made with finely crushed freeze dried raspberries, this super creamy ice cream has a. So that is going to wrap it up with this special food banana ice cream with frozen raspberries recipe. Thank you very much for reading. I'm sure you can make this at home. There's gonna be more interesting food in home recipes coming up. Don't forget to save this page in your browser, and share it to your loved ones, colleague and friends. Thank you for reading. Go on get cooking!
Java
UTF-8
977
2.6875
3
[]
no_license
package test.optimizingfetching; import java.util.List; import model.Users; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Order; import dao.UsersDAO; public class PagingResult { public static void main(String[] args) { UsersDAO dao=new UsersDAO(); Session session=dao.getSession(); /* Query query=session.createQuery("from Users u order by u.userId"); query.setFirstResult(10*1); query.setMaxResults(10); */ /* Criteria query = session.createCriteria(Users.class); query.addOrder( Order.asc("userId") ); query.setFirstResult(5); query.setMaxResults(10); */ Query query =session.createSQLQuery("select {u.*} from USERS {u}").addEntity("u", Users.class); query.setFirstResult(5); query.setMaxResults(10); List<Users> list=query.list(); for (Users users : list) { System.out.println(users); } session.close(); } }
Shell
UTF-8
497
3.484375
3
[]
no_license
#!bin/bash #usage : sh makeBigBeds.sh <directory name> #converts all bed files in directory $1 to bigBeds for filename in $1/*.bed; do echo "processing $filename..." awk -F, '{$1="chr"$1;print $0}' OFS=, $filename | sed 's/chrdmel_mitochondrion_genome/chrM/g' | sort -k1,1 -k2,2n > $filename.chr.bed bedToBigBed $filename.chr.bed /raid/modencode/DCC/fileupload/encValData/dm3/chrom.sizes "${filename%%.bed}.bb" rm $filename.chr.bed echo " $filename converted to BigBed" done
Python
UTF-8
497
3.4375
3
[]
no_license
import os print("When you input path please write it with in forward slash in place of blackslash, Thank you.") path = input("Give your path: ") name = input("new file name: ") type = input("the file's type") def main(): i = 0 dest = path for filename in os.listdir(dest): my_dest = name + str(i) + type my_src = dest + filename my_dest = dest + my_dest os.rename(my_src, my_dest) i = i+1 if __name__ == '__main__': main()
Ruby
UTF-8
96
2.9375
3
[]
no_license
class NumberGames def self.next_odd_number (number) return number + number%2 + 1 end end
Java
UTF-8
7,487
1.703125
2
[]
no_license
package com.tappx.a; import android.content.Context; import android.os.Build; import android.util.DisplayMetrics; import android.view.WindowManager; import android.webkit.WebSettings; import android.webkit.WebView; import java.lang.reflect.Constructor; import java.util.Locale; import java.util.concurrent.CountDownLatch; public final class p0 { /* renamed from: a reason: collision with root package name */ public final String f780a; public final String b; public final String c; public final String d; public final String e; public final int f; public final int g; public final int h; public final String i; public final String j; public final String k; public static class b { private static volatile b d; /* renamed from: a reason: collision with root package name */ private final Context f781a; private final d<String> b; private final a c; /* access modifiers changed from: package-private */ public static class a { /* renamed from: a reason: collision with root package name */ private final Context f782a; /* access modifiers changed from: private */ /* renamed from: com.tappx.a.p0$b$a$a reason: collision with other inner class name */ public static final class C0033a { /* renamed from: a reason: collision with root package name */ private String f783a; private final Context b; /* access modifiers changed from: package-private */ /* renamed from: com.tappx.a.p0$b$a$a$a reason: collision with other inner class name */ public class RunnableC0034a implements Runnable { /* renamed from: a reason: collision with root package name */ final /* synthetic */ CountDownLatch f784a; RunnableC0034a(CountDownLatch countDownLatch) { this.f784a = countDownLatch; } public void run() { C0033a aVar = C0033a.this; aVar.f783a = aVar.b(); this.f784a.countDown(); } } /* access modifiers changed from: private */ /* access modifiers changed from: public */ private String b() { WebView webView = new WebView(this.b); String userAgentString = webView.getSettings().getUserAgentString(); webView.destroy(); return userAgentString; } private C0033a(Context context) { this.b = context; } public String a() { if (g3.a()) { return b(); } CountDownLatch countDownLatch = new CountDownLatch(1); g3.a(new RunnableC0034a(countDownLatch)); try { countDownLatch.await(); return this.f783a; } catch (InterruptedException unused) { return null; } } } public a(Context context) { this.f782a = context; } private String b() { return WebSettings.getDefaultUserAgent(this.f782a); } private String c() { return new C0033a(this.f782a).a(); } private String d() { Constructor declaredConstructor = WebSettings.class.getDeclaredConstructor(Context.class, WebView.class); boolean isAccessible = declaredConstructor.isAccessible(); if (!isAccessible) { declaredConstructor.setAccessible(true); } try { return ((WebSettings) declaredConstructor.newInstance(this.f782a, null)).getUserAgentString(); } finally { if (!isAccessible) { declaredConstructor.setAccessible(false); } } } /* JADX WARNING: Can't wrap try/catch for region: R(5:0|(3:2|3|4)|5|6|7) */ /* JADX WARNING: Code restructure failed: missing block: B:10:0x0014, code lost: if (r0 == null) goto L_0x0016; */ /* JADX WARNING: Code restructure failed: missing block: B:12:?, code lost: return java.lang.System.getProperty("http.agent"); */ /* JADX WARNING: Code restructure failed: missing block: B:13:?, code lost: return r0; */ /* JADX WARNING: Code restructure failed: missing block: B:8:0x0010, code lost: r0 = c(); */ /* JADX WARNING: Failed to process nested try/catch */ /* JADX WARNING: Missing exception handler attribute for start block: B:5:0x000b */ public String a() { if (Build.VERSION.SDK_INT >= 17) { return b(); } return d(); } } public b(Context context) { this(context, new a(context)); } private int a(int i, int i2) { if (i == i2) { return 0; } return i < i2 ? 1 : 2; } public static final b a(Context context) { if (d == null) { synchronized (b.class) { if (d == null) { d = new b(context.getApplicationContext()); } } } return d; } private String b() { Locale locale = Locale.getDefault(); return locale != null ? locale.getLanguage() : "en-us"; } private String c() { String a2 = this.b.a(); if (a2 != null) { return a2; } String a3 = this.c.a(); this.b.a(a3); return a3; } b(Context context, a aVar) { this.b = new k(); this.f781a = context; this.c = aVar; } public p0 a() { String b2 = b(); String str = Build.MANUFACTURER; String str2 = Build.MODEL; String str3 = Build.PRODUCT; String str4 = Build.VERSION.RELEASE; DisplayMetrics displayMetrics = new DisplayMetrics(); ((WindowManager) this.f781a.getSystemService("window")).getDefaultDisplay().getMetrics(displayMetrics); int i = displayMetrics.widthPixels; int i2 = displayMetrics.heightPixels; return new p0(b2, str, str2, str3, "android", str4, i, i2, a(i, i2), String.valueOf(displayMetrics.scaledDensity), c()); } } public p0(String str, String str2, String str3, String str4, String str5, String str6, int i2, int i3, int i4, String str7, String str8) { this.k = str; this.f780a = str2; this.b = str3; this.c = str4; this.d = str5; this.e = str6; this.g = i2; this.h = i3; this.f = i4; this.i = str7; this.j = str8; } }
Markdown
UTF-8
871
2.78125
3
[ "MIT" ]
permissive
# Precision Sawmill Addition ------ ```java mods.mekanism.sawmill.addRecipe(IItemStack inputStack, IItemStack outputStack, @Optional IItemStack bonusOutput, @Optional double bonusChance) mods.mekanism.sawmill.addRecipe(<minecraft:bow>, <minecraft:stick> * 3, <minecraft:string> * 3, 0.5); mods.mekanism.sawmill.addRecipe(<minecraft:torch>, <minecraft:stick>); ``` Removal ------ ```java mods.mekanism.sawmill.removeRecipe(IIngredient inputStack, @Optional IIngredient outputStack, @Optional IIngredient bonusOutput) mods.mekanism.sawmill.removeRecipe(<minecraft:bed>, <minecraft:planks>, <minecraft:wool>); mods.mekanism.sawmill.removeRecipe(<minecraft:planks>); ``` Specifying an output parameter will only remove the specific recipe that results in that output from that input. Omitting the output parameter will remove all recipes that the input item can produce.
C
UTF-8
769
2.59375
3
[]
no_license
/* emulator.h * Jason Iskenderian and Alexa Bosworth * 11/16/17 * Provides definitions and headers for the Emulator Module */ #ifndef EMULATOR_INCLUDED #define EMULATOR_INCLUDED #define T Emulator_T typedef struct T *T; #include <stdio.h> /* run * Purpose: Runs the um on the provided file * Arguments: Emulator_T - the emulator to run * Returns: none */ void run(T em); /* new_em * Purpose: to create a new instance of the um emulator that is initialized * Arguments: FILE *fp - the file containing the program * Returns: Emulator_T - the initialized instance of the emulator */ T new_em(FILE *fp); /* free_em * Purpose: To free the memory used by the emulator * Arguments: Emulator_T - the emulator to free * Returns: none */ void free_em(T em); #undef T #endif
Ruby
UTF-8
269
3.328125
3
[]
no_license
require 'pry' def solution(number) arry = [] counter = 0 number = number - 1 number.times do counter += 1 if counter % 3 == 0 || counter % 5 == 0 arry << counter end end arry.sum end p solution(10) p solution(20) p solution(200)
Python
UTF-8
543
2.96875
3
[]
no_license
import matplotlib.pyplot as plt from skimage import measure,data,color #生成二值测试图像 img=color.rgb2gray(data.horse()) #检测所有图形的轮廓 contours = measure.find_contours(img, 0.5) #绘制轮廓 fig, axes = plt.subplots(1,2,figsize=(8,8)) ax0, ax1= axes.ravel() ax0.imshow(img,plt.cm.gray) ax0.set_title('original image') rows,cols=img.shape ax1.axis([0,rows,cols,0]) for n, contour in enumerate(contours): ax1.plot(contour[:, 1], contour[:, 0], linewidth=2) ax1.axis('image') ax1.set_title('contours') plt.show()
JavaScript
UTF-8
1,947
2.5625
3
[]
no_license
(function(){ $.fn.cProgress = function(){ var $ct2 = $('.ct2'), $art = $ct2.find('article'), /*$ct3 = $('.ct3'), $art2 = $ct3.find('article'),*/ num = 0, per = 0, leftDeg = 180, rightDeg = 0, nowDeg = 0; //선택된 요소의 갯수에 따라 각각 적용될 함수를 실행 $art.each(function(i){ num = $('#per'+(i+1)).val(); $art.eq(i).find('span').text(0); console.log("num : " + num); $({percent:0}).animate({percent:num},{ duration:2000, progress:function(){ per = parseInt(this.percent) console.log("per : " + per); nowDeg = per*360/100; rightDeg = Math.min(nowDeg, 180); leftDeg = Math.max(nowDeg, 180); $art.eq(i).find('span').text(per); $art.eq(i).find('.right li').css({ transform : 'rotate('+rightDeg+'deg)' }); $art.eq(i).find('.left li').css({ transform : 'rotate('+leftDeg+'deg)' }); } }); }); } $.fn.bProgress = function(){ var $ct3 = $('.ct3'), $art = $ct3.find('article'), num = 0, per = 0; //선택된 요소의 갯수에 따라 각각 적용될 함수를 실행 $art.each(function(i){ num = $('#bPer'+(i+1)).val(); $art.eq(i).find('span').text(0); console.log("num : " + num); $({percent:0}).animate({percent:num},{ duration:3000, progress:function(){ per = (parseInt(this.percent)); console.log(this.percent); $art.eq(i).find('span').text(per); $art.eq(i).find('.bar').css({width:per + '%'}); } }); }); } })($);
Java
UTF-8
18,074
2.84375
3
[]
no_license
/** * Created on 09.11.2002 * * To change this generated comment edit the template variable "filecomment": * Window>Preferences>Java>Templates. To enable and disable the creation of file * comments go to Window>Preferences>Java>Code Generation. */ package ru.myx.ae3.help; import java.math.RoundingMode; import java.text.NumberFormat; import java.util.Date; import java.util.Locale; /** * @author barachta * * To change this generated comment edit the template variable * "typecomment": Window>Preferences>Java>Templates. To enable and * disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public class Format { /** * Inexact, Human readable */ public static final class Compact { private static final class NumberFormatter { private static final int CAPACITY = 32; private static volatile int counter = 0; private static final NumberFormat[] POOL1 = new NumberFormat[NumberFormatter.CAPACITY]; private static final NumberFormat[] POOL2 = new NumberFormat[NumberFormatter.CAPACITY]; private static final NumberFormat[] POOL3 = new NumberFormat[NumberFormatter.CAPACITY]; NumberFormatter() { for (int i = 0; i < NumberFormatter.CAPACITY; i++) { NumberFormatter.POOL1[i] = NumberFormat.getInstance( Locale.ROOT ); NumberFormatter.POOL1[i].setMaximumFractionDigits( 1 ); NumberFormatter.POOL1[i].setMinimumFractionDigits( 0 ); NumberFormatter.POOL1[i].setMinimumIntegerDigits( 1 ); NumberFormatter.POOL1[i].setGroupingUsed( false ); NumberFormatter.POOL1[i].setRoundingMode( RoundingMode.HALF_UP ); NumberFormatter.POOL2[i] = NumberFormat.getInstance( Locale.ROOT ); NumberFormatter.POOL2[i].setMaximumFractionDigits( 2 ); NumberFormatter.POOL2[i].setMinimumFractionDigits( 0 ); NumberFormatter.POOL2[i].setMinimumIntegerDigits( 1 ); NumberFormatter.POOL2[i].setGroupingUsed( false ); NumberFormatter.POOL2[i].setRoundingMode( RoundingMode.HALF_UP ); NumberFormatter.POOL3[i] = NumberFormat.getInstance( Locale.ROOT ); NumberFormatter.POOL3[i].setMaximumFractionDigits( 3 ); NumberFormatter.POOL3[i].setMinimumFractionDigits( 0 ); NumberFormatter.POOL3[i].setMinimumIntegerDigits( 0 ); NumberFormatter.POOL3[i].setGroupingUsed( false ); NumberFormatter.POOL3[i].setRoundingMode( RoundingMode.HALF_UP ); } } String format1(final double d) { final int index = NumberFormatter.counter++; final NumberFormat current = NumberFormatter.POOL1[index % NumberFormatter.CAPACITY]; synchronized (current) { return current.format( d ); } } String format2(final double d) { final int index = NumberFormatter.counter++; final NumberFormat current = NumberFormatter.POOL2[index % NumberFormatter.CAPACITY]; synchronized (current) { return current.format( d ); } } String format3(final double d) { final int index = NumberFormatter.counter++; final NumberFormat current = NumberFormatter.POOL3[index % NumberFormatter.CAPACITY]; synchronized (current) { return current.format( d ); } } } private static final DateFormatterCompact DATE = new DateFormatterCompact(); private static final NumberFormatter FORMATTER = new NumberFormatter(); /** * @param date * @return string */ public static final String date(final Date date) { return Compact.DATE.format( date ); } /** * @param time * @return string */ public static final String date(final long time) { return Compact.DATE.format( time ); } /** * @param date * @return string */ public static final String dateRelative(final Date date) { return Compact.DATE.formatRelative( date ); } /** * @param time * @return string */ public static final String dateRelative(final long time) { return Compact.DATE.formatRelative( time ); } /** * @param value * @return string */ public static final String toBytes(final double value) { if (value < 1000L) { if (value < 0) { return '-' + Format.Compact.toBytes( -value ); } if (value >= 1) { return Compact.FORMATTER.format2( value ) + ' '; } if (value >= Format.DOUBLE_MILLI) { return Compact.FORMATTER.format2( value / Format.DOUBLE_MILLI_BYTES ) + " ml"; } if (value >= Format.DOUBLE_MICRO) { return Compact.FORMATTER.format2( value / Format.DOUBLE_MICRO_BYTES ) + " mk"; } return Compact.FORMATTER.format2( value / Format.DOUBLE_NANO_BYTES ) + " n"; } if (value >= 1000L * 1000L * 1000L * 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_TERA_BYTES ) + " T"; } if (value >= 1000L * 1000L * 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_GIGA_BYTES ) + " G"; } if (value >= 1000L * 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_MEGA_BYTES ) + " M"; } if (value >= 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_KILO_BYTES ) + " k"; } return "n/a"; } /** * @param value * @return string */ public static final String toBytes(final long value) { if (value < 0) { return '-' + Format.Compact.toBytes( -value ); } if (value < 1000L) { return String.valueOf( value ) + ' '; } if (value >= 1000L * 1000L * 1000L * 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_TERA_BYTES ) + " T"; } if (value >= 1000L * 1000L * 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_GIGA_BYTES ) + " G"; } if (value >= 1000L * 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_MEGA_BYTES ) + " M"; } return Compact.FORMATTER.format2( value / Format.DOUBLE_KILO_BYTES ) + " k"; } /** * @param value * @return string */ public static final String toDecimal(final double value) { if (Double.isInfinite( value )) { return value > 0 ? "+inf" : "-inf"; } if (Double.isNaN( value )) { return "NaN"; } if (value < 0) { return '-' + Format.Compact.toDecimal( -value ); } if (value < Format.DOUBLE_NANO) { return String.valueOf( value ); } if (value >= 100L * 1000L * 1000L * 1000L * 1000L) { return Compact.FORMATTER.format1( value / Format.DOUBLE_TERA ) + "T"; } if (value >= 1000L * 1000L * 1000L * 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_TERA ) + "T"; } if (value >= 100L * 1000L * 1000L * 1000L) { return Compact.FORMATTER.format1( value / Format.DOUBLE_GIGA ) + "G"; } if (value >= 1000L * 1000L * 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_GIGA ) + "G"; } if (value >= 100L * 1000L * 1000L) { return Compact.FORMATTER.format1( value / Format.DOUBLE_MEGA ) + "M"; } if (value >= 1000L * 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_MEGA ) + "M"; } if (value >= 100L * 1000L) { return Compact.FORMATTER.format1( value / Format.DOUBLE_KILO ) + "k"; } if (value >= 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_KILO ) + "k"; } if (value >= 20L) { return Compact.FORMATTER.format1( value ); } if (value >= 1L) { return Compact.FORMATTER.format2( value ); } if (value >= Format.DOUBLE_MILLI) { if (value >= Format.DOUBLE_MILLI * 10) { return Compact.FORMATTER.format3( (int) (value * 1000) / 1000.0 ); } return Compact.FORMATTER.format2( value / Format.DOUBLE_MILLI ) + "ml"; } if (value >= Format.DOUBLE_MICRO) { return Compact.FORMATTER.format2( value / Format.DOUBLE_MICRO ) + "mk"; } return Compact.FORMATTER.format2( value / Format.DOUBLE_NANO ) + "n"; } /** * @param value * @return string */ public static final String toDecimal(final long value) { if (value < 0) { return '-' + Format.Compact.toDecimal( -value ); } if (value >= 100L * 1000L * 1000L * 1000L * 1000L) { return Compact.FORMATTER.format1( value / Format.DOUBLE_TERA ) + "T"; } if (value >= 1000L * 1000L * 1000L * 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_TERA ) + "T"; } if (value >= 100L * 1000L * 1000L * 1000L) { return Compact.FORMATTER.format1( value / Format.DOUBLE_GIGA ) + "G"; } if (value >= 1000L * 1000L * 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_GIGA ) + "G"; } if (value >= 100L * 1000L * 1000L) { return Compact.FORMATTER.format1( value / Format.DOUBLE_MEGA ) + "M"; } if (value >= 1000L * 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_MEGA ) + "M"; } if (value >= 100L * 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_KILO ) + "k"; } if (value >= 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_KILO ) + "k"; } if (value >= 100L) { return Compact.FORMATTER.format1( value ); } return Compact.FORMATTER.format2( value ); } /** * @param value * @return string */ public static final String toPeriod(final double value) { if (value <= 0) { return String.valueOf( value ); } if (value >= Format.DOUBLE_WEEK_PERIOD) { return Compact.FORMATTER.format2( value / Format.DOUBLE_WEEK_PERIOD ) + " week(s)"; } if (value >= Format.DOUBLE_DAY_PERIOD) { return Compact.FORMATTER.format2( value / Format.DOUBLE_DAY_PERIOD ) + " day(s)"; } if (value >= Format.DOUBLE_HOUR_PERIOD) { return Compact.FORMATTER.format2( value / Format.DOUBLE_HOUR_PERIOD ) + " hour(s)"; } if (value >= Format.DOUBLE_MINUTE_PERIOD) { return Compact.FORMATTER.format2( value / Format.DOUBLE_MINUTE_PERIOD ) + " minute(s)"; } if (value >= Format.DOUBLE_SECOND_PERIOD) { return Compact.FORMATTER.format2( value / Format.DOUBLE_SECOND_PERIOD ) + " second(s)"; } if (value >= Format.DOUBLE_MILLISECOND_PERIOD) { // return formatter.format(value / dMILLISECOND_PERIOD) + " ms"; return Compact.FORMATTER.format2( value ) + " ms"; } if (value >= Format.DOUBLE_MICROSECOND_PERIOD) { return Compact.FORMATTER.format2( value / Format.DOUBLE_MICROSECOND_PERIOD ) + " mks"; } return Compact.FORMATTER.format2( value / Format.DOUBLE_NANOSECOND_PERIOD ) + " nanos"; } /** * @param value * @return string */ public static final String toPeriod(final long value) { if (value <= 0) { return String.valueOf( value ); } if (value >= 1000L * 60L * 60L * 24L * 7L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_WEEK_PERIOD ) + " week(s)"; } if (value >= 1000L * 60L * 60L * 24L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_DAY_PERIOD ) + " day(s)"; } if (value >= 1000L * 60L * 60L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_HOUR_PERIOD ) + " hour(s)"; } if (value >= 1000L * 60L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_MINUTE_PERIOD ) + " minute(s)"; } if (value >= 1000L) { return Compact.FORMATTER.format2( value / Format.DOUBLE_SECOND_PERIOD ) + " second(s)"; } return Compact.FORMATTER.format2( value ) + " ms"; } private Compact() { // empty } } /** * Common web formatting */ public static final class Ecma { private static final DateFormatterEcma DATE = new DateFormatterEcma(); /** * @param date * @return string */ public static final String date(final Date date) { return Ecma.DATE.format( date ); } /** * @param time * @return string */ public static final String date(final long time) { return Ecma.DATE.format( time ); } /** * Returns -1 on error or parsed HTTP date. * * @param string * @return date */ public static final long parse(final String string) { return Ecma.DATE.parse( string ); } private Ecma() { // empty } } /** * Exact, Machine/Human readable */ public static final class Exact { /** * @param value * @return string */ public static final String toBytes(double value) { if (value <= 0) { return String.valueOf( value ); } final StringBuilder result = new StringBuilder( 64 ); if (value > 1024L * 1024L * 1024L * 1024L) { final int ml = (int) (value / (1024L * 1024L * 1024L * 1024L)); value -= 1024L * 1024L * 1024L * 1024L * ml; result.append( ml ).append( 'T' ); } if (value > 1024L * 1024L * 1024L) { final int ml = (int) (value / (1024L * 1024L * 1024L)); value -= 1024L * 1024L * 1024L * ml; result.append( ml ).append( 'G' ); } if (value > 1024L * 1024L) { final int ml = (int) (value / (1024L * 1024L)); value -= 1024L * 1024L * ml; result.append( ml ).append( 'M' ); } if (value > 1024L) { final int ml = (int) (value / 1024L); value -= 1024L * ml; result.append( ml ).append( 'k' ); } if (value > 0) { result.append( value ); } return result.toString(); } /** * @param value * @return string */ public static final String toBytes(long value) { if (value <= 0) { return String.valueOf( value ); } final StringBuilder result = new StringBuilder( 64 ); if (value > 1024L * 1024L * 1024L * 1024L) { final int ml = (int) (value / (1024L * 1024L * 1024L * 1024L)); value -= 1024L * 1024L * 1024L * 1024L * ml; result.append( ml ).append( 'T' ); } if (value > 1024L * 1024L * 1024L) { final int ml = (int) (value / (1024L * 1024L * 1024L)); value -= 1024L * 1024L * 1024L * ml; result.append( ml ).append( 'G' ); } if (value > 1024L * 1024L) { final int ml = (int) (value / (1024L * 1024L)); value -= 1024L * 1024L * ml; result.append( ml ).append( 'M' ); } if (value > 1024L) { final int ml = (int) (value / 1024L); value -= 1024L * ml; result.append( ml ).append( 'k' ); } if (value > 0) { result.append( value ); } return result.toString(); } /** * @param value * @return string */ public static final String toPeriod(long value) { if (value <= 0) { return String.valueOf( value ); } final StringBuilder result = new StringBuilder( 64 ); if (value > 1000L * 60L * 60L * 24L * 7L) { final int ml = (int) (value / (1000L * 60L * 60L * 24L * 7L)); value -= 1000L * 60L * 60L * 24L * 7L * ml; result.append( ml ).append( 'w' ); } if (value > 1000L * 60L * 60L * 24L) { final int ml = (int) (value / (1000L * 60L * 60L * 24L)); value -= 1000L * 60L * 60L * 24L * ml; result.append( ml ).append( 'd' ); } if (value > 1000L * 60L * 60L) { final int ml = (int) (value / (1000L * 60L * 60L)); value -= 1000L * 60L * 60L * ml; result.append( ml ).append( 'h' ); } if (value > 1000L * 60L) { final int ml = (int) (value / (1000L * 60L)); value -= 1000L * 60L * ml; result.append( ml ).append( 'm' ); } if (value > 1000L) { final int ml = (int) (value / 1000L); value -= 1000L * ml; result.append( ml ).append( 's' ); } if (value > 0) { result.append( value ); } return result.toString(); } private Exact() { // empty } } /** * Common web formatting */ public static final class Web { private static final DateFormatterWeb DATE = new DateFormatterWeb(); /** * @param date * @return string */ public static final String date(final Date date) { return Web.DATE.format( date ); } /** * @param time * @return string */ public static final String date(final long time) { return Web.DATE.format( time ); } /** * Returns -1 on error or parsed HTTP date. * * @param string * @return date */ public static final long parse(final String string) { return Web.DATE.parse( string ); } private Web() { // empty } } /** * */ public static final double DOUBLE_KILO_BYTES = 1024L; /** * */ public static final double DOUBLE_MEGA_BYTES = 1024L * 1024L; /** * */ public static final double DOUBLE_GIGA_BYTES = 1024L * 1024L * 1024L; /** * */ public static final double DOUBLE_TERA_BYTES = 1024L * 1024L * 1024L * 1024L; /** * */ public static final double DOUBLE_MILLI_BYTES = Format.DOUBLE_KILO_BYTES / Format.DOUBLE_MEGA_BYTES; /** * */ public static final double DOUBLE_MICRO_BYTES = Format.DOUBLE_KILO_BYTES / Format.DOUBLE_GIGA_BYTES; /** * */ public static final double DOUBLE_NANO_BYTES = Format.DOUBLE_KILO_BYTES / Format.DOUBLE_TERA_BYTES; /** * */ public static final double DOUBLE_KILO = 1000L; /** * */ public static final double DOUBLE_MEGA = 1000L * 1000L; /** * */ public static final double DOUBLE_GIGA = 1000L * 1000L * 1000L; /** * */ public static final double DOUBLE_TERA = 1000L * 1000L * 1000L * 1000L; /** * */ public static final double DOUBLE_MILLI = 1000L / Format.DOUBLE_MEGA; /** * */ public static final double DOUBLE_MICRO = 1000L / Format.DOUBLE_GIGA; /** * */ public static final double DOUBLE_NANO = 1000L / Format.DOUBLE_TERA; /** * */ public static final double DOUBLE_SECOND_PERIOD = 1000L; /** * */ public static final double DOUBLE_MINUTE_PERIOD = 1000L * 60L; /** * */ public static final double DOUBLE_HOUR_PERIOD = 1000L * 60L * 60L; /** * */ public static final double DOUBLE_DAY_PERIOD = 1000L * 60L * 60L * 24L; /** * */ public static final double DOUBLE_WEEK_PERIOD = 1000L * 60L * 60L * 24L * 7L; /** * */ public static final double DOUBLE_MILLISECOND_PERIOD = 1.0; /** * */ public static final double DOUBLE_MICROSECOND_PERIOD = Format.DOUBLE_MILLISECOND_PERIOD / 1000.0; /** * */ public static final double DOUBLE_NANOSECOND_PERIOD = Format.DOUBLE_MICROSECOND_PERIOD / 1000.0; private Format() { // empty } }
Markdown
UTF-8
2,386
2.953125
3
[]
no_license
# PHP Telegram Bot A simple code to create a bot to telegram application This bot was created with colaboration of [LeonelF](https:/LeonelF) **The host must support HTTPS in order for this to work.** ### Create Telegram Bot Start a conversation with the *BotFather*: ``` GLOBAL SEARCH -> BotFather ``` > **BotFather**: The *BotFather* is the one bot to rule them all. Use it to create new bot accounts and manage your existing bots. Create a new bot: `/newbot` Choose a user-friendly name for your bot, for example: `Notifier` Choose a unique username for your bot (must ends with “bot”), for example: `notifier_bot` Once the bot is created, you will get a token to access the Telegram API. > TOKEN: The token is a string that is required to authorize the bot and send requests to the Telegram API, e.g. 4334584910:AAEPmjlh84N62Lv3jGWEgOftlxxAfMhB1gs ### Get The Chat ID > CHAT_ID: To send a message through the Telegram API, the bot needs to provide the ID of the chat it wishes to speak in. The chat ID will be generated once you start the first conversation with your bot. Start a conversation with your bot: ``` GLOBAL SEARCH -> MY_BOT_NAME -> START ``` Send the /start command: `/start` To get the chat ID, open the following URL in your web-browser: https://api.telegram.org/bot**TOKEN**/getUpdates (replace **«TOKEN»** with your bot token). ### Edit conf.php file and upload Rename the conf.example.php file to conf.php and put the bot token that you got from bot father and if you want your bot to awnser to anyone change to **FALSE** the onlytrusted parameter, otherwise add your chatid to the trusted array. Upload the files to your host (I recommend creating a unique directory name, you can use an MD5 hash of a string of your choice, for example: 5277d6cf9f917a1da0ef9e55f3ae9f8f) ### Set the Webhook To set the webhook to your telegram bot you only need to access the following url with the bot token and the url to your webhook https://api.telegram.org/bot**TOKEN**/setwebhook?url=https://example.domain/path/to/hook.php (replace **«TOKEN»** with your bot token and the webhook url to your own). example: ``` https://api.telegram.org/bot4334584910:AAEPmjlh84N62Lv3jGWEgOftlxxAfMhB1gs/setwebhook?url=https://yourdomain.com/5277d6cf9f917a1da0ef9e55f3ae9f8f/hook.php ``` More help on how to create a webhook [here](https://core.telegram.org/bots/webhooks). Have fun!
Markdown
UTF-8
1,095
2.609375
3
[]
no_license
**Description** Please include a summary of the change and which issue is fixed (Add to Resolves list). Be sure to elaborate on any current functionality this may affect. **Resolves These Issues** Resolves #(replace parentheses and the stuff here with the issue number, if there isn't one, create one.) **Type of change** Check options that are relevant. - [ ] Bug fix (fixes a bug issue) - [ ] New feature (adds functionality) - [ ] This fix or feature will cause existing functionality to not work as expected. (Please elaborate in Description.) **Steps to Verify Functionality** Make a bulleted/numbered list of steps to verify this feature/bugfix. Include screenshots if necessary. **Final Checklist:** Go down the list and check them off. - [ ] My code follows the style guidelines of this project - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have performed a self-review of my own code - [ ] My changes pass Flow, build without errors and (if applicable) pass Jest tests. - [ ] This change requires a update in the design document (if applicable)
Java
UTF-8
550
3.421875
3
[]
no_license
package com.tiarebalbi.section_one; public interface Stack<T> { /** * Insert a new item onto stack * * @param item item to be inserted */ void push(T item); /** * Remove and return the item most recently added * * @return most recently item added */ T pop(); /** * Check if stack is empty or not * * @return {@code false} if empty and {@code true} if is not empty */ boolean isEmpty(); /** * Number of items on the stack * * @return total of elements in the stack */ int size(); }
Ruby
UTF-8
745
3.21875
3
[]
no_license
require "yaml" CHANNEL_MANAGER_FILE = "data/channel_manager.yaml" class ChannelManager attr_accessor :channels def initialize() @channels = Array.new() end def add_channel_to_manager(channel) if does_not_contain_channel(channel) @channels << channel end end def does_not_contain_channel(channel) @channels.each do |channel_in_manager| if channel_in_manager.name == channel.name return false end end return true end end def save_as_YAML(channel_manager) File.open(CHANNEL_MANAGER_FILE, 'w') do |file| file.write YAML::dump(channel_manager) end end channel_manager = ChannelManager.new() channel_manager.add_channel_to_manager("THING") save_as_YAML(channel_manager)
TypeScript
UTF-8
4,584
2.59375
3
[]
no_license
import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable, of } from 'rxjs'; import { SearchResults } from '../models/SearchResults.model'; import { MovieInformation } from '../models/MovieInformation.model'; import { BannerState } from '../models/BannerState.model'; import { BannerContext } from '../enums/BannerContext.enum'; @Injectable({ providedIn: 'root', }) export class SearchMovieStoreService { //State: Search readonly _searchedString = new BehaviorSubject<string>(null); readonly searchedString$ = this._searchedString.asObservable(); readonly _isLoading = new BehaviorSubject<boolean>(false); readonly isLoading$ = this._isLoading.asObservable(); readonly _results = new BehaviorSubject<SearchResults>({ Response: false, Search: [], totalResults: '' }); readonly results$ = this._results.asObservable(); //State: Nominations readonly _nominations = new BehaviorSubject<MovieInformation[]>([]); readonly nominations$ = this._nominations.asObservable(); readonly _nominationLimit = new BehaviorSubject<number>(0); readonly nominationLimit$ = this._nominations.asObservable(); //State: Banner readonly _bannerState = new BehaviorSubject<BannerState>({ isVisible: false, context: BannerContext.Info, message: "test" }); readonly bannerState$ = this._bannerState.asObservable(); get searchedString(): string { return this._searchedString.getValue(); } set searchedString(str: string) { this._searchedString.next(str); } get results(): SearchResults { return this._results.getValue(); } set results(results: SearchResults) { this._results.next(results); } get nominations(): MovieInformation[] { return this._nominations.getValue(); } set nominations(nominations: MovieInformation[]) { this._nominations.next(nominations); } get isLoading(): boolean { return this._isLoading.getValue(); } set isLoading(state: boolean) { this._isLoading.next(state); } get bannerState(): BannerState { return this._bannerState.getValue(); } set bannerState(state: BannerState) { this._bannerState.next(state); } get nominationLimit(): number { return this._nominationLimit.getValue(); } set nominationLimit(limit: number) { this._nominationLimit.next(limit); } //Nominations functions public addElementToNominations(movie: MovieInformation): void { //imdbID should be enough but just to be sure compare Titles and year or release if (!this._nominations.getValue().some(nominee => this.compareMovieNominee(movie, nominee)) && this._nominations.getValue().length < this._nominationLimit.getValue()) { this._nominations.next([...this._nominations.getValue(), movie]); this.updateLocalStorage(); if (this._nominations.getValue().length === this._nominationLimit.getValue()) { this.bannerState = this.createNewBanner(BannerContext.Success, "Thank you for participating"); } //Unreleased Feature: //A bit invasive, Notifies the user everytime they add a movie to the nomination list // else { // this.bannerState = this.createNewBanner(BannerContext.Info, `${movie.Title} was added to you nomination list. You have ${this._nominationLimit.getValue() - this._nominations.getValue().length} more movie to select`); // setTimeout(() => { // this.bannerState = { ...this.bannerState, isVisible: false }; // }, 2000); // } } } public removeElementFromNominations(movie: MovieInformation): void { this.nominations = this._nominations.getValue().filter((m) => m !== movie); this.updateLocalStorage(); if (this._nominations.getValue().length === (this._nominationLimit.getValue() - 1)) { this.bannerState = { ...this.bannerState, isVisible: false }; } } private compareMovieNominee(movie: MovieInformation, nominee: MovieInformation): boolean { return nominee.Title === movie.Title && nominee.Year === movie.Year && nominee.imdbID === movie.imdbID } private updateLocalStorage(): void { //Hardcoded for 'nominees' since only information storing in the local storage localStorage.setItem("nominees", JSON.stringify(this._nominations.getValue())); } public isNominated(nominee: MovieInformation): Observable<boolean> { return of(this._nominations.getValue().includes(nominee)); } public createNewBanner(context: BannerContext, message: string): BannerState { return { isVisible: true, context: context, message: message } } }
Java
UTF-8
996
2.25
2
[]
no_license
package com.lvsint.abp.server.feeds.enetpulse.creators; public class ImporterResultInfo { private String gameId; private int scoreHome; private int scoreAway; private boolean abandoned; private final long countryId; public ImporterResultInfo(String gameId, long countryId, boolean abandoned) { this.gameId = gameId; this.countryId = countryId; this.abandoned = abandoned; } public ImporterResultInfo(String gameId, long countryId, int scoreHome, int scoreAway) { this.gameId = gameId; this.countryId = countryId; this.scoreHome = scoreHome; this.scoreAway = scoreAway; } public String getGameId() { return gameId; } public int getScoreAway() { return scoreAway; } public int getScoreHome() { return scoreHome; } public boolean isAbandoned() { return abandoned; } public long getCountryId() { return countryId; } }
Shell
UTF-8
4,178
2.875
3
[]
no_license
#!/bin/bash #simple script to determine what graphics package to use set -x #revision 2 20101201 (complete rewrite) #revision 3 20110523 for spup #revision 4 20110927 nouveau rant #revision 5 20120129 new kernels #revision 6 20120225 more new kernels -unionfs #revision 7 20121317 back to aufs rm -f /tmp/luci_recomend 2>/dev/null rm -f /tmp/card_brand 2>/dev/null #define working directorys APPDIR="/usr/local/graphics-test" KERNVER="`uname -r`" CURDRIVER="`grep -E -i " connected|card detect|primary dev" /var/log/Xorg.0.log|cut -d ':' -f1|rev|cut -d ' ' -f1|rev|cut -d '(' -f1|tr '[:upper:]' '[:lower:]'|head -n1`" MODEL=`lspci|grep -iw vga|cut -d ':' -f3` BRAND=`echo $MODEL|awk '{print $1}'` DRIVER="mesa-" VIDEODETAILS="`lspci -nn -m | grep 'VGA compatible controller'`" MANUFACTURER="`cat /etc/X11/xorg.conf | tr '\n' ' ' | tr '\t' ' ' | tr -s ' ' | grep -o '#card0driver .*' | grep -o 'VendorName "[^"]*' | cut -f 2 -d '"'`" #'geany #DEVICEID="`echo -n "$VIDEODETAILS" | cut -f 6 -d '"' | rev | cut -f 2 -d ']' | cut -f 1 -d '[' | rev`" #'geany DEVICEID="`lspci -nn|grep -iE vga|tr '[' '\n'|tr ']' '\n'|grep ^[0-9]|grep -v '\.'|grep '\:'|cut -d ':' -f2`" if [ "$BRAND" != "Intel" ];then #20110329 RandSec issue ATI=`grep -i $DEVICEID $APPDIR/ati` NVID_285=`grep -i $DEVICEID $APPDIR/285nvid` #NVID_275=`grep -i $DEVICEID $APPDIR/275nvid` NVID_173=`grep -i $DEVICEID $APPDIR/173nvid` NVID_96=`grep -i $DEVICEID $APPDIR/96nvid` if [[ "$ATI" != "" ]];then MODEL=`echo $ATI|cut -d '|' -f1` #DRIVER="ATI_fglrx-10.10 Catalyst driver" #DRIVER="ati_fglrx-11.7 Catalyst driver" case $KERNVER in 2.6.37.6)DRIVER="ati_fglrx-11.8 Catalyst driver";; 2.6.39.4)DRIVER="ati_fglrx-11.9 Catalyst driver";; 3.1.10-slacko_4gA)DRIVER="amd_fglrx-12.4 Catalyst driver";; #amd_fglrx-12.1-3.1.10-slacko_4gA-s.pet 3.1.10-slacko_paeA)DRIVER="amd_fglrx-12.4 Catalyst driver";; #amd_fglrx-12.1-3.1.10-slacko_paeA-s.pet esac fi if [[ "$NVID_285" != "" ]];then #MODEL=`echo $NVID_280|cut -d '|' -f1` #upgraded to 285 111023 #290 120129 case $KERNVER in 2.6.37.6)MODEL=`echo $NVID_285|cut -d '|' -f1` ; DRIVER="nvidia-285.05.09 driver";; 2.6.39.4)MODEL=`echo $NVID_285|cut -d '|' -f1` ; DRIVER="nvidia-285.05.09 driver";; 3.1.10-slacko_4gA)MODEL=`echo $NVID_285|cut -d '|' -f1` ; DRIVER="nvidia-295.20 driver";; 3.1.10-slacko_paeA)MODEL=`echo $NVID_285|cut -d '|' -f1` ; DRIVER="nvidia-295.20 driver";; esac fi #if [[ "$NVID_275" != "" ]];then MODEL=`echo $NVID_275|cut -d '|' -f1` #upgraded to 275 stable 111002 #DRIVER="nvidia-275.28 driver" #fi if [[ "$NVID_173" != "" ]];then MODEL=`echo $NVID_173|cut -d '|' -f1` case $KERNVER in 2.6.37.6)DRIVER="nvidia-173.14.31 driver";; 2.6.39.4)DRIVER="nvidia-173.14.31 driver";; 3.1.10-slacko_4gA)DRIVER="nvidia-173.14.31 driver";; 3.1.10-slacko_paeA)DRIVER="nvidia-173.14.31 driver";; esac fi if [[ "$NVID_96" != "" ]];then MODEL=`echo $NVID_96|cut -d '|' -f1` case $KERNVER in 2.6.37.6)DRIVER="nvidia-96.43.16 driver";; 3.1.10-slacko_4gU)DRIVER="nvidia-96.43.20 driver";; 3.1.10-slacko_4gA)DRIVER="mesa-" esac fi fi if [[ "$DRIVER" = "nvidia-173.14.31 driver" || "$DRIVER" = "nvidia-285.05.09 driver" || "$DRIVER" = "nvidia-96.43.16 driver" || "$DRIVER" = "nvidia-295.20 driver" || "$DRIVER" = "nvidia-96.43.20 driver" ]];then EXTRANVIDIA="Alternatively you could use the 'nouveau video' open source driver, which is much smaller and usually works. Then you can add the 'mesa' package from PPM too for acceleration." elif [ "$CURDRIVER" = "nouveau" ];then EXTRANVIDIA="" fi RECO1="For your $BRAND video card, $MODEL we think the best add on driver is ${DRIVER}. It would be required for some programs and games with high graphical content and your desktop might seem a bit more snappy. ${EXTRANVIDIA}" # RECOMEND=$RECO1 DRIVERSEL=`echo "$DRIVER"|grep -v pet$|awk '{print $1}'` [ ! "$DRIVERSEL" ] && DRIVERSEL="$DRIVER" echo "$RECOMEND" > /tmp/luci_recomend echo "$RECOMEND" echo $NVID_285 echo $MODEL echo $BRAND echo $DEVICEID echo $DRIVERSEL > /tmp/graphic_driver_selection echo $DRIVERSEL echo "$CURDRIVER" echo "$CURDRIVER"> /tmp/graphic_driver_current ###END
Python
UTF-8
1,933
3.046875
3
[]
no_license
import requests import json import sys from bs4 import BeautifulSoup def parseUrl(url): r = requests.get(url) titles_list = [] text_list = [] soup = BeautifulSoup(r.text, 'html.parser') main_title = soup.h1.text main_title = list(main_title) for i in main_title: if i == '\xa0' or i == '\xad': main_title.insert(main_title.index(i), ' ') main_title.remove(i) main_title = ''.join(main_title) first_dict = {'Title' : None, 'Audio' : None } first_dict['Title'] = main_title first_dict['Audio'] = soup.audio.get('src') for i in soup.find_all('h3'): if i.text.startswith('Кондак') or i.text.startswith('Икос'): titles_list.append(i.text) all_p = soup.find_all('p', {'class' : 'paint'}) for i in all_p: text_list.append([i.text]) clean_text = [] for i in range(len(text_list)): for j in text_list[i]: s = list(j) for xad in s: if xad == '\xad' or xad == '\xa0': s.remove(xad) n = ''.join(s) clean_text.append([n]) # for i in range(len(clean_text)): n = len(clean_text) i = 0 while i < n: for j in clean_text[i]: if j.startswith('Слава'): clean_text[i-1].extend(clean_text[i]) clean_text.remove(clean_text[i]) n -= 1 else: i += 1 final_dict = dict.fromkeys(titles_list) i = 0 while i < len(final_dict): for j in final_dict: final_dict[j] = clean_text[i] i += 1 final_tuple = (first_dict, final_dict) return final_tuple if len(sys.argv) == 1: raise Exception("You should provide URL to parse as the first argument") obj = parseUrl(sys.argv[1]) print(json.dumps(obj,ensure_ascii=False))
Java
UTF-8
8,113
2.265625
2
[]
no_license
package gui; import code.Main; import code.ManagerBill; import code.ManagerCostumer; import code.ManagerGeneralValidations; import code.ManagerProduct; import java.awt.event.ItemEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; public class InformationOptions extends javax.swing.JFrame { private static final int COMPETITORS = 0; private static final int COSTUMERS_SPENDED_MORE_THAN = 1; private static final int TOTAL_INCOMES = 2; private static final int PRODUCTS_CHEAPER_THAN = 3; private static final int BILLS_BY_COSTUMERS = 4; private static final int DEFAULT = COMPETITORS; public InformationOptions() { initComponents(); this.setResizable(false); options.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Clientes seleccionados para participar por premios", "Clientes cuyo valor total en compras sea mayor a...", "Dinero total producido por ventas", "Productos con precio menor a...", "Facturas por clientes"})); getDataForTable(DEFAULT); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { options = new javax.swing.JComboBox(); jScrollPane1 = new javax.swing.JScrollPane(); table = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); btnBack = new javax.swing.JButton(); btnRefresh = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); options.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); options.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { optionsItemStateChanged(evt); } }); table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } ) { boolean[] canEdit = new boolean [] { false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(table); jLabel1.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N jLabel1.setText("Digite una opcion para visualizar:"); btnBack.setText("Volver"); btnBack.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnBackActionPerformed(evt); } }); btnRefresh.setText("Actualizar Tabla"); btnRefresh.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRefreshActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 586, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(options, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addComponent(btnRefresh) .addGap(18, 18, 18) .addComponent(btnBack))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnBack, btnRefresh}); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(options, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE) .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnBack) .addComponent(btnRefresh)) .addContainerGap()) ); layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnBack, btnRefresh}); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed OfficesOptions oo = new OfficesOptions(); oo.setVisible(true); dispose(); }//GEN-LAST:event_btnBackActionPerformed private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed getDataForTable(options.getSelectedIndex()); }//GEN-LAST:event_btnRefreshActionPerformed private void optionsItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_optionsItemStateChanged if(evt.getStateChange() == ItemEvent.SELECTED){ getDataForTable(options.getSelectedIndex()); } }//GEN-LAST:event_optionsItemStateChanged private void getDataForTable(int newOp) { ArrayList<LinkedHashMap<String, String>> data; String s; data = new ArrayList(); switch (newOp) { case COMPETITORS: data = ManagerCostumer.getCompetitors(); break; case COSTUMERS_SPENDED_MORE_THAN: s = ManagerGeneralValidations.askNumber("Digite un valor:"); if (s != null) { data = ManagerCostumer.getCostumersSpendMoreThan(Integer.parseInt(s)); } break; case TOTAL_INCOMES: data = ManagerCostumer.getTotalSales(); break; case PRODUCTS_CHEAPER_THAN: s = ManagerGeneralValidations.askNumber("Digite un valor:"); if (s != null) { data = ManagerProduct.getProductsCheaperThan(Integer.parseInt(s)); } break; case BILLS_BY_COSTUMERS: s = ManagerGeneralValidations.askNumber("Digite la cedula del cliente del cual desea ver las facturas:"); if (s != null) { data = ManagerBill.getBillsByCostumer(Long.parseLong(s)); } break; } Main.refreshTable(table, data); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnBack; private javax.swing.JButton btnRefresh; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JComboBox options; private javax.swing.JTable table; // End of variables declaration//GEN-END:variables }
Markdown
UTF-8
972
2.96875
3
[]
no_license
## greeting-web-app *Small server app, created for educational purposes. Build with spring boot, maven, docker* ```shell $ mvn spring-boot:run $ docker build -t greeting-app . $ docker run -p 5000:5000 greeting-app ``` # Specification: 1. Given the following input values account=personal and id=123 and the allowable values for an account are personal and business and the allowable values for id are all positive integers then return "Hi, userId 123". 2. Given the following input values account=business and type=small and and the allowable values for an account are personal and business and the allowable values for type are small and big then return an error that the path is not yet implemented. 3. Given the following input values account=business and type=big and and the allowable values for an account are personal and business and the allowable values for type are small and big then return "Welcome, business user!".
TypeScript
UTF-8
658
2.78125
3
[ "MIT" ]
permissive
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; import * as bcrypt from 'bcrypt'; export type UserDocument = User & Document; @Schema({ timestamps: true }) export class User { @Prop({ trim: true, required: true, lowercase: true, unique: true }) email: string; @Prop({ trim: true, required: true }) name: string; @Prop({ required: true }) password: string; comparePassword: Function; } export const UserSchema = SchemaFactory.createForClass(User); UserSchema.methods.comparePassword = function(candidatePassword: string) { return bcrypt.compare(candidatePassword, this.password); };
Ruby
UTF-8
450
4.125
4
[]
no_license
# [1,2,3] # init like arr = [] # new new new arr1 = Array.new(5) arr2 = Array.new(2, true) arr3 = Array.new(2, "abc") arr3.first.upcase! puts arr3 arr4 = Array.new(25) {"abc"} pos = arr4.length-6 arr4[pos].upcase! puts arr4 puts arr4.length # array of symbols instantiated with %i arr_sym = %i(w a s d) puts arr_sym puts arr_sym.size # slicing up eyballs arr = [1,2,3,4,5,6,7,8,9] puts arr[2..6] # math rock stuff [12345, 2,3,4,5] - [3, 5]
C++
UTF-8
1,862
3.03125
3
[ "MIT" ]
permissive
#include <algorithm> #include <iostream> #include <sstream> #include <iomanip> #include <vector> #include "Bohr.hpp" int main() { using MyBohr = Bohr<uint32_t>; using symbol_t = MyBohr::symbol_t; using pattern_t = MyBohr::pattern_t; MyBohr b; std::vector<pattern_t> patterns{{1,2,3,0}, {1,2,0}, {2,0}, {3,1}, {2,3,4}}; std::vector<symbol_t> text{1,2,0,4,1,2,3,0,1,2,3,0,}; std::for_each(patterns.cbegin(), patterns.cend(), [&b](const pattern_t &p) { b.add_pattern(p); std::cout << "added_pattern:\t"; std::copy(p.begin(), p.end(), std::ostream_iterator<symbol_t>(std::cout, " ")); std::cout << std::endl; }); std::cout << "--------------------------------\n"; std::vector<pattern_t> false_patterns_to_check{{4,5}, {1,0}, {1,2,3}, {3,4}, {2,3,1}}; std::cout << "false patterns:\n"; std::for_each(false_patterns_to_check.begin(), false_patterns_to_check.end(), [&b](const pattern_t &p) { std::ostringstream ss; std::copy(p.begin(), p.end(), std::ostream_iterator<symbol_t>(ss, " ")); std::cout << std::setw(15) << std::left << ss.str() << ":\t" << std::boolalpha << b.contains(p) << std::endl; }); std::cout << "\ntrue patterns:\n"; std::for_each(patterns.begin(), patterns.end(), [&b](const pattern_t &p) { std::ostringstream ss; std::copy(p.begin(), p.end(), std::ostream_iterator<symbol_t>(ss, " ")); std::cout << std::setw(15) << std::left << ss.str() << ":\t" << std::boolalpha << b.contains(p) << std::endl; }); auto res = b.find(text); std::cout << "--------------------------------\n"; std::cout << "text: "; std::copy(text.begin(), text.end(), std::ostream_iterator<symbol_t>(std::cout, " ")); std::cout << std::endl; for (const auto &el : res) { std::cout << "{ pattern_number: " << el.first << ", i: " << el.second << " }" << std::endl; } return 0; }
JavaScript
UTF-8
1,565
2.8125
3
[ "Apache-2.0" ]
permissive
const http = require('http'); const {Readability} = require('@mozilla/readability'); const JSDOM = require('jsdom').JSDOM; const portsParam = process.env.PORT; // get the port from the env variable let port = 8080; // default port if (portsParam) { ports = portsParam } else { console.error('Can not read port parameter'); console.error('Go with default'); console.error('Port 8080'); } /** * Handle the income request and reply with the parse object * @param req * @param res */ const handleRequest = function (req, res) { let payload = ''; req.on('data', function (data) { payload += data; // Too much POST data, kill the connection! // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB if (payload.length > 1e6) { res.writeHead(431, {'Content-Type': 'text/plain'}).end(); req.connection.destroy(); } }); req.on('end', function () { let payloadJson = JSON.parse(payload); if (payloadJson['data']) { let doc = new JSDOM(payloadJson['data']); let reader = new Readability(doc.window.document, {}); let article = reader.parse(); const responsePayload = JSON.stringify(article) res.writeHead(200, {'Content-Type': 'application/json'}); res.end(responsePayload) } else { res.writeHead(400, {'Content-Type': 'application/json'}); res.end('{"err":"Can not parse document"}') } }); }; http.createServer(handleRequest).listen(port);
TypeScript
UTF-8
254
2.5625
3
[ "MIT" ]
permissive
import { Exception } from './exception'; export class CapacityFullException extends Exception { constructor(message: string) { super(message); } public toString() { return `CapacityFullException${super.toString()}`; } }
Shell
UTF-8
1,783
3.21875
3
[ "MIT" ]
permissive
#!/bin/bash ################################ # Author: Rum Coke # Data : 2015/05/06 # Ver : 1.4.0 ################################ # for EL-USB-RT # path of tempsensor binary BIN_PATH="/usr/local/bin" # Setting threshold value for warn and critical. WARN_TEMP='30' CRITICAL_TEMP='35' WARN_HYD='40:' CRITICAL_HYD='30:' WARN_DISCOMFORT='75' CRITICAL_DISCOMFORT='80' if [ "$1" = "autoconf" ]; then echo yes exit 0 fi if [ "$1" = "config" ]; then # glaph common echo 'graph_title room_temperature/himidity' echo 'graph_args -l 0 ' echo 'graph_vlabel Temp/Himid' echo 'graph_category system' # temp data echo 'temperature.label temperature' echo 'temperature.draw LINE' echo "temperature.warning ${WARN_TEMP}" echo "temperature.critical ${CRITICAL_TEMP}" # himidity data echo 'himidity.label himidity' echo 'himidity.draw LINE' echo "himidity.warning ${WARN_HYD}" echo "himidity.critical ${CRITICAL_HYD}" # discomfort index data echo 'discomfort.label discomfort index' echo 'discomfort.draw LINE' echo "discomfort.warning ${WARN_DISCOMFORT}" echo "discomfort.critical ${CRITICAL_DISCOMFORT}" print_warning temperature print_critical temperature print_warning himidity print_critical himidity print_warning discomfort print_critical discomfort exit 0 fi work=`${BIN_PATH}/tempsensor -s` ROOM_TEMP=`echo ${work} | awk -F',' '{print $1}'` ROOM_HYD=`echo ${work} | awk -F',' '{print $2}'` ROOM_RELUX=`echo "scale=2; 0.81*$ROOM_TEMP+0.01*$ROOM_HYD*(0.99*$ROOM_TEMP-14.3)+46.3" | bc | cut -d "." -f 1` echo "temperature.value ${ROOM_TEMP}" echo "himidity.value ${ROOM_HYD}" echo "discomfort.value ${ROOM_RELUX}"
Java
UTF-8
1,042
2.5625
3
[]
no_license
package org.geektimes.projects.user.web.listener; import org.apache.activemq.command.ActiveMQTextMessage; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.jms.MessageProducer; import javax.jms.Topic; public class TestingComponent { @Resource(name = "jms/activemq-topic") private Topic topic; @Resource(name = "jms/message-producer") private MessageProducer messageProducer; @PostConstruct public void init() { System.out.println("topic is " + topic); } @PostConstruct public void sendMessage() throws Throwable { //Create a message String text = "Hello World! From :" + Thread.currentThread().getName() + ":" + this.hashCode(); ActiveMQTextMessage message = new ActiveMQTextMessage(); message.setText(text); //Tell the producer to send the message messageProducer.send(message); System.out.printf("[Thread : %s] Sent message : %s\n", Thread.currentThread().getName(), message.getText()); } }
JavaScript
UTF-8
4,530
2.734375
3
[]
no_license
import $ from 'jQuery'; class Base{ //中间列表HTML getContentListHTML(data=[]){ let self = this, html = ``; this.dataList = new Set(data); let list = this.changeDataToMap(data); for( let [y,year] of list.entries()){ html += `<div class="content_year tips" id="content_year_${y}">${y}</div>`; for( let [m,month] of year.entries()){ html += `<div class="content_month tips" id="content_month_${y}_${m}">${m}月</div>`; for( let [idx,li] of month.entries()){ let lunar = self.GetLunarDateString(new Date(li.date)); html += ` <div class="content_item content_item_${idx%2==0?'left':'right'} ${idx==0?'first':''}"> <div class="content_item_icon_arrow"></div> <div class="content_item_icon_dot"> <div class="content_item_icon_dot_child"></div> </div> <div class="content_item_icon_head"> <div class="content_item_icon_head_title"> <div class="content_item_icon_head_title_lunar">${lunar.substr(0,1)}<br>&nbsp;&nbsp;&nbsp;${lunar.substr(1,1)}</div> ${li.date.replace(/\//g,'-')} </div> <div class="content_item_head_intro"> <i class="ui_icon quote_before"></i> ${li.intro} <i class="ui_icon quote_after"></i> </div> </div> <div class="content_item_media"> ${li.media} </div> <div class="content_item_footer"> <div class="content_item_footer_info"> <a href="javascript:;" title="赞"><i class="icon_zan"></i>(${li.like})</a> <a href="javascript:;" title="评论"><i class="icon_pin"></i>(${li.comment})</a> </div> <div class="content_item_footer_like"> ${li.like>=10000?Number(li.like/10000).toFixed(1)+'万':li.like}人觉得很赞 </div> </div> </div> `; } } } html +=`<div class="content_year" id="content_month_0_0">出生</div>`; $(self.content_el).html(html); this.getscrubberHTML(list); } //左边索引HTML getscrubberHTML(list){ let self = this; let html = `<a href="javascript:;" class="current" id="top">现在</a>`; for(let [y,year] of list.entries()){ html += `<a href="javascript:;" class="scrubber_year" id="scrubber_year_${y}">${y}年</a>`; for(let [m,month] of year.entries()){ html += `<a href="javascript:;" class="scrubber_month scrubber_month_in_${y}" year="${y}" month="${m}" id="scrubber_month_${y}_${m}">${m}月</a>`; } } html += `<a href="javascript:;" id="bottom">出生</a>`; $(self.scrubber_el).html(html); } //根据年份,月份,转化data格式; changeDataToMap(data=[]){ let list = new Map(); let lastyear ,lastyearMap = new Map(); let lastmonth, lastmonthArr = []; for(let li of data){ let year = li.date.split('/')[0]; let month = li.date.split('/')[1]; if(lastyear === year){ if(lastmonth === month){ lastmonthArr.push(li); }else{ lastmonthArr = [li]; lastyearMap.set(month,lastmonthArr); } }else{ lastyearMap = new Map(); lastmonthArr = [li]; lastyearMap.set(month,lastmonthArr); list.set(year,lastyearMap); } lastmonth = month; lastyear = year; } return list; } //标签跳转 事件 changeTabNav(e){ let self = this; let id = e.currentTarget.id.replace(/scrubber/,'content'); let top = 0; if(id === 'top'){ top = 0; }else if(id === 'bottom'){ top = $(document).height()-$(window).height(); }else{ top = $('#'+id).offset().top-50; } // $(document).scrollTop(top); //页面抖动 // var timer = setInterval(function(){ // let osTop = $(document).scrollTop(); // let ispeed = Math.floor((top-osTop) / 6); // $(document).scrollTop(osTop + ispeed) ; // if(Math.abs(ispeed)<=2){ // clearInterval(timer); // } // },30); $('html, body').animate({ 'scrollTop': top }, 400); } //监听滚动事件 listenScroll(e){ let self = this; let scrollTop = $(document).scrollTop(); let scruTop = self.scrubberTop; let cha = scrollTop-scruTop; if(scrollTop<scruTop&&$(self.scrubber_el).attr('style')!=""){ $(self.scrubber_el).removeAttr("style") }else if(scrollTop>=scruTop){ $(self.scrubber_el).css({top:cha+"px"}); } let arr = $(self.content_el).find(".tips").filter((idx,ele)=>$(ele).offset().top<(scrollTop+100)); if(arr.length>0){ let id = arr[arr.length-1].id.replace(/content/,'scrubber'); $('#'+id).addClass("current").siblings().removeClass("current"); } } } export default Base;
C++
UTF-8
4,608
2.921875
3
[ "MIT" ]
permissive
#include "stdafx.h" #include "latool.h" #include "memory.h" namespace ODER{ Mat4::Mat4(float mat[4][4]){ memcpy(m, mat, 16 * sizeof(float)); } Mat4::Mat4(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33){ m[0][0] = m00; m[0][1] = m01; m[0][2] = m02; m[0][3] = m03; m[1][0] = m10; m[1][1] = m11; m[1][2] = m12; m[1][3] = m13; m[2][0] = m20; m[2][1] = m21; m[2][2] = m22; m[2][3] = m23; m[3][0] = m30; m[3][1] = m31; m[3][2] = m32; m[3][3] = m33; } Mat4 Transpose(const Mat4& mat){ Mat4 m; for (int i = 0; i < 4; i++){ for (int j = 0; j < 4; j++){ m.m[i][j] = mat.m[j][i]; } } return m; } Mat4 Inverse(const Mat4& mat){ Mat4 m; float scaleSquareInverse = 1.0f; float inverse_mat_ij = 0.0; for (int j = 0; j < 3; j++){ scaleSquareInverse = 1.0f / (mat.m[0][j] * mat.m[0][j] + mat.m[1][j] * mat.m[1][j] + mat.m[2][j] * mat.m[2][j]); for (int i = 0; i < 3; i++){ inverse_mat_ij = mat.m[i][j] * scaleSquareInverse; m.m[j][i] = inverse_mat_ij;//inverse rotation and scale m.m[j][3] -= inverse_mat_ij*mat.m[i][3];//inverse translate } } return m; } Mat4::Mat4(const Quaternion &q){ float xx = q.v.x*q.v.x, yy = q.v.y*q.v.y, zz = q.v.z*q.v.z; float xy = q.v.x*q.v.y, xz = q.v.x*q.v.z, yz = q.v.y*q.v.z; float wx = q.w*q.v.x, wy = q.w*q.v.y, wz = q.w*q.v.z; m[0][0] = 1.0f - 2.0f*(yy + zz); m[0][1] = 2.0f*(xy + wz); m[0][2] = 2.0f*(xz - wy); m[0][3] = 0.0f; m[1][0] = 2.0f*(xy - wz); m[1][1] = 1.0f - 2.0f*(xx + zz); m[1][2] = 2.0f*(yz - wx); m[1][3] = 0.0f; m[2][0] = 2.0f*(xz + wy); m[2][1] = 2.0f*(yz - wx); m[2][2] = 1.0f - 2.0f*(xx + yy); m[2][3] = 0.0f; m[3][0] = 0.0f; m[3][1] = 0.0f; m[3][2] = 0.0f; m[3][3] = 1.0f; } Quaternion::Quaternion(const Mat4 &m){ float trace = m.m[0][0] + m.m[0][1] + m.m[0][2]; if (trace > 0.0f){ float s = sqrtf(trace + 1.0f); w = s / 2.0f; s = 0.5f / s; v.x = (m.m[2][1] - m.m[1][2])*s; v.y = (m.m[0][2] - m.m[2][0])*s; v.z = (m.m[1][0] - m.m[0][1])*s; } else{ int i = 0; if (m.m[1][1] > m.m[0][0]) i = 1; if (m.m[2][2] > m.m[i][i]) i = 2; float s = 0.f; switch (i){ case 0: s = sqrtf(m.m[0][0] - m.m[1][1] - m.m[2][2] + 1.0f); v.x = s*0.5f; if (s != 0.0f) s = 0.5f / s; w = (m.m[1][2] - m.m[2][1])*s; v.y = (m.m[0][1] + m.m[1][0])*s; v.z = (m.m[2][0] + m.m[0][2])*s; break; case 1: s = sqrtf(m.m[1][1] - m.m[0][0] - m.m[2][2] + 1.0f); v.y = s*0.5f; if (s != 0.0f) s = 0.5f / s; w = (m.m[2][0] - m.m[0][2])*s; v.x = (m.m[0][1] + m.m[1][0])*s; v.z = (m.m[2][1] + m.m[1][2])*s; break; case 2: s = sqrtf(m.m[2][2] - m.m[1][1] - m.m[0][0] + 1.0f); v.z = s*0.5f; if (s != 0.0f) s = 0.5f / s; w = (m.m[0][1] - m.m[1][0])*s; v.y = (m.m[2][0] + m.m[0][2])*s; v.z = (m.m[1][2] + m.m[2][1])*s; break; } } } SparseVector::SparseVector(SparseVector&& vec) { capability = vec.capability; size = vec.size; values = vec.values; indices = vec.indices; vec.capability = 0; vec.size = 0; vec.values = NULL; vec.indices = NULL; } SparseVector& SparseVector::operator=(SparseVector&& vec) { std::swap(size, vec.size); std::swap(capability, vec.capability); std::swap(values, vec.values); std::swap(indices, vec.indices); return *this; } void SparseVector::reallocSpace(size_t count) { Scalar *valuesTmp = (Scalar *)realloc(values, sizeof(Scalar) * count); if (valuesTmp == NULL) { valuesTmp = (Scalar *)malloc(sizeof(Scalar) * count); memcpy(valuesTmp, values, sizeof(Scalar) * size); } values = valuesTmp; int *indicesTmp = (int *)realloc(indices, sizeof(int) * count); if (indicesTmp == NULL) { indicesTmp = (int *)malloc(sizeof(int) * count); memcpy(indicesTmp, indices, sizeof(int) * size); } indices = indicesTmp; } FastSparseVector::FastSparseVector(int col) { column = col; indexIndicators = new int[column]; Initiation(indexIndicators, column); vector.Reserve(column + 1); vector.emplaceBack(-1, 0); } FastSparseVector::FastSparseVector(FastSparseVector&& vec): vector(std::move(vec.vector)) { column = vec.column; indexIndicators = vec.indexIndicators; vec.column = 0; vec.indexIndicators = NULL; } FastSparseVector& FastSparseVector::operator=(FastSparseVector&& vec) { std::swap(vector, vec.vector); std::swap(column, vec.column); std::swap(indexIndicators, vec.indexIndicators); return *this; } }
Java
UTF-8
312
2.953125
3
[]
no_license
package stringPrograms; import java.util.ArrayList; import java.util.List; public class StringContains { public static void main(String[] args) { List<String> cityName = new ArrayList<>(); cityName.add("Chennai Egmore"); for(String city: cityName) { System.out.println(city.contains("Egmore")); } } }
Python
UTF-8
1,284
2.6875
3
[]
no_license
#Logfile Parser from string import split from operator import itemgetter def parseline(line): try: arr=split(line, "z_*") print(arr) time=arr[0] module=arr[1] urgency=arr[2] message=arr[3] parsedtime=split(time, "|") return(parsedtime[0], parsedtime[1], parsedtime[2], module, urgency, message) except: return None Lines=[] def parsefile(filepath): filep=open(filepath, "r") filed=filep.read() for line in split(filed, "\n"): try: Foo=parseline(line) if Foo!=None: (h, m, s, mod, lvl, msg) = Foo Lines.append([h, m, s, mod, lvl, msg]) except: pass def sortbyUrgency(): foo=Lines sorted(foo, key=itemgetter(4)) print("\n"*10) for x in foo: print x return foo def printNice(lines): print("Typing") for line in lines: print(line[0]+":"+line[1]+":"+line[2]+" ("+line[3]+") "+line[4]+" - "+line[5]) def printListctl(lines, instance): for line in lines: instance.InsertStringItem(lines.index(line), "0"*(2-len(line[0]))+line[0]+":"+"0"*(2-len(line[1]))+line[1]+":"+"0"*(2-len(line[2]))+line[2]) instance.SetStringItem(lines.index(line), 1, line[4]) instance.SetStringItem(lines.index(line), 2, line[3]) instance.SetStringItem(lines.index(line), 3, line[5]) instance.SetItemData(lines.index(line), lines.index(line))
Java
UTF-8
1,113
2.203125
2
[]
no_license
package com.travel.buddy.coreproject.utils; import com.travel.buddy.coreproject.model.Interest; import com.travel.buddy.coreproject.model.UserProfile; import com.travel.buddy.coreproject.repository.InterestRepository; import com.travel.buddy.coreproject.utils.SlopeOne.SlopeOne; import org.springframework.beans.factory.annotation.Autowired; import java.util.HashMap; import java.util.Map; import java.util.Set; public class ModifyInterestDatabaseService { @Autowired private static InterestRepository interestRepository; public static void Update() { SlopeOne.prepareUpdate(); Map<UserProfile, HashMap<String, Double>> userInterests = SlopeOne.outputData; for(UserProfile user : userInterests.keySet()){ Interest interest = user.getInterest(); Set<String> interestsAsStringSet = userInterests.get(user).keySet(); Interest updatedInterest = GetUserInterestFromStringListHelper.getInterest(interestsAsStringSet); updatedInterest.setId(interest.getId()); interestRepository.save(updatedInterest); } } }
Python
UTF-8
357
2.9375
3
[ "MIT" ]
permissive
import jieba def get_seg_features(text): word_sentence = [] seg_sentence = [] for word in jieba.cut(text): word = word.lower() for ch in word: word_sentence.append(ch) seg_sentence.append(word) return word_sentence, seg_sentence def joint_output_str(sentence, i, j): return sentence[i:j + 1]
PHP
UTF-8
389
2.8125
3
[ "MIT" ]
permissive
<?php /** * * @author developer * */ class UserRepository extends BaseRepository{ private $_updateKeys = ['true_name', 'accounts', 'phone', 'e_mail']; public function save($id, $save_data) { $user = User::find($id); foreach ($save_data as $key => $value) { if (in_array($key, $this->_updateKeys)) { $user->$key = $value; } } return $user->save(); } }
SQL
UTF-8
475
3.09375
3
[]
no_license
create table hospital( reference_id number , name varchar(30) not null, age number not null, gender varchar(10) check ((gender='male' or gender='female')) not null , marital_status varchar(10) not null, phone_number number check ((phone_number>7000000000)or(phone_number<100000000000)) not null, disease_type varchar(30) not null, user_name varchar(20) , password varchar(20) ); create sequence h_name start with 100 increment by 1 select * from HOSPITAL
TypeScript
UTF-8
1,529
2.703125
3
[]
no_license
/// <reference types="node" /> import { StateKey, State, Fn, ReactEventHandlerKey, ReactEventHandlers, InternalConfig, InternalHandlers } from './types'; declare type GestureTimeouts = Partial<{ [stateKey in StateKey]: NodeJS.Timeout; }>; /** * The controller will keep track of the state for all gestures and also keep * track of timeouts, and window listeners. * * @template BinderType the type the bind function should return */ export default class Controller { config: InternalConfig; handlers: Partial<InternalHandlers>; state: State; timeouts: GestureTimeouts; private bindings; /** * Function ran on component unmount: cleans timeouts. */ clean: () => void; /** * Function run every time the bind function is run (ie on every render). * Resets the binding object */ resetBindings: () => void; /** * this.bindings is an object which keys match ReactEventHandlerKeys. * Since a recognizer might want to bind a handler function to an event key already used by a previously * added recognizer, we need to make sure that each event key is an array of all the functions mapped for * that key. */ addBindings: (eventNames: ReactEventHandlerKey | ReactEventHandlerKey[], fn: Fn) => void; /** * getBindings will return an object that will be bound by users * to the react component they want to interact with. */ getBindings: () => ReactEventHandlers; getBind: () => ReactEventHandlers; } export {};
Java
UTF-8
660
1.820313
2
[]
no_license
package com.honeywen.credit.modules.sys.web; import com.honeywen.credit.modules.sys.entity.SysUser; import com.honeywen.credit.modules.sys.service.SystemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @author wangwei * @date 2019/1/25 下午8:29 */ @RestController public class SystemController { @Autowired private SystemService systemService; @GetMapping("/user/list") public List<SysUser> findAllUser() { return systemService.findAllUser(); } }
Python
UTF-8
34
2.640625
3
[]
no_license
a = float(input()) * 2.54 print(a)
C++
UTF-8
1,044
2.53125
3
[]
no_license
#ifndef __I_FACADE__ #define __I_FACADE__ #include "gameStd.h" class IMediator; class Notification; class ICommand; class IProxy; class IFacade { public: virtual void notifyMediator(Notification& noti)=0; virtual void notifyCommand(Notification& noti)=0; virtual void registerCommand(const string& notificationName,const ICommand* command)=0; virtual void removeCommand(const string& notificationName)=0; virtual bool hasCommand(const string& notificationName)=0; virtual ICommand* getCommand(const string& name)=0; virtual void registerProxy(IProxy* proxy)=0; virtual IProxy* getProxy(const string& name)=0; virtual void removeProxy(const string& name)=0; virtual void registerMediator(IMediator* mediator)=0; virtual IMediator* getMediator(const string& mediatorName)=0; virtual bool hasMediator(const string& mediatorName)=0; virtual IMediator* removeMediator(const string& mediatorName)=0; protected: virtual void initModel()=0; virtual void initController()=0; virtual void initView()=0; }; #endif
Python
UTF-8
3,138
3.140625
3
[]
no_license
import Queue import abc import threading import Manager import time import binascii class CommunicationManager(Manager.Manager): def __init__(self): self.thread = threading.Thread(target=self.read) self.connected = False # queue holding the data self._incoming_messages = Queue.Queue(maxsize=20) self._outgoing_messages = Queue.Queue(maxsize=20) # tread for reading the serial port self._server = None super(CommunicationManager, self).__init__() @abc.abstractmethod def setup(self): pass @property def server(self): return self._server @server.setter def server(self, value): self._server = value def start(self): """ Starts the tread to read from the sensor. :return: """ self.connect() self.thread.start() def stop(self): """ Starts the tread to read from the sensor. :return: """ self.disconnect() def connect(self): """ Connect to the device. :return: """ self.connected = True def disconnect(self): """ Diconnect to the device. :return: """ self.connected = False @property def have_data(self): """ Check if there is data in the queue. :return: :rtype bool """ return not self._incoming_messages.empty() @abc.abstractmethod def read_port(self): pass def get_data(self): # type: () -> Queue.Queue """ Get reading from the queue. :return: :rtype array """ return self._incoming_messages def read(self): """ continually read the server :return: """ while 1: # only read if connected if self.connected: time.sleep(39 * 10 ** (-6)) raw_data = self.read_port() if raw_data is not None: if len(raw_data) > 162 and raw_data[0] == "X" and raw_data[1] == "O": #self._incoming_messages.put(raw_data) self.publisher.publish(raw_data) # publish the data #print self.parse(raw_data[153], raw_data[154]) @abc.abstractmethod def send(self, msg): pass ### REMOVE AFTER TESTING def parse(self, block1, block2): """ convers the bytes to a decimal value :param block1: byte 1 :param block2: byte 2 :type block1: byte :type block2: byte :return: """ a = self.binbits(int(binascii.hexlify(block1), 16), 8) b = self.binbits(int(binascii.hexlify(block2), 16), 8) c = 3.3*int('0b' + a[0:4] + b, 2) / 4095 return c def binbits(self, x, n): """Return binary representation of x with at least n bits""" bits = bin(x).split('b')[1] if len(bits) < n: ans = '0' * (n - len(bits)) + bits else: ans = bits return ans
Java
UTF-8
719
2.734375
3
[]
no_license
package com.company.arrays; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class FindLuckyIntegerInArrayTest { @Test void findLuckyWithAnswer3() { FindLuckyIntegerInArray luck = new FindLuckyIntegerInArray(); assertEquals(3, luck.findLucky(new int[]{1,2,3,6,5,3,3})); } @Test void findLuckyWithAll0() { FindLuckyIntegerInArray luck = new FindLuckyIntegerInArray(); assertEquals(-1, luck.findLucky(new int[]{0,0,0,0,0,0,0})); } @Test void findLuckyWithAll1() { FindLuckyIntegerInArray luck = new FindLuckyIntegerInArray(); assertEquals(-1, luck.findLucky(new int[]{1,1,1,1,1,1,1,1,1,1})); } }
Java
UTF-8
4,426
1.898438
2
[]
no_license
package com.constants; import java.io.File; import android.os.Environment; public class AppConstant { public static final String UPLOAD_MESSAGE_ACTION = "com.upload.uploadprogressbar"; public static final String UPLOAD_SUCCESS_MESSAGE = "com.upload.success"; public static final String UPLOAD_ERROR_MESSAGE = "com.upload.error"; public final static String serverUrl = "http://218.249.255.29:9080/nesdu-webapp/api/"; //公网服务器地址 // public final static String serverUrl = "http://192.168.8.112:8080/nesdu-webapp/api/"; //本机地址 // public final static String serverUrl = "http://59.64.176.73:8080/nesdu-webapp/api/"; // 网院 /** SD卡文件夹地址 */ public static final String BASE_DIR_CACHE = Environment .getExternalStorageDirectory() + File.separator + "mmqa" + File.separator + "cache";// 北邮内网服务器地址 /** SD卡文件夹地址 */ public static final String BASE_DIR_PATH = Environment .getExternalStorageDirectory() + File.separator + "mmqa" + File.separator + "temp"; /** wav文件地址 */ public static final String VOICE_PATH = BASE_DIR_PATH + File.separator + "mmqa.wav"; /** mp4文件地址 */ public static final String VIDEO_PATH = BASE_DIR_PATH + File.separator + "mmqa.mp4"; /** jpg卡文件地址 */ public static final String THUMB_PATH = BASE_DIR_PATH + File.separator + "mmqa.jpg"; /** jpg卡文件地址 */ public static final String IMAGE1_PATH = BASE_DIR_PATH + File.separator + "image1.jpg"; /** jpg卡文件地址 */ public static final String IMAGE2_PATH = BASE_DIR_PATH + File.separator + "image2.jpg"; /** jpg卡文件地址 */ public static final String IMAGE3_PATH = BASE_DIR_PATH + File.separator + "image3.jpg"; /** jpg卡文件地址 */ public static final String IMAGE4_PATH = BASE_DIR_PATH + File.separator + "image4.jpg"; /** jpg卡文件地址 */ public static final String IMAGE5_PATH = BASE_DIR_PATH + File.separator + "image5.jpg"; /** jpg卡文件地址 */ public static final String TEMP_PATH = BASE_DIR_PATH + File.separator + "imageTemp.jpg"; /**头像文件*/ public static final String USER_IMAGE = BASE_DIR_PATH + File.separator + "protrait.jpg"; /** APK文件名 */ public static final String APK_NAME = "mmqa.apk"; /** 拍摄图片的返回ID */ public static final int TAKE_PHOTO_ID = 0x1991; /** 取图片返回ID */ public static final int TAKE_PIC_ID = 0x1992; /** 取图片返回ID */ public static final int TAKE_VIDEO_ID = 0x1993; /** 取语音图片中图片返回ID */ public static final int TAKE_IAMGE_IV_ID = 0x1994; /** 取语音图片中拍照返回ID */ public static final int TAKE_CAMERA_IV_ID = 0x1996; /** 取语音图片中语音返回ID */ public static final int TAKE_VOICE_IV_ID = 0x1995; /** handler各种错误TAG */ public static final int HANDLER_HTTPSTATUS_ERROR = 1002; public static final int HANDLER_MESSAGE_NULL = 1001; public static final int HANDLER_MESSAGE_NORMAL = 1000; public static final int HANDLER_PUBLISH_SUCCESS = 1003; public static final int HANDLER_VERSION_UPDATE = 2001; public static final int HANDLER_APK_DOWNLOAD_PROGRESS = 2002; public static final int HANDLER_APK_DOWNLOAD_FINISH = 2003; public static final int HANDLER_UPLOAD_IMAGE = 3001; public static final int HANDLER_UPLOAD_VIDEO = 3002; public static final int HANDLER_UPLOAD_IMAGE_SUCCESS = 3003; public static final int HANDLER_UPLOAD_VIDEO_SUCCESS = 3004; public static final int PAGESIZE = 10; public static final int QVIDEOViewType = 11; public static final int AVIDEOViewType = 21; public static final int QIMAGEViewType = 12; public static final int AIMAGEViewType = 22; public static final int QVOICEViewType = 14; public static final int AVOICEViewType = 24; public static final int QIMAGEVOICEViewType = 13; public static final int AIMAGEVOICEViewType = 23; public static final int ATEXTViewType = 25; public interface Qiniu{ public static final String bucketName_img = "mmqa-img"; public static final String bucketName_aud = "mmqa-aud"; public static final String bucketName_vid = "mmqa-vid"; public static final String domain_img = "http://mmqa-img.qiniudn.com/"; public static final String domain_aud = "http://mmqa-aud.qiniudn.com/"; public static final String domain_vid = "http://mmqa-vid.qiniudn.com/"; } }
TypeScript
UTF-8
13,747
2.71875
3
[ "MIT" ]
permissive
/* The following applies to the code modifications The MIT License (MIT) Copyright (c) 2021 Florian Stamer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE */ import ICustomerOrder from "../../../GenericClasses/GenericSimulationClasses/Interfaces/ICustomerOrder"; import MsgLog from "../../../SystemManagement/MessengingSystem/MsgLog"; import ResourceV2 from "./ResourceV2"; import OrderV2 from "./OrderV2"; export default class ProductionControlV2 { /** * Estimates the shortest completion time for an order and a given amount of machines * @param machines * @param order * @returns */ estimateShortestCompletionTime(machines: ResourceV2[], order: OrderV2): number { let temp = order.dueDate; // save duedate for more robust solution order.dueDate = 0; //setze null um kürzeste Zeit zu bekommen let shortestTime = this.findSlotMinDelay(machines, order)[2]; //an 3-1 Position ist das plannedDate! order.dueDate = temp; return shortestTime; } /** * Plans an order into an amount of machines based on the minimum slack rule * @param machines * @param order * @returns */ planOrder(machines: ResourceV2[], order: OrderV2): ResourceV2 { let result = this.findSlotForOrder(machines, order) result[0].insertIntoQueueAndUpdate(order, result[1]); result[0].flagUsed = true; result[0].flagUsedKPI = true; return result[0]; } private findSlotForOrder(sort: ResourceV2[], order: OrderV2): [ResourceV2, number] { let chosenCapa: ResourceV2 | null = null; let qIndex = -1; //1. Find the second most unused machine //2.1. Sort order into queue and check if order can be produced in time //2.2. if not, got to the next machine with longer queue and test there //2.3 check for all following orders to be in time, if not go to 2.2, else finish //3. if order is not planned yet use most unused machine an force plan it into that queue //Sort queue by capacity sort.sort((MachineA, MachineB) => MachineA.getTotalDurationInQueue() - MachineB.getTotalDurationInQueue()); if (sort.length == 1)// Es gibt nur eine Machine, dann muss das da rein { chosenCapa = sort[0]; MsgLog.log(MsgLog.types.debug, "Only one machine| name: " + sort[0].parent.name, this, false, true) qIndex = this.checkSingleQueueNoDelay(sort[0], order)[1]; if (qIndex == -1) { qIndex = this.checkSingleQueueMinDelay(sort[0], order)[1]; } } else { [chosenCapa, qIndex] = this.findSlotNoDelay(sort, order); if (chosenCapa == null) { let plannedDate = 0; [chosenCapa, qIndex, plannedDate] = this.findSlotMinDelay(sort, order); } } MsgLog.log(MsgLog.types.debug, "Chosen machine name: " + chosenCapa!.parent.name + " machine ID: (" + chosenCapa!.machineID + ") total duration: " + chosenCapa!.getTotalDurationInQueue(), this, false, false) return [chosenCapa!, qIndex]; } private findSlotMinDelay(sort: ResourceV2[], order: OrderV2): [ResourceV2, number, number] { let chosenCapa: ResourceV2 | null = null; let qIndex = -1; let tempCapa: ResourceV2, tempqIndex: number, plannedDate: number = 0, tempPlannedDate: number = 0; for (let index = 0; index < sort.length; index++) //alles Maschinen dieses Mal { const single_queue = sort[index]; //s. Schritt 2.1 [tempCapa, tempqIndex, tempPlannedDate] = this.checkSingleQueueMinDelay(single_queue, order); if (chosenCapa == null || tempPlannedDate < plannedDate) { chosenCapa = tempCapa; qIndex = tempqIndex; plannedDate = tempPlannedDate; } } return [chosenCapa!, qIndex, plannedDate]; } private findSlotNoDelay(sort: ResourceV2[], order: OrderV2): [ResourceV2, number] { let chosenCapa: ResourceV2 | null = null; let qIndex = -1; for (let index = 1; index < sort.length; index++) { const single_queue = sort[index]; //s. Schritt 2.1 [chosenCapa, qIndex] = this.checkSingleQueueNoDelay(single_queue, order); if (chosenCapa != null) { break; }; } if (chosenCapa == null)//Sonderfall alle Maschinen ausgelastet, nutze die "geschonte" Maschine beim index = 0, falls möglich { [chosenCapa, qIndex] = this.checkSingleQueueNoDelay(sort[0], order); } return [chosenCapa!, qIndex]; } private checkSingleQueueMinDelay(single_queue: ResourceV2, order: OrderV2): [ResourceV2, number, number] { let queued_order; let next_order; if (single_queue.queue.length != 0) { for (let index = 0; index < single_queue.queue.length; index++) //suche die Stelle in dieser Schlange, an der einsortiert werden sollte { queued_order = single_queue.queue[index]; let tempPlan: number; if (index == 0) { if (single_queue.inMachining != undefined) { tempPlan = single_queue.inMachining.plannedDate + single_queue.getProdTime(order) } else { tempPlan = single_queue.parent.sim.time() + single_queue.getProdTime(order) } } else //Nur wenn es min. einen Vorgänger gibt { //Schau dir Eintrag vor dem betrachteten an, das ist der Vorgänger tempPlan = single_queue.queue[index - 1].plannedDate + single_queue.getProdTime(order) } //Prüfe, ob einschieben okay ist für alle nachfolgenden order in der queue let trigger = true; let planned = tempPlan; //Summierer, der in jeder Iterationschleife das Ende des vorherigen Auftrags anzeigt for (let index2 = index; index2 < single_queue.queue.length; index2++) { next_order = single_queue.queue[index2]; planned = planned + next_order.duration; if (planned > next_order.dueDate) { trigger = false; //Verletzung einer Verspätungsbedingung, setze trigger auf false, sodass einschieben verhindert wird break; //brich prüfung ab bzw. verlasse diese for schleife, wenn ein order due Date verletzt ist } } if (trigger)//Wenn trigger, dann war für alle nachfolgenden order okay, also einschieben und updaten { return [single_queue, index, tempPlan - (single_queue.parent.sim.time() + single_queue.getProdTime(order))]; } } let plannedDate = single_queue.queue[single_queue.queue.length - 1].plannedDate + single_queue.getProdTime(order); return [single_queue, single_queue.queue.length, plannedDate - (single_queue.parent.sim.time() + single_queue.getProdTime(order))] } else { let plannedDate = 0; if (single_queue.inMachining != undefined) { plannedDate = single_queue.inMachining.plannedDate + single_queue.getProdTime(order) } else { plannedDate = single_queue.parent.sim.time() + single_queue.getProdTime(order) } return [single_queue, single_queue.queue.length, plannedDate - (single_queue.parent.sim.time() + single_queue.getProdTime(order))] } } private checkSingleQueueNoDelay(single_queue: ResourceV2, order: OrderV2): [ResourceV2 | null, number] { let orderPlanned = false; if (single_queue.queue.length == 0) //Wenn queue leer ist, dann kann die Order direkt eingefügt werden { let plannedDate = 0; if (single_queue.inMachining != undefined) { plannedDate = single_queue.inMachining.plannedDate + single_queue.getProdTime(order) } else { plannedDate = single_queue.parent.sim.time() + single_queue.getProdTime(order) } if (plannedDate < order.dueDate) { return [single_queue, 0]; } else { return [null, -1]; } } else { for (let index2 = 0; index2 < single_queue.queue.length; index2++) //suche die Stelle in dieser Schlange, an der einsortiert werden sollte { const queued_order = single_queue.queue[index2]; if (queued_order.dueDate > order.dueDate) //Stelle gefunden, wo eingefügt werden muss { let tempPlan //Temporärer Zeitplan für order, wird gleich aktualisiertm wenn es einen Vorgänger in der queue gibt if (index2 != 0) //Nur wenn es min. einen Vorgänger gibt { //Schau dir Eintrag vor dem betrachteten an, das ist der Vorgänger tempPlan = single_queue.queue[index2 - 1].plannedDate + single_queue.getProdTime(order); //Produktionsendzeit des Vorgängers + Dauer des neuen Auftrags } else { if (single_queue.inMachining != undefined) { tempPlan = single_queue.inMachining.plannedDate + single_queue.getProdTime(order) } else { tempPlan = single_queue.parent.sim.time() + single_queue.getProdTime(order) } } if (tempPlan < order.dueDate) //Ist dieser temporäre Zeitplan für den aktuellen Auftrag okay? { //Prüfe, ob einschieben okay ist für alle nachfolgenden order in der queue let trigger = true; let planned = tempPlan; //Summierer, der in jeder Iterationschleife das Ende des vorherigen Auftrags anzeigt for (let index3 = index2; index3 < single_queue.queue.length; index3++) { const next_order = single_queue.queue[index3]; if (planned + next_order.duration > next_order.dueDate) { trigger = false; //Verletzung einer Verspätungsbedingung, setze trigger auf false, sodass einschieben verhindert wird break; //brich prüfung ab bzw. verlasse diese for schleife, wenn ein order due Date verletzt ist } planned = planned + next_order.duration; //Setze den Zeiger nun auf das virtuelle Ende des next_order für den darauf folgenden next_order } if (trigger)//Wenn trigger, dann war für alle nachfolgenden order okay, also einschieben und updaten { orderPlanned = true; //order konnte eingeplant werden //single_queue.insertIntoQueueAndUpdate(order, index2) return [single_queue, index2]; } break; } } } if (!orderPlanned && single_queue.queue[single_queue.queue.length - 1].plannedDate + single_queue.getProdTime(order) < order.dueDate) //sonderfall: Auftrag noch nicht eingeplant, aber kommt eventuell an das Ende der Schlange { let planned = single_queue.queue[single_queue.queue.length - 1].plannedDate + single_queue.getProdTime(order); //planned ist abschluss des letzten elements in der queue + order.duration if (planned < order.dueDate) { //single_queue.insertIntoQueueAndUpdate(order, single_queue.queue.length); return [single_queue, single_queue.queue.length]; } } } return [null, -1]; } }
Java
ISO-8859-1
1,719
3.25
3
[]
no_license
package de.stegemann.examples; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import java.util.HashSet; import java.util.Set; import org.junit.Test; public class PersonenEqualsTest { private final static Straen DEFAULT_STRASSE = new Straen("Test"); @Test public void personenMitEqualsVergleichen() throws Exception { Person person1 = new Person("Jan", DEFAULT_STRASSE); Person person2 = new Person("Arne", DEFAULT_STRASSE); assertNotEquals(person1, person2); } @Test public void identischePersonenSindEqual() throws Exception { Person person1 = new Person("Jan", DEFAULT_STRASSE); Person person2 = new Person("Jan", DEFAULT_STRASSE); assertEquals(person1, person2); } @Test public void filternVonPersonen() throws Exception { Person person1 = new Person("Arne", DEFAULT_STRASSE); Person person2 = new Person("Jan", DEFAULT_STRASSE); Person person3 = new Person("Jan", DEFAULT_STRASSE); Set<Person> allePersonen = new HashSet<>(); allePersonen.add(person1); allePersonen.add(person2); allePersonen.add(person3); assertEquals(2, allePersonen.size()); assertTrue(allePersonen.contains(person1)); assertTrue(allePersonen.contains(person2)); assertTrue(allePersonen.contains(person3)); assertTrue(allePersonen.contains(new Person("Arne", DEFAULT_STRASSE))); assertFalse(allePersonen.contains(new Person("Dieter", DEFAULT_STRASSE))); } @Test public void personHatDieKorrekteStrasse() throws Exception { Person testPerson = new Person("Jan", DEFAULT_STRASSE); assertEquals(DEFAULT_STRASSE, testPerson.getStrasse()); } }
Python
UTF-8
2,352
2.71875
3
[]
no_license
import math import re from pytv import Shows, Show as TvShow from pytv.tvmaze import ApiError, get_updates from .models import Show # keys that match the pattern are added by the library pytv excluding them # allows **dict dump into Show model default_pattern = r"_url|_list|id|type|next|_links" def dict_data(show, pattern=default_pattern): """Filters the keys in vars(show) so it matches the model :param str pattern: regex pattern to filter un wanted keys :param show: pytv.tvmaze Show object :return: dict of class with un needed values filtered """ return {k: v for k, v in vars(show).items() if not re.search(pattern, k)} def save_show(show): """Save show to db""" return Show.objects.get_or_create( show_id=show.show_id, show_type=show.type, links=show._links, **dict_data(show) ) def save_shows(page=0): """Gets show data from api and stores it locally""" try: shows = Shows(page=page) except ApiError as e: raise e else: for show in shows.shows: save_show(show) else: save_shows(page + 1) def resume_save_shows(): """Start saving shows from the last page""" if Show.objects.count(): # resume at last page page = int(math.floor(Show.objects.last().show_id / 250)) save_shows(page) else: # start at page 0 save_shows() def sync_data(): """Syncs api show data to local show data""" data = get_updates() for show_id, update_time, in data.items(): try: show = Show.objects.get(show_id=show_id) except Show.DoesNotExist: # index missing show save_show(TvShow(show_id=show_id)) else: if int(show.updated) != update_time: # compare values and update needed show_data = TvShow(show_id=show_id) if show_data.type != show.show_type: show.show_type = show_data.type if show_data._links != show.links: show.links = show_data._links for key in dict_data(TvShow(show_id=1)).keys(): if getattr(show_data, key) != getattr(show, key): setattr(show, key, getattr(show_data, key)) show.save()
Markdown
UTF-8
1,070
2.765625
3
[ "MIT" ]
permissive
<h1 dir="rtl">ضم الملك عبدالعزيز الأحساء .</h1> <h5 dir="rtl">العام الهجري: 1331 الشهر القمري: جمادى الأولى العام الميلادي: 1913</h5> <p dir="rtl">بدأ الملك عبدالعزيز بالاستعداد في القيام بدخول الأحساء فاتفق مع بعض كبار رجالات أسر الأحساء في تنفيذ عملية الفتح. غادر الملك عبدالعزيز الرياض بقواته إلى الأحساء ووصل الرقيقة ومعه 600 جندي ثم وصل الكوت من الناحية الغربية ثم اجتاز أسوار المدينة بعد أن فاجأ الحامية التركية التي سرعان ما أذعنت له بالاستسلام ثم أجلاها إلى البحرين، ولقي عبدالعزيز ترحيب السكان به، ورغم معرفة الملك عبدالعزيز موقف بريطانيا الرافض لضمه الأحساء إلا أنه لم يثنه ذلك من عزمه على دخولها.</p></br>
C#
UTF-8
3,483
2.75
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ConsoleApp5 { class GameLogic { const int MOVE_SIZE = 5; Timer t = new Timer(); public List<Coordinate> Snake = new List<Coordinate>(); public Coordinate food = new Coordinate(); public int max_pos_x; public int max_pos_y; Random rand = new Random(); public GameLogic(int width, int height) { max_pos_x = width; max_pos_y = height; t.Interval = 50; t.Tick += (ob, args) => Move(); t.Start(); } public void Move() { for (int i = Snake.Count - 1; i >= 0; i--) { if (i == 0) { switch (Settings.direction) { case Direction.up: Snake[i].pos_y-= MOVE_SIZE; break; case Direction.down: Snake[i].pos_y += MOVE_SIZE; break; case Direction.left: Snake[i].pos_x -= MOVE_SIZE; break; case Direction.right: Snake[i].pos_x += MOVE_SIZE; break; default: break; } } //int max_pos_x = Background.Size.Width; //int max_pos_y = Background.Size.Height; if (Snake[i].pos_x < 0 || Snake[i].pos_y < 0 || Snake[i].pos_x > max_pos_x || Snake[i].pos_y > max_pos_y) Die(); for (int j = 1; j < Snake.Count; j++) { if (Snake[i].pos_x == Snake[j].pos_x || Snake[i].pos_y == Snake[j].pos_y) Die(); } if (Snake[i].pos_x >= food.pos_x- Settings.Width && Snake[i].pos_x <= food.pos_x + Settings.Width && Snake[i].pos_y >= food.pos_y - Settings.Height && Snake[i].pos_y <= food.pos_y + Settings.Height) Eat(); else { Snake[i].pos_x = Snake[i].pos_x; Snake[i].pos_y = Snake[i].pos_y; } } } public void Die() { Settings.GameOwer = true; } public void Eat() { Coordinate body = new Coordinate { pos_x = Snake[Snake.Count - 1].pos_x, pos_y = Snake[Snake.Count - 1].pos_y }; Snake.Add(body); Settings.Score += Settings.Points; GenerateFood(); } public void GenerateFood() { food = new Coordinate { pos_x = rand.Next(0, max_pos_x), pos_y = rand.Next(0, max_pos_y) }; } public void StartGame(int startX = 150, int startY = 50) { // Form1.label1.Visible = false; // new Settings(); Snake.Clear(); Coordinate head = new Coordinate { pos_x = startX, pos_y = startY }; Snake.Add(head); GenerateFood(); } } }
Go
UTF-8
114
2.546875
3
[]
no_license
package utils import "strconv" // ToInt ... func ToInt(str string) int { i, _ := strconv.Atoi(str) return i }
C#
UTF-8
1,990
2.578125
3
[]
no_license
using UnityEngine; using UnityEngine.Events; using System.Collections; using System.Collections.Generic; [System.Serializable] public class SourceEvent : UnityEvent<GameObject> { } public class EventManager : MonoBehaviour { private Dictionary <string, SourceEvent> eventDictionary; private static EventManager eventManager; public static EventManager instance { get { if (!eventManager) { eventManager = FindObjectOfType (typeof (EventManager)) as EventManager; if (!eventManager) { Debug.LogError ("There needs to be one active EventManger script on a GameObject in your scene."); } else { eventManager.Init (); } } return eventManager; } } void Init () { if (eventDictionary == null) { eventDictionary = new Dictionary<string, SourceEvent>(); } } public static void StartListening (string eventName, UnityAction<GameObject> listener) { SourceEvent thisEvent = null; if (instance.eventDictionary.TryGetValue (eventName, out thisEvent)) { thisEvent.AddListener (listener); } else { thisEvent = new SourceEvent(); thisEvent.AddListener (listener); instance.eventDictionary.Add (eventName, thisEvent); } } public static void StopListening (string eventName, UnityAction<GameObject> listener) { if (eventManager == null) return; SourceEvent thisEvent = null; if (instance.eventDictionary.TryGetValue (eventName, out thisEvent)) { thisEvent.RemoveListener (listener); } } public static void TriggerEvent (GameObject source , string eventName) { SourceEvent thisEvent = null; if (instance.eventDictionary.TryGetValue (eventName, out thisEvent)) { thisEvent.Invoke (source); } } public static string FormateEventName (GameObject source, string param) { return source.name + "-" + param; } public static string FormateEventName (GameObject source, string param1, string param2) { return source.name + "-" + param1 + "-" + param2; } }
Python
UTF-8
1,222
2.734375
3
[]
no_license
import time import giphy_client from giphy_client.rest import ApiException from pprint import pprint import webbrowser def gifGenerator(txt, results): # create an instance of the API class api_instance = giphy_client.DefaultApi() api_key = 'dc6zaTOxFJmzC' # str | Giphy API Key. q = txt # str | Search query term or prhase. limit = results # int | The maximum number of records to return. (optional) (default to 25) offset = 0 # int | An optional results offset. Defaults to 0. (optional) (default to 0) lang = 'en' # str | Specify default country for regional content; use a 2-letter ISO 639-1 country code. See list of supported languages <a href = \"../language-support\">here</a>. (optional) fmt = 'json' # str | Used to indicate the expected response format. Default is Json. (optional) (default to json) try: # Search Endpoint api_response = api_instance.gifs_search_get(api_key, q, limit=limit, offset=offset, lang=lang, fmt=fmt) x = api_response.data for gif in x: y = gif webbrowser.open(y.images.downsized.url) except ApiException as e: print("Exception when calling DefaultApi->gifs_search_get: %s\n" % e)
C
UTF-8
1,083
3.75
4
[]
no_license
//***Here c is a constant for (int i = 1; i <= c; i++) { a += 5; } //***incremented / decremented by a constant amount for (int i = 1; i <= n; i += c) { } for (int i = n; i > 0; i -= c) { } //***divided / multiplied by a constant amount for (int i = 1; i <=n; i += c) { for (int j = 1; j <=n; j += c) { // some O(1) expressions } } for (int i = n; i > 0; i -= c) { for (int j = i+1; j <=n; j += c) { // some O(1) expressions } } //***variables is reduced / increased exponentially by a constant amount // Here c is a constant greater than 1 - logN - 1 c c2 c3 for (int i = 2; i <=n; i = pow(i, c)) { // some O(1) expressions } //Here fun is sqrt or cuberoot or any other constant root for (int i = n; i > 1; i = fun(i)) { // some O(1) expressions } //***sum of time complexities of individual loops for (int i = 1; i <=m; i += c) { // some O(1) expressions } for (int i = 1; i <=n; i += c) { // some O(1) expressions } Time complexity of above code is O(m) + O(n) which is O(m+n) If m == n, the time complexity becomes O(2n) which is O(n).
Java
UTF-8
1,775
2.3125
2
[]
no_license
package com.month.controller; import com.month.domain.member.Member; import com.month.domain.member.MemberCreator; import com.month.domain.member.MemberRepository; import com.month.exception.ConflictException; import com.month.type.session.MemberSession; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Profile; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpSession; import static com.month.exception.type.ExceptionDescriptionType.MEMBER; import static com.month.type.session.SessionConstants.LOGIN_SESSION; // TODO 프론트와 인증 연동후 삭제하기 (배포시 ?) @Profile("local") @RequiredArgsConstructor @RestController public class TestController { private final HttpSession httpSession; private final MemberRepository memberRepository; @GetMapping("/test-auth") public String testAuth() { String email = "test@test.com"; Member member = memberRepository.findMemberByEmail(email); if (member == null) { member = memberRepository.save(MemberCreator.create(email, "name", null, "uid")); } httpSession.setAttribute(LOGIN_SESSION, MemberSession.of(member.getId())); return httpSession.getId(); } @GetMapping("/test-auth/custom") public String testAuth(@RequestParam String email) { if (memberRepository.findMemberByEmail(email) != null) { throw new ConflictException("이미 존재하는 멤버", MEMBER); } Member member = memberRepository.save(MemberCreator.create(email, "테스트 계정", null, email + "uid")); httpSession.setAttribute(LOGIN_SESSION, MemberSession.of(member.getId())); return httpSession.getId(); } }
C++
UTF-8
2,917
3.625
4
[]
no_license
#include "Collision.h" #include <cmath> /** * Simple collision detection. */ /** * @return Whether two SDL_Rects collided. * @param a_ , b_ : The rectangles to check. */ bool Collision::rectsCollided(const SDL_Rect& firstRectangle, const SDL_Rect& secondRectangle){ // Calculate the sides of rect A. const int leftFirstRectangle = firstRectangle.x; const int rightFirstRectangle = firstRectangle.x + firstRectangle.w; const int topFirstRectangle = firstRectangle.y; const int bottomFirstRectangle = firstRectangle.y + firstRectangle.h; // Calculate the sides of rect B. const int leftSecondRectangle = secondRectangle.x; const int rightSecondRectangle = secondRectangle.x + secondRectangle.w; const int topSecondRectangle = secondRectangle.y; const int bottomSecondRectangle = secondRectangle.y + secondRectangle.h; // If any of the sides from A are outside of B. if(bottomFirstRectangle <= topSecondRectangle || topFirstRectangle >= bottomSecondRectangle || rightFirstRectangle <= leftSecondRectangle || leftFirstRectangle >= rightSecondRectangle){ return false; } // If none of the sides from A are outside B. else{ return true; } } /** * @return The side (RectangleSide) which two SDL_Rects collided on. * @param a_ , b_ : The rectangles to check. */ Collision::RectangleSide Collision::rectsCollidedSide(const SDL_Rect& firstRectangle, const SDL_Rect& secondRectangle){ const double width = 0.5 * (firstRectangle.w + secondRectangle.w); const double height = 0.5 * (firstRectangle.h + secondRectangle.h); const double centerFirstRectangleOnX = firstRectangle.x + (firstRectangle.w / 2); const double centerFirstRectangleOnY = firstRectangle.y + (firstRectangle.h / 2); const double centerSecondRectangleOnX = secondRectangle.x + (secondRectangle.w / 2); const double centerSecondRectangleOnY = secondRectangle.y + (secondRectangle.h / 2); const double dx = centerFirstRectangleOnX - centerSecondRectangleOnX; const double dy = centerFirstRectangleOnY - centerSecondRectangleOnY; if (abs(dx) <= width && abs(dy) <= height){ // collision is calculated here. const double relativeWidth = width * dy; const double relativeHeight = height * dx; if (relativeWidth > relativeHeight){ if (relativeWidth > -relativeHeight){ return RectangleSide::TOP; } else{ return RectangleSide::LEFT; } } else{ if (relativeWidth > -relativeHeight){ return RectangleSide::RIGHT; } else{ return RectangleSide::BOTTOM; } } } else{ return RectangleSide::NONE; } }
PHP
UTF-8
1,779
2.609375
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; /** * This is the model class for table "fault_rate_forecast_data". * * @property integer $fault_rate_forecast_data_id * @property integer $fault_rate_forecast_id * @property string $date * @property string $sales_date * @property integer $sales_count * @property string $fault_rate_1 * @property string $fault_rate_2 * @property string $fault_rate_3 * * @property FaultRateForecast $faultRateForecast */ class FaultRateForecastData extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'fault_rate_forecast_data'; } /** * @inheritdoc */ public function rules() { return [ [['fault_rate_forecast_id', 'sales_count', 'fault_rate_1', 'fault_rate_2', 'fault_rate_3'], 'required'], [['fault_rate_forecast_id', 'sales_count'], 'integer'], [['date', 'sales_date'], 'safe'], [['fault_rate_1', 'fault_rate_2', 'fault_rate_3'], 'number'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'fault_rate_forecast_data_id' => 'Fault Rate Forecast Data ID', 'fault_rate_forecast_id' => 'Fault Rate Forecast ID', 'date' => 'Date', 'sales_date' => 'Sales Date', 'sales_count' => 'Sales Count', 'fault_rate_1' => 'Fault Rate 1', 'fault_rate_2' => 'Fault Rate 2', 'fault_rate_3' => 'Fault Rate 3', ]; } /** * @return \yii\db\ActiveQuery */ public function getFaultRateForecast() { return $this->hasOne(FaultRateForecast::className(), ['product_id' => 'fault_rate_forecast_id']); } }
Markdown
UTF-8
7,177
2.984375
3
[]
permissive
## 术语 - Advertiser:广告主,花钱做广告的人 - Publisher:发布者 - Creative:一般指实际被展示出去的图/视频 - Impression:Creative一次就是一个Impression - Click:点击 - Conversion / Action:转化,点击户的后续行为 - CTR: 点击率, click / impression - IR / CR:转化率 action / click - DAU:日活 - MAU:月活 - ARPU:平均用户收入 - PV:日阅览量或者点击量 - UV:独立访客数 ### 售卖术语 - CPM:按展示付费 - CPC:按点击付费 - CPA:按行为付费 - CPS:按销售付费 - CPT:按时常付费 以流量主的角度,对比各售卖方式的收益,假设展示量1,000,000次: ``` CPM售卖:1000CPM * 15元/CPM = 15000元 CPC售卖:1,000,000 * 3%CTR * 0.3元/C = 9000元 CPA售卖:1,000,000 * 3%CTR * 2%CR * 8元/A = 4800元 ``` ## 交易 移动广告一般使用 **RTB** 交易,也称实时竞价,特点为: 1. 当用户打开流量的载体(App或Wap站点)时,广告位要显示的东西还尚未确定,只有当竞价结束的时候,才会最终确定实际被展示的内容(Creative) 2. 竞价时间非常短,一般在 100ms 内,对参与的各方技术要求很高 3. 完全以 CPM 计价 RTB的优势在于: 1. 很好地匹配流量的需求和供给 2. 充分利用长尾流量 3. 通过RTB可以很容易买到世界各个地区的流量,打破地域限制 ### RTB中的角色 - DSP: Demand Side Platform, 需求方平台,需求方平台可以视为广告主的集合,DSP意味着可以把很多广告主的预算放到自己的平台来投放广告,对销售队伍能力要求高 - SSP: Supply Side Platform,供给方平台,一般会有自己的SDK并与许多APP的开发者合作,SSP供给的商品就是展示的机会 - Ad Exchange: 同时连接大量的DSP和SSP,并让其之间沟通 - DMP:Data Management Platform,数据提供平台。对于DSP而言,从SSP处获得的信息不足以支撑DSP作出决策,DSP会从DMP购买一些数据。一般而言,DMP会标识用户并有对应的用户标签 #### 没有Ad Exchange的一次交易 1. APP有展示机会 2. SSP通知DSP竞价,各个DSP相互之间不知道价格 3. SSP选取胜利者DSP 4. DSP只需支付第二高的出价,并进行展示 #### Ad Exchange的交易 有Exchange时,SSP也将Exchange视为一个DSP,DSP将Exchange也视为一个SSP。对于Exchange本身,Exchange把从SSP收到的Bid Request发给DSP,然后从DSP收到Response,从中选出胜者的价格再向SSP去竞价。 如此能达到纳什均衡。(整体来看,这过程类似拍卖) ![Ad Exchange模式图](https://pic1.zhimg.com/v2-e775687d9e9b9917605c463d9dcb48bc_r.jpg) #### RTB其他 其中的难点在于: 1. 数据量大 2. 对延迟要求高 劣势在于: 1. 传统行业的广告主对RTB较陌生,并不一定能够接受纯粹的CPM 2. 大多是长尾流量 ### RTB 如何套利 RTB按照CPM交易,假设广告主按照CPA付费,5元共买一个APP新增安装,如果我可以花10元买1000个展示,点击率为10%,安装率为3%。则可以从广告主哪里挣到15元,展示购买为10元,这样就实现了套利 ## 常见广告类型 ### Banner广告 ![Banner广告参考](https://pic2.zhimg.com/80/f5193ec11acb7015f50e8c145bce6bf1_hd.jpg) 收益较高,一般出现在底部或顶部,短小精悍,重点突出。以CPC结算为主,价格浮动大,收益较为平稳。有时候因为与所在应用展现形式不匹配而影响用户体验 ### 插屏广告 ![插屏广告参考](https://pic1.zhimg.com/80/a30171b09cc8f8daf145c2d223b671a3_hd.jpg) 相对于Banner更大气美观,CTR和CR也更高,冲击力更强,是比较有效的精准广告推广形式。CPM、CPC、CPI都有。一般在游戏过关或暂时时弹出,易误点,比较影响用户体验。 ### 开屏广告 ![开屏广告参考](https://pic4.zhimg.com/80/a34c1fd21b81929a11cf79e293c2a035_hd.jpg) 开屏广告实际上和插屏差别不大,他们出现的时机决定了他们的不同。在APP打开时,出现3~5妙,独占。广告效果最大化,收益高,用户在阅览广告没有其他干扰,主要适用于品牌广告 ### 积分墙 ![积分墙产考](https://pic2.zhimg.com/80/v2-059b95e3998293d7f6683db98a2ee33b_hd.jpg) 收益高,通过在应用内展示各种积分任务(下载、注册、跳表等)以换取各种道具、成就等。一般为CPA。积分墙容易引起用户反感。 ### 信息流广告 ![信息流参考](https://pic3.zhimg.com/80/7089491b3bd3902243cd1d9167f9fb83_hd.jpg) 收益浮动大,依赖于内容。不容易被辨认 ### 原生广告 ![原生广告参考](https://pic1.zhimg.com/80/v2-1cf8f95e2fcd0d75d976894a65b7960d_hd.jpg) 收益高,广告内容化,通过精准投放,实现“广告是一条有价值的信息的效果”,而不是一条令人厌烦的广告。不难发现原生广告可以衍生出其他广告形式 ## 趋势 [此段摘自](https://www.zhihu.com/question/21696664/answer/575881364) 一、在2018年视频移动化、资讯视频化和视频社交化的趋势带动下,短视频营销正在成为新的品牌营销风口,短视频形式成为移动广告最火热的形式之一。 二、激励式视频广告成为游戏厂商“最爱”奖励性视频广告是目前手游行业普遍采用的移动广告形式,游戏玩家通过观看广告获得相应奖励。根据第三方数据显示,大约60%的玩家乐意通过看视频来获取虚拟奖励,奖励式视频广告的CTR高于其他的游戏投放形式。对于游戏厂商来说,不管是流量变现还是广告投放上,奖励性视频广告依然是主要的形式。 ![激励视屏奖励形式](https://pic4.zhimg.com/80/v2-0bd670ce2203cc6c406f78710798a85c_hd.jpg) 三、信息流广告增长迅猛 凭借“AI+搜索”的信息流广告优势,百度信息流广告增长迅猛。 四、广告内容化逐渐成为常态 随着硬广和软广的边界正变得越来越模糊,广告内容化已成为不可逆的营销常态,有条件的媒体开始布局私有ADX平台。通过足够大的用户数据,足够的用户标签,足够大的UGC让信息流跑起来。广告主和代理可以对运营能力布局,研究用户心理,优化素材。 五、社交广告稳健增长 全球范围内,社交网络营销整体呈现快速增长的趋势,增加移动社交媒体的广告投入已成为广告主的普遍选择。信息流、视频广告、H5广告形式则是关注度最高的几种形式。甚至可以预料“社交+音乐”,“社交+短视频”等新玩法将会走上营销的舞台。 六、苹果搜索广告将入华,游戏类App更偏好ASM ![ASM游戏类型分布](https://pic3.zhimg.com/80/v2-3b378a3888ca77f267cac69e9732a425_hd.jpg) 从上图中可得知,投放比例排名依次是游戏、教育、工具、娱乐、摄影与录像等,其中,游戏类App投放竞价广告比例最高,游戏类应用对ASM更具偏好。 七、2018年,OTT广告将会迎来大增长 ## 参考 [移动广告入门,这一篇就够了](https://zhuanlan.zhihu.com/p/24674479)
JavaScript
UTF-8
939
3.59375
4
[]
no_license
const daysE1 = document.getElementById('days'); const hoursE1 = document.getElementById('hours'); const minsE1 = document.getElementById('mins'); const secondsE1 = document.getElementById('seconds'); const newYears = "1 jan 2022"; function countdown() { const newYearsDate=new Date(newYears); const currentDate = new Date(); const totalSeconds =(newYearsDate - currentDate) / 1000; const days = Math.floor(totalSeconds / 3600 /24); const hours = Math.floor(totalSeconds / 3600 ) % 24; const mins = Math.floor(totalSeconds / 60) % 60; const seconds = Math.floor(totalSeconds ) % 60; daysE1.innerHTML = timeFormat(days); hoursE1.innerHTML = timeFormat(hours); minsE1.innerHTML = timeFormat(mins); secondsE1.innerHTML = timeFormat(seconds); } function timeFormat(time) { return time < 10 ? `0${time}` : time; } countdown(); setInterval(countdown, 1000 );
Shell
UTF-8
162
2.90625
3
[]
no_license
#!/bin/sh for pair in $(printenv) do var=$(echo "$pair" | cut -d= -f1) value=$(echo "$pair" | cut -d= -f2) sed -i "s|{{ $var }}|$value|g" "$1" done
C#
UTF-8
1,478
2.53125
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Seven.BLL; namespace Seven.UI { public partial class CreateCategory : Form { public CreateCategory() { InitializeComponent(); } BLLCategory blc = new BLLCategory(); int categoryid = 0; private void button1_Click(object sender, EventArgs e) { int i = blc.CreateCategory(txtCategoryName.Text); MessageBox.Show("Category" + " " + txtCategoryName.Text + " is Saved"); // MessageBox.Show("New category is entered", "Success", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } private void btnUpdate_Click(object sender, EventArgs e) { } private void btnDelete_Click(object sender, EventArgs e) { // int i=blc.DeleteCategory(dataGridView1.r) } private void CreateCategory_Load(object sender, EventArgs e) { LoadCategory(); } private void LoadCategory() { DataTable dt = blc.GetAllCategory(); dataGridView1.DataSource = dt; } private void dataGridView1_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { } } }
Shell
UTF-8
587
3.015625
3
[]
no_license
#!/bin/bash -e # usage: init.sh 1.2.3.4 # more info: https://github.com/kylemanna/docker-openvpn/blob/master/docs/docker-compose.md HOST=${1:-$(echo $DOCKER_HOST | awk -F'[/:]' '{print $4}')} # first arg or docker host from env var echo "Initializing config for host '$HOST'" docker-compose run --rm openvpn ovpn_genconfig -u udp://$HOST docker-compose run --rm openvpn bash -c 'touch /etc/openvpn/vars && yes | ovpn_initpki nopass' docker-compose run --rm openvpn easyrsa build-client-full anon nopass docker-compose run --rm openvpn ovpn_getclient anon > vpn.ovpn docker-compose up -d
Java
UTF-8
11,621
3.453125
3
[]
no_license
//*******1*********2*********3*********4*********5*********6*********7*********8 package ics240.assignment4; /****************************************************************************** * This class is a homework assignment; A DoubleLinkedSeq</CODE> is a collection * of double</CODE> numbers. The sequence can have a special "current element," * which is specified and accessed through four methods that are not available * in the sequence class (start, getCurrent, advance and isCurrent). * * <dl> * <dt><b>Limitations:</b> Beyond Int.MAX_VALUE</CODE> elements, the size</CODE> * method does not work. * * <dt><b>Note:</b> * <dd> * This file contains only blank implementations ("stubs") because this is a * Programming Project for my students. * * <dt><b>Outline of Java Source Code for this class:</b> * <dd> * <A HREF="../../../../edu/colorado/collections/DoubleLinkedSeq.java"> * http://www * .cs.colorado.edu/~main/edu/colorado/collections/DoubleLinkedSeq.java </A> * </dl> * * * @version Jan 24, 1999 ******************************************************************************/ public class DoubleLinkedSeq implements Cloneable { private int nodeCount = -1; private DoubleNode headNode = null; private DoubleNode tailNode = null; private DoubleNode preCursorNode = null; private DoubleNode cursorNode = null; // private static final double EMPTY_VALUE = -.0000001; /** * Initialize an empty sequence. * * @param - none <dt><b>Postcondition:</b> * <dd> * This sequence is empty. **/ public DoubleLinkedSeq() { this.nodeCount = 0; } public DoubleLinkedSeq(int a_initSize) { this(); } /** * This method sets the initial value * * @param a_initial_value */ private void initNodes(double a_initial_value) { headNode = new DoubleNode(a_initial_value, null); cursorNode = this.headNode; tailNode = headNode; preCursorNode = null; } /** * Add a new element to this sequence, after the current element. * * @param element * </CODE> the new element that is being added <dt> * <b>Postcondition:</b> * <dd> * A new copy of the element has been added to this sequence. If * there was a current element, then the new element is placed * after the current element. If there was no current element, * then the new element is placed at the end of the sequence. In * all cases, the new element becomes the new current element of * this sequence. * @exception OutOfMemoryError * Indicates insufficient memory for a new node. **/ public void addAfter(double a_val) { if (headNode == null) { initNodes(a_val); } else { this.cursorNode.addNodeAfter(a_val); this.cursorNode = this.cursorNode.getLink(); this.tailNode = this.cursorNode; } this.nodeCount++; } /** * Add a new element to this sequence, before the current element. * * @param element * </CODE> the new element that is being added <dt> * <b>Postcondition:</b> * <dd> * A new copy of the element has been added to this sequence. If * there was a current element, then the new element is placed * before the current element. If there was no current element, * then the new element is placed at the start of the sequence. * In all cases, the new element becomes the new current element * of this sequence. * @exception OutOfMemoryError * Indicates insufficient memory for a new node. **/ public void addBefore(double a_val) { if (headNode == null) { initNodes(a_val); } else { if (this.preCursorNode == null) { // This means its a new-ish list this.headNode = new DoubleNode(a_val, this.headNode); this.preCursorNode = this.headNode; } else { this.preCursorNode.addNodeAfter(a_val); this.cursorNode = this.preCursorNode.getLink(); } } this.nodeCount++; } /** * Place the contents of another sequence at the end of this sequence. * * @param addend * </CODE> a sequence whose contents will be placed at the end of * this sequence <dt><b>Precondition:</b> * <dd> * The parameter, addend</CODE>, is not null. * <dt><b>Postcondition:</b> * <dd> * The elements from addend</CODE> have been placed at the end of * this sequence. The current element of this sequence remains * where it was, and the addend</CODE> is also unchanged. * @exception NullPointerException * Indicates that addend</CODE> is null. * @exception OutOfMemoryError * Indicates insufficient memory to increase the size of this * sequence. **/ public void addAll(DoubleLinkedSeq addend) { this.end(); for (int i = 0; i < addend.size(); i++) { this.addAfter(addend.getElementAtIndex(i)); } } /** * Move forward, so that the current element is now the next element in this * sequence. * * @param - none <dt><b>Precondition:</b> * <dd> * isCurrent()</CODE> returns true. * <dt><b>Postcondition:</b> * <dd> * If the current element was already the end element of this * sequence (with nothing after it), then there is no longer any * current element. Otherwise, the new element is the element * immediately after the original current element. * @exception IllegalStateException * Indicates that there is no current element, so * advance</CODE> may not be called. **/ public void advance() { if (this.cursorNode == null) { throw new IllegalStateException("No more room to advance"); } else { this.preCursorNode = this.cursorNode; this.cursorNode = this.cursorNode.getLink(); } } /** * Generate a copy of this sequence. * * @param - none * @return The return value is a copy of this sequence. Subsequent changes * to the copy will not affect the original, nor vice versa. Note * that the return value must be type cast to a * DoubleLinkedSeq</CODE> before it can be used. * @exception OutOfMemoryError * Indicates insufficient memory for creating the clone. **/ public Object clone() { // Clone a DoubleLinkedSeq object. return this.clone(); } /** * Create a new sequence that contains all the elements from one sequence * followed by another. * * @param s1 * </CODE> the first of two sequences * @param s2 * </CODE> the second of two sequences <dt><b>Precondition:</b> * <dd> * Neither s1 nor s2 is null. * @return a new sequence that has the elements of s1</CODE> followed by the * elements of s2</CODE> (with no current element) * @exception NullPointerException. Indicates * that one of the arguments is null. * @exception OutOfMemoryError * Indicates insufficient memory for the new sequence. **/ public static DoubleLinkedSeq catenation(DoubleLinkedSeq s1, DoubleLinkedSeq s2) { int finalSize = s1.size() + s2.size(); DoubleLinkedSeq theReturn = new DoubleLinkedSeq(finalSize); theReturn.addAll(s1); theReturn.addAll(s2); return theReturn; } /** * Accessor method to get the current element of this sequence. * * @param - none <dt><b>Precondition:</b> * <dd> * isCurrent()</CODE> returns true. * @return the current capacity of this sequence * @exception IllegalStateException * Indicates that there is no current element, so * getCurrent</CODE> may not be called. **/ public double getCurrent() { return this.cursorNode.getData(); } /** * Accessor method to determine whether this sequence has a specified * current element that can be retrieved with the getCurrent</CODE> method. * * @param - none * @return true (there is a current element) or false (there is no current * element at the moment) **/ public boolean isCurrent() { if (this.cursorNode != null) { return true; } return false; } /** * Remove the current element from this sequence. * * @param - none <dt><b>Precondition:</b> * <dd> * isCurrent()</CODE> returns true. * <dt><b>Postcondition:</b> * <dd> * The current element has been removed from this sequence, and the * following element (if there is one) is now the new current * element. If there was no following element, then there is now no * current element. * @exception IllegalStateException * Indicates that there is no current element, so * removeCurrent</CODE> may not be called. **/ public void removeCurrent() { this.cursorNode = this.cursorNode.getLink(); this.nodeCount--; } /** * Determine the number of elements in this sequence. * * @param - none * @return the number of elements in this sequence **/ public int size() { return nodeCount; } /** * Set the current element at the front of this sequence. * * @param - none <dt><b>Postcondition:</b> * <dd> * The front element of this sequence is now the current element (but * if this sequence has no elements at all, then there is no current * element). **/ public void start() { this.cursorNode = this.headNode; } /** * Add an element to the front * * @param a_val */ public void addFront(double a_val) { if (headNode == null) { initNodes(a_val); } else { start(); this.headNode = new DoubleNode(a_val, this.headNode); this.cursorNode = this.headNode; } this.nodeCount++; } /** * Add an element to the end * @param a_val */ public void addLast(double a_val) { if (headNode == null) { initNodes(a_val); } else { this.tailNode.addNodeAfter(a_val); this.tailNode = this.tailNode.getLink(); } this.nodeCount++; } /** * Remove the first element */ public void removeFront() { this.start(); this.headNode = this.headNode.getLink(); this.nodeCount--; } /** * Gets the value at the specificed index * * @param inIndex * @return */ public double getElementAtIndex(int inIndex) { int i = 0; double theReturn = 0; for (this.cursorNode = this.headNode; this.cursorNode != null; this.cursorNode = this.cursorNode .getLink()) { if (inIndex == i) { theReturn = this.cursorNode.getData(); break; } i++; } return theReturn; } /** * Sets pointer to end, tail node. */ public void end() { this.cursorNode = this.tailNode; } /** * Sets cursor node to given index * @param inIndex */ public void setCurrent(int inIndex) { int i = 0; DoubleNode tempPrec = this.headNode; for (this.cursorNode = this.headNode; this.cursorNode != null; this.cursorNode = this.cursorNode .getLink()) { if (inIndex == i) { break; } // Second time through, the cursor node. tempPrec = this.cursorNode; i++; } this.preCursorNode = tempPrec; } /** * Overridden toString method */ public String toString() { StringBuilder sb = new StringBuilder("DoubleLinkedSeq: "); for (int i = 0; i < this.size(); i++) { sb.append("["); sb.append(String.valueOf(this.getElementAtIndex(i))); sb.append("]"); } return sb.toString(); } }
Java
UTF-8
1,804
1.773438
2
[]
no_license
package com.google.android.gms.location.internal; import android.app.PendingIntent; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.ActivityRecognitionApi; public class zza implements ActivityRecognitionApi { /* renamed from: com.google.android.gms.location.internal.zza$zza reason: collision with other inner class name */ static abstract class C0033zza extends com.google.android.gms.location.ActivityRecognition.zza<Status> { public C0033zza(GoogleApiClient googleApiClient) { super(googleApiClient); } /* renamed from: a */ public Status zzc(Status status) { return status; } } public PendingResult<Status> removeActivityUpdates(GoogleApiClient googleApiClient, final PendingIntent pendingIntent) { return googleApiClient.zzd(new C0033zza(googleApiClient) { /* access modifiers changed from: protected */ /* renamed from: a */ public void zza(zzl zzl) { zzl.zzb(pendingIntent); zzc(Status.vY); } }); } public PendingResult<Status> requestActivityUpdates(GoogleApiClient googleApiClient, long j, PendingIntent pendingIntent) { final long j2 = j; final PendingIntent pendingIntent2 = pendingIntent; AnonymousClass1 r0 = new C0033zza(googleApiClient) { /* access modifiers changed from: protected */ /* renamed from: a */ public void zza(zzl zzl) { zzl.zza(j2, pendingIntent2); zzc(Status.vY); } }; return googleApiClient.zzd(r0); } }
C#
UTF-8
1,811
3.3125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; class Program02 { static void Main() { string[] input = Console.ReadLine().Split(new char[] { ' ', '.' }, StringSplitOptions.RemoveEmptyEntries); ulong bitrhDayMulty = 1L; int birthMonth = int.Parse(input[1]); for (int i = 0; i < 3; i++) { bitrhDayMulty *= ulong.Parse(input[i]); } if (birthMonth % 2 != 0) { bitrhDayMulty *= bitrhDayMulty; } string name = input[3]; int sumLetters = 0; ulong totalSum = 0; for (int i = 0; i < name.Length; i++) { if (name[i] >= 65 && name[i] <= 90) { int valueLetter = 2 * (name[i] - 'A' + 1); sumLetters += valueLetter; } else if (name[i] >= 97 && name[i] <= 122) { int valueLetter = name[i] - 'a' + 1; sumLetters += valueLetter; } else { int valueLetter = name[i] - '0'; sumLetters += valueLetter; } } totalSum = (ulong)sumLetters + bitrhDayMulty; if (totalSum <= 13) { Console.WriteLine(totalSum); } else { do { ulong newSum = 0; string digits = totalSum.ToString(); for (int i = 0; i < digits.Length; i++) { newSum += (ulong)(digits[i] - '0'); } totalSum = newSum; } while (totalSum > 13 || totalSum < 0); Console.WriteLine(totalSum); } } }
Rust
UTF-8
2,556
2.609375
3
[]
no_license
use gfx::*; use ggez::*; use ggez::graphics::{Color, Drawable, DrawParam, Image}; use image::RgbaImage; use crate::ggez_utils::Point2; use crate::transitions::transition::Transition; // Define the input struct for our shader. gfx_defines! { constant Dim { rate: f32 = "u_Rate", center_x: f32 = "center_x", center_y: f32 = "center_y", radius: f32 = "radius", aspect_ratio: f32 = "aspectRatio", refractive_index: f32 = "refractiveIndex", } } pub struct Sphere { image: Option<Image>, ended: bool, shader: Option<graphics::Shader<Dim>>, dim: Dim, } impl Sphere { pub fn new() -> Sphere { let dim = Dim { rate: 1.0, center_x: 0.5, center_y: 0.5, radius: 0.5, aspect_ratio: 1.0, refractive_index: 1.0, }; Sphere { image: None, ended: true, shader: None, dim } } } impl Transition for Sphere { fn draw(&mut self, ctx: &mut Context) -> GameResult<bool> { if !self.ended { if self.dim.rate <= 0.0 { self.ended = true; } else { self.dim.refractive_index = 2.0 - self.dim.rate; self.dim.radius = self.dim.refractive_index / 2.0; match &self.image { Some(i) => { graphics::clear(ctx, Color::BLACK); let param = DrawParam::new().dest(Point2::new(0.0, 0.0)); if let Some(ref shader) = self.shader { let _lock = graphics::use_shader(ctx, shader); shader.send(ctx, self.dim)?; i.draw(ctx, param)?; } } None => {} } self.dim.rate -= 0.01; } } Ok(!self.ended) } fn update_image(&mut self, ctx: &mut Context, image: RgbaImage) { self.dim.aspect_ratio = image.width() as f32 / image.height() as f32; let shader = graphics::Shader::new( ctx, "/basic_150.glslv", "/sphere_150.glslf", self.dim, "Dim", None, ).expect("Error creating shader."); self.shader = Some(shader); let i = Image::from_rgba8(ctx, image.width() as u16, image.height() as u16, &image.into_raw()).unwrap(); self.image = Some(i); self.ended = false; self.dim.rate = 1.0; } }
PHP
UTF-8
452
2.78125
3
[]
no_license
<?php include __DIR__ . '/src/GenerateImage.php'; if ((empty($_GET['userName'])) && (empty($_GET['userSurname']))) { header($_SERVER['SERVER_PROTOCOL'] . '404 Not Found '); exit(); } else { $name = $_GET['userName']; $surname = $_GET['userSurname']; $userName = $name . ' ' . $surname; $mark = "прошел тест на оценку 5"; $objectImage = new GenerateImage(); $objectImage->generate($userName,$mark); }
C++
UTF-8
526
3.15625
3
[]
no_license
#ifndef queue_h #define queue_h #include "node.h" template <class T> class Queue { private: Node<T> *head; Node<T> *bottom; public: Queue() { head = 0; bottom = 0; }; void queue(T Value) { Node<T> *n = new Node<T>; n->data = Value; n->next = 0; if(head == 0) head = bottom = n; else { bottom->next = n; bottom = n; } }; T DeQueue() { T t = head->data; Node<T> *q = head; head = head->next; delete q; return t; }; bool IsEmpty() const { return head == 0; }; }; #endif
Java
UTF-8
1,103
2.265625
2
[ "Apache-2.0" ]
permissive
package com.newolf.refreshlayout.adapter; import android.util.Log; import android.widget.TextView; import androidx.annotation.Nullable; import com.newolf.library.adapt.base.BaseQuickAdapter; import com.newolf.library.adapt.base.viewholder.BaseViewHolder; import com.newolf.refreshlayout.R; import java.util.List; /** * ================================================ * * @author : NeWolf * @version : 1.0 * @date : 2018/5/21 * 描述: * 历史:<br/> * ================================================ */ public class TestAdapter extends BaseQuickAdapter<String, BaseViewHolder> { public TestAdapter( @Nullable List<String> data) { super(R.layout.adapter_test, data); } @Override protected void convert(BaseViewHolder helper, String item) { helper.setText(R.id.tv_show, item); TextView tvShow = helper.getView(R.id.tv_show); int h = (int) ((Math.random() * 9 + 1) * 100); tvShow.setHeight(h); // tvShow.requestLayout(); Log.wtf("wolf", "convert: h = " + h + " , position = " + helper.getPosition()); } }
Python
UTF-8
241
3.484375
3
[]
no_license
import random num = random.randint(1,100) i = int(input("input a number: " )) while i != num: if i > num: i = int(input("input smaller:")) elif i < num: i = int(input("input bigger:")) print("congratulation!")
Java
UTF-8
1,228
2.046875
2
[]
no_license
package com.scholarship.demo.service; import com.scholarship.demo.api.*; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service public interface StudentService { /** * 当前流程查询接口 * @param * @return */ CurrentProcessRep currentPorcess(String account); /** * 下载前查询存放地址 * @param leaderAccount * @return */ String selectById(String leaderAccount); /** * 学生保存 * @param studentRequestDto 传这个对象 * @return */ String studentSave(StudentRequestDto studentRequestDto); /** * 学生提交 * @param studentRequestDto 传这个对象 * @return */ String studentApply(StudentRequestDto studentRequestDto); /** * 学生编辑 * @param key 传studentId,year * @return */ Map<String,Object> edit(Key key); /** * 我的项目查询数据接口 * @param leaderAccount 传登陆id * @return */ List<MyProjectDto> myProject(String leaderAccount); /** * 统一登陆管理 * @param loginDto * @return */ LoginResponse login(LoginDto loginDto); }
C#
UTF-8
1,936
2.546875
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace OnlineJobPortal { public partial class Login : Form { public Login() { InitializeComponent(); } private void Login_Load(object sender, EventArgs e) { headinglbl.BackColor = Color.Transparent; emaillbl.BackColor = Color.Transparent; passwordlbl.BackColor = Color.Transparent; loginbtn.BackColor = Color.Transparent; resetbtn.BackColor = Color.Transparent; newherelbl.BackColor = Color.Transparent; } private void resetbtn_Click(object sender, EventArgs e) { Controls.Clear(); InitializeComponent(); } private void loginbtn_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dhwani\Documents\Project_Final.mdf;Integrated Security=True;Connect Timeout=30"); SqlDataAdapter sda = new SqlDataAdapter("SELECT COUNT(*) FROM Signup WHERE Email='" + mailtxtbox.Text + "' AND Password='" + pwdtxtbox.Text + "'", con); DataTable dt = new DataTable(); sda.Fill(dt); //sda.Fill(dt); if (dt.Rows[0][0].ToString() == "1") { MessageBox.Show("You have Applied for the job!!!!"); } else MessageBox.Show("Invalid username or password"); } private void button1_Click(object sender, EventArgs e) { SignUp form = new SignUp(); form.Show(); } } }
Python
UTF-8
5,069
2.671875
3
[]
no_license
#!/usr/bin/env python # # Generate a key, self-signed certificate, and certificate request. # Usage: csrgen <fqdn> # # When more than one hostname is provided, a SAN (Subject Alternate Name) # certificate and request are generated. This can be acheived by adding -s. # Usage: csrgen <hostname> -s <san0> <san1> # # Author: Courtney Cotton <cotton@cottoncourtney.com> 06-25-2014 # Contributor: Gary Waters <gwaters@caltech.edu> 01-05-2017 (added external config file) # Libraries/Modules import argparse import ConfigParser from OpenSSL import crypto # Generate Certificate Signing Request (CSR) def generateCSR(nodename, sans = [], config_file = None): while not config_file: C = raw_input("Enter your Country Name (2 letter code) [US]: ") if len(C) != 2: print "You must enter two letters. You entered %r" % (C) continue ST = raw_input("Enter your State or Province <full name> []:California: ") if len(ST) == 0: print "Please enter your State or Province." continue L = raw_input("Enter your (Locality Name (eg, city) []:San Francisco: ") if len(L) == 0: print "Please enter your City." continue O = raw_input("Enter your Organization Name (eg, company) []:FTW Enterprise: ") if len(L) == 0: print "Please enter your Organization Name." continue OU = raw_input("Enter your Organizational Unit (eg, section) []:IT: ") if len(OU) == 0: print "Please enter your OU." continue # Allows you to permanently set values required for CSR # To use, comment raw_input and uncomment this section. # C = 'US' # ST = 'New York' # L = 'Location' # O = 'Organization' # OU = 'Organizational Unit' csrfile = 'host.csr' keyfile = 'host.key' TYPE_RSA = crypto.TYPE_RSA # Appends SAN to have 'DNS:' ss = [] for i in sans: ss.append("DNS: %s" % i) ss = ", ".join(ss) req = crypto.X509Req() req.get_subject().CN = nodename if config_file: config = ConfigParser.ConfigParser() conf = {} try: file = open(config_file, 'r') config.read(config_file) conf.update({"country_name": config.get("location", "country_name")}) conf.update({"state_or_province_name": config.get("location", "state_or_province_name")}) conf.update({"locality_name": config.get("location", "locality_name")}) conf.update({"organization_name": config.get("location", "organization_name")}) conf.update({"organizational_unit_name": config.get("location", "organizational_unit_name")}) req.get_subject().countryName = conf['country_name'] req.get_subject().stateOrProvinceName = conf['state_or_province_name'] req.get_subject().localityName = conf['locality_name'] req.get_subject().organizationName = conf['organization_name'] req.get_subject().organizationalUnitName = conf['organizational_unit_name'] file.close() except IOError: print "Error: File not found: %s" % config_file exit(-1) except Exception, error: print "Error: %s " % error exit(-1) else: req.get_subject().countryName = C req.get_subject().stateOrProvinceName = ST req.get_subject().localityName = L req.get_subject().organizationName = O req.get_subject().organizationalUnitName = OU # Add in extensions base_constraints = ([ crypto.X509Extension("keyUsage", False, "Digital Signature, Non Repudiation, Key Encipherment"), crypto.X509Extension("basicConstraints", False, "CA:FALSE"), ]) x509_extensions = base_constraints # If there are SAN entries, append the base_constraints to include them. if ss: san_constraint = crypto.X509Extension("subjectAltName", False, ss) x509_extensions.append(san_constraint) req.add_extensions(x509_extensions) # Utilizes generateKey function to kick off key generation. key = generateKey(TYPE_RSA, 2048) req.set_pubkey(key) #update sha? #req.sign(key, "sha1") req.sign(key, "sha256") generateFiles(csrfile, req) generateFiles(keyfile, key) return req # Generate Private Key def generateKey(type, bits): key = crypto.PKey() key.generate_key(type, bits) return key # Generate .csr/key files. def generateFiles(mkFile, request): if mkFile == 'host.csr': f = open(mkFile, "w") f.write(crypto.dump_certificate_request(crypto.FILETYPE_PEM, request)) f.close() print crypto.dump_certificate_request(crypto.FILETYPE_PEM, request) elif mkFile == 'host.key': f = open(mkFile, "w") f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, request)) f.close() else: print "Failed." exit() # Run Portion parser = argparse.ArgumentParser() parser.add_argument("name", help="Provide the FQDN", action="store") parser.add_argument("-s", "--san", help="SANS", action="store", nargs='*', default="") parser.add_argument("-c", "--config", help="Config_File", action="store", default="") args = parser.parse_args() hostname = args.name sans = args.san config_file = args.config generateCSR(hostname, sans, config_file)
Java
UTF-8
5,031
1.96875
2
[]
no_license
package cn.honry.oa.allWorks.vo; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; /** * @Description:流转中和已办毕vo * @Author: zhangkui * @CreateDate: 2018/2/5 20:08 * @Modifier: zhangkui * @version: V1.0 */ public class ProcessVo implements Serializable { private static final long serialVersionUID = 141011066447017287L; private String nodeCreateTime;//当前节点创建时间 private String endTime;//办毕时间 private String totalTime;//流程总用时 private String blockTime;//停留时间 private String approver;//当前审批人 private String pType;//流程分类 private String blDept;//所属科室 private String processInstanceId;//PROCESS_INSTANCE_ID private String businessKey;//t_oa_task_info的id private String option;//操作 private String tid;//t_oa_task_info的id private String title;//申请标题 private String curNode;//当前环节(名称) private String allApproversJobNum;//所有原审批人审批人员工号 private String allApproversName;//所有原审批人审批人名字 private String startTime;//流程开始时间 private String owner;//发起人名字 private String ownerJobNum;//发起人员工号 private String taskId;//t_oa_task_info的task_id public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getCurNode() { return curNode; } public void setCurNode(String curNode) { this.curNode = curNode; } public String getApprover() { return approver; } public void setApprover(String approver) { this.approver = approver; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public String getTotalTime() { return totalTime; } public void setTotalTime(String totalTime) { this.totalTime = totalTime; } public String getBlockTime() { return blockTime; } public void setBlockTime(String blockTime) { this.blockTime = blockTime; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getpType() { return pType; } public void setpType(String pType) { this.pType = pType; } public String getBlDept() { return blDept; } public void setBlDept(String blDept) { this.blDept = blDept; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getBusinessKey() { return businessKey; } public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } public String getOption() { return option; } public void setOption(String option) { this.option = option; } public String getNodeCreateTime() { return nodeCreateTime; } public void setNodeCreateTime(String nodeCreateTime) { this.nodeCreateTime = nodeCreateTime; } public String getTid() { return tid; } public void setTid(String tid) { this.tid = tid; } public String getAllApproversJobNum() { return allApproversJobNum; } public void setAllApproversJobNum(String allApproversJobNum) { if(StringUtils.isNotBlank(allApproversJobNum)){ if(allApproversJobNum.endsWith(",")){ allApproversJobNum=allApproversJobNum.substring(0,allApproversJobNum.length()-2); } } this.allApproversJobNum = allApproversJobNum; } public String getAllApproversName() { return allApproversName; } public void setAllApproversName(String allApproversName) { if(StringUtils.isNotBlank(allApproversName)){ if(allApproversName.endsWith(",")){ allApproversName=allApproversName.substring(0,allApproversName.length()-2); } } this.allApproversName = allApproversName; } public String getOwnerJobNum() { return ownerJobNum; } public void setOwnerJobNum(String ownerJobNum) { this.ownerJobNum = ownerJobNum; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } }
Java
UTF-8
375
1.757813
2
[ "MIT" ]
permissive
package com.example.agendapublica.Repository; import com.example.agendapublica.Config.EntityMapper; import com.example.agendapublica.DTO.TelephoneNumberDTO; import com.example.agendapublica.Entities.TelephoneNumber; import org.mapstruct.Mapper; @Mapper(componentModel = "spring") public interface NumberMapping extends EntityMapper<TelephoneNumberDTO, TelephoneNumber> { }
C++
UTF-8
1,315
2.953125
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. */ /* * File: ExpBuilder.h * Author: Admin * * Created on March 21, 2019, 3:10 PM */ #ifndef EXPBUILDER_H #define EXPBUILDER_H #include <stack> #include <iostream> #include <vector> using namespace std; class ExpBuilder: public Builder{ protected: stack<Node*> expStack; public: virtual void addOperand(string operand){ Node* newOperand = new Node(operand); expStack.push(newOperand); }; virtual void addLiteral(string literal){ Node* newOperand = new Node(literal); expStack.push(newOperand); }; virtual void addLeftParenthesis(){}; virtual void addRightParenthesis(){ Node* rightChild = expStack.top(); expStack.pop(); Node* parent = expStack.top(); expStack.pop(); Node* leftChild = expStack.top(); expStack.pop(); parent->setLeftChild(leftChild); parent->setRightChild(rightChild); expStack.push(parent); }; virtual Node* getExpression(){ Node* root = expStack.top(); expStack.pop(); return root; }; }; #endif /* EXPBUILDER_H */
SQL
UTF-8
1,257
3.828125
4
[]
no_license
create schema project; create table student( StudentID varchar(100) not null primary key, Lastname varchar(100) default null, OtherNames varchar(100) default null, DOB date default null, GroupLeader varchar(100) null); select * from student; create table Description( ProjectID varchar(100) not null primary key, ProjectTitle varchar(100) default null, ProjectSummary varchar(100) default null, SupervisorID varchar(100) default null, StudentID varchar(100) default null, constraint fk_StudentID foreign key(StudentID) references Student(StudentID), constraint fk_SupervisorID foreign key(SupervisorID) references Supervisor(SupervisorID) ); create table Supervisor( SupervisorID varchar(100) not null primary key, lastname varchar(100) default null, OtherNames varchar(100) default null); create table Submissions( SubmissionID int(100) not null primary key auto_increment, ProjectID varchar(100) default null, ComponentSubmitted varchar(100) default null, DateSubmitted timestamp default current_timestamp, constraint fk_PrjectID foreign key(ProjectID) references Description(ProjectID)); alter table submissions add column(remark varchar(100)); select * from description; select * from student; select * from submissions; select * from supervisor;
JavaScript
UTF-8
1,120
3.421875
3
[ "MIT" ]
permissive
var BowlingGame = function() { this.rolls = []; this.currentRoll = 0; this.roll = function(pins) { this.rolls[this.currentRoll++] = pins; console.log("rolls : " + this.rolls); console.log("longueur : " + this.rolls.length); console.log("currentRoll : " + this.currentRoll); }; this.score = function() { function sumOfBallsInFrame() { frameScore = self.rolls[frameIndex] + self.rolls[frameIndex + 1]; if (self.rolls[frameIndex] == 10) { frameScore += self.rolls[frameIndex + 2]; } return frameScore; } function frameOrGame() { if (self.rolls.length > 2) { return 10; } else { return 1; } } var score = 0; var frameIndex = 0; var self = this; console.log("frameOrGame [1] : " + frameOrGame()); for (var i = 0; i < frameOrGame(); i++) { score += sumOfBallsInFrame(); frameIndex += 2; console.log('i : ' + i + " / frameIndex : " + frameIndex + " / score : " + score); } console.log("frameOrGame [2] : " + frameOrGame()); return score; }; };
Java
UTF-8
3,078
2.703125
3
[]
no_license
package bundle; import exception.QuickException; import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyObject; import java.io.File; import java.io.FilenameFilter; import play.Logger; import play.Play; /** * Load classes and script in the bundle context * * @author Paolo Di Tommaso * */ public class BundleScriptLoader { File scriptPath; File libPath; GroovyClassLoader gcl; { gcl = new GroovyClassLoader(Play.classloader); } /** * Initialize the loader using the current path as the path * where scripts are located */ public BundleScriptLoader() { init( new File("."), null ); } /** * Initialize the classload accordingly with the 'scripts' and libraries path specified * * @param scripts the path where the scritps to load are located * @param libs the path where the libraries '.jar' are located */ public BundleScriptLoader( File scripts, File libs ) { init(scripts, libs); } /** * Initialize the classload accordingly with the 'scripts' and libraries path specified * * @param scripts * @param libs */ void init(File scripts, File libs) { this.scriptPath = scripts; this.libPath = libs; // add the labraries to the classpath if( libPath != null ) { addLibClasspath(libPath); } // add the script path to the classpath if( scriptPath != null ) { gcl.addClasspath(scriptPath.getAbsolutePath()); } } /** * Add all the java libraries '.jar' files to the specified groovy class loader. * * @param loader to classloader to which classpath append the libraries * @return the liast of added paths */ void addLibClasspath(File libPath) { if( libPath == null ) { return ; } if( !libPath.exists() || !libPath.isDirectory() ) { Logger.warn("The libraries path provided is not valid: '%s'", libPath); return ; } libPath.list( new FilenameFilter() { @Override public boolean accept(File dir, String name) { boolean yes = name.toLowerCase().endsWith(".jar"); if( yes ) { String _it = new File(dir,name).getAbsolutePath(); gcl.addClasspath( _it ); } return yes; } }); } public Object getExtensionByFile( String theScriptFile ) { try { Class clazz = gcl.parseClass(new File(scriptPath,theScriptFile)); return clazz.newInstance(); } catch (Exception e) { throw new QuickException(e, "Cannot parse script file '%s'", theScriptFile); } } public Object getExtensionByClass( String className ) { try { return gcl.loadClass(className).newInstance(); } catch (Exception e) { throw new QuickException(e, "Cannot create script class '%s'", className); } } /** * Create an instance of the script object * * @param script a groovy script to be executed in the bundle context * * @return A {@link GroovyObject} */ public Object getExtensionByScript( String script ) { try { return gcl.parseClass(script).newInstance(); } catch (Exception e) { throw new QuickException(e, "Cannot parse provided script"); } } }
C
UTF-8
322
3.1875
3
[]
no_license
#include<stdio.h> int main() { int code1,unite1,code2,unite2; double price1,price2,cost1,cost2,cost; scanf("%d %d %lf\n%d %d %lf",&code1,&unite1,&price1,&code2,&unite2,&price2); cost1=unite1*price1; cost2=unite2*price2; cost=cost1+cost2; printf("VALOR A PAGAR: R$ %.2lf",cost); return 0; }
Shell
UTF-8
342
3.53125
4
[]
no_license
#! /usr/bin/env bash # File: print_num_args.sh # Write a Bash program that prints the number of arguments provided to that program multiplied by the first argument provided to the program. echo "Number of args: $#" echo "Number of args times first arg:" # HOW SUPPRESS NEWLINE SO NUMBER APPEARS ON THIS LINE??? expr "$# * $1" | bc -l