language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
670
3.859375
4
[]
no_license
public class MyFirstClass { private String name; private int age = 0; private String school = "Unknown"; MyFirstClass(String Name){ this.name = Name; } MyFirstClass(String Name, int Age) { this.name = Name; this.age = Age; } MyFirstClass(String Name, int Age, String School){ this.name = Name; this.age = Age; this.school = School; } public void printInformation(){ System.out.println("Name: " + name +" Age: " + age + " School: " + school); } public String getName(){ return name; } public int getAge(){ return age; } public String getSchool(){ return school; } }
Swift
UTF-8
639
2.578125
3
[ "MIT" ]
permissive
// // Interactor.swift // YoyoFramework // // Created by Amadeu Cavalcante Filho on 04/11/18. // Copyright © 2018 Amadeu Cavalcante Filho. All rights reserved. // import Foundation final class DetailMovieInteractor: MovieDetailInteractorInputProtocol { var presenter: MovieDetailInteractorOutputProtocol? var gateway: FavoriteMovieLocalGatewayProtocol? func favorite(_ movie: MovieEntity) { gateway?.favorite(movie: movie) presenter?.movieDidChange(movie.favorited()) } func unFavorite(_ movie: MovieEntity) { gateway?.unFavorite(movie: movie) presenter?.movieDidChange(movie.unFavorited()) } }
C#
UTF-8
662
4.0625
4
[]
no_license
void Main() { foreach (string word in EnumerateCaveNames()) Console.WriteLine(word); } IEnumerable<string> EnumerateCaveNames() { for (int i = 0; i < 26 * 26 * 26; ++i) { yield return BuildCaveName(i); } } string BuildCaveName(int caveNum) { string name = (GetLetterFromNumber(caveNum / (26 * 26)) + GetLetterFromNumber((caveNum / 26) % 26) + GetLetterFromNumber(caveNum % 26)).TrimStart('a'); if (name == "") name = "a"; return name; } string GetLetterFromNumber(int num) { return ('a' + (num - 1)).ToString(); }
Java
UTF-8
4,845
2.484375
2
[ "Apache-2.0" ]
permissive
/* * Minecraft Forge * Copyright (c) 2016-2019. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version 2.1 * of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.minecraftforge.registries; import net.minecraft.util.ResourceLocation; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.RegistryObject; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.function.Supplier; /** * Utility class to help with managing registry entries. * Maintains a list of all suppliers for entries and registers them during the proper Register event. * Suppliers should return NEW instances every time. * *Example Usage: *<pre> * private static final DeferredRegister<Item> ITEMS = new DeferredRegister<>(ForgeRegistries.ITEMS, MODID); * private static final DeferredRegister<Block> BLOCKS = new DeferredRegister<>(ForgeRegistries.BLOCKS, MODID); * * public static final RegistryObject<Block> ROCK_BLOCK = BLOCKS.register("rock", () -> new Block(Block.Properties.create(Material.ROCK))); * public static final RegistryObject<Item> ROCK_ITEM = ITEMS.register("rock", () -> new BlockItem(ROCK_BLOCK.get(), new Item.Properties().group(ItemGroup.MISC))); * * public ExampleMod() { * ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus()); * BLOCKS.register(FMLJavaModLoadingContext.get().getModEventBus()); * } *</pre> * * @param <T> The base registry type, must be a concrete base class, do not use subclasses or wild cards. */ public class DeferredRegister<T extends IForgeRegistryEntry<T>> { private final IForgeRegistry<T> type; private final String modid; private final Map<RegistryObject<T>, Supplier<? extends T>> entries = new LinkedHashMap<>(); private final Set<RegistryObject<T>> entriesView = Collections.unmodifiableSet(entries.keySet()); public DeferredRegister(IForgeRegistry<T> reg, String modid) { this.type = reg; this.modid = modid; } /** * Adds a new supplier to the list of entries to be registered, and returns a RegistryObject that will be populated with the created entry automatically. * * @param name The new entry's name, it will automatically have the modid prefixed. * @param sup A factory for the new entry, it should return a new instance every time it is called. * @return A RegistryObject that will be updated with when the entries in the registry change. */ @SuppressWarnings("unchecked") public <I extends T> RegistryObject<I> register(final String name, final Supplier<? extends I> sup) { Objects.requireNonNull(name); Objects.requireNonNull(sup); final ResourceLocation key = new ResourceLocation(modid, name); RegistryObject<I> ret = RegistryObject.of(key, this.type); if (entries.putIfAbsent((RegistryObject<T>) ret, () -> sup.get().setRegistryName(key)) != null) { throw new IllegalArgumentException("Duplicate registration " + name); } return ret; } /** * Adds our event handler to the specified event bus, this MUST be called in order for this class to function. * See the example usage. * * @param bus The Mod Specific event bus. */ public void register(IEventBus bus) { bus.addListener(this::addEntries); } /** * @return The unmodifiable view of registered entries. Useful for bulk operations on all values. */ public Collection<RegistryObject<T>> getEntries() { return entriesView; } private void addEntries(RegistryEvent.Register<?> event) { if (event.getGenericType() == this.type.getRegistrySuperType()) { @SuppressWarnings("unchecked") IForgeRegistry<T> reg = (IForgeRegistry<T>)event.getRegistry(); for (Entry<RegistryObject<T>, Supplier<? extends T>> e : entries.entrySet()) { reg.register(e.getValue().get()); e.getKey().updateReference(reg); } } } }
Python
UTF-8
1,738
2.71875
3
[ "Apache-2.0" ]
permissive
import numpy as np import torch from torch import nn from torch.nn import init class SpatialGroupEnhance(nn.Module): def __init__(self, groups): super().__init__() self.groups=groups self.avg_pool = nn.AdaptiveAvgPool2d(1) self.weight=nn.Parameter(torch.zeros(1,groups,1,1)) self.bias=nn.Parameter(torch.zeros(1,groups,1,1)) self.sig=nn.Sigmoid() self.init_weights() def init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): init.kaiming_normal_(m.weight, mode='fan_out') if m.bias is not None: init.constant_(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): init.constant_(m.weight, 1) init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): init.normal_(m.weight, std=0.001) if m.bias is not None: init.constant_(m.bias, 0) def forward(self, x): b, c, h,w=x.shape x=x.view(b*self.groups,-1,h,w) #bs*g,dim//g,h,w xn=x*self.avg_pool(x) #bs*g,dim//g,h,w xn=xn.sum(dim=1,keepdim=True) #bs*g,1,h,w t=xn.view(b*self.groups,-1) #bs*g,h*w t=t-t.mean(dim=1,keepdim=True) #bs*g,h*w std=t.std(dim=1,keepdim=True)+1e-5 t=t/std #bs*g,h*w t=t.view(b,self.groups,h,w) #bs,g,h*w t=t*self.weight+self.bias #bs,g,h*w t=t.view(b*self.groups,1,h,w) #bs*g,1,h*w x=x*self.sig(t) x=x.view(b,c,h,w) return x if __name__ == '__main__': input=torch.randn(50,512,7,7) sge = SpatialGroupEnhance(groups=8) output=sge(input) print(output.shape)
C
UTF-8
1,469
3.109375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <math.h> int main(){ int N, L, C; while(scanf("%d %d %d", &N, &L, &C) != EOF){ char * str = (char *) malloc(N * 70 * sizeof(char)); scanf(" %[^\n]s",str); int i = 0, j=0, contC = C, nPage = 0, nLine=0; for(i=0; i < N; i++){ int sizeWord = 0; while(str[j] == ' '){ j++; } while(str[j] != ' ' && str[j] != '\0'){ sizeWord++; j++; } int vWord = contC - sizeWord; if(vWord > 0){ contC = vWord - 1; if(contC==0){ nLine++; contC = C; } }else if(vWord == 0){ nLine++; contC = C; }else{ nLine++; contC = C - sizeWord - 1; if(contC<=0){ nLine++; contC = C; } } if(nLine>=L){ nLine = nLine - L; nPage++; } } if(contC<C){ nLine++; } if(nLine > 0){ nPage++; } printf("%d\n",nPage); free(str); } return 0; }
Python
UTF-8
1,280
2.765625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 25 14:41:02 2019 @author: amalvnair """ ################ URL Extraction ################## import scrapy class BookSpider(scrapy.Spider): name = 'bookurls' #links = [] allowed_domains = [''] start_urls = [''] def parse(self, response): temp = [] links_div = response.css('div.s-result-list.s-search-results.sg-row') links_div = links_div.css('h2.a-size-mini.a-spacing-none.a-color-base.s-line-clamp-2') temp = links_div.css('a::attr(href)').extract() print(temp) #self.links = self.links + links_div.css('a::attr(href)').extract() with open('Urls.csv','a+') as f: for ls in temp : f.write("https://www.example.com{}\n".format(ls)) # write items next_page = response.css('li.a-last').css('a::attr(href)').extract() if next_page: next_href = next_page[0] next_page_url = "https://www.example.com" + next_href with open('pages.csv','a+') as f: f.write("{}\n".format(next_page_url)) # write items request = scrapy.Request(url=next_page_url) yield request
C#
UTF-8
692
2.609375
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DifficultyOptions : MonoBehaviour { public Slider difficultySlider; public int difficultyLevel; // Use this for initialization void Start () { this.difficultyLevel = 0; difficultySlider.onValueChanged.AddListener(delegate { DifficultyChanged(); }); } // take in difficulty change void DifficultyChanged() { Debug.Log(difficultySlider.value); this.difficultyLevel = (int)(difficultySlider.value); // call the static method to set the level DifficultyChosen.setDifficultyLevel(this.difficultyLevel); } }
C++
UTF-8
4,282
3.09375
3
[]
no_license
// BWNumber.cpp // A simple number library // by Bill Weinman <http://bw.org/> // Copyright (c) 2014 The BearHeart Group LLC // #include "BWNumber.h" #pragma mark - constructors BWNumber::BWNumber(const int &n) { _lnum = n; _dnum = double(_lnum = n); } BWNumber::BWNumber(const long &n) { _lnum = n; _dnum = double(_lnum = n); } BWNumber::BWNumber(const double &d) { _lnum = int(_dnum = d); _dnum = d; } BWNumber::BWNumber(const char *s) { _lnum = atol(s); _dnum = atof(s); } BWNumber::BWNumber(const BWNumber &bwn) { _lnum = bwn._lnum; _dnum = bwn._dnum; } BWNumber::~BWNumber() { _dnum = _lnum = 0; } #pragma mark - utilities void BWNumber::reset() { _lnum = 0L; _dnum = 0.0; } const char *BWNumber::c_str_long() { snprintf(_buffer, __BWNumber_BUFSIZE, "%ld", _lnum); return _buffer; } const char *BWNumber::c_str_double() { snprintf(_buffer, __BWNumber_BUFSIZE, "%lf", _dnum); return _buffer; } #pragma mark - arithmetic BWNumber &BWNumber::add(const BWNumber &n) { _lnum += n._lnum; _dnum += n._dnum; return *this; } BWNumber &BWNumber::sub(const BWNumber &n) { _lnum -= n._lnum; _dnum -= n._dnum; return *this; } BWNumber &BWNumber::div(const BWNumber &n) { _lnum /= n._lnum; _dnum /= n._dnum; return *this; } BWNumber &BWNumber::mul(const BWNumber &n) { _lnum *= n._lnum; _dnum *= n._dnum; return *this; } #pragma mark - assignment overloads BWNumber &BWNumber::operator=(const BWNumber &n) { _lnum = n._lnum; _dnum = n._dnum; return *this; } BWNumber &BWNumber::operator=(const long &n) { _lnum = int(n); _dnum = (double) n; return *this; } BWNumber &BWNumber::operator=(const double &n) { _lnum = (long int) n; _dnum = double(n); return *this; } #pragma mark - operators BWNumber &BWNumber::operator+=(const BWNumber &n) { return this->add(n); } BWNumber &BWNumber::operator-=(const BWNumber &n) { return this->sub(n); } BWNumber &BWNumber::operator/=(const BWNumber &n) { return this->div(n); } BWNumber &BWNumber::operator*=(const BWNumber &n) { return this->mul(n); } #pragma mark - comparison operators bool BWNumber::operator==(const BWNumber &rhs) const { if ((_lnum == rhs._lnum) && (_dnum == rhs._dnum)) return true; else return false; } bool BWNumber::operator!=(const BWNumber &rhs) const { if ((_lnum != rhs._lnum) && (_dnum != rhs._dnum)) return true; else return false; } bool BWNumber::operator>(const BWNumber &rhs) const { if ((_lnum > rhs._lnum) && (_dnum > rhs._dnum)) return true; else return false; } bool BWNumber::operator<(const BWNumber &rhs) const { if ((_lnum < rhs._lnum) && (_dnum < rhs._dnum)) return true; else return false; } bool BWNumber::operator>=(const BWNumber &rhs) const { if ((_lnum >= rhs._lnum) && (_dnum >= rhs._dnum)) return true; else return false; } bool BWNumber::operator<=(const BWNumber &rhs) const { if ((_lnum <= rhs._lnum) && (_dnum <= rhs._dnum)) return true; else return false; } #pragma mark - increment/decrement operators BWNumber &BWNumber::operator++() { _lnum += 1; _dnum += 1.0; return *this; } BWNumber BWNumber::operator++(int) { BWNumber temp = *this; ++(*this); return temp; } BWNumber &BWNumber::operator--() { _lnum -= 1; _dnum -= 1.0; return *this; } BWNumber BWNumber::operator--(int) { BWNumber temp = *this; --(*this); return temp; } #pragma mark - conversion operators BWNumber::operator int() const { return (int) _lnum; } BWNumber::operator long() const { return _lnum; } BWNumber::operator double() const { return _dnum; } //BWNumber::operator BWString() const { // //} #pragma mark - binary operators BWNumber operator+(const BWNumber &lhs, const BWNumber &rhs) { BWNumber rn = lhs; rn += rhs; return rn; } BWNumber operator-(const BWNumber &lhs, const BWNumber &rhs) { BWNumber rn = lhs; rn -= rhs; return rn; } BWNumber operator/(const BWNumber &lhs, const BWNumber &rhs) { BWNumber rn = lhs; rn /= rhs; return rn; } BWNumber operator*(const BWNumber &lhs, const BWNumber &rhs) { BWNumber rn = lhs; rn *= rhs; return rn; }
Python
UTF-8
823
2.5625
3
[]
no_license
import FP_growth def generateRules(freqItemStatic,freqItem, freqItemsDict, itemSet,Rule,minConf=0.9): # freqItem : {'t', 'y', 'x'} if len(freqItem) > 1: for e in freqItem: item = set([e]) | itemSet #item 为后件 conf = freqItemsDict[frozenset(freqItemStatic)]/freqItemsDict.get(frozenset(freqItemStatic-item),100) if conf >= minConf: Rule.append([frozenset(freqItemStatic-item),item,conf]) generateRules(freqItemStatic,freqItemStatic-item,freqItemsDict,item,Rule) if __name__ == "__main__": freqItems,freqItemsDict = FP_growth.fpGrowth() #生成频繁项集 [{a,b},{b,c}...] res = [] for freqItem in freqItems: succedent = set([]) generateRules(freqItem,freqItem,freqItemsDict,succedent,res) print(res)
Java
UTF-8
2,531
2.046875
2
[ "Apache-2.0" ]
permissive
/* * © [2021] Cognizant. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cognizant.collector.artifactory.component; import com.cognizant.collector.artifactory.beans.ArtifactoryProperties; import com.cognizant.collector.artifactory.config.CustomBasicAuthentication; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import static com.cognizant.collector.artifactory.constants.Constant.SOURCE_BUILD; import static com.cognizant.collector.artifactory.constants.Constant.SOURCE_STORAGE; /** * ArtifactoryCommonUtility - Configuration class for auth header * @author Cognizant */ @Component public class ArtifactoryCommonUtility { private HttpHeaders headers = new HttpHeaders(); static String buildCollectionName; static String storageCollectionName; @Autowired private ArtifactoryProperties properties; @Autowired CustomBasicAuthentication customBasicAuthentication; @PostConstruct private void postConstructMethod() { headers.setAll(customBasicAuthentication.getBasicAuthentication(properties.getUsername(), properties.getToken())); } public HttpHeaders getHeaders(){ return headers; } @Value("${spring.data.mongodb.collection.build}") public void setBuildCollectionName(String collectionName) { this.buildCollectionName = SOURCE_BUILD+collectionName; } public static String getBuildCollectionName(){ return buildCollectionName; } @Value("${spring.data.mongodb.collection.storage}") public void setStorageCollectionName(String collectionName) { this.storageCollectionName = SOURCE_STORAGE+collectionName; } public static String getStorageCollectionName(){ return storageCollectionName; } }
Python
UTF-8
527
3.109375
3
[]
no_license
import numpy as np from matplotlib import pyplot as plt #Input X1 and Y1 value X1,Y1=np.meshgrid(np.linspace(-1,1,10),np.linspace(-1,1,10)) Z1=np.exp(-((X1**2)+(Y1**2))) # Function for 2D plot dx, dy = np.gradient(Z1) n = -2 # Defining color color = np.sqrt(((dx-n)/2)*2 + ((dy-n)/2)*2) fig, ax = plt.subplots() fig = plt.figure() ax = fig.add_subplot() q = ax.quiver(X1,Y1,dx,dy,color) ax.set_aspect('equal') plt.title('Gradient HedgeHog Plot') plt.savefig('gradientHedgehog.png') plt.show()
C
UTF-8
22,273
2.65625
3
[]
no_license
/** * @name buffer2 * this library allows the use of buffers in Lua * these buffers can be resized dynamically and accessed as arrays of any type */ /** * list of functions in the main library: * new: creates a buffer * calloc: creates a buffer filled with zeroes * getsize: returns the size of a buffer * setsize: resizes a buffer * getlength: returns the length of a buffer used as an array * setlength: resizes a buffer so that its length would be a specific value * gettype: returns the type of the array * settype: sets the type of the array * get: returns the value at a given index, of a given type * set: sets the value at a given index, of a given type * iter: an iterator which can be used on any table-like object */ /** * list of properties of buffer objects: * size: the size of the buffer, in bytes * length: the length of the buffer used as an array * type: the type of objects stored in the buffer, when used as an array */ /** * list of methods on buffer objects: * getsize: returns its size property * setsize: sets its size property * getlength: returns its length property * setlength: sets its length property * gettype: returns its type property * settype: sets its type property * get: reads at a given index, as a given type * set: writes at a given index, as a given type * @remark other functions from the main library will be available as buffer methods, but will cause undefined behavior if called an potentially throw */ #include "lua.h" #include "lauxlib.h" #include "lualib.h" #include "buffer2.h" #include <stdint.h> #include <string.h> #include <limits.h> // function type markers #define API static #define INTERNAL static #define OTHER static #define ENTRYPOINT //BEGIN type constants // useful constants #define typename(sgn, name) T_##sgn##name #define typeid(name) TYPE_##name // class name #define BUFFER_CLASS "buffer2" // findstr struct typedef struct { int val; char* str; } findstr_t; // signedness #define TYPE_UNSIGNED 0x00 #define TYPE_SIGNED 0x10 // standard types #define TYPE_CHAR 0x0 #define T_UCHAR unsigned char #define T_SCHAR signed char #if LUA_MAXINTEGER>=SHRT_MAX #define TYPE_SHORT 0x1 #define T_USHORT unsigned short #define T_SSHORT signed short #endif #if LUA_MAXINTEGER>=INT_MAX #define TYPE_INT 0x2 #define T_UINT unsigned int #define T_SINT signed int #endif #if LUA_MAXINTEGER>=LONG_MAX #define TYPE_LONG 0x3 #define T_ULONG unsigned long #define T_SLONG signed long #endif #if LUA_MAXINTEGER>=LLONG_MAX #define TYPE_LONGLONG 0x4 #define T_ULONGLONG unsigned long long #define T_SLONGLONG signed long long #endif #define TYPE_FLOAT 0x5 #define T_UFLOAT float #define T_SFLOAT float #if LUA_FLOAT_TYPE>=LUA_FLOAT_DOUBLE #define TYPE_DOUBLE 0x6 #define T_UDOUBLE double #define T_SDOUBLE double #endif // fixed-width types #define TYPE_8 0x7 #define T_U8 uint8_t #define T_S8 int8_t #if LUA_MAXINTEGER>=32767 #define TYPE_16 0x8 #define T_U16 uint16_t #define T_S16 int16_t #endif #if LUA_MAXINTEGER>=2147483647 #define TYPE_32 0x9 #define T_U32 uint32_t #define T_S32 int32_t #endif #if LUA_MAXINTEGER>=9223372036854775807 #define TYPE_64 0xa #define T_U64 uint64_t #define T_S64 int64_t #endif //END type constants //BEGIN function prototypes // setup functions ENTRYPOINT int luaopen_buffer2(lua_State *L); INTERNAL int setupMeta(lua_State *L); INTERNAL int setupLib(lua_State *L); // internal functions INTERNAL int isValidType(int type); INTERNAL buffer_t *bufferFromArg(lua_State *L); INTERNAL int typeFromArg(lua_State *L, buffer_t *buf, int arg); INTERNAL int startswith(const char* str, const char* beginning); INTERNAL int findstr(const char* str, findstr_t* list); INTERNAL int getLength(buffer_t *buf, int type); INTERNAL int typeSize(int type); // size (in bytes) getter/setter API int api_bufferGetSize(lua_State *L); API int api_bufferSetSize(lua_State *L); // length (according to type) getter/setter API int api_bufferGetLength(lua_State *L); API int api_bufferSetLength(lua_State *L); // type getter/setter API int api_bufferGetType(lua_State *L); API int api_bufferSetType(lua_State *L); // value getter/setter API int api_bufferGet(lua_State *L); API int api_bufferSet(lua_State *L); // buffer creator API int api_bufferNew(lua_State *L); API int api_bufferCalloc(lua_State *L); // metamethods API int meta_index(lua_State *L); API int meta_newindex(lua_State *L); API int meta_len(lua_State *L); API int meta_ipairs(lua_State *L); API int meta_gc(lua_State *L); // other Lua functions OTHER int other_iter(lua_State *L); //END function prototypes //BEGIN internal functions /** * @name isValidType * checks if a type is valid for the current configuration * excludes types that are too wide for the current Lua configuration * @param type: int, internal representation of the type * @returns int, 0 if invalid, nonzero if valid */ int isValidType(int type) { // check if there are illegal bits if((type&0x1f)!=type) return 0; // check individual types switch(type&0xf) { // standard types case TYPE_CHAR: return 1; #ifdef TYPE_SHORT case TYPE_SHORT: return 1; #endif #ifdef TYPE_INT case TYPE_INT: return 1; #endif #ifdef TYPE_LONG case TYPE_LONG: return 1; #endif #ifdef TYPE_LONGLONG case TYPE_LONGLONG: return 1; #endif case TYPE_FLOAT: return 1; #ifdef TYPE_DOUBLE case TYPE_DOUBLE: return 1; #endif // fixed-width types case TYPE_8: return 1; #ifdef TYPE_16 case TYPE_16: return 1; #endif #ifdef TYPE_32 case TYPE_32: return 1; #endif #ifdef TYPE_64 case TYPE_64: return 1; #endif default: return 0; } } /** * @name bufferFromArg * unwraps the buffer_t contained in Lua arg1 * throws on error * @param L: lua_State, the Lua instance * @returns buffer_t*, a pointer to the buffer_t */ buffer_t *bufferFromArg(lua_State *L) { return luaL_checkudata(L, 1, BUFFER_CLASS); } /** * @name typeFromArg * reads a type from Lua arg#arg * defaults to the type set by the buffer * throws on error * @param L: lua_State, the Lua instance * @param buf: buffer_t*, a pointer to the buffer* * @param arg: int, the index of the argument * @returns int, the type */ int typeFromArg(lua_State *L, buffer_t *buf, int arg) { if(lua_isnumber(L, arg)) { // treat the argument as a direct type and return it if it is valid int type=luaL_checkinteger(L, arg); if(isValidType(type)) return type; } else if(lua_isstring(L, arg)) { // treat the argument as a string type and return it if it is valid size_t len=0; const char* str=luaL_checklstring(L, arg, &len); // check if the type is signed int signedness=startswith(str, "signed "); if(signedness) { str+=7; // length of "signed " } else { if(startswith(str, "unsigned ")) str+=9; // length of "unsigned " } // get type from name int type=findstr(str, (findstr_t[]) { {TYPE_CHAR, "char"} #ifdef TYPE_SHORT ,{TYPE_SHORT, "short"} #endif #ifdef TYPE_INT ,{TYPE_INT, "int"} #endif #ifdef TYPE_LONG ,{TYPE_LONG, "long"} #endif #ifdef TYPE_LONGLONG ,{TYPE_LONGLONG, "long long"} #endif ,{TYPE_FLOAT, "float"} #ifdef TYPE_DOUBLE ,{TYPE_DOUBLE, "double"} #endif ,{TYPE_8, "8"} ,{TYPE_8, "int8"} #ifdef TYPE_16 ,{TYPE_16, "16"} ,{TYPE_16, "int16"} #endif #ifdef TYPE_32 ,{TYPE_32, "32"} ,{TYPE_32, "int32"} #endif #ifdef TYPE_64 ,{TYPE_64, "64"} ,{TYPE_64, "int64"} #endif ,{-1, NULL} }); // return the type if it is valid if(type!=-1) { type|=signedness<<4; if(isValidType(type)) return type; } } else if(lua_isnoneornil(L, arg)&&buf!=NULL) { // return the type stored in the buffer return buffer_getUser(buf)&0x1f; } // if we're still here, there was an error that we need to throw return luaL_argerror(L, arg, "must be a valid type"); } /** * @name startswith * determines if a C string starts with a sub-sequence * @param str: char*, the string in which to read * @param beginning: char*, the string to be detected inside str * @returns int, 1 if present, 0 if absent */ int startswith(const char* str, const char* beginning) { while(*beginning!='\0') { if(*str!=*beginning) return 0; str++; beginning++; } return 1; } /** * @name findstr * matches a string against a number of others to find a corresponding number * the list must be terminated by an element with a string value of NULL; its number will be the return value * @param str: char*, the string to test * @param list: findstr_t*, the list of number-string pairs * @returns the number associated with the string */ int findstr(const char* str, findstr_t* list) { while(list->str!=NULL) { if(!strcmp(str, list->str)) return list->val; list++; } return list->val; } #define lenForType(type) case TYPE_##type: \ return buffer_getLength(buf, typename(U, type)); /** * @name getLength * determines the length of a buffer according to its type * @param buf: buffer_t*, the buffer * @param type: int, the type * @returns int, the length, -1 if unable to determine it */ int getLength(buffer_t *buf, int type) { switch(type&0xf) { lenForType(CHAR) #ifdef TYPE_SHORT lenForType(SHORT) #endif #ifdef TYPE_INT lenForType(INT) #endif #ifdef TYPE_LONG lenForType(LONG) #endif #ifdef TYPE_LONGLONG lenForType(LONGLONG) #endif lenForType(FLOAT) #ifdef TYPE_DOUBLE lenForType(DOUBLE) #endif lenForType(8) #ifdef TYPE_16 lenForType(16) #endif #ifdef TYPE_32 lenForType(32) #endif #ifdef TYPE_64 lenForType(64) #endif } return -1; } #undef lenForType #define sizeForType(type) case TYPE_##type: \ return sizeof(typename(U, type)); /** * @name typeSize * determines the size of the type * @param type: int, the type * @returns int, the size, -1 if unable to determine it */ int typeSize(int type) { switch(type&0xf) { sizeForType(CHAR) #ifdef TYPE_SHORT sizeForType(SHORT) #endif #ifdef TYPE_INT sizeForType(INT) #endif #ifdef TYPE_LONG sizeForType(LONG) #endif #ifdef TYPE_LONGLONG sizeForType(LONGLONG) #endif sizeForType(FLOAT) #ifdef TYPE_DOUBLE sizeForType(DOUBLE) #endif sizeForType(8) #ifdef TYPE_16 sizeForType(16) #endif #ifdef TYPE_32 sizeForType(32) #endif #ifdef TYPE_64 sizeForType(64) #endif } return -1; } #undef sizeForType //END internal functions //BEGIN buffer creator /** * @ref buffer.new(size) * @arg1: int, size * @rer1: buffer, buf */ int api_bufferNew(lua_State *L) { int size=luaL_checkinteger(L, 1); if(size<=0) return luaL_argerror(L, 1, "size must be positive"); buffer_t* buf=(buffer_t*) lua_newuserdata(L, sizeof(buffer_t)); if(!buffer_allocData(buf, size, 0)) { buf->alloc=0; return luaL_error(L, "failed to allocate buffer"); } luaL_setmetatable(L, BUFFER_CLASS); return 1; } /** * @ref buffer.calloc(len, elem) * @arg1: int, len * @arg2: int|string, elem * @rer1: buffer, buf */ int api_bufferCalloc(lua_State *L) { // get size and/or type int len=luaL_checkinteger(L, 1); if(len<=0) return luaL_argerror(L, 1, "length must be positive"); int elem, type=TYPE_UNSIGNED|TYPE_CHAR; if(lua_isnumber(L, 2)) elem=luaL_checkinteger(L, 2); else { type=typeFromArg(L, NULL, 2); elem=typeSize(type); } if(elem<=0) return luaL_argerror(L, 2, "element size must be positive"); // allocate and create buffer_t* buf=(buffer_t*) lua_newuserdata(L, sizeof(buffer_t)); if(!buffer_callocData(buf, len, elem, 0)) { buf->alloc=0; return luaL_error(L, "failed to allocate buffer"); } luaL_setmetatable(L, BUFFER_CLASS); // set type lua_pushinteger(L, type); lua_pushcfunction(L, api_bufferSetType); lua_insert(L, -3); lua_copy(L, -2, 1); lua_call(L, 2, 0); lua_settop(L, 1); return 1; } //END buffer creator //BEGIN size getter/setter /** * @ref buf.size * @ref buf:getsize() * @ref buffer.getsize(buf) * @arg1: buffer, buf * @ret1: int, size */ int api_bufferGetSize(lua_State *L) { buffer_t *buf=bufferFromArg(L); lua_pushinteger(L, buffer_getSize(buf)); return 1; } /** * @ref buf.size=val * @ref buf:setsize(val) * @ref buffer.setsize(buf, val) * @arg1: buffer, buf * @arg2: int, val */ int api_bufferSetSize(lua_State *L) { buffer_t *buf=bufferFromArg(L); int size=luaL_checkinteger(L, 2); if(size<=0) return luaL_argerror(L, 2, "the size must be positive"); if(!buffer_resize(buf, size)) return luaL_error(L, "error while resizing buffer"); return 0; } //END size getter/setter //BEGIN length getter/setter /** * @ref #buf * @ref buf.length * @ref buf:getlength([type]) * @ref buffer.getlength(buf, [type]) * @arg1: buffer, buf * @arg2: string|int?, type * @ret1: int, length */ int api_bufferGetLength(lua_State *L) { buffer_t *buf=bufferFromArg(L); int type=typeFromArg(L, buf, 2); int len=getLength(buf, type); if(len==-1) return luaL_error(L, "unable to get length"); lua_pushinteger(L, len); return 1; } /** * @ref buf.length=val * @ref buf:setlength(val, [type]) * @ref buffer.setlength(buf, val, [type]) * @arg1: buffer, buf * @arg2: int, val * @arg3: string|int?, type */ int api_bufferSetLength(lua_State *L) { buffer_t *buf=bufferFromArg(L); int len=luaL_checkinteger(L, 2); int type=typeFromArg(L, buf, 3); int size=typeSize(type); if(size==-1) return luaL_error(L, "unable to get size of type for resizing"); if(len<=0) return luaL_argerror(L, 2, "the length must be positive"); if(!buffer_resize(buf, size*len)) return luaL_error(L, "error while resizing buffer"); return 0; } //END length getter/setter //BEGIN type getter/setter /** * @ref buf.type * @ref buf:gettype() * @ref buffer.gettype(buf) * @arg1: buffer, buf * @ret1: int, type */ int api_bufferGetType(lua_State *L) { buffer_t *buf=bufferFromArg(L); lua_pushinteger(L, buffer_getUser(buf)&0x1f); return 1; } /** * @ref buf.type=val * @ref buf:settype(val) * @ref buffer.settype(buf, val) * @arg1: buffer, buf * @arg2: string|int, type */ int api_bufferSetType(lua_State *L) { buffer_t *buf=bufferFromArg(L); int type=typeFromArg(L, buf, 2); int user=buffer_getUser(buf)&~0x1f; buffer_setUser(buf, user|type); return 0; } //END type getter/setter //BEGIN value getter/setter #define get(type, sgn, luatype) case typeid(type): \ ok=1; \ lua_push##luatype(L, buffer_get(buf, idx, typename(sgn, type))); \ break; /** * @ref buf[idx] * @ref buf:get(idx, [type]) * @ref buffer.get(buf, idx, [type]) * @arg1: buffer, buf * @arg2: int, idx * @arg2: string|int?, type * @ret1: number, value */ int api_bufferGet(lua_State *L) { buffer_t *buf=bufferFromArg(L); int idx=luaL_checkinteger(L, 2)-1; int type=typeFromArg(L, buf, 3); if(idx<0||idx>=getLength(buf, type)) return 0; int ok=0; if(type&TYPE_SIGNED) { switch(type&0xf) { get(CHAR, S, integer) #ifdef TYPE_SHORT get(SHORT, S, integer) #endif #ifdef TYPE_INT get(INT, S, integer) #endif #ifdef TYPE_LONG get(LONG, S, integer) #endif #ifdef TYPE_LONGLONG get(LONGLONG, S, integer) #endif get(FLOAT, S, number) #ifdef TYPE_DOUBLE get(DOUBLE, S, number) #endif get(8, S, integer) #ifdef TYPE_16 get(16, S, integer) #endif #ifdef TYPE_32 get(32, S, integer) #endif #ifdef TYPE_64 get(64, S, integer) #endif } } else { switch(type&0xf) { get(CHAR, U, integer) #ifdef TYPE_SHORT get(SHORT, U, integer) #endif #ifdef TYPE_INT get(INT, U, integer) #endif #ifdef TYPE_LONG get(LONG, U, integer) #endif #ifdef TYPE_LONGLONG get(LONGLONG, U, integer) #endif get(FLOAT, U, number) #ifdef TYPE_DOUBLE get(DOUBLE, U, number) #endif get(8, U, integer) #ifdef TYPE_16 get(16, U, integer) #endif #ifdef TYPE_32 get(32, U, integer) #endif #ifdef TYPE_64 get(64, U, integer) #endif } } if(ok) return 1; else return luaL_error(L, "unable to get value"); } #undef get #define set(type, luatype) case typeid(type): \ ok=1; \ buffer_set(buf, idx, (typename(U, type)) luaL_check##luatype(L, 3), typename(U, type)); \ break; \ /** * @ref buf[idx]=val * @ref buf:set(idx, val, [type]) * @ref buffer.set(buf, idx, val, [type]) * @arg1: buffer, buf * @arg2: int, idx * @arg3: number, val * @arg4: string|int?, type */ int api_bufferSet(lua_State *L) { buffer_t *buf=bufferFromArg(L); int idx=luaL_checkinteger(L, 2)-1; int type=typeFromArg(L, buf, 4); if(idx<0||idx>=getLength(buf, type)) return 0; int ok=0; switch(type&0xf) { set(CHAR, integer) #ifdef TYPE_SHORT set(SHORT, integer) #endif #ifdef TYPE_INT set(INT, integer) #endif #ifdef TYPE_LONG set(LONG, integer) #endif #ifdef TYPE_LONGLONG set(LONGLONG, integer) #endif set(FLOAT, number) #ifdef TYPE_DOUBLE set(DOUBLE, number) #endif set(8, integer) #ifdef TYPE_16 set(16, integer) #endif #ifdef TYPE_32 set(32, integer) #endif #ifdef TYPE_64 set(64, integer) #endif } if(!ok) return luaL_error(L, "unable to set value"); else return 0; } #undef set //END value getter/setter //BEGIN metamethods /** * @name __index * @ref buf[key] * @arg1: buffer, buf * @arg2: any, key * @ret: any */ int meta_index(lua_State *L) { if(lua_isnumber(L, 2)) return api_bufferGet(L); else { // try getting from the first upvalue (the getter list) lua_settop(L, 3); lua_copy(L, 2, 3); if(lua_gettable(L, lua_upvalueindex(1))) { // call the function lua_remove(L, 2); lua_insert(L, 1); lua_call(L, 1, LUA_MULTRET); return lua_gettop(L); } lua_pop(L, 1); // try getting from the second upvalue (the library) if(lua_gettable(L, lua_upvalueindex(2))) return 1; return 0; } } /** * @name __newindex * @ref buf[key]=val * @arg1: buffer, buf * @arg2: any, key * @arg3: any, val */ int meta_newindex(lua_State *L) { if(lua_isnumber(L, 2)) return api_bufferSet(L); else { // try getting from the first upvalue (the setter list) lua_settop(L, 4); lua_copy(L, 2, 4); if(lua_gettable(L, lua_upvalueindex(1))) { // call the function lua_remove(L, 2); lua_insert(L, 1); lua_call(L, 2, LUA_MULTRET); return lua_gettop(L); } return 0; } } /** * @name __len * @ref #buf * @arg1: buffer, buf * @ret1: int, length */ int meta_len(lua_State *L) { lua_settop(L, 1); return api_bufferGetLength(L); } /** * @name __ipairs * @ref ipairs(buf) * @arg1: any, buf * @ret1: function, iter * @ret2: any, buf * @ret3: int, 0 */ int meta_ipairs(lua_State *L) { // keep only the buffer on the stack lua_settop(L, 1); // insert the iterator at the bottom of the stack lua_pushcfunction(L, other_iter); lua_insert(L, 1); // push 0 lua_pushinteger(L, 0); return 3; } /** * @name __gc * @arg1: buffer, buf */ int meta_gc(lua_State *L) { buffer_t *buf=bufferFromArg(L); buffer_destroyData(buf); return 0; } //END metamethods //BEGIN other Lua functions /** * @name iter * @ref i, v=iter(tab, idx) * iterates through a table or table-like object * @arg1: table, tab * @arg2: number, idx * @ret1: number, i * @ret2: any, v */ int other_iter(lua_State *L) { lua_Integer idx=luaL_checkinteger(L, 2)+1; lua_pushinteger(L, idx); if(lua_gettable(L, 1)) { lua_pushinteger(L, idx); lua_insert(L, -2); return 2; } else return 1; } //END other Lua functions //BEGIN setup functions /** * @name luaopen_buffer2 * this is the entrypoint which is called when the module is loaded * creates the library and the metatable, and returns the library only */ int luaopen_buffer2(lua_State *L) { // clear the stack lua_settop(L, 0); // create the library setupLib(L); // create the metatable setupMeta(L); // return the library return 1; } /** * @name setupLib * creates the buffer2 library and leaves it on the stack */ int setupLib(lua_State *L) { // create table with all the functions static luaL_Reg lib[]={ {"new", api_bufferNew}, {"calloc", api_bufferCalloc}, {"getsize", api_bufferGetSize}, {"setsize", api_bufferSetSize}, {"getlength", api_bufferGetLength}, {"setlength", api_bufferSetLength}, {"gettype", api_bufferGetType}, {"settype", api_bufferSetType}, {"get", api_bufferGet}, {"set", api_bufferSet}, {"iter", other_iter}, {NULL, NULL} }; luaL_newlib(L, lib); // create table with all the types lua_newtable(L); lua_pushinteger(L, TYPE_CHAR); lua_setfield(L, -2, "char"); #ifdef TYPE_SHORT lua_pushinteger(L, TYPE_SHORT); lua_setfield(L, -2, "short"); #endif #ifdef TYPE_INT lua_pushinteger(L, TYPE_INT); lua_setfield(L, -2, "int"); #endif #ifdef TYPE_LONG lua_pushinteger(L, TYPE_LONG); lua_setfield(L, -2, "long"); #endif #ifdef TYPE_LONGLONG lua_pushinteger(L, TYPE_LONGLONG); lua_setfield(L, -2, "long long"); #endif lua_pushinteger(L, TYPE_FLOAT); lua_setfield(L, -2, "float"); #ifdef TYPE_DOUBLE lua_pushinteger(L, TYPE_DOUBLE); lua_setfield(L, -2, "double"); #endif lua_pushinteger(L, TYPE_8); lua_setfield(L, -2, "8"); lua_pushinteger(L, TYPE_8); lua_setfield(L, -2, "int8"); #ifdef TYPE_16 lua_pushinteger(L, TYPE_16); lua_setfield(L, -2, "16"); lua_pushinteger(L, TYPE_16); lua_setfield(L, -2, "int16"); #endif #ifdef TYPE_32 lua_pushinteger(L, TYPE_32); lua_setfield(L, -2, "32"); lua_pushinteger(L, TYPE_32); lua_setfield(L, -2, "int32"); #endif #ifdef TYPE_64 lua_pushinteger(L, TYPE_64); lua_setfield(L, -2, "64"); lua_pushinteger(L, TYPE_64); lua_setfield(L, -2, "int64"); #endif lua_setfield(L, 1, "types"); return 1; } /** * @name setupMeta * creates the metatable for buffers */ int setupMeta(lua_State *L) { // create metatable luaL_newmetatable(L, BUFFER_CLASS); // simple methods lua_pushcfunction(L, meta_len); lua_setfield(L, 2, "__len"); lua_pushcfunction(L, meta_gc); lua_setfield(L, 2, "__gc"); lua_pushcfunction(L, meta_ipairs); lua_setfield(L, 2, "__ipairs"); // __index static luaL_Reg getters[]={ {"size", api_bufferGetSize}, {"length", api_bufferGetLength}, {"type", api_bufferGetType}, {NULL, NULL} }; luaL_newlib(L, getters); lua_settop(L, lua_gettop(L)+1); lua_copy(L, 1, -1); lua_pushcclosure(L, meta_index, 2); lua_setfield(L, 2, "__index"); // __newindex static luaL_Reg setters[]={ {"size", api_bufferSetSize}, {"length", api_bufferSetLength}, {"type", api_bufferSetType}, {NULL, NULL} }; luaL_newlib(L, setters); lua_pushcclosure(L, meta_newindex, 1); lua_setfield(L, 2, "__newindex"); lua_pop(L, 1); return 0; } //END setup functions
Java
UTF-8
2,888
3.625
4
[]
no_license
package VBUtils; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; /** * Read, Write, Clear and Crete files * @author vinicius.reif */ public class VBFile { private File file; /** * Create new file manager * @param path * @throws IOException */ public VBFile(String path) throws IOException { File f = new File(path); if(f.isDirectory()) { throw new IOException("The path is a directory"); } if(!f.exists()) { f.createNewFile(); } this.file = f; } /** * Create new file manager * @param file * @throws IOException */ public VBFile(File file) throws IOException { if(file.isDirectory()) { throw new IOException("The path is a directory"); } if(!file.exists()) { file.createNewFile(); } this.file = file; } /** * Write text in file * @param text * @throws IOException */ public void write(String text) throws IOException { PrintWriter pw = new PrintWriter(this.file); pw.write(text); pw.flush(); pw.close(); } /** * Write text in file using append before * @param text * @throws IOException */ public void writeAppendBefore(String text) throws IOException { String content = this.read(); text = text + "\n" + content; PrintWriter pw = new PrintWriter(this.file); pw.write(text); pw.flush(); pw.close(); } /** * Write text in file using append after * @param text * @throws IOException */ public void writeAppendAfter(String text) throws IOException { String content = this.read(); text = content + text; PrintWriter pw = new PrintWriter(this.file); pw.write(text); pw.flush(); pw.close(); } /** * Read file * @return * @throws java.io.IOException */ public String read() throws IOException { String result = ""; try (Scanner s = new Scanner(this.file)) { while(s.hasNext()) { result += s.nextLine() + "\n"; } } return result; } /** * Clear file content */ public void clearContents() throws IOException { PrintWriter pw = new PrintWriter(this.file); pw.write(""); pw.flush(); pw.close(); } /** * Delete file */ public void delete() { this.file.delete(); } public File getFile() { return file; } public void setFile(File file) { this.file = file; } }
Java
UTF-8
5,867
2.109375
2
[]
no_license
package haitham.kinneret.appsusage; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; import com.rvalerio.fgchecker.AppChecker; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class AppUsageTrackerService extends Service { private static final String TAG = AppUsageTrackerService.class.getSimpleName(); AppChecker appChecker; String startTime ; String endTime = null; String usageDuration = null; boolean alredyGotStartTime = false; String overallUsageTime ; static long overallDiff = 0; @Override public int onStartCommand(Intent intent, int flags, int startId) { appChecker.whenAny(new AppChecker.Listener() { @Override public void onForeground(String process) { //Toast.makeText(getApplicationContext(),process+ " is foreground",Toast.LENGTH_SHORT).show(); int timeInSeconds = 0; if(!process.contains("launcher")){ Log.e(TAG,process+ " is foreground"); if(!alredyGotStartTime) { SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); startTime = format.format(new Date()); } alredyGotStartTime = true; } else { SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); endTime = format.format(new Date()); Date time1 = null; Date time2 = null; try{ if(startTime != null) { time1 = format.parse(startTime); time2 = format.parse(endTime); //In milliseconds long diff = time2.getTime() - time1.getTime(); overallDiff += diff; //Convert diff from milliseconds to hh:mm:ss long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 50 * 1000) % 24; //Convert overallDiff from milliseconds to hh:mm:ss long overallDiffSeconds = overallDiff / 1000 % 60; long overallDiffMinutes = overallDiff / (60 * 1000) % 60; long overallDiffHours = overallDiff / (60 * 50 * 1000) % 24; usageDuration = String.valueOf(diffHours) + ":" + String.valueOf(diffMinutes) + ":" + String.valueOf(diffSeconds); overallUsageTime = String.valueOf(overallDiffHours) + ":" + String.valueOf(diffMinutes) + ":" + String.valueOf(overallDiffSeconds); Log.e(TAG,"Usage duration: " + usageDuration); Log.e(TAG,"overall Usage time: " + overallUsageTime); startTime =null; alredyGotStartTime=false; } } catch (ParseException e) { e.printStackTrace(); } } } }). when("com.whatsapp", new AppChecker.Listener() { @Override public void onForeground(String process) { Log.e(TAG, "whatsapp -> social"); } }). when("com.instagram.android", new AppChecker.Listener() { @Override public void onForeground(String process) { Log.e(TAG, "instagram -> social"); } }). when("com.facebook.katana", new AppChecker.Listener() { @Override public void onForeground(String process) { Log.e(TAG, "facebook -> social"); } }). when("com.facebook.lite", new AppChecker.Listener() { @Override public void onForeground(String process) { Log.e(TAG, "facebook -> social"); } }). when("com.facebook.mlite", new AppChecker.Listener() { @Override public void onForeground(String process) { Log.e(TAG, "facebook -> social"); } }). when("com.facebook.orca", new AppChecker.Listener() { @Override public void onForeground(String process) { Log.e(TAG, "facebook -> social"); } }). when("com.snapchat.android", new AppChecker.Listener() { @Override public void onForeground(String process) { Log.e(TAG, "snapchat -> social"); } }). when("com.twitter.android", new AppChecker.Listener() { @Override public void onForeground(String process) { Log.e(TAG, "twitter -> social"); } }). timeout(1000).start(getApplicationContext()); return START_STICKY; } @Override public void onCreate() { super.onCreate(); appChecker = new AppChecker(); } @Override public void onDestroy() { super.onDestroy(); appChecker.stop(); } @Override public IBinder onBind(Intent intent) {return null;} }
PHP
UTF-8
3,583
2.640625
3
[]
no_license
<!DOCTYPE html> <?php // connexion a la basse de donnée $bdd = new PDO('mysql:host=localhost;dbname=workshop2;charset=utf8','root',''); if(isset($_POST['inscription'])){ $nom = htmlspecialchars($_POST['nom']); $prenom = htmlspecialchars($_POST['prenom']); $ville = htmlspecialchars($_POST['ville']); $mail = htmlspecialchars($_POST['mail']); $mdp = sha1($_POST['mdp']); $mdp2 = sha1($_POST['mdp2']); $date_naissance = htmlspecialchars($_POST['date_naissance']); $description = htmlspecialchars($_POST['description']); if(!empty($_POST['nom']) AND !empty($_POST['prenom']) AND !empty($_POST['ville']) AND !empty($_POST['mail']) AND !empty($_POST['mdp']) AND !empty($_POST['mdp2']) AND !empty($_POST['description'])) { $reqmail = $bdd->prepare("SELECT * FROM USERS WHERE mail = ? "); $reqmail->execute(array($mail)); $mailexist = $reqmail->rowCount(); if ($mailexist == 0){ if($mdp==$mdp2){ $req = $bdd->prepare('INSERT INTO users(nom, prenom, ville, mail, date_naissance, description, motdepasse) VALUE(:nom, :prenom, :ville, :mail, :date_naissance, :description, :motdepasse)'); $req->bindParam(':nom', $nom); $req->bindParam(':prenom', $prenom); $req->bindParam(':ville', $ville); $req->bindParam(':mail', $mail); $req->bindParam(':date_naissance', $date_naissance); $req->bindParam(':description', $description); $req->bindParam(':motdepasse', $mdp); $req->execute(); $erreur = "Votre compte a bien ete cree !"; header('Location: connexion.php'); } else { $erreur = "vos mots de passes ne correspondent pas !"; } } else{ $erreur = "Adresse mail déja utilisée !"; } } else { $erreur = "Tout les champs doivent etre completes !"; } } ?> <html> <head> <!-- importer le fichier de style --> <link href="../Css/Inscription.css" rel="stylesheet" type="text/css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <meta charset="utf-8"> </head> <body> <div id="container_inscription"> <!-- zone d'inscription --> <h1 id="Title">Inscription</h1> <form method="POST" action=""> <br> <input type="text" placeholder="Nom" id="nom" name="nom"> <input type="text" placeholder="Prenom" id="prenom" name="prenom"> <input type="text" placeholder="Ville" id="ville" name="ville"> <input type="email" placeholder="Mail" id="mail" name="mail"> <input type="password" placeholder="Mot de passe" id="password" name="mdp"> <input type="text" placeholder="Confirme mot de passe" id="password2" name="mdp2"> <input type="date" max="2005-01-01" min="1900-01-01" id="date_naissance" name="date_naissance" > <input type="text" placeholder="Description de vous" id="description" name="description"> <input id="Valider" type="submit" name="inscription" value="je m'inscris"> </form> <?php if(isset($erreur)){ echo '<font color="red">'.$erreur."</font>"; } ?> </div> </body> </html>
Python
UTF-8
1,417
2.90625
3
[]
no_license
N = int(input()) coor = [] for i in range(N): x,y = [int(x) for x in input().split()] coor.append((x,y)) count = 0 for i in range(N): for j in range(i+1, N): for k in range(j+1, N): if (coor[i][0] - coor[j][0]) == 0 or (coor[i][0] - coor[k][0]) == 0 or (coor[j][0] - coor[k][0]) == 0: if (coor[i][0] - coor[j][0]) != 0 or (coor[i][0] - coor[k][0]) != 0 or (coor[j][0] - coor[k][0]) != 0 : count += 1 continue tana = (coor[i][1] - coor[j][1]) / (coor[i][0] - coor[j][0]) tanb = (coor[i][1] - coor[k][1]) / (coor[i][0] - coor[k][0]) tanc = (coor[j][1] - coor[k][1]) / (coor[j][0] - coor[k][0]) if tana != tanb or tanb != tanc or tana != tanc: count += 1 print(count) # count = 0 # for i in range(N): # for j in range(N): # for k in range(N): # if i == j or i == k or j == k: continue # if (coor[i][0] - coor[j][0]) == 0 or (coor[i][0] - coor[k][0]) == 0: # if (coor[i][0] - coor[j][0]) != 0 or (coor[i][0] - coor[k][0]) != 0: # count += 1 # continue # tana = (coor[i][1] - coor[j][1]) / (coor[i][0] - coor[j][0]) # tanb = (coor[i][1] - coor[k][1]) / (coor[i][0] - coor[k][0]) # if tana != tanb: # count += 1 # print(count)
Java
UTF-8
334
2.0625
2
[]
no_license
package com.example.myinterface.Model; import com.google.gson.annotations.SerializedName; import java.util.List; public class BaseCollectionResponse<T> { @SerializedName("collection") private T data; public T getData() { return data; } public void setData(T data) { this.data = data; } }
Java
UTF-8
3,978
2.0625
2
[]
no_license
package com.minipg.fanster.armoury.adapter; import android.content.Intent; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.minipg.fanster.armoury.R; import com.minipg.fanster.armoury.activity.LoginActivity; import com.minipg.fanster.armoury.activity.TopicListActivity; import com.minipg.fanster.armoury.dao.CategoryItemDao; import com.minipg.fanster.armoury.fragment.TabCategoryFragment; import com.minipg.fanster.armoury.manager.CategoryListManager; import com.minipg.fanster.armoury.view.CategoryListItem; import java.util.List; import java.util.Locale; /** * Created by MFEC on 8/7/2017. */ //public class CategoryAdapter extends BaseAdapter { // // List<CategoryItemDao> dao; // // public void setDao(List<CategoryItemDao> dao) { // this.dao = dao; // } // // @Override // public int getCount() { // if (dao == null) // return 0; // return dao.size(); // } // // @Override // public Object getItem(int i) { // return CategoryListManager.getInstance().getDao().get(i); // } // // @Override // public long getItemId(int i) { // return 0; // } // // @Override // public View getView(int i, View view, ViewGroup viewGroup) { // CategoryListItem item; // if(view != null) // item = (CategoryListItem) view; // else // item = new CategoryListItem(viewGroup.getContext()); // CategoryItemDao dao = (CategoryItemDao) getItem(i); // item.setCategory(dao.getName()); // item.setAmount(i); // return item; // } //} public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.CategoryListItemHolder>{ TabCategoryFragment fragmentCategory; List<CategoryItemDao> categoryList; TabCategoryFragment fragmentCategory1; CategoryItemDao dao; public CategoryAdapter(TabCategoryFragment fragmentCategory, List<CategoryItemDao> categoryList, TabCategoryFragment fragmentCategory1){ this.fragmentCategory = fragmentCategory; this.categoryList = categoryList; this.fragmentCategory1 = fragmentCategory1; } @Override public CategoryListItemHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()). inflate(R.layout.list_category,parent,false); return new CategoryListItemHolder(itemView); } @Override public void onBindViewHolder(CategoryListItemHolder holder, int position) { if(categoryList!=null) dao = categoryList.get(position); if(dao!=null) holder.tvCate.setText(dao.getName()); else holder.tvCate.setText("IOS"); holder.tvAmount.setText("Amount : "+ position+1); holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(fragmentCategory.getActivity(), TopicListActivity.class); fragmentCategory1.startActivity(intent); } }); } @Override public int getItemCount() { if(categoryList == null) return 4; return categoryList.size(); } static class CategoryListItemHolder extends RecyclerView.ViewHolder { private final TextView tvCate; private final TextView tvAmount; private final CardView cardView; public CategoryListItemHolder(View itemView) { super(itemView); tvCate = (TextView) itemView.findViewById(R.id.tvCategory); tvAmount = (TextView) itemView.findViewById(R.id.tvAmount); cardView = (CardView) itemView.findViewById(R.id.cardViewCategory); } } }
Java
UTF-8
496
3.0625
3
[]
no_license
package game; import java.awt.Color; import java.awt.Graphics; public class FrutaTipoFrutaComum extends FrutasDiversas { public FrutaTipoFrutaComum(int dX, int dY, int tileSize) { this.dX = dX; this.dY = dY; WIDTH = tileSize; HEIGHT = tileSize; } public void draw(Graphics g) { g.setColor(Color.GREEN); g.fillRect(dX*WIDTH, dY*HEIGHT, WIDTH, HEIGHT); g.setColor(Color.WHITE); g.fillRect(dX*WIDTH, dY*HEIGHT, WIDTH/2, HEIGHT/2); } }
C++
UTF-8
584
3.234375
3
[]
no_license
/** * @file laguerre.h * @brief calcule la valeur des polynomes de laguerre */ #ifndef LAGUERRE_HPP # define LAGUERRE_HPP # include <armadillo> /** * Renvoie un cube, contenant les valeurs des polynomes de Laguerre, * indexé en L[z][m][n] * @param z un vecteur colonne contenant les abscisses 'z' * @param mMax la valeur maximal de 'm' dans le calcul * @param nMax la valeur maximal de 'n' dans le calcul * @return L un cube contenant les valeurs de polynomes de Laguerre : L[z][m][n] */ arma::cube laguerre(arma::vec z, unsigned int mMax, unsigned int nMax); #endif
TypeScript
UTF-8
971
2.75
3
[]
no_license
/*Aufgabe: <11> Name: <Franziska Winkler> Matrikel: <260944> Datum: <06.06.2019> Hiermit versichere ich, dass ich diesen Code selbst geschrieben habe. Er wurde nicht kopiert und auch nicht diktiert.*/ namespace Unterwasserwelt { export class Bubble { x: number; y: number; dx: number; dy: number; draw(): void { let bubble: Path2D = new Path2D(); bubble.arc(this.x, this.y, 6, 0, 2 * Math.PI); crc.fillStyle = "blue"; crc.fill(bubble); crc.strokeStyle = "blue"; crc.stroke(bubble); } update(): void { this.move(); this.draw(); } move(): void { if (this.y < 10) { this.x = 150; this.y = 350; this.x = 0 + (Math.random() * 900); } this.x += this.dx; this.y += this.dy; this.draw(); } } }
C++
UTF-8
1,190
2.78125
3
[]
no_license
#include "engine/system/render/ShaderParameter.h" namespace ds_render { ShaderParameter::ShaderParameter() { } ShaderParameter::ShaderParameter(const std::string &name, ShaderParameter::ShaderParameterType dataType, size_t dataSize, const void *dataIn) { m_name = name; m_dataType = dataType; m_dataBuffer.Clear(); m_dataBuffer.Insert(dataSize, dataIn); } const std::string &ShaderParameter::GetName() const { return m_name; } void ShaderParameter::SetName(const std::string &uniformName) { m_name = uniformName; } ShaderParameter::ShaderParameterType ShaderParameter::GetDataType() const { return m_dataType; } void ShaderParameter::SetDataType(ShaderParameter::ShaderParameterType dataType) { m_dataType = dataType; } const void *ShaderParameter::GetData() const { return m_dataBuffer.GetDataPtr(); } size_t ShaderParameter::GetDataSize() const { return m_dataBuffer.AvailableBytes(); } void ShaderParameter::SetData(size_t dataSize, const void *dataIn) { // Clear data already in buffer m_dataBuffer.Clear(); // Insert new data m_dataBuffer.Insert(dataSize, dataIn); } }
JavaScript
UTF-8
829
2.921875
3
[]
no_license
var express=require('express'); var app=express(); app.get('/',function(req,res){ res.send('Welcome to my assignemnt') }); app.get('/speak/animal:',function(req,res){ var animal={ pig:"oink", dog:"woof", cow:"mu", } var animal=req.params.animal.toLowerCase(); var sound=sound[animal]; res.send('The ' +animal +'says' +sound) }); app.get('/repeat/:messge/:times',function(req,res){ var message=req.params.message; var times=Number(req.params.times); var result=""; for (var i=0;i<times;i++){ result += message + " " } res.send(result) }) app.get('*',function(req,res){ res.send('You have an error ') }) app.listen(8080,(err)=>{ if(err){ console.error(err); return } console.log('Server started successfully ') })
Java
UTF-8
5,307
2.078125
2
[]
no_license
package com.washingtonpost.arc.sub.cache; import com.hazelcast.aws.AwsDiscoveryStrategyFactory; import com.hazelcast.config.*; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import com.hazelcast.instance.HazelcastInstanceFactory; import com.hazelcast.spi.properties.GroupProperty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Singleton; import java.util.HashMap; import java.util.Map; @Singleton public class HazelCache { private static Logger log = LoggerFactory.getLogger(HazelCache.class); public static final EvictionConfig NEVER_EVICT_CONFIG = new EvictionConfig().setEvictionPolicy(EvictionPolicy.NONE); private static NearCacheConfig LONG_TERM_NEAR_CACHE_CONFIG = new NearCacheConfig().setName("as-long-term-near-cache") .setInMemoryFormat(InMemoryFormat.OBJECT) .setCacheLocalEntries(true) .setTimeToLiveSeconds(0) .setInvalidateOnChange(true) .setEvictionConfig(NEVER_EVICT_CONFIG); private static MapStoreConfig DB_BACKED_MAP_CONFIG = new MapStoreConfig() .setClassName("com.washingtonpost.arc.sub.cache.SettingsStore") .setEnabled(true) .setWriteDelaySeconds(1) .setInitialLoadMode(MapStoreConfig.InitialLoadMode.EAGER) .setWriteCoalescing(false); /** * Settings Map Config with Near-Cache And DB Store */ private static MapConfig MAPCONFIG_WITH_NEAR_CACHE_AND_MAPSTORE = ( new MapConfig() ).setName("tenant-settings") .setBackupCount(2) .setTimeToLiveSeconds(300) .setNearCacheConfig(LONG_TERM_NEAR_CACHE_CONFIG) .setMapStoreConfig(DB_BACKED_MAP_CONFIG); private static Config MAIN_HAZEL_CONFIG = new Config(); HazelcastInstance hazelcastInstance; @Inject public HazelCache(com.typesafe.config.Config config) { log.info("Starting HazelCast Cache configuration"); AwsDiscoveryStrategyFactory awsDiscoveryStrategyFactory = new AwsDiscoveryStrategyFactory(); Map<String, Comparable> properties = new HashMap<String, Comparable>(); properties.put("hz-port", config.getInt("hazel.port")); properties.put("iam-role","ecsInstanceRole"); DiscoveryStrategyConfig discoveryStrategyConfig = new DiscoveryStrategyConfig(awsDiscoveryStrategyFactory, properties); //DiscoveryConfig dc = new DiscoveryConfig().addDiscoveryStrategyConfig(com.hazelcast MAIN_HAZEL_CONFIG.setProperty(GroupProperty.DISCOVERY_SPI_ENABLED.getName(), String.valueOf(true)); NetworkConfig networkConfig = MAIN_HAZEL_CONFIG.getNetworkConfig(); networkConfig.getInterfaces() .addInterface(config.getString("hazel.interfaces")); JoinConfig njc = networkConfig.getJoin(); njc.getTcpIpConfig() .setEnabled(false); njc.getAwsConfig() .setEnabled(false); njc.getMulticastConfig() .setEnabled(false); njc.getDiscoveryConfig() .addDiscoveryStrategyConfig(discoveryStrategyConfig); networkConfig .setPort(config.getInt("hazel.port")) .setPortAutoIncrement(false); hazelcastInstance = HazelcastInstanceFactory.newHazelcastInstance(MAIN_HAZEL_CONFIG); IMap<String, Object> map = hazelcastInstance .getMap("tenant-settings"); } public void put(String s, String counter, long counter1) { hazelcastInstance.getMap(s) .put(counter, counter1); } public <T> T get(String s, String counter) { return (T) hazelcastInstance.getMap(s) .get(counter); } public long count(String s) { return hazelcastInstance.getMap(s) .size(); } }
Java
UTF-8
1,749
2.609375
3
[]
no_license
package org.wpa.DTO; import org.wpa.BO.Senator; /** * * @author Veronika Maurerova */ public class SenatorDto extends ParticipationDto { private final String ROLE = "Senátor"; CommitteDto commiteDto; FractionDto fractionDto; StateDto stateDto; DistrictDto districtDto; public SenatorDto() { } public <E extends Senator> SenatorDto(E senator) { super(senator); this.districtDto = new DistrictDto(senator.getDistrict()); this.commiteDto = new CommitteDto(senator.getCommitte()); this.fractionDto = new FractionDto(senator.getFraction()); this.stateDto = new StateDto(senator.getState()); } public CommitteDto getCommiteDto() { return commiteDto; } public void setCommiteDto(CommitteDto commiteDto) { this.commiteDto = commiteDto; } public FractionDto getFractionDto() { return fractionDto; } public void setFractionDto(FractionDto fractionDto) { this.fractionDto = fractionDto; } public StateDto getStateDto() { return stateDto; } public void setStateDto(StateDto stateDto) { this.stateDto = stateDto; } public DistrictDto getDistrictDto() { return districtDto; } public void setDistrictDto(DistrictDto districtDto) { this.districtDto = districtDto; } @Override public String getROLE() { return ROLE; } @Override public String toString() { return "org.wpa.DTO.SenatorDto[" + toTmpString() + " ]"; } @Override public String toTmpString() { return super.toTmpString() + ", districDto=" + districtDto; } }
C++
UTF-8
2,391
3.453125
3
[]
no_license
/* There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog starts at point 0 in the second lane and wants to jump to point n. However, there could be obstacles along the way. You are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 to 3) describes an obstacle on the lane obstacles[i] at point i. If obstacles[i] == 0, there are no obstacles at point i. There will be at most one obstacle in the 3 lanes at each point. For example, if obstacles[2] == 1, then there is an obstacle on lane 1 at point 2. The frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle on the lane at point i + 1. To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane. For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. Return the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0. Note: There will be no obstacles on points 0 and n. Example 1: Input: obstacles = [0,1,2,3,0] Output: 2 Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows). Note that the frog can jump over obstacles only when making side jumps (as shown at point 2). Example 2: Input: obstacles = [0,1,1,3,3,0] Output: 0 Explanation: There are no obstacles on lane 2. No side jumps are required. Example 3: Input: obstacles = [0,2,1,0,3,0] Output: 2 Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps. Constraints: obstacles.length == n + 1 1 <= n <= 5 * 105 0 <= obstacles[i] <= 3 obstacles[0] == obstacles[n] == 0 */ class Solution { public: int dp[4][500001]; int helper(vector<int>& arr,int lev,int i) { if(arr[i]==lev) return INT_MAX; if(dp[lev][i]!=-1) return dp[lev][i]; if(i+1 >= arr.size()) return 0 ; int ans = 0; if(arr[i+1] == lev) dp[lev][i]= 1+min(helper(arr,((lev+1)%3 == 0)?3:(lev+1)%3,i),helper(arr,((lev+2)%3 == 0)?3:(lev+2)%3,i)); else dp[lev][i]=helper(arr,lev,i+1); return dp[lev][i]; } int minSideJumps(vector<int>& arr) { memset(dp,-1,sizeof(dp)); return helper(arr,2,0); } };
C++
UTF-8
1,112
2.65625
3
[]
no_license
class Solution { public: void showVec( const vector<int>& v ) { cout << "["; for( auto const& i : v ) cout << i << ","; cout << "]" << endl; } bool containsNearbyDuplicate(vector<int>& nums, int k) { // showVec(nums1); // cout << k << endl; map<int,size_t> distMap; for( size_t i=0; i<nums.size(); i++ ) { /* for( auto const& [k,v] : distMap ) cout << "[" << k << "," << v << "]" << " "; cout << endl; */ if( distMap.find(nums[i]) != distMap.end() ) { // cout << "[" << nums[i] << "," << distMap[nums[i]] << "]" << endl; // cout << k << " " << i << endl; if( i - distMap[nums[i]] <= k ) return true; else distMap[nums[i]] = i; } else distMap[nums[i]] = i; } return false; } };
Markdown
UTF-8
4,310
3.21875
3
[ "MIT" ]
permissive
##### Textarea base ```js import React from 'react'; import { Textarea } from 'react-rainbow-components'; const containerStyles = { maxWidth: 700, }; <Textarea id="example-textarea-1" label="Textarea Label" rows={4} placeholder="Placeholder Text" style={containerStyles} className="rainbow-m-vertical_x-large rainbow-p-horizontal_medium rainbow-m_auto" />; ``` ##### Textarea required ```js import React from 'react'; import { Textarea } from 'react-rainbow-components'; const containerStyles = { maxWidth: 700, }; <Textarea label="Textarea Label" required rows={4} placeholder="Placeholder Text Required" style={containerStyles} className="rainbow-m-vertical_x-large rainbow-p-horizontal_medium rainbow-m_auto" />; ``` ##### Textarea disabled ```js import React from 'react'; import { Textarea } from 'react-rainbow-components'; const containerStyles = { maxWidth: 700, }; <Textarea label="Textarea Label" disabled rows={4} placeholder="Textarea disabled" style={containerStyles} className="rainbow-m-vertical_x-large rainbow-p-horizontal_medium rainbow-m_auto" />; ``` ##### Textarea with bottom help ```js import React from 'react'; import { Textarea } from 'react-rainbow-components'; const containerStyles = { maxWidth: 700, }; <Textarea label="Textarea Label" bottomHelpText="This is the bottom help" placeholder="Placeholder Text" rows={4} style={containerStyles} className="rainbow-m-vertical_x-large rainbow-p-horizontal_medium rainbow-m_auto" />; ``` ##### Textarea error ```js import React from 'react'; import { Textarea } from 'react-rainbow-components'; const containerStyles = { maxWidth: 700, }; <Textarea label="Textarea Label Error" error="This Field is Required" rows={4} placeholder="Placeholder Text Error" style={containerStyles} className="rainbow-m-vertical_x-large rainbow-p-horizontal_medium rainbow-m_auto" />; ``` ##### Textarea read only ```js import React from 'react'; import { Textarea } from 'react-rainbow-components'; const containerStyles = { maxWidth: 700, }; <Textarea label="Textarea read only Label" rows={4} value="A rainbow is a meteorological phenomenon that is caused by reflection, refraction and dispersion of light in water droplets resulting in a spectrum of light appearing in the sky. It takes the form of a multicoloured circular arc. Rainbows caused by sunlight always appear in the section of sky directly opposite the sun." readOnly style={containerStyles} className="rainbow-m-vertical_x-large rainbow-p-horizontal_medium rainbow-m_auto" />; ``` ##### Textarea with footer ```js import React, { useState } from 'react'; import { Textarea } from 'react-rainbow-components'; import styled from 'styled-components'; const StyledFooter = styled.div.attrs(props => { return props.theme.rainbow.palette; }) ` font-size: 12px; color: ${props => props.text.header}; text-align: right; padding: 10px; border-radius: 0 0 0.875rem 0.875rem; background-color: #F6F7F9; padding: 16px; `; const containerStyles = { maxWidth: 700, }; function TextareaExample(props) { const [count, setCount] = useState(0); const maxLength = props.maxLength; return ( <Textarea label="Textarea Label" rows={4} onChange={(event) => setCount(event.target.value.length)} maxLength={maxLength} placeholder="Placeholder Text" style={containerStyles} footer={ <StyledFooter> {`${count}/${maxLength}`} </StyledFooter>} className="rainbow-m-vertical_x-large rainbow-p-horizontal_medium rainbow-m_auto" /> ); } <TextareaExample maxLength={160} /> ``` ##### Textarea with variant shaded ```js import React from 'react'; import { Textarea } from 'react-rainbow-components'; const containerStyles = { maxWidth: 700, }; <Textarea id="example-textarea-1" label="Textarea Label" rows={4} placeholder="Placeholder Text" style={containerStyles} variant="shaded" className="rainbow-m-vertical_x-large rainbow-p-horizontal_medium rainbow-m_auto" />; ```
C++
UTF-8
7,390
2.890625
3
[]
no_license
#include <iostream> #include <opencv2/opencv.hpp> #include <vector> #include <string> #include <fstream> #include <sstream> #include <cstdlib> #include <stdexcept> using namespace std; using namespace cv; class Result { vector<string> name_vec; //每一幅图片的名字 //vector<Mat> image_vec; //Mat格式的每一幅图 vector<string> data_path; //每幅图的存储路径(含名字) vector< vector<Point2d> > kp_vec; //key points string dump_dir; //导出加入关键点的图片的目录,必须以/结尾 public: //pic_path: 图片完整位置信息txt文件,包含文件名 //name_path: 图片名txt,保留前一级目录lfw或net的信息,用于导出标识图 //label_path: 图片关键点信息txt文件 Result(const string& pic_path, const string& name_path, const string& label_path) { getDataPath(pic_path); getLabel(label_path); getName(name_path); if ((name_vec.size()!=data_path.size()) || (data_path.size()!=kp_vec.size())) { throw runtime_error("vectors not aligned\n"); } } //path所在的文本,每一行是一个路径 void getDataPath(const string& path) { ifstream in(path.c_str()); if (!in) { cout << "in getPath, path error" << endl; return; } string cur_path; int cnt = 0; while (1) { getline(in, cur_path); if (in.eof()) break; this->data_path.push_back(cur_path); ++cnt; } cout << "in getDataPath, cnt=" << cnt << endl; in.close(); } void getLabel(const string& path) { ifstream in(path.c_str()); if (!in) { cout << "in getLable, error" << endl; return; } string line; int cnt = 0; while (1) { getline(in, line); if (in.eof()) break; istringstream iss(line); vector<cv::Point2d> temp_vec; string x; string y; int num = 5; while (num > 0) { iss >> x; iss >> y; temp_vec.push_back(Point2d(atof(x.c_str()), atof(y.c_str()))); --num; } this->kp_vec.push_back(temp_vec); } cout << "in getLable, cnt=" << cnt << endl; in.close(); } void getName(const string& path) { ifstream in(path.c_str()); if (!in) { cout << "in getName, error" << endl; return; } string name; int cnt = 0; while (1) { getline(in, name); if (in.eof()) break; this->name_vec.push_back(name); ++cnt; } cout << "in getName, cnt=" << cnt << endl; in.close(); } void generateMarkedImage(const string& dump_dir) const { for (int i = 0; i < this->data_path.size(); ++i) { //读取图片 Mat image = imread(data_path[i], CV_LOAD_IMAGE_COLOR); //读取图片对应的所有关键点 vector<cv::Point2d> temp_vec = kp_vec[i]; //画出关键点 for (int j = 0; j < 5; ++j) { circle(image, temp_vec[j], 1, Scalar(0, 255, 0), -1); } string dump_path(dump_dir + this->name_vec[i]); bool b = imwrite(dump_path, image); if (b==false) { cout << "path: " << dump_path << endl; cout << "imwrite false" << endl; return; } //break; } cout << "dump finish" << endl; } void generateMarkedImageWithDifferentColor(const string& dump_dir, const string& failure_txt) const { ifstream in(failure_txt.c_str()); if (!in) { cout << "in generateMarkedImageWithDifferentColor, path error" << endl; return; } string line; for (int i = 0; i < this->data_path.size(); ++i) { //读取图片 getline(in, line); //读取记录每个样本的模型输出关键点是否失败的txt文件的一行 istringstream iss(line); //创建一个istringstream对象 Mat image = imread(data_path[i], CV_LOAD_IMAGE_COLOR); //读取图片对应的所有关键点 vector<cv::Point2d> temp_vec = kp_vec[i]; //画出关键点 for (int j = 0; j < 5; ++j) { string temp; iss >> temp; int tf_mark = atoi(temp.c_str()); if (tf_mark == 0) circle(image, temp_vec[j], 1, Scalar(0, 255, 0), -1); else circle(image, temp_vec[j], 1, Scalar(255, 0, 0), -1); } string dump_path(dump_dir + this->name_vec[i]); bool b = imwrite(dump_path, image); if (b==false) { cout << "path: " << dump_path << endl; cout << "imwrite false" << endl; return; } //break; } in.close(); //关闭文件流 cout << "dump finish" << endl; } }; void dump_train(const string& pic_path, const string& name_path, const string& label_path, const string& dump_dir, const string& failure_txt) { Result res(pic_path, name_path, label_path); cout << "初始化完成" << endl; res.generateMarkedImageWithDifferentColor(dump_dir, failure_txt); cout << "图片生成完成" << endl; } void dump_test(const string& pic_path, const string& name_path, const string& label_path, const string& dump_dir, const string& failure_txt) { Result res(pic_path, name_path, label_path); cout << "初始化完成" << endl; res.generateMarkedImageWithDifferentColor(dump_dir, failure_txt); cout << "图片生成完成" << endl; } int main(int argc, char* argv[]) { //图片绝对路径 cout <<"argc=" << argc << endl; cout << "argv[1]: " << argv[1] << endl; string pic_path(argv[1]); //"/home/zanghu/Pro_Datasets/yisun/train/roi/my_pic_trainImageList_roi"); //图片名和上一级目录 string name_path(argv[2]); //"/home/zanghu/Pro_Datasets/yisun/train/roi/my_train_nameList"); //关键点坐标txt string label_path(argv[3]); //"/home/zanghu/Pro_Datasets/yisun/train/show_res/train_label.txt"); //导出路径 string dump_dir(argv[4]); //"/home/zanghu/Pro_Datasets/yisun/train/marked_iamges/train/"); //注意dump_dir必须以/结尾 string failure_txt_train(argv[9]); dump_train(pic_path, name_path, label_path, dump_dir, failure_txt_train); //图片绝对路径 string pic_path_test(argv[5]); //"/home/zanghu/Pro_Datasets/yisun/train/roi/my_pic_testImageList_roi"); //图片名和上一级目录 string name_path_test(argv[6]); //"/home/zanghu/Pro_Datasets/yisun/train/roi/my_test_nameList"); //关键点坐标txt string label_path_test(argv[7]); //"/home/zanghu/Pro_Datasets/yisun/train/show_res/test_label.txt"); string dump_dir_test(argv[8]); //"/home/zanghu/Pro_Datasets/yisun/train/marked_iamges/test/"); //注意dump_dir必须以/结尾 string failure_txt_test(argv[10]); dump_test(pic_path_test, name_path_test, label_path_test, dump_dir_test, failure_txt_test); return 1; }
C++
UHC
1,064
2.59375
3
[]
no_license
#include <stdio.h> #include "CheckSkills/Level_1/Sol1.h" #include "Practice/StackNQueue/FeaturesDevelop.h" #include "Practice/StackNQueue/Top.h" #include "Practice/StackNQueue/Printer.h" #include "Practice/DFSnBFS/TargetNumber.h" int main(int argc, char* argv[]) { //Sol1 sol1; //sol1.solution("abcde"); //sol1.solution("qwer"); //int aa = sol1.solution(5000); //int bb = sol1.solution(1); /* ########## SOL. > /ť > ɰ ########## */ /* //std::vector<int> lProgresses{93, 30, 99, 55, 99, 0, 99, 55, 2, 5}; //std::vector<int> lSpeeds{1, 30, 2, 5, 1, 100, 2, 5, 30, 21}; std::vector<int> lProgresses{5, 5, 5}; std::vector<int> lSpeeds{21, 25, 20}; std::vector<int> lReturn; FeaturesDevelop features; lReturn = features.solution(lProgresses, lSpeeds); */ //std::vector<int> lHeight{ 6, 9, 5, 7, 4 }; ////std::vector<int> lHeight{ 9, 1, 1, 1 }; //Top top; //top.solution(lHeight); vector<int> lNumbers = { 3, 3, 3 }; int ret = 3; TargetNumber targetNumber; targetNumber.solution(lNumbers, ret); return 0; }
Java
UTF-8
4,555
2.078125
2
[]
no_license
package intersky.task.receiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler; import android.os.Message; import intersky.appbase.BaseReceiver; import intersky.task.TaskManager; import intersky.task.asks.ProjectAsks; import intersky.task.asks.ProjectStageAsks; import intersky.task.asks.TaskAsks; import intersky.task.handler.TaskStructureHandler; import intersky.task.view.activity.TaskStructureActivity; /** * Created by xpx on 2017/8/4. */ public class TaskStructureReceiver extends BaseReceiver { public Handler mHandler; public TaskStructureReceiver(Handler mHandler) { this.mHandler = mHandler; this.intentFilter = new IntentFilter(); this.intentFilter.addAction(TaskStructureActivity.ACTION_SET_PROJECT); this.intentFilter.addAction(TaskStructureActivity.ACTION_SET_STAGE); this.intentFilter.addAction(TaskStructureActivity.ACTION_SET_PARENT); intentFilter.addAction(ProjectAsks.ACTION_PROJECT_SET_NEME); intentFilter.addAction(ProjectStageAsks.ACTION_PROJECT_STAGE_UPDATE); intentFilter.addAction(TaskAsks.ACTION_TASK_NAME_SUCCESS); intentFilter.addAction(TaskAsks.ACTION_TASK_FINSH); intentFilter.addAction(TaskAsks.ACTION_TASK_ADD); intentFilter.addAction(TaskAsks.ACTION_TASK_LEADER); intentFilter.addAction(TaskAsks.ACTION_TASK_CHANGE_STAGE); intentFilter.addAction(TaskAsks.ACTION_TASK_CHANGE_PROJECT); intentFilter.addAction(TaskAsks.ACTION_TASK_PARENT); intentFilter.addAction(ProjectAsks.ACTION_DELETE_PROJECT); intentFilter.addAction(TaskAsks.ACTION_EXIT_TASK); intentFilter.addAction(TaskAsks.ACTION_DELETE_TASK); intentFilter.addAction(TaskManager.ACTION_TASK_UPDATE); } @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(TaskStructureActivity.ACTION_SET_PROJECT)) { if(mHandler != null) { Message message = new Message(); message.obj = intent; message.what = TaskStructureHandler.SET_PROJECT; mHandler.sendMessage(message); } } else if (intent.getAction().equals(TaskStructureActivity.ACTION_SET_STAGE)) { if(mHandler != null) { Message message = new Message(); message.obj = intent; message.what = TaskStructureHandler.SET_STAGE; mHandler.sendMessage(message); } } else if (intent.getAction().equals(TaskStructureActivity.ACTION_SET_PARENT)) { if(mHandler != null) { Message message = new Message(); message.obj = intent; message.what = TaskStructureHandler.SET_PARENT; mHandler.sendMessage(message); } } else if (intent.getAction().equals(TaskAsks.ACTION_TASK_NAME_SUCCESS)|| intent.getAction().equals(TaskAsks.ACTION_TASK_FINSH) || intent.getAction().equals(TaskAsks.ACTION_TASK_ADD)|| intent.getAction().equals(TaskAsks.ACTION_TASK_LEADER) || intent.getAction().equals(TaskAsks.ACTION_TASK_CHANGE_STAGE)|| intent.getAction().equals(TaskAsks.ACTION_TASK_CHANGE_PROJECT) || intent.getAction().equals(TaskAsks.ACTION_TASK_PARENT) || intent.getAction().equals(TaskManager.ACTION_TASK_UPDATE)) { if(mHandler != null) { Message message = new Message(); message.obj = intent; message.what = TaskStructureHandler.UPDATA_TASK; mHandler.sendMessage(message); } } else if (intent.getAction().equals(ProjectAsks.ACTION_PROJECT_SET_NEME)||intent.getAction().equals(ProjectStageAsks.ACTION_PROJECT_STAGE_UPDATE)) { if(mHandler != null) { Message message = new Message(); message.obj = intent; message.what = TaskStructureHandler.UPDATA_PROJECT; mHandler.sendMessage(message); } } else if (intent.getAction().equals(TaskAsks.ACTION_EXIT_TASK)) { if(mHandler != null) { Message message = new Message(); message.obj = intent; message.what = TaskStructureHandler.TASK_DELETE; mHandler.sendMessage(message); } } } }
PHP
UTF-8
4,031
2.703125
3
[]
no_license
<?php /** * Module Text. * * Show text blocks with rich editor. * @package ThemifyFlow * @since 1.0.0 */ class TF_Element_Featured_Image extends TF_Module_Element { /** * Constructor. */ public function __construct() { parent::__construct(array( 'name' => __('Featured Image', 'themify-flow'), 'slug' => 'featured-image', 'shortcode' => 'tf_featured_image', 'description' => 'Featured Image', 'category' => 'loop' )); // Register shortcode add_shortcode( $this->shortcode, array( $this, 'render_shortcode' ) ); } /** * Module settings field * * @since 1.0.0 * @access public * @return array */ public function fields() { return apply_filters( 'tf_element_featured_image_fields', array( 'image_size' => array( 'type' => 'select', 'label' => __('Image Size', 'themify-flow'), 'options' => tf_get_image_sizes_list() ), 'image_dimension' => array( 'type' => 'multi', 'label' => __('Dimensions', 'themify-flow'), 'fields' => array( 'image_width' => array( 'type' => 'text', 'class' => 'tf_input_width_20', 'wrapper' => 'no', 'description' => 'x' ), 'image_height' => array( 'type' => 'text', 'class' => 'tf_input_width_20', 'wrapper' => 'no', 'description' => 'px' ) ) ), 'image_link_to_post' => array( 'type' => 'radio', 'label' => __( 'Link to post', 'themify-flow'), 'options' => array( array( 'name' => 'Yes', 'value' => 'yes', 'selected' => true ), array( 'name' => 'No', 'value' => 'no' ) ) ), 'display_inline_block'=> array( 'type' => 'checkbox', 'label' => __( 'Display Inline', 'themify-flow' ), 'text' => __( 'Display this module inline (float left)', 'themify-flow' ), ) ) ); } /** * Render main shortcode. * * Should be returned with apply_filters('tf_shortcode_module_render') so it can be editable in Builder. * * @since 1.0.0 * @access public * @param array $atts * @param string $content * @return string */ public function render_shortcode( $atts, $content = null ) { $atts = shortcode_atts( array( 'image_size' => 'blank', 'image_width' => '', 'image_height' => '', 'image_link_to_post' => 'yes', 'display_inline_block'=>false ), $atts, $this->shortcode ); // must add the third params $this->shortcode, for builder shortcode rendering $output = ''; $image_size = 'blank' != $atts['image_size'] ? $atts['image_size'] : 'large'; if ( has_post_thumbnail( get_the_ID() ) ) { $post_thumbnail = get_post_thumbnail_id( get_the_ID() ); $post_thumbnail_object = get_post( $post_thumbnail ); $thumbnail_title = is_object( $post_thumbnail_object ) ? $post_thumbnail_object->post_title : ''; $image_attribute = wp_get_attachment_image_src( $post_thumbnail, $image_size ); $post_image = sprintf( '<img itemprop="image" src="%s" alt="%s" width="%s" height="%s" />', esc_url( $image_attribute[0] ), esc_attr( $thumbnail_title ), esc_attr( $atts['image_width'] ), esc_attr( $atts['image_height'] ) ); $class = isset($atts['display_inline_block']) && $atts['display_inline_block']?' tf_element_inline_block':''; $output = '<figure class="tf_post_image'.$class.'">'; if ( 'no' == $atts['image_link_to_post'] ) { $output.=$post_image; } else{ $output.= sprintf( '<a href="%s">%s</a>', get_permalink(), $post_image ); } $output.='</figure>'; } return apply_filters( 'tf_shortcode_element_render', $output, $this->slug, $atts, $content ); } } new TF_Element_Featured_Image();
Java
UTF-8
4,750
1.914063
2
[ "MIT" ]
permissive
package com.faforever.api.data; import com.faforever.api.AbstractIntegrationTest; import com.faforever.api.data.domain.GroupPermission; import com.faforever.api.security.OAuthScope; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.Sql.ExecutionPhase; import static com.faforever.api.data.JsonApiMediaType.JSON_API_MEDIA_TYPE; import static org.hamcrest.Matchers.hasSize; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:sql/truncateTables.sql") @Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:sql/prepDefaultData.sql") @Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:sql/prepModData.sql") public class ModVersionElideTest extends AbstractIntegrationTest { private static final String MOD_VERSION_HIDE_FALSE_ID_1 = "{\n" + " \"data\": {\n" + " \"type\": \"modVersion\",\n" + " \"id\": \"1\",\n" + " \"attributes\": {\n" + " \t\"hidden\": false\n" + " }\n" + " } \n" + "}"; private static final String MOD_VERSION_HIDE_TRUE_ID_1 = "{\n" + " \"data\": {\n" + " \"type\": \"modVersion\",\n" + " \"id\": \"1\",\n" + " \"attributes\": {\n" + " \t\"hidden\": true\n" + " }\n" + " } \n" + "}"; private static final String MOD_VERSION_RANKED_FALSE_ID_1 = "{\n" + " \"data\": {\n" + " \"type\": \"modVersion\",\n" + " \"id\": \"1\",\n" + " \"attributes\": {\n" + " \t\"ranked\": false\n" + " }\n" + " } \n" + "}"; private static final String MOD_VERSION_RANKED_TRUE_ID_1 = "{\n" + " \"data\": {\n" + " \"type\": \"modVersion\",\n" + " \"id\": \"1\",\n" + " \"attributes\": {\n" + " \t\"ranked\": true\n" + " }\n" + " } \n" + "}"; @Test public void canReadModVersionWithoutScopeAndRole() throws Exception { mockMvc.perform(get("/data/modVersion") .with(getOAuthTokenWithActiveUser(NO_SCOPE, NO_AUTHORITIES))) .andExpect(status().isOk()) .andExpect(jsonPath("$.data", hasSize(2))); } @Test public void canUpdateModVersionWithScopeAndRole() throws Exception { mockMvc.perform( patch("/data/modVersion/1") .with(getOAuthTokenWithActiveUser(OAuthScope._MANAGE_VAULT, GroupPermission.ROLE_ADMIN_MOD)) .header(HttpHeaders.CONTENT_TYPE, JSON_API_MEDIA_TYPE) .content(MOD_VERSION_HIDE_FALSE_ID_1)) .andExpect(status().isNoContent()); } @Test public void cannotModVersionBanWithoutScope() throws Exception { mockMvc.perform( patch("/data/modVersion/1") .with(getOAuthTokenWithActiveUser(NO_SCOPE, GroupPermission.ROLE_ADMIN_MOD)) .header(HttpHeaders.CONTENT_TYPE, JSON_API_MEDIA_TYPE) .content(MOD_VERSION_HIDE_FALSE_ID_1)) .andExpect(status().isForbidden()); } @Test public void cannotModVersionBanWithoutRole() throws Exception { mockMvc.perform( patch("/data/modVersion/1") .with(getOAuthTokenWithActiveUser(OAuthScope._MANAGE_VAULT, NO_AUTHORITIES)) .header(HttpHeaders.CONTENT_TYPE, JSON_API_MEDIA_TYPE) .content(MOD_VERSION_HIDE_TRUE_ID_1)) .andExpect(status().isForbidden()); } @Test public void cannotUpdateHideToFalseAsEntityOwner() throws Exception { mockMvc.perform( patch("/data/modVersion/1") .with(getOAuthTokenForUserId(USERID_USER)) .header(HttpHeaders.CONTENT_TYPE, JSON_API_MEDIA_TYPE) .content(MOD_VERSION_HIDE_FALSE_ID_1)) .andExpect(status().isForbidden()); } @Test public void cannotUpdateRankedToFalseAsEntityOwner() throws Exception { mockMvc.perform( patch("/data/modVersion/1") .with(getOAuthTokenForUserId(USERID_USER)) .header(HttpHeaders.CONTENT_TYPE, JSON_API_MEDIA_TYPE) .content(MOD_VERSION_RANKED_FALSE_ID_1)) .andExpect(status().isForbidden()); } @Test public void cannotUpdateRankedToTrueAsEntityOwner() throws Exception { mockMvc.perform( patch("/data/modVersion/1") .with(getOAuthTokenForUserId(USERID_USER)) .header(HttpHeaders.CONTENT_TYPE, JSON_API_MEDIA_TYPE) .content(MOD_VERSION_RANKED_TRUE_ID_1)) .andExpect(status().isForbidden()); } }
Ruby
UTF-8
659
3.59375
4
[]
no_license
basket = {} total = 0 loop do puts "Введите наименование товара и стоп когда список покупок окончен" name = gets.chomp break if name == 'стоп' puts "Количество товара" quantity = gets.chomp.to_f puts "Цена за единицу товара" price = gets.chomp.to_f cost = price * quantity total += cost basket[name] = {price: price, quantity: quantity} end basket.each do |name, description| puts "#{name} #{description[:quantity]} #{description[:price]} #{description[:price] * description[:quantity]}" end puts "Итого в корзине: #{total}"
Java
UTF-8
1,515
2.46875
2
[]
no_license
package com.yeollu.getrend.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; /** * @Class : LoginInterceptor.java * @Package : com.yeollu.getrend.interceptor * @Project : GeTrend * @Author : 박민열 * @Since : 2020. 4. 11. * @Version : 1.0 * @Desc : */ public class LoginInterceptor extends HandlerInterceptorAdapter { /** * Fields */ private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class); /** * Overriding * @Method : preHandle * @Return : boolean * @Author : 박민열 * @Since : 2020. 4. 11. * @Version : 1.0 * @Desc : 모든 페이지에 접근할 때 로그인 여부를 확인하여 로그인 상태가 아닐 경우 로그인 페이지로 보낸다. * @param request * @param response * @param handler * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.info("LoginInterceptor 실행"); HttpSession session = request.getSession(); String loginEmail = (String) session.getAttribute("loginemail"); if(loginEmail == null) { response.sendRedirect(request.getContextPath() + "/users/userLogin"); return false; } return super.preHandle(request, response, handler); } }
Java
UTF-8
610
2.796875
3
[]
no_license
package pozoriste; public class Pozoriste { private static int next_id = 0; private int id; private String naziv; public Pozoriste(String naziv) { this.id = next_id++; this.naziv = naziv; } public int getId() { return id; } public String getNaziv() { return naziv; } @Override public String toString() { return "Pozoriste{" + "id=" + id + ", naziv='" + naziv + '\'' + '}'; } // Jugoslovensko dramsko pozoriste -> JDP // TODO: Метода getSkraceniNaziv() }
Python
UTF-8
2,421
2.921875
3
[ "Apache-2.0" ]
permissive
# import the required libraries import numpy as np import time import random import cPickle # set numpy output to something sensible np.set_printoptions(precision=8, edgeitems=6, linewidth=200, suppress=True) # import our command line tools # libraries required for visualisation: from IPython.display import SVG, display import svgwrite # conda install -c omnia svgwrite=1.1.6 if you don't have this lib # helper function for draw_strokes def get_bounds(data, factor): min_x = 0 max_x = 0 min_y = 0 max_y = 0 abs_x = 0 abs_y = 0 for i in xrange(len(data)): x = float(data[i,0])/factor y = float(data[i,1])/factor abs_x += x abs_y += y min_x = min(min_x, abs_x) min_y = min(min_y, abs_y) max_x = max(max_x, abs_x) max_y = max(max_y, abs_y) return (min_x, max_x, min_y, max_y) # little function that displays vector images and saves them to .svg def draw_strokes_mod(data, factor=0.2, svg_filename = 'sample.svg'): min_x, max_x, min_y, max_y = get_bounds(data, factor) dims = (50 + max_x - min_x, 50 + max_y - min_y) dwg = svgwrite.Drawing(svg_filename, size=dims) dwg.add(dwg.rect(insert=(0, 0), size=dims,fill='white')) lift_pen = 1 abs_x = 25 - min_x abs_y = 25 - min_y p = "M%s,%s " % (abs_x, abs_y) command = "m" for i in xrange(len(data)): if (lift_pen == 1): command = "m" elif (command != "l"): command = "l" else: command = "" x = float(data[i,0])/factor y = float(data[i,1])/factor lift_pen = data[i, 2] p += command+str(x)+","+str(y)+" " the_color = "black" stroke_width = 1 dwg.add(dwg.path(p).stroke(the_color,stroke_width).fill("none")) dwg.save() return SVG(dwg.tostring()) #If the file is a .npy file, then a single array is returned. #If the file is a .npz file, then a dictionary-like object is returned, containing {filename: array} key-value pairs, one for each file in the archive. #npy_file = np.load("cat.npy") #npz_file = np.load() npz_data = np.load("cat.npz") train_set = npz_data['train'] valid_set = npz_data['valid'] test_set = npz_data['test'] #single_img = random.choice(train_set) for i in range(0,1000): current_img = train_set[i] svg_img = draw_strokes_mod(current_img,svg_filename="svgs/img"+str(i)+".svg") # draw a random example (see draw_strokes.py) #draw_strokes(single_img) #cairosvg.svg2png(url="sample.svg", write_to='image.png')
Markdown
UTF-8
4,134
3.140625
3
[ "Apache-2.0" ]
permissive
# Official Docker Images Polynote publishes official Docker images upon every release. Most users are recommended to use the `latest` tag by running `docker pull polynote/polynote:latest`. ## Published Tags Every release of Polynote will publish four images: | Description | Tag name | |-------------------------------|-------------------------------------------------------| |Base image with Scala 2.11 | `polynote/polynote:${POLYNOTE_VERSION}-2.11` | |Base image with Scals 2.12 | `polynote/polynote:${POLYNOTE_VERSION}-2.12` | |Spark 2.4 image with Scala 2.11| `polynote/polynote:${POLYNOTE_VERSION}-2.11-spark2.4` | |Spark 2.4 image with Scala 2.12| `polynote/polynote:${POLYNOTE_VERSION}-2.12-spark2.4` | Additionally, the `latest` tag is updated to point to `polynote/polynote:${POLYNOTE_VERSION}-2.11-spark2.4`. ## Usage Instructions Here are some simple instructions for running Polynote from a Docker image. Please note that these instructions are meant for use in a safe, development environment and should not be used in production. > Keep in mind that Polynote, like all notebook tools, allows arbitrary remote code execution. Running it in a Docker container, while mitigating certain possible attack vectors, does not automatically make it safe. > > For this reason, the Docker images we publish do NOT come with any changes to the default configuration. Here are some instructions for a simple setup enabling users try out the `latest` Polynote image. First, we'll do some setup and create a local directory in which to put our configuration and save our notebooks. ``` mkdir ~/polynote-docker cd ~/polynote-docker ``` Next, make a `config.yml` file with the following contents: ``` listen: host: 0.0.0.0 storage: dir: /opt/notebooks mounts: examples: dir: examples ``` > The `listen` directive tells Polynote to listen on all interfaces inside the Docker container. > While this is probably fine for trying it out, it's not fit for production settings. > > The `storage` directive specifies `/opt/notebooks` as the primary notebook location. It also tells Polynote to > mount the examples directory that is present in the Docker distribution as a secondary mount, allowing you to see the > examples and try them out! > Note that changes to the examples might not be persisted onto the host if you follow the instructions below. Ok, now we are ready to run the Docker container! Use the following command: ``` docker run --rm -it -p 127.0.0.1:8192:8192 -p 127.0.0.1:4040-4050:4040-4050 -v `pwd`:/opt/config -v `pwd`/notebooks:/opt/notebooks polynote/polynote:latest --config /opt/config/config.yml ``` Let's go over what this command does. - `-p 127.0.0.1:8192:8192` This binds `127.0.0.1:8192` on the host machine to port `8192` inside the container. - `-p 127.0.0.1:4040-4050:4040-4050` This binds a range of ports on the host machine so you can see the Spark UI. - ``-v `pwd`:/opt/config`` This mounts the current directory (the one you just created) into the container at `/opt/config` - ``-v `pwd`/notebooks:/opt/notebooks`` This mounts the `./notebooks` directory on the host into the container at `/opt/notebooks`, so that any notebooks you create are saved back to the host. - `polynote/polynote:latest` pulls the latest Polynote image - `--config /opt/config/config.yml` tells Polynote to use the `config.yml` file you created earlier. Great! Now just open up Chrome and navigate over to http://localhost:8192/ and you'll see the Polynote UI! You'll see the example folder show up on the left. Open it up and run some of the examples! :smile: > Note: Changes you make to the example notebooks won't persist, since they aren't mounted to the host. Try making a new notebook by clicking the new notebook button and typing "my first notebook" into the dialog box. You should see it show up in the notebooks tree! Now, if you open up a new terminal window and run `ls -l ~/polynote-docker/notebooks`, you should see `my first notebook.ipynb` on your host machine!
SQL
UTF-8
2,679
3.703125
4
[]
no_license
DROP TABLE IF EXISTS fa_user; DROP TABLE IF EXISTS fa_role; DROP TABLE IF EXISTS fa_user_role; -- User CREATE TABLE fa_user( id BIGINT IDENTITY PRIMARY KEY, username VARCHAR(50) NOT NULL, value_sec VARCHAR(255) NOT NULL, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, created_by VARCHAR(50) NOT NULL, created_date BIGINT NOT NULL, modified_by VARCHAR(50) NOT NULL, modified_date BIGINT NOT NULL ); ALTER TABLE fa_user ADD CONSTRAINT fa_user_username_unique_constraint UNIQUE (username); -- Role create TABLE fa_role ( id bigint IDENTITY PRIMARY KEY, name character varying(30) NOT NULL ); ALTER TABLE fa_role ADD CONSTRAINT fa_role_name_unique_constraint UNIQUE (name); -- User's role create TABLE fa_user_role( id bigint IDENTITY PRIMARY KEY, user_id bigint NOT NULL, role_id bigint NOT NULL ); ALTER TABLE fa_user_role ADD CONSTRAINT user_role_user_id_fkey FOREIGN KEY (user_id) REFERENCES fa_user (id); ALTER TABLE fa_user_role ADD CONSTRAINT user_role_role_id_fkey FOREIGN KEY (role_id) REFERENCES fa_role (id); ALTER TABLE fa_user_role ADD CONSTRAINT fa_user_role_unique_constraint UNIQUE (user_id, role_id); -- OAuth2 drop table if exists oauth_client_details; create table oauth_client_details ( client_id VARCHAR(255) PRIMARY KEY, resource_ids VARCHAR(255), client_secret VARCHAR(255), scope VARCHAR(255), authorized_grant_types VARCHAR(255), web_server_redirect_uri VARCHAR(255), authorities VARCHAR(255), access_token_validity INTEGER, refresh_token_validity INTEGER, additional_information VARCHAR(4096), autoapprove VARCHAR(255) ); drop table if exists oauth_client_token; create table oauth_client_token ( token_id VARCHAR(255), token LONGVARBINARY, authentication_id VARCHAR(255) PRIMARY KEY, user_name VARCHAR(255), client_id VARCHAR(255) ); drop table if exists oauth_access_token; create table oauth_access_token ( token_id VARCHAR(255), token LONGVARBINARY, authentication_id VARCHAR(255) PRIMARY KEY, user_name VARCHAR(255), client_id VARCHAR(255), authentication LONGVARBINARY, refresh_token VARCHAR(255) ); drop table if exists oauth_refresh_token; create table oauth_refresh_token ( token_id VARCHAR(255), token LONGVARBINARY, authentication LONGVARBINARY ); drop table if exists oauth_code; create table oauth_code ( code VARCHAR(255), authentication LONGVARBINARY); drop table if exists oauth_approvals; create table oauth_approvals ( userId VARCHAR(255), clientId VARCHAR(255), scope VARCHAR(255), status VARCHAR(10), expiresAt TIMESTAMP, lastModifiedAt TIMESTAMP );
Java
UTF-8
743
2.96875
3
[]
no_license
package graph.easy; import utils.info.Enhance; import utils.info.Question; @Question(url = "https://leetcode.com/problems/find-the-town-judge/") @Enhance(details = "Time complexity") public class FindTheTownJudge { private static int findJudge(int N, int[][] trust) { int[] trustCount = new int[N]; for(int [] trust1: trust) { trustCount[trust1[0]-1]--; trustCount[trust1[1]-1]++; } for(int i = 0; i < trustCount.length; i++) if(trustCount[i] == N-1) return i+1; return -1; } public static void main(String[] args) { int[][] trust1 = new int[][] {{1,4}, {1,3}, {2,3}, {2,4}, {4,3}}; System.out.println(findJudge(4, trust1)); } }
Java
UTF-8
1,172
2.40625
2
[]
no_license
package bg.mdg.pageobjects; import org.openqa.selenium.By; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public abstract class BasePageObject { private WebDriver driver; public BasePageObject(WebDriver driver) { this.driver = driver; } protected WebDriver getDriver() { return this.driver; } protected String getPageTitle() { return this.driver.getTitle(); } protected Boolean waitForElementToBeDisplayed(By locator, Integer... timeout) { try { waitFor(ExpectedConditions.visibilityOfElementLocated(locator), (timeout.length > 0 ? timeout[0] : null)); } catch (TimeoutException exception) { return false; } return true; } private void waitFor(ExpectedCondition<WebElement> condition, Integer timeout) { timeout = timeout != null ? timeout : 5; WebDriverWait wait = new WebDriverWait(driver, timeout); wait.until(condition); } }
Markdown
UTF-8
1,116
2.71875
3
[]
no_license
# 正向代理 就是在本地请求服务器数据的时候,中间放置一个代理层。通过代理层的特性来实现跨域请求。 跨域是只在前端浏览器中的才有的。后台请求是不会的。 本地页面地址: http://localhost:8080 服务器接口地址:https://m.aihuishou.com/portal-api/product/category-brands/1 中间代理层(nodejs)http://localhost:8080 前端页面 -> 中间代理层(node) -> 服务器接口地址 #### 实现方式 1. 自己动手实现一个 nodejs 服务 2. 直接使用 vue-cli 提供的配置 #### 直接使用 vue-cli 提供的配置 1. vue-cli 3.x 在项目根目录下 创建一个 vue.config.js 文件 2. 在 vue.config.js 中 暴露一个对象。对象中配置 proxy 选项 3. 重新启动项目。试一试 访问如下地址, http://localhost:8080/api/portal-api/product/category-brands/1 希望能够获取 https://m.aihuishou.com/portal-api/product/category-brands/1 的数据 访问如下地址: http://localhost:8080/api/portal-api/product/search 希望得到 https://m.aihuishou.com/portal-api/product/search 的数据
Java
UTF-8
2,947
2.5
2
[]
no_license
package com.ozoon.ozoon.Adapters; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.ozoon.ozoon.Model.Objects.MessageModel; import com.ozoon.ozoon.R; import com.ozoon.ozoon.Utils.GMethods; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class ConversationMessagesAdapter extends RecyclerView.Adapter<ConversationMessagesAdapter.ConversationMessageHolder> { private Context mContext; private ArrayList<MessageModel> items; private OnItemClick onItemClick; private static final int SEND_MESSAGE = 0; private static final int RECEIVED_MESSAGE = 1; public ConversationMessagesAdapter(Context mContext, ArrayList<MessageModel> items, OnItemClick onItemClick) { this.mContext = mContext; this.items = items; this.onItemClick = onItemClick; } public interface OnItemClick { void setOnItemClick(int position); } @Override public int getItemViewType(int position) { if (items.get(position).isMine()){ return SEND_MESSAGE; } else { return RECEIVED_MESSAGE; } } @NonNull @Override public ConversationMessageHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if (viewType == SEND_MESSAGE) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.send_message_item, parent, false); GMethods.ChangeViewFont(view); return new ConversationMessageHolder(view); } else { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.receive_message_item, parent, false); GMethods.ChangeViewFont(view); return new ConversationMessageHolder(view); } } @Override public void onBindViewHolder(@NonNull final ConversationMessageHolder holder, int position) { holder.message.setText(items.get(position).getMessage()); holder.date.setText(items.get(position).getDate()); } @Override public int getItemCount() { return items.size(); } public class ConversationMessageHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ @BindView(R.id.message) TextView message; @BindView(R.id.date) TextView date; public ConversationMessageHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); itemView.setOnClickListener(this); } @Override public void onClick(View view) { int position = getAdapterPosition(); onItemClick.setOnItemClick(position); } } }
Ruby
UTF-8
2,123
2.8125
3
[ "MIT" ]
permissive
module PryMoves::Recursion class Tracker attr_reader :loops def initialize @history = [] @loops = 0 @missing = 0 @currently_missing = [] @missing_lines = [] end def track file, line_num, bt_index, binding_index line = "#{file}:#{line_num}" if @last_index check_recursion line, bt_index, binding_index elsif (prev_index = @history.rindex line) @loops += 1 @last_index = prev_index @recursion_size = 1 else @history << line @last_index = nil end @repetitions_start ||= bt_index if @loops == 2 end def check_recursion line, bt_index, binding_index prev_index = @history.rindex line if prev_index == @last_index @loops += 1 @missing = 0 @recursion_size = 0 @missing_lines.concat @currently_missing @repetitions_end = bt_index elsif prev_index && prev_index > @last_index @last_index = prev_index + 1 @recursion_size += 1 # todo: finish tracking and debug multi-line recursions elsif @missing <= @recursion_size @missing += 1 @currently_missing << binding_index false else # @missing_lines = nil # @last_index = nil @is_finished = true false end end def finished? @is_finished end def good? @repetitions_start and @repetitions_end end def apply result label = "♻️ recursion with #{@loops} loops" label += " Ⓜ️ #{@missing} missing lines #{@missing_lines}" if @missing_lines.present? label = "...(#{label})..." # puts "#{@repetitions_start}..#{@repetitions_end}" result[@repetitions_start..@repetitions_end] = [label] end end class Holder < Array def initialize(*args) super new_tracker end def new_tracker @tracker = Tracker.new end def track *args @tracker.track *args if @tracker.finished? self << @tracker if @tracker.good? new_tracker end end end end
C#
GB18030
5,603
3.078125
3
[]
no_license
using System; using System.Security.Cryptography; using System.Text; using System.IO; namespace YxLiCai.Tools.SafeEncrypt { /// <summary> /// DESܷ /// </summary> public class DES { private const string DES_KEY = "FDSFIojslsk;fjlk;)*(+nmjdsf$#@dsf54641#&*(()"; /// <summary> /// ַ /// ע:ԿΪλ /// </summary> /// <param name="inputString">ַ</param> /// <param name="encryptKey">Կ</param> /// <returns></returns> public static string DesEncrypt(string inputString, string encryptKey) { byte[] byKey = null; byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; try { byKey = System.Text.Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.UTF8.GetBytes(inputString); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); inputString = Convert.ToBase64String(ms.ToArray()); } catch { } return inputString; } /// <summary> /// ַ /// ע:ԿΪλ /// </summary> /// <param name="inputString">ַܵ</param> /// <param name="decryptKey">Կ</param> /// <returns></returns> public static string DesDecrypt(string inputString, string decryptKey) { byte[] byKey = null; byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; byte[] inputByteArray = new Byte[inputString.Length]; try { byKey = System.Text.Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(inputString); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = new System.Text.UTF8Encoding(); inputString = encoding.GetString(ms.ToArray()); } catch { } return inputString; } /// <summary> /// 3desַ /// </summary> /// <param name="plainText"></param> /// <param name="encoding">뷽ʽ</param> /// <returns>ܺ󲢾base63ַ</returns> /// <remarks>أָ뷽ʽ</remarks> public static string Encrypt3DES(string plainText, Encoding encoding) { if (string.IsNullOrEmpty(plainText)) return string.Empty; var DES = new TripleDESCryptoServiceProvider(); var hashMD5 = new MD5CryptoServiceProvider(); DES.Key = hashMD5.ComputeHash(encoding.GetBytes(DES_KEY)); DES.Mode = CipherMode.ECB; ICryptoTransform DESEncrypt = DES.CreateEncryptor(); byte[] Buffer = encoding.GetBytes(plainText); return Convert.ToBase64String(DESEncrypt.TransformFinalBlock (Buffer, 0, Buffer.Length)); } /// <summary> /// 3desַ /// </summary> /// <param name="plainText"></param> /// <returns>ܺ󲢾base63ַ</returns> public static string Encrypt3DES(string plainText) { return Encrypt3DES(plainText, Encoding.Default); } /// <summary> /// 3desַ /// </summary> /// <param name="entryptText"></param> /// <returns>ַܺ</returns> public static string Decrypt3DES(string entryptText) { return Decrypt3DES(entryptText, Encoding.Default); } /// <summary> /// 3desַ /// </summary> /// <param name="entryptText"></param> /// <param name="encoding">뷽ʽ</param> /// <returns>ַܺ</returns> /// <remarks>ָ̬뷽ʽ</remarks> public static string Decrypt3DES(string entryptText, Encoding encoding) { var DES = new TripleDESCryptoServiceProvider(); var hashMD5 = new MD5CryptoServiceProvider(); DES.Key = hashMD5.ComputeHash(encoding.GetBytes(DES_KEY)); DES.Mode = CipherMode.ECB; ICryptoTransform DESDecrypt = DES.CreateDecryptor(); string result; try { byte[] Buffer = Convert.FromBase64String(entryptText); result = encoding.GetString(DESDecrypt.TransformFinalBlock (Buffer, 0, Buffer.Length)); } catch (Exception e) { throw (new Exception("Invalid Key or input string is not a valid base64 string", e)); } return result; } } }
Java
UTF-8
5,107
2.46875
2
[]
no_license
package com.example.taskassignment; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class SignInActivity extends AppCompatActivity { EditText email, password; Button signIn, newUser; private FirebaseAuth mAuth; private DatabaseReference myRef; String TAG = "Sign"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_in); mAuth = FirebaseAuth.getInstance(); myRef = FirebaseDatabase.getInstance().getReference("users"); signIn = findViewById(R.id.button_sign_in); signIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { email = findViewById(R.id.email_sign_in); password = findViewById(R.id.password_sign_in); Toast.makeText(SignInActivity.this, "Authentication processing.", Toast.LENGTH_SHORT).show(); if(checkCredentials(email.getText().toString(), password.getText().toString())) { signIn(email.getText().toString(), password.getText().toString()); } else { Toast.makeText(SignInActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } } }); newUser = findViewById(R.id.button_new_user); newUser.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); Intent intent = new Intent(SignInActivity.this, SignUpActivity.class); startActivity(intent); } }); } public void signIn(String email, String password) { mAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Toast.makeText(SignInActivity.this, "Authentication success.", Toast.LENGTH_SHORT).show(); FirebaseUser user = mAuth.getCurrentUser(); onAuthSuccess(user); } else { // If sign in fails, display a message to the user. Toast.makeText(SignInActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } } }); } public boolean checkCredentials(String email, String password) { if(email == null || password == null) { return false; } else if(password.length() < 8) { return false; } else return true; } private void onAuthSuccess(FirebaseUser user) { // Read from the database myRef.child(user.getUid()).child("role").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // This method is called once with the initial value and again // whenever data at this location is updated. String role = dataSnapshot.getValue(String.class); Log.d(TAG, "Value is: " + role); // Go to MainActivity finish(); if(role.equalsIgnoreCase("Manager")) { Intent intent = new Intent(SignInActivity.this, ManagerActivity.class); startActivity(intent); } else { Intent intent = new Intent(SignInActivity.this, EmployeeActivity.class); startActivity(intent); } } @Override public void onCancelled(DatabaseError error) { // Failed to read value Log.w(TAG, "Failed to read value.", error.toException()); } }); } }
Java
UTF-8
988
1.796875
2
[]
no_license
package com.app.maskit_app; import android.app.Application; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.net.Uri; import java.util.ArrayList; import java.util.List; public class Bootstrap extends Application { public Uri SavedUri; public String temp; Bitmap originalImage; // to backup image with filter applied Bitmap filteredImage; Bitmap filteredImage1; Bitmap blurredImage; // the final image after applying // brightness, saturation, contrast Bitmap finalImage; boolean loadimage; String currPhotoPath; String LoadLandscapePath ; Integer currentFilterNo; List<Triplet<Rect, Integer, Canvas>> filters; List<TupleFace<Rect, Float>> _faces; @Override public void onCreate() { super.onCreate(); LoadLandscapePath = ""; filters = new ArrayList<>(); _faces = new ArrayList<>(); loadimage = false; }; }
Python
UTF-8
657
4.09375
4
[]
no_license
#백준 5585 거스름돈 (신지원) def money(pay): pay = 1000-pay #1000엔에서 거스름돈을 계산할 것이기 때문에 money = [500,100,50,10,5,1] #반복문을 통해 간결하게 하기 위해 화폐를 담아줌 total = 0 #최종 거스름돈의 개수 for i in money: if pay//i: #몫이 존재한다면. 나누어질 수 있다면. total += pay//i #몫을 거스름돈의 개수에 추가. pay %= i #나머지를 다시 반복시켜 더 작은 단위로 거스름돈을 받을 수 있도록. return total mon = int(input()) #구매한 가격 print(money(mon)) #거스름돈 개수 출력
Python
UTF-8
222
3.703125
4
[]
no_license
fruits = ['apple','bannana','pear','grapes','orange'] counter = 0 for fruit in fruits: print "%s is an awesome fruit" % fruit counter += 1 print "The counter is %d" % counter if counter == 2: break
Java
UTF-8
3,302
2.296875
2
[]
no_license
package com.graygrass.healthylife.fragment; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.graygrass.healthylife.R; import com.graygrass.healthylife.adapter.ViewPagerAdapter; import com.graygrass.healthylife.layout.SlidingTabLayout; import java.util.ArrayList; /** * Created by 橘沐 on 2015/12/27. * 首页 */ public class HealthFragment extends Fragment { private View view; private ViewPager viewPager; private ArrayList<Fragment> list; private SlidingTabLayout tabLayout; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_health, container, false); viewPager = (ViewPager) view.findViewById(R.id.viewPager_health); tabLayout = (SlidingTabLayout) view.findViewById(R.id.tabLayout); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); list = new ArrayList<>(); list.add(new KnowledgeFragment()); list.add(new DrugFragment()); // list.add(new DrugStoreFragment()); list.add(new BookFragment()); list.add(new IllnessFragment()); ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager(), view.getContext(), list); viewPager.setAdapter(adapter); viewPager.setOffscreenPageLimit(4); //定义SlidingTabLayout tabLayout.setCustomTabView(R.layout.tab_text, 0);//注意这句一定要放在setViewPager前面 tabLayout.setViewPager(viewPager); tabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() { @Override public int getIndicatorColor(int position) { return Color.WHITE; } }); // tabLayout.setSelectedIndicatorColors(Color.WHITE); tabLayout.setBackgroundColor(getResources().getColor(R.color.title_green)); } /** * 当显示的是首页的时候双击返回键退出程序 */ long lastPress; @Override public void onResume() { super.onResume(); getView().setFocusableInTouchMode(true); getView().requestFocus(); getView().setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) { long currentTime = System.currentTimeMillis(); if (currentTime - lastPress > 2000) { Toast.makeText(view.getContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); lastPress = currentTime; } else System.exit(0);//退出应用 return true; } return false; } }); } }
SQL
UTF-8
401
2.75
3
[]
no_license
DROP DATABASE IF EXISTS estacionamento; CREATE DATABASE estacionamento; USE estacionamento; CREATE TABLE carro( placa CHAR(7) NOT NULL, cor VARCHAR(15), descricao VARCHAR(100), PRIMARY KEY (placa) ); CREATE TABLE tbusuario( idUsuario INT AUTO_INCREMENT, nomeUsu VARCHAR(15), senhaUsu VARCHAR(15), PRIMARY KEY (idUsuario) ); INSERT INTO tbUsuario (nomeUsu, senhaUsu) VALUES ("admin", "admin");
Java
UTF-8
549
2.109375
2
[]
no_license
package com.atu.erp.dao; import com.atu.erp.domain.ItemDescription; public interface ItemDescriptionDao{ /** * 添加商品描述信息 * @param itemDescription * @return */ public Integer insert(ItemDescription itemDescription); /** * 依据商品ID修改商品描述信息 * @param itemDescription */ public void modify(ItemDescription itemDescription); /** * 依据商品ID查询商品描述信息 * @param itemId * @return */ public ItemDescription selectByItemId(int itemId); }
C++
UTF-8
3,111
3.546875
4
[]
no_license
#include"MaxHeap.h" #include<iostream> #include<math.h> using namespace std; MaxHeap::MaxHeap() {// Generate an empty heap with the default array size of 30. arraySize = 30; H = new int[arraySize]; heapSize = 0; }; MaxHeap::MaxHeap(int* A, int size) {// A contains a sequence of elements arraySize = size; //array size is the max capacity for the new array. heapSize = 0;//starts at 0, modified within Insert(); H = new int[size]; for (int i = 0; i < size - 1; i++) { this->Insert(A[i]); } }; MaxHeap::~MaxHeap() { }; int MaxHeap::Left(int i) {// return the index of the left child of node i return 2 * i; }; int MaxHeap::Right(int i) {// return the index of the right child of node i return 2 * i + 1; }; int MaxHeap::Parent(int i) {// return the index of the parent of node i return i / 2; // It returns floored value (truncated value) }; void MaxHeap::PercolateDown(int nodeIndex) { // DownHeap method. It will be called in MaxHeap and DeleteMax int leftChildIndex, rightChildIndex, minIndex, tmp; leftChildIndex = Left(nodeIndex); rightChildIndex = Right(nodeIndex); if (rightChildIndex >= heapSize) { if (leftChildIndex >= heapSize) return; else minIndex = leftChildIndex; } else { if (H[leftChildIndex] <= H[rightChildIndex]) minIndex = leftChildIndex; else minIndex = rightChildIndex; } if (H[nodeIndex] > H[minIndex]) { tmp = H[minIndex]; H[minIndex] = H[nodeIndex]; H[nodeIndex] = tmp; PercolateDown(minIndex); } }; void MaxHeap::Insert(int x) {// Insert a new element containing word and its weight heapSize++; H[heapSize] = x; // Find the insertion node, whose index is determined by heap_size int i = heapSize; // UpHeap Operation using Swap Operations while (i > 1 && H[i] > H[Parent(i)]) { // swap H[i] with H[Parent(i)] int temp = H[i]; H[i] = H[Parent(i)]; H[Parent(i)] = temp; i = Parent(i); } }; int MaxHeap::DeleteMax() {// Find, return, and remove the element with the maximum weight int temp = H[1]; H[1] = H[heapSize]; H[heapSize] = 0; heapSize--; PercolateDown(1); // restore the heap-order property starting from the root return temp; }; void MaxHeap::PrintHeap() {// Print the heap in tree structure; each node containing word and weight //round two! int cellsForHeight = 1; for (int i = 1; i < arraySize; i++) { cout << "[" << H[i] << "]"; if (i == cellsForHeight) { //end of row. cout << endl; cellsForHeight = (cellsForHeight * 2) + 1; } } cout << endl; }; void MaxHeap::Merge(const MaxHeap &secondHeap) {// Merge with another heap to form a larger heap //duplicate original. int* copy = this->H; //extend original heap's size to be the sum of both. arraySize = arraySize + secondHeap.arraySize - 1; H = new int[arraySize]; //write all of copy into H. for (int i = 1; i < heapSize + 1; i++) { H[i] = copy[i]; } //write all of secondHeap into array. for (int i = 1; i < secondHeap.heapSize + 1; i++) { Insert(secondHeap.H[i]); } };
Python
UTF-8
699
3.265625
3
[ "MIT" ]
permissive
"""Rx Workshop: Event Processing. Part 2 - Grouping. Usage: python wksp5.py """ from __future__ import print_function import rx class Program: @staticmethod def main(): src = rx.Observable.from_iterable(get_input(), rx.concurrency.Scheduler.new_thread) res = src.group_by(lambda s: len(s)).to_blocking() res.for_each(lambda g: print("New group with length = " + str(g.key)) and g.subscribe(lambda x: print (" " + str(x) + " member of " + g.key))) def get_input(): while True: yield raw_input() if __name__ == '__main__': Program.main()
Java
UTF-8
1,604
3.015625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package uva10000_10599; import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.lang.*; public class uva10066 { public static void main(String[] args)throws IOException { Scanner scanner = new Scanner(new BufferedInputStream(System.in)); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); for(int c=1;;c++) { int a = scanner.nextInt(); int b = scanner.nextInt(); if(a==0&&b==0) break; int data1[] = new int[a]; int data2[] = new int[b]; for(int i=0;i<a;i++) data1[i] = scanner.nextInt(); for(int j=0;j<b;j++) data2[j] = scanner.nextInt(); int data[][] = new int[a+1][b+1]; for(int i=0;i<a;i++) { for(int j=0;j<b;j++) { if(data1[i]==data2[j]) { data[i+1][j+1] = data[i][j] + 1; } else { data[i+1][j+1] = Math.max(data[i][j+1], data[i+1][j]); } } } System.out.println("Twin Towers #"+c); System.out.println("Number of Tiles : "+data[a][b]+"\n"); } } }
JavaScript
UTF-8
4,073
2.53125
3
[]
no_license
import React, { useEffect, useState } from "react"; import sanityClient from "../client"; export default function Project(){ const [projectData, setProjectData] = useState(null); useEffect(() => { sanityClient.fetch(`*[_type == "project"]{ title, date, place, description, projectType, link, tags }`).then((data) => setProjectData(data)) .catch(console.error); }, []); //2XL: ACIMA -1536px //XL: 4K -1280px //LG: Computador/TV -1024px //MD: Tablet -768px //SM: Mobile -320a425px //block h-64 relative rounded shadow leading-snug bg-white border-l-8 border-green-400 //relative rounded-lg shadow-xl bg-white p-16 //text-gray-800 font-bold mb-2 hover:text-red-700 sm:text-xs lg:text-xs //grid grid-cols-2 // bg-green-500 md:bg-red-500 lg:bg-purple-500 return ( <main className="bg-green-100 min-h-screen p-12 overflow-y-hidden"> <section className="container mx-auto"> <h1 className="text-5xl flex justify-center cursive"> Meus projetos </h1> <h2 className="text-lg text-gray-600 flex justify-center mb-12 cursive"> Bem vindo à minha página de projetos! </h2> <section className="flex flex-col gap-8 sm:grid grid-cols-2"> {projectData && projectData.map((project, index) => ( <article className="relative rounded-lg shadow-xl bg-white lg:p-12" > <h3 className="text-gray-800 font-bold sm:text-xs md:text-xl lg:text-3xl text-center mb-2"> <a href={project.link} alt={project.title} target="_blank" rel="noopener noreferrer" > {project.title} </a> </h3> <div className="text-gray-500 text-xs"> <div> <span className="text-base"> <strong className="font-bold lg:text-xl">Finalizado em:</strong>{" "} {new Date(project.date).toLocaleDateString()} </span> </div> <div> <span className="text-base"> <strong className="font-bold lg:text-xl">Empresa:</strong>{" "} {project.place} </span> </div> <div> <span className="text-base"> <strong className="font-bold lg:text-xl">Tipo:</strong>{" "} {project.projectType} </span> </div> <p className="my-6 text-lg text-gray-700 leading-relaxed"> {project.description} </p> <a href={project.link} rel="noopener noreferrer" target="_blank" className="text-red-500 font-bold hover:underline hover:text-red-400 text-xl" > Veja o projeto{" "} <span role="img" aria-label="right pointer"> 👉 </span> </a> </div> </article> ))} </section> </section> </main> ) }
C++
UTF-8
2,296
3.296875
3
[ "Apache-2.0" ]
permissive
#pragma once #include <iostream> #include <fstream> #include <string> enum class TruelogType { INFO, ERROR, WARNING, DEBUG }; enum class TruelogStreamType { CONSOLE, FILE, ALL }; class Truelog { //private: class LogHelper; public: static void InitFile(const std::string& path = "log.txt"); // Write logs static Truelog& Stream(TruelogStreamType streamt = TruelogStreamType::ALL); template <class Arg> LogHelper & operator<<(const Arg & arg) { if (m_streamType == TruelogStreamType::ALL) { std::cout << std::endl; m_log << std::endl; } else if (m_streamType == TruelogStreamType::CONSOLE) { std::cout << std::endl; } else { m_log << std::endl; } return (LogHelper(this) << arg); } private: Truelog() = delete; Truelog(const Truelog&) = delete; Truelog(TruelogStreamType stream) : m_streamType(stream), m_warningCount(0), m_errorCount(0) {} static const std::string GetDate(); static std::ofstream m_log; TruelogStreamType m_streamType; unsigned int m_warningCount; unsigned int m_errorCount; class LogHelper { public: LogHelper(Truelog* owner) : m_owner(owner) {} LogHelper& operator<<(const TruelogType& type) { std::string output; switch (type) { case TruelogType::INFO: output = "[INFO] " + GetDate() + ": "; break; case TruelogType::ERROR: output = "[ERROR] " + GetDate() + ": "; m_owner->m_errorCount++; break; case TruelogType::WARNING: output = "[WARNING] " + GetDate() + ": "; m_owner->m_warningCount++; break; case TruelogType::DEBUG: output = "[DEBUG] " + GetDate() + ": "; break; default: break; } if (m_owner->m_streamType == TruelogStreamType::ALL) { std::cout << output; m_log << output; } else if (m_owner->m_streamType == TruelogStreamType::CONSOLE) { std::cout << output; } else { m_log << output; } return *this; } template<class Arg> LogHelper& operator<<(const Arg& arg) { if (m_owner->m_streamType == TruelogStreamType::ALL) { std::cout << arg << ' '; m_log << arg << ' '; } else if (m_owner->m_streamType == TruelogStreamType::CONSOLE) { std::cout << arg << ' '; } else { m_log << arg << ' '; } return *this; } private: Truelog* m_owner; }; };
C#
UTF-8
271
2.9375
3
[]
no_license
public class A { } public class B { public A AInstance { get; set; } public B (A a) { AInstance = a; } public void test() { /* do something with `AInstance` */ } }
C++
UTF-8
685
3.390625
3
[]
no_license
// it's in the Python class OrderLog: def __init__(self, size): self.log = list() self.size = size def __repr__(self): return str(self.log) def record(self, order_id): self.log.append(order_id) if len(self.log) > self.size: self.log = self.log[1:] def get_last(self, i): return self.log[-i] log = OrderLog(5) log.record(1) log.record(2) assert log.log == [1, 2] log.record(3) log.record(4) log.record(5) assert log.log == [1, 2, 3, 4, 5] log.record(6) log.record(7) log.record(8) assert log.log == [4, 5, 6, 7, 8] assert log.get_last(4) == 5 assert log.get_last(1) == 8
Java
UTF-8
1,105
3.46875
3
[]
no_license
package dp; public class LongestPalindromeSubString { public static void main(String[] args) { String str = "geekeg"; System.out.println(longestPalindromeSubString(str)); } private static int longestPalindromeSubString(String A) { int n = A.length(); int start = 0; int length = 0; int M[][] = new int[n][n]; for (int i = 0; i < n; i++) { M[i][i] = 1; } for (int i = 0; i < n - 1; i++) { if (A.charAt(i) == A.charAt(i + 1)) { M[i][i + 1] = 1; start = i; length = 2; } else M[i][i + 1] = 0; } for (int l = 3; l <= n; l++) { for (int i = 0; i <= n - l; i++) { int j = i + l - 1; if (A.charAt(i) == A.charAt(j) && M[i + 1][j - 1] == 1) { M[i][j] = 1; start = i; length = l; } else M[i][j] = 0; } } System.out.println(start + " " + (start + length - 1)); System.out.println(A.substring(start, start + length)); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print(M[i][j] + " "); System.out.println(); } return length; } }
TypeScript
UTF-8
969
2.875
3
[]
no_license
/** * The widget configuration options */ export interface WidgetOptions { embedMode?: EmbedMode; // Default: modal env?: Environment; // Default: production brandColor?: string; // Default: #262525 brandImageUrl?: string; // Default: REDSHIFT Image containerId?: string; // The id of the container that the widget will be attached to. Default: body invoice?: string; // an optional invoice to pass to the widget. Used for pre-populating the invoice input. } /** * Whether the widget should appear as a modal or directly embedded in the webpage */ export enum EmbedMode { DIRECT_EMBED = 'direct-embed', MODAL = 'modal', } /** * Whether the widget should run in production (mainnet) or development (kovan testnet) mode */ export enum Environment { PRODUCTION = 'production', DEVELOPMENT = 'development', } /** * Redshift widget wrapper errors */ export enum RedshiftError { INVALID_REDSHIFT_EMBED_MODE = 'Invalid Redshift Embed Mode', }
Python
UTF-8
2,920
3.828125
4
[]
no_license
########## Unterstützender Code ########## class Node: def __init__(self): self.key = None self.parent = None self.left = None self.right = None ########## Lösung ########## # Node in parameter represents root of tree def insert(root, insert): current_node = root last_node = None while current_node != None: last_node = current_node if insert.key < current_node.key: current_node = current_node.left else: current_node = current_node.right insert.parent = last_node if last_node == None: root = insert elif insert.key < last_node.key: last_node.left = insert else: last_node.right = insert return root ########## Tests ########## def compare_trees(m, n): # None check if n is None and m is None: return True if n is not None and m is None: return False if n is None and m is not None: return False # Root if n.parent is None and m.parent is not None: return False if n.parent is not None and m.parent is None: return False if n.parent is not None and m.parent is not None: if n.parent.key != m.parent.key: return False # Key if m.key != n.key: return False # Left side if n.left is None and m.left is not None: return False if n.left is not None and m.left is None: return False if n.left is not None and m.left is not None: if not compare_trees(n.left, m.left): return False # Right side if n.right is None and m.right is not None: return False if n.right is not None and m.right is None: return False if n.right is not None and m.right is not None: if not compare_trees(n.right, m.right): return False # Correct parents if n.right is not None: if n.right.parent is not n: return False if n.left is not None: if n.left.parent is not n: return False if m.right is not None: if m.right.parent is not m: return False if m.left is not None: if m.left.parent is not m: return False # All passed return True ### Test 1 # build tree root = Node() root.key = 2 # build target target = Node() target.key = 1 # Call insert root = insert(root, target) # Compare NewRoot = Node() NewRoot.key = 2 NewRoot.left = Node() NewRoot.left.key = 1 NewRoot.left.parent = NewRoot if compare_trees(root, NewRoot): print("Test 1: Success") else: print("Test 1: Failure") ### Test 2 # build tree root = Node() root.key = 2 # build target target = Node() target.key = 3 # Call insert root = insert(root, target) # Compare NewRoot = Node() NewRoot.key = 2 NewRoot.right = Node() NewRoot.right.key = 3 NewRoot.right.parent = NewRoot if compare_trees(root, NewRoot): print("Test 2: Success") else: print("Test 2: Failure")
Java
UTF-8
2,603
2.53125
3
[]
no_license
package app.ui.expenseType.list; import app.data.model.StatusResponse; import app.data.network.Api; import app.ui.base.BasePresenter; import app.util.Utils; import io.reactivex.rxjava3.schedulers.Schedulers; import java.util.HashMap; /** * The presenter class responsible for the communication between the view and * the API. * * @param <V> the view attached to this presenter */ public class ExpenseTypeListPresenter<V extends ExpenseTypeListContract.View> extends BasePresenter<V> implements ExpenseTypeListContract.Presenter<V> { /** * Called when the view needs to load the expense types from the database. */ @Override public void loadExpenseTypes() { Api.getInstance().getExpenseTypeService().getExpenseTypes() .subscribeOn(Schedulers.io()) .observeOn(Schedulers.single()) .subscribe((expenseTypes) -> { getView().showExpenseTypes(expenseTypes); }, throwable -> { getView().onError("Error de conexión al cargar datos." + "\nIntente de nuevo"); }); } /** * Called when the view needs to disable an expense type from the database. * * @param expenseTypeId id of the expense type */ @Override public void disableExpenseType(int expenseTypeId) { // Create the request data HashMap<String, Object> request = new HashMap<>(2); request.put("expenseTypeId", expenseTypeId); request.put("isActive", 0); // Executes the request Api.getInstance().getExpenseTypeService().updateExpenseType(request) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.single()) .subscribe(() -> { // Request successful getView().refreshData(); getView().onSuccess("Se eliminó el tipo de viatico"); }, throwable -> { // Request error StatusResponse response = Utils.parseStatusResponse(throwable); if (response != null) { if (response.getStatusCode() == 1) { getView().onError("El tipo de viatico ya no" + " existe."); } } else { getView().onError("Error de conexión." + "\nIntente de nuevo"); } }); } }
C
UTF-8
621
3.796875
4
[]
no_license
/*Write a fn which accepts radius of circle from main() and calculates diameter, area and circumference. print result achieved from main*/ #include<stdio.h> #include<conio.h> void calc(int,int*,float*, float*); /*fn decln*/ void main() { int r,d; float ar,cc; clrscr(); printf("Enter the radius of the circle:- "); scanf("%d",&r); calc(r,&d,&ar,&cc); printf("Radius of circle=%d\n",r); printf("Diameter of circle=%d,area=%.2f,circumference=%.2f",d,ar,cc); getch(); } void calc(int r, int *ptr_d, float *ptr_ar, float *ptr_cc) { *ptr_d=2*r; *ptr_ar=3.14*r*r; *ptr_cc=2*3.14*r; } 
Python
UTF-8
186
2.9375
3
[]
no_license
a = [{"width": 0}, {"width": 56}, {"width": 3}, {"width": 9} ] def so(a): return a["width"] b = sorted(a, key=(lambda data: data["width"])) print(b) print(a)
Java
UTF-8
2,323
3.3125
3
[]
no_license
package com.chnye.common.tuple; //import org.apache.commons.lang3.builder.HashCodeBuilder; public class Pair<K, V> implements Tuple, Comparable<Pair<K, V>> { private final K first; private final V second; public static <T, U> Pair<T, U> of(T first, U second) { return new Pair<T, U>(first, second); } public Pair(K first, V second) { this.first = first; this.second = second; } public K first() { return first; } public V second() { return second; } public Object get(int index) { switch (index) { case 0: return first; case 1: return second; default: throw new ArrayIndexOutOfBoundsException(); } } public int size() { return 2; } @Override public int hashCode() { // HashCodeBuilder hcb = new HashCodeBuilder(); // return hcb.append(first).append(second).toHashCode(); int result = first != null ? first.hashCode() : 0; result = 31 * result + ( second != null ? second.hashCode() : 0 ); return result; } @Override public boolean equals(Object obj) { if (this == obj){ return true; } if (obj == null || getClass() != obj.getClass() ){ return false; } final Pair<?, ?> other = (Pair<?, ?>) obj; if( first != null ? !first.equals(other.first) : other.first != null ){ return false; } if( second != null ? !second.equals(other.second) : other.second != null ){ return false; } return true; // return (first == other.first || (first != null && first.equals(other.first))) && // (second == other.second || (second != null && second.equals(other.second))); } @Override public String toString() { StringBuilder sb = new StringBuilder("Pair{first="); sb.append(first).append(", second=").append(second).append("}"); return sb.toString(); } private int cmp(Object lhs, Object rhs) { if (lhs == rhs) { return 0; } else if (lhs != null && Comparable.class.isAssignableFrom(lhs.getClass())) { return ((Comparable) lhs).compareTo(rhs); } return (lhs == null ? 0 : lhs.hashCode()) - (rhs == null ? 0 : rhs.hashCode()); } @Override public int compareTo(Pair<K, V> o) { int diff = cmp(first, o.first); if (diff == 0) { diff = cmp(second, o.second); } return diff; } }
PHP
UTF-8
1,189
2.671875
3
[]
no_license
<?php function removeStudentFromClass($id, $classid) { $id = mysql_real_escape_string($id); $classid = mysql_real_escape_string($classid); //Remove user from class and all his/her notepads from the class $deleteduser = mysql_query("DELETE FROM classmates WHERE userid='$id' AND classid='$classid'"); $removed = mysql_affected_rows() != 0; $classnotepads = mysql_query("SELECT notebookid FROM classbooks WHERE classid='$classid'"); while ($row = mysql_fetch_assoc($classnotepads)) { $notebook = mysql_query("SELECT userid FROM notebooks WHERE id='".$row['notebookid']."'"); $nrow = mysql_fetch_assoc($notebook); mysql_free_result($notebook); if ($nrow) { if ($nrow['userid'] == $id) mysql_query("DELETE FROM classbooks WHERE notebookid='".$row['notebookid']."' AND classid='$classid'"); } } mysql_free_result($classnotepads); return $removed; } function removeNotepadFromClass($id, $classid) { $id = mysql_real_escape_string($id); $classid = mysql_real_escape_string($classid); mysql_query("DELETE FROM classbooks WHERE notebookid='$id' AND classid='$classid'"); return mysql_affected_rows() != 0; } ?>
Swift
UTF-8
3,688
3.265625
3
[]
no_license
// // FamiliEmptyView.swift // Component // // Created by Owen Prasetya on 17/11/20. // import UIKit /** Empty View Create an empty view with predefined positioning. How to use: * Using xib * * Drag and drop a UIView and change the class to FamiliEmptyView, put it inside a container view. * Programatically * Init a new empty view, with functions to set the image name and label text of the view. * Use setLabel function to change the text into the desired text. * Use setImage function to change the image into the desired image. */ @IBDesignable public class FamiliEmptyView: UIView { // MARK: - Alias typealias CommonProperty = FamiliEmptyViewConstant.CommonProperties // MARK: - Property @IBInspectable var labelText: String = "" { didSet { emptyViewLabel.text = labelText setupLabel() } } @IBInspectable var imageName: UIImage = UIImage() { didSet { emptyViewImage.image = imageName setupImage() } } private var emptyViewLabel = UILabel() private var emptyViewImage = UIImageView() // MARK: - Initialization public override init(frame: CGRect) { super.init(frame: frame) setupView() } public required init?(coder: NSCoder) { super.init(coder: coder) setupView() } /// Update display for usage in Interface Builder public override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setupView() } // MARK: - Private Function /// Setup the view by adding label and image to this view private func setupView() { self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.width, height: self.frame.height) setupImage() setupLabel() } /// Setup the label and its position private func setupImage() { emptyViewImage.frame = CGRect(x: self.frame.width/2, y: CommonProperty.initialPosition, width: self.frame.width/2, height: self.frame.width/2) emptyViewImage.contentMode = .scaleAspectFit addSubview(emptyViewImage) } /// Setup the label and its position private func setupLabel() { emptyViewLabel.frame = CGRect(x: self.frame.width/2, y: emptyViewLabel.frame.width + CommonProperty.elementSpacing, width: self.frame.width/2, height: self.frame.width/2 - CommonProperty.elementSpacing) emptyViewLabel.textAlignment = .center addSubview(emptyViewLabel) } // MARK: - Public Function /** Set Image Set image for the empty view - Parameters: - className: the parent for empty view - image: the name of the image on the empty view */ public func setImage(for className: AnyObject, withImage image: String) { let bundle = Bundle(for: type(of: className)) guard let image = UIImage(named: image, in: bundle, compatibleWith: nil) else { return } emptyViewImage.image = image self.setupImage() } /** Set Label Set text for the empty view - Parameters: - text: the text to be shown on the empty view */ public func setLabel(text: String) { emptyViewLabel.text = text self.setupLabel() } }
Markdown
UTF-8
4,687
3.25
3
[ "MIT" ]
permissive
# Quick Start Once you run all Docker containers, visit <http://localhost:8080/#/> Or any other URL where you install Whoops Monitor. ## Login Now you can log in. Use the admin password you can read from the Docker Compose file, the `APP_PASSWORD` variable. You might also click on the "Are you a guest?" link, allowing anonymous users to view dashboard data. <img src="/docs/img/quick-start/app-password-variable.png" alt="image" height="300" /> ## Dashboard Now you're logged in to the dashboard. At this point, there is nothing useful to see. So we have to configure some checks. ## Docker image goes first However, to do be able to do that, you also need a Docker image first. Then you can use this image to run your checks or alerts. That is the same for checks as well as for alerts. So search in the menu on the left for the `Docker Images` item. <img src="/docs/img/quick-start/menu-docker-images.png" alt="image" width="294" /> ## Docker images As we already said, Whoops Monitor is all about Docker images. There are two types of images you should care about: - one for checks, - and one for alerting. Click on the `New Image` button and go right to the form. There are some fields you have to configure. The first one is about the type of Docker image. So select the purpose of your image. ### Select image You can either select one of the predefined images from the select box or enter the path of your own. Docker image must be available in some registries, like Docker Hub, GitLab Registry, or even your private one. You can also enter some credentials in case your registry storage requires it to log in. ### Existing images We created a different kind of images so you can start pretty smoothly. - [checks](https://github.com/whoopsmonitor?q=check-&type=&language=) - [alerts](https://github.com/whoopsmonitor?q=alert-&type=&language=) ### Custom images To create your checks or alerts, follow our tutorials: - [custom check](./custom-check.md) - [custom alert](./custom-alert.md) ### Local image option You might have noticed the `local image` option in the form. This option is mostly used for local debugging. So you can even have a local image right on the server Whoops Monitoring is running on. ## Saving Docker Image When you save the image, wait for a minute (approximately) until the gray circle will turn into green. That means the Docker image is ready to be used. <div> <img src="/docs/img/quick-start/docker-images-list-grey.png" alt="image" width="350" /> <img src="/docs/img/quick-start/docker-images-list-green.png" alt="image" width="350" /> </div> ## Ready to create a new check? Once we added our image, we are ready to create our first check. Just go to the `Checks` menu item. <img src="/docs/img/quick-start/checks-menu.png" alt="image" width="293" /> Next, click on the `New Check` button, and you're right in the form you're about to configure. There are many fields you can configure. Some of them are optional, but most of them required. ### Tab: General - `Check Name` - Just enter the name of the check displayed on the dashboard. - `Image` - Select the image we created earlier. In our case, the `URL Alive` image. - `Cron` - Enter interval (cron notation) how often the check will run. You can use [Crontab Guru](https://crontab.guru/) to help you to build a cron. Little helper below the field will show you the cron in the "human-readable" format. ### Tab: Env Variables This tab is the most important one. Docker containers take environmental variables, so they are easily configurable. Every check and its env vars should be well documented in the README file. So you can read further details in there. Remembering all the variables is a bit unfriendly. However, there is a small help. A little button called `Reset Variables` will override the field's content with default values parsed right from the image. This only works if the image supports it (our images do that), and the image is healthy (remember the small green circle?). But just to prevent any misunderstanding, please read the README file as well. That's how we configured the `URL Alive` check. <img src="/docs/img/quick-start/tab-env-vars.png" alt="image" width="394" /> ## Finally That's actually all you need to know right now. Save the form. Don't forget to publish the check. Go to the dashboard and wait for the check to run for the first time. <img src="/docs/img/quick-start/dashboard-first-check.png" alt="image" width="600" /> ## Next step Every check might report its result to the alerting service. Would you like to set up a new alert? Let's [move to the next level](./quick-start-alerts.md).
C++
UTF-8
842
3.015625
3
[]
no_license
#ifndef PLACE_H #define PLACE_H #include "enums.h" #include "farmer.h" class Place { protected: int level_; int upgrade_day_; bool is_upgrading_; public: const uint upgrade_time; Place(uint upgrade_time) : upgrade_time(upgrade_time){} int level() const { return level_; } int upgrade_day() const { return upgrade_day_; } bool is_upgrading() const { return is_upgrading_; } virtual int upgradeXp() = 0; virtual bool isUpgradeFinished() const = 0; virtual void finishUpgrade() = 0; virtual int isUpgradable(int farmer_id) const = 0; virtual void upgrade(Farmer& farmer, int barn_id) = 0; virtual int neededNailsToUpgrade() const = 0; virtual int neededShovelsToUpgrade() const = 0; virtual int neededCoinsToUpgrade() const = 0; virtual ~Place() {} }; #endif // PLACE_H
Java
UTF-8
640
2.390625
2
[]
no_license
package com.util.dataConverter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.entity.Payment; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; public class JsonPaymentDataConverter implements PaymentDataConverter { private final ObjectReader reader = new ObjectMapper().readerFor(Payment[].class); @Override public ArrayList<Payment> convert(byte[] data) throws IOException { List<Payment> payments = Arrays.asList(reader.readValue(data)); return new ArrayList<>(payments); } }
Java
UTF-8
3,989
1.9375
2
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.skywalking.apm.webapp.proxy; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.env.AbstractEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerList; import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import org.springframework.cloud.netflix.ribbon.SpringClientFactory; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest @DirtiesContext public class NIWSServerListTest { @Autowired private Environment env; @Autowired private SpringClientFactory factory; private Map<String, String> serverListClassNames = new HashMap<String, String>(); @Before public void initServerListClassNames() { for (Iterator<?> iter = ((AbstractEnvironment) env).getPropertySources().iterator(); iter.hasNext();) { Object propertySource = iter.next(); if (propertySource instanceof MapPropertySource) { Map<String, Object> mapPropertySource = ((MapPropertySource) propertySource).getSource(); for (Map.Entry<String, Object> entry : mapPropertySource.entrySet()) { String key = entry.getKey(); int index; if (key.endsWith(".NIWSServerListClassName") && (index = key.indexOf(".ribbon")) > 0) { String clientName = key.substring(0, index); serverListClassNames.put(clientName,(String)entry.getValue()); } } } } } @Test public void serverListClass() throws ClassNotFoundException { for (String serverListClassName : serverListClassNames.values()) { Class<?> clazz = Class.forName(serverListClassName); } } @Test public void serverListFliter() { for (Map.Entry<String, String> entry : serverListClassNames.entrySet()) { String clientName = entry.getKey(); String serverListClassName = entry.getValue(); ServerList<Server> serverList = getLoadBalancer(clientName).getServerListImpl(); assertNotNull("Client: " + clientName + "'s ServerListImpl is null",serverList); assertEquals("Clinet: " + clientName + "'s ServerListImpl not Same with setting in configs", serverListClassName, serverList.getClass().getName()); } } @SuppressWarnings("unchecked") private ZoneAwareLoadBalancer<Server> getLoadBalancer(String name) { return (ZoneAwareLoadBalancer<Server>)this.factory.getLoadBalancer(name); } }
Java
UTF-8
469
2.15625
2
[]
no_license
package ren.shuaipeng.demo.springboot.statemachine; import lombok.extern.log4j.Log4j2; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.concurrent.TimeUnit; @Transactional(rollbackFor = Exception.class) @Service @Log4j2 public class IterationService { public void create() throws InterruptedException { log.info("迭代创建"); TimeUnit.SECONDS.sleep(10); } }
Markdown
UTF-8
1,619
2.875
3
[ "MIT" ]
permissive
# Pathfinding [![AI in Action](https://github.com/SudoSandwichX/Pathfinding/blob/master/Game%20Images/AI%20Moving.PNG)](https://www.youtube.com/watch?v=egGQED1TgxE&feature=youtu.be) [View demo on YouTube](https://www.youtube.com/watch?v=egGQED1TgxE&feature=youtu.be) This is an opensource project that is a personal exploration of A* for grid based pathfinding. I'm working on this as part of hackathons and free time as a way to continue exploring my passion outside of my day job. Goals: - Create an algorithm that can locate a target and avoid obstacles such as non-traversable objects, objects/materials that buff or debuff movement and moving obstacles. - Allow for dynamic and efficient updates to path as obstacles move or the target moves. Stretch Goal: - Remove grid size limit and make algorithm build grid only around units based in a larger world container. - Have grid build using varying grid block sizes on low to high precision based on locality. e.g. if target is far away we only need an approximate area of low density to locate. As we move closer increase precision. ## Controls for test scene |Key |Action | |---|---| |Left Click |Move target | |Right Click & Drag |Rotate Camera | |WASD |Pan Camera | |R |Respawn AI to random spawn points | |Space |Scatter AI paths| ## References for project A* algorithm based off YouTube tutorial by Sebastian Lague https://www.youtube.com/watch?v=-L-WgKMFuhE&list=PLFt_AvWsXl0cq5Umv3pMC9SPnKjfp9eGW Sebastian's original tutorial was made into a GitHub repo that can be found at: https://github.com/SebLague/Pathfinding
Java
UTF-8
920
3.171875
3
[]
no_license
package com.tk.algorithm.binary_tree_paths_257; import java.util.ArrayList; import java.util.List; public class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> res = new ArrayList<>(); if (root == null) return res; if (root.left == null && root.right == null) { res.add(String.valueOf(root.val)); return res; } List<String> left = binaryTreePaths(root.left); for (int i = 0; i < left.size(); i++) { res.add(root.val + "->" + left.get(i)); } List<String> right = binaryTreePaths(root.right); for (int i = 0; i < right.size(); i++) { res.add(root.val + "->" + right.get(i)); } return res; } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } }
Java
UTF-8
1,329
2.453125
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package gov.samhsa.c2s.c2suiapi.service; public interface EnforceUserAuthService { /** * Enforces only granting access to users who are authorized * to access a particular patient's MRN * <p> * If current user is not authorized to access the specified patient MRN, * then a PatientNotBelongToCurrentUserException is throw, which will * trigger an HTTP 412 - PRECONDITION FAILED status code to be returned * to the client. * @see gov.samhsa.c2s.c2suiapi.service.exception.PatientNotBelongToCurrentUserException * * @param mrn - the patient MRN to verify the current user is permitted to access */ void assertCurrentUserAuthorizedForMrn(String mrn); /** * Enforces only granting access to a user specified by user id if * the currently authenticated user matches the specified user id * <p> * If current user is not the user specified by user id, then a * UserUnauthorizedException is thrown, which will trigger an * HTTP 403 - FORBIDDEN FAILED status code to be returned * to the client. * @see gov.samhsa.c2s.c2suiapi.service.exception.UserUnauthorizedException * * @param userId - the user ID to verify matches the currently authenticated user */ void assertCurrentUserMatchesUserId(Long userId); }
Markdown
UTF-8
953
4
4
[ "MIT" ]
permissive
# 在 C++ 中使用 ifstream 逐行读取文件 文件内容如下 >5 3 6 4 7 1 10 5 11 6 12 3 12 4 5 3 是一个坐标,我在 C++ 中怎么逐行的处理这些数据? ## 回答 首先 创建 ifstream 实例 ```C++ #include <fstream> std::ifstream infile("thefile.txt") ``` 有两种标准的方法: 1. 假设每一行都由两个数字组成可以逐个 token 的读取: ```C++ int a, b; while(infile >> a >> b) { //process pair (a, b) } ``` 2. 基于行的解析,使用字符串流 ```C++ #include <sstream> #include <string> std::string line; while (std::getline(infile, line)) { std::istringstream iss(line); int a, b; if (!(iss >> a >> b)) { break; } // error // process pair (a,b) } ``` 你不能混合使用 (1) 和 (2), 因为基于 token 的解析并不读入换行符,所以你在它后面使用 getline() 会得到一个空行,因为 基于 token 的解析已经到达行尾了。
Markdown
UTF-8
1,558
3.671875
4
[]
no_license
# call、apply、bind - 都用来改变函数的this指向 - 第一个参数都是this - 都可以利用后续参数传参 - call:fn.call(this,1,2,3) - apply:fn.apply(this,[1,2,3]) - bind:fn.bind(this)(1,2,3) ## call的实现 ```javascript Function.prototype.myCall=function(context=window,...rest){ context.fn=this let result=context.fn(...rest) delete context.fn return result } ``` ## apply ```javascript Function.prototype.myApply=function(context=window,params=[]){ context.fn=this let result if(params.length){ result=context.fn(...params) }else{ result=context.fn() } delete context.fn return result } ``` ## bind ```javascript Function.prototype.myBind=function(oThis){ if(typeof this!=='function'){ throw new TypeError('Function.prototype.bind-what is trying to be bound is not callable') } // 拿到参数 let aArgs=Array.prototype.slice.call(arguments,1) let fToBind=this let fNOP=function(){} let fBound=function(){ return fToBind.apply( this instanceof fNOP?this:oThis, // 拼接参数 aArgs.concat(Array.prototype.slice.call(arguments)) ) } // 创建一个空对象,把控对象的原型指向调用的原型 fNOP.prototype=this.prototype // 原型指向一个新的fNOP实例,完成了拷贝一个fNOP的prototype,也就是调用函数的prototype fBound.prototype=new fNOP() return fBound } ``` 参考:https://www.cnblogs.com/goloving/p/9380076.html
C++
UTF-8
1,529
3.234375
3
[]
no_license
#include"NrRat.h" NrRat::NrRat() { this->numarator = 0; this->numitor = 0; } NrRat::NrRat(int a,int b) { this->numarator = a; this->numitor = b; } std::istream &operator >> (std::istream &flux, NrRat &Nr) { flux >> Nr.numarator; std::cout << '-' << std::endl; flux >> Nr.numitor; return flux; } std::ostream &operator << (std::ostream &flux, NrRat Nr) { flux << Nr.numarator<<'/'<<Nr.numitor; return flux; } NrRat NrRat::operator +(NrRat &nr) { NrRat rez; rez.numarator = getNumarator()*nr.getNumitor() + getNumitor()*nr.getNumarator(); rez.numitor = getNumitor() * nr.getNumitor(); return rez; } NrRat NrRat::operator -(NrRat &nr) { NrRat rez; rez.numarator = getNumarator()*nr.getNumitor() - getNumitor()*nr.getNumarator(); rez.numitor = getNumitor() * nr.getNumitor(); return rez; } bool NrRat::operator<(NrRat nr) { if (getNumarator()*nr.getNumitor() < getNumitor()*nr.getNumarator()) return true; else return false; } NrRat NrRat::operator *(NrRat &nr) { NrRat rez; rez.numarator = getNumarator() * nr.getNumarator(); rez.numitor = getNumitor() * nr.getNumitor(); return rez; } NrRat NrRat::operator!() { NrRat rez; rez.numarator = numitor; rez.numitor = numarator; return rez; } NrRat NrRat::operator/(NrRat &nr) { NrRat rez; rez = (*this)*(!nr); return rez; } int NrRat::getNumarator() { return numarator; } int NrRat::getNumitor() { return numitor; } void NrRat::setNumarator(int a) { this->numarator = a; } void NrRat::setNumitor(int a) { this->numitor = a; } NrRat::~NrRat() { }
Python
UTF-8
1,415
3
3
[]
no_license
import streamlit as st import pandas as pd import matplotlib.pyplot as plt import plotly.express as px st.title('Life Expectancy vs GNI per capita') @st.cache def data_p(): ley = pd.read_csv("Data/life_expectancy_years.csv") gni = pd.read_csv("Data/gnipercapita_ppp_current_international.csv") pop = pd.read_csv("Data/population_total.csv") ley.ffill(inplace=True) gni.ffill(inplace=True) gni.backfill(inplace=True) gni_ty = pd.melt(gni, ["country"], var_name=["year"], value_name="GNI per capita") pop_ty = pd.melt(pop, ["country"], var_name=["year"], value_name="population") ley_ty = pd.melt(ley, ["country"], var_name=["year"], value_name="life expectancy") ley_gni_ty = pd.merge(ley_ty, gni_ty, how= 'left', on=['country', 'year']) merged_ty = pd.merge(ley_gni_ty, pop_ty, how= 'left', on=['country', 'year']) return merged_ty merged_ty = data_p() max_year = int(merged_ty['year'].max()) year = st.sidebar.slider('Year', min_value = 1990, max_value= max_year) year = str(year) countries = st.multiselect('Select countries', merged_ty.country.unique()) mty = merged_ty.loc[lambda d: d['country'].isin(countries)] mty = mty.loc[mty['year'] == year] fig = px.scatter(mty, x='GNI per capita', y='life expectancy', size='population', color='population', hover_name='country', log_x=True, range_x=[1, 12000], range_y=[0, 90]) st.plotly_chart(fig)
Markdown
UTF-8
3,889
3.234375
3
[ "CC-BY-4.0" ]
permissive
--- id: p-model title: Abstract Programming Model permalink: book/en/p-model.html --- CKB has a very different programming model, an abstract programming model. Why do we need an abstract programming model? ## Why abstract programming model? There is a problem that blockchains are often lack of cryptography primitives. An abstract programming model fix this. Why is the lack of cryptography primitives a problem? As a layer1, you need to communicate with all kinds of layer2 protocols, and many of these layer2 protocols use novel cryptography technologies as components of their protocols. For example, different layer2 protocols may use different signature algorithms, layer1 is expected to be able to handle them all well. This is just one example, people always want to use all kinds of cryptography primitives on layer2, and expecting layer1 can handle it anyway. But on Bitcoin or Ethereum, the only way to add a new primitive is to do a hard fork, adding a new OP_CODE to the chains. But if we have an abstract programming model, this is easy to do. Being abstract means trying the best to push things to upper layers, so that the layer1 VM itself can be as simple and abstract as possible.  Being simple means a lot to a layer1 blockchain. We can have a much simpler cost model. It's easy to determine how many gas you should charge for a certain OP_CODE. CKB VM uses RISC-V instruction set. Nervos believes blockchain instructions should be low-level. High-level is a synonym to complexity. So it's very easy to get how many CPU cycles one OP_CODE cost, as we calculating the gas fee for it. ## Adding Primitives At Will A Blockchain is a hardware-like software. It is a software, but it's like hardware in that it is hard to upgrade. By pushing the complexity to an upper layer, we can do a lot things in user space. And blockchain and evolve faster because its always easy to do things in user space. There is NO hard coded crypto-primitives in CKB-VM. There is no special OP_CODE in CKB-VM. The problem with this design is that if you run all the primitives in VM layer, it ought to be slow. That's why no other chain is doing it this way. But CKB VM uses a hardware instruction set, which makes it easy to optimize the compiled code, to make the primitive code run faster. For example, secp256k1 is the default primitive CKB default transaction signature. It works as a smart contract deployed on CKB. How to do it? We get the source code for secp256k1, compile it to RISC-V supported binary format, deploy the binary to CKB-VM. And whenever a transaction needs to be signed, the VM refers to the binary running. As tests shows, a verification takes 9ms, while it's 1ms if the primitive is built in the chain. So it's not as fast but acceptable, since the bottleneck is somewhere else. That is way CKB-VM is very flexible, because whenever a layer2 user wants her own primitive, she can just deploy it on CKB-VM, as we do for secp256k1. Moreover, since it's just gcc compatible hardware-like instruction set, and all other primitives are mostly written in C, so it's easy to deploy them on CKB-VM.  ## Abstract State Model VM is only the computation part of the abstract programming model, the other part is an abstract state model. CKB is a generalization of Bitcoin. CKB state object is a generalization of UTXO, which we call cell. You can store not just numbers but all sorts of data in a cell. The transaction structure is similar to Bitcoin. And the whole system is very much like Bitcoin, so we won't go details here. ## Conclusion CKB has an abstract programming model. The VM is made very simple and low level, so that most things is don't in user space. Layer2 users can deploy there own crypto-primitives at will, and CKB also offers a abstract state model to support the programming model. ref: - https://www.youtube.com/watch?v=F1nfrTsGJqk
Markdown
UTF-8
1,877
2.71875
3
[ "MIT" ]
permissive
--- layout: default title: Home nav_order: 1 description: "Just the Docs is a responsive Jekyll theme with built-in search that is easily customizable and hosted on GitHub Pages." permalink: mathjax: true. --- This is a fork of documentation template "Just the Docs" with MathJax support and a few changes. ## Usage Just copy this repository to your project's `docs` directory and then set the publishing directory as docs from repository setting as explained in [github pages documents](https://docs.github.com/en/pages/getting-started-with-github-pages/configuring-a-publishing-source-for-your-github-pages-site). Everything is in place for github pages usage. However, in case this is how `GemFile` should look like: ```ruby # frozen_string_literal: true source "https://rubygems.org" git_source(:github) {|repo_name| "https://github.com/#{repo_name}" } # gem "rails" gem "github-pages", group: :jekyll_plugins gem "jekyll-seo-tag", "~> 2.7" ``` Finally, clear the `content` directory and add your own documentation. ## Local Installation with Bundler First, we need ruby for jekyll so check [here](https://jekyllrb.com/docs/installation/) for installation. We already have the `Gemfile` so no initialization is necessary. 1. Set the installation directory as local ```bash bundle config set --local path 'vendor/bundle' ``` 2. Install dependencies ```bash bundle install ``` 3. Serve the site locally ```bash bundle exec jekyll s ``` 4. Point your web browser to [http://localhost:4000](http://localhost:4000) ## MathJax Support Add `mathjax: true` to frontmatter of a page: ```markdown --- layout: default title: Home mathjax: true. --- ``` ## Configure Just the Docs Default directory name is changed to `content` from `docs` since repository itself is used as docs. - [See configuration options]({{ site.baseurl }}{% link content/configuration.md %})
Python
UTF-8
2,822
3.796875
4
[]
no_license
""" In this question your task is again to run the clustering algorithm from lecture, but on a MUCH bigger graph. So big, in fact, that the distances (i.e., edge costs) are only defined implicitly, rather than being provided as an explicit list. The data set is below. clustering_big.txt The format is: [# of nodes] [# of bits for each node's label] [first bit of node 1] ... [last bit of node 1] [first bit of node 2] ... [last bit of node 2] ... For example, the third line of the file "0 1 1 0 0 1 1 0 0 1 0 1 1 1 1 1 1 0 1 0 1 1 0 1" denotes the 24 bits associated with node #2. The distance between two nodes uu and vv in this problem is defined as the Hamming distance--- the number of differing bits --- between the two nodes' labels. For example, the Hamming distance between the 24-bit label of node #2 above and the label "0 1 0 0 0 1 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 0 1" is 3 (since they differ in the 3rd, 7th, and 21st bits). The question is: what is the largest value of kk such that there is a kk-clustering with spacing at least 3? That is, how many clusters are needed to ensure that no pair of nodes with all but 2 bits in common get split into different clusters? NOTE: The graph implicitly defined by the data file is so big that you probably can't write it out explicitly, let alone sort the edges by cost. So you will have to be a little creative to complete this part of the question. For example, is there some way you can identify the smallest distances without explicitly looking at every pair of nodes? """ import collections import itertools from unionfind import UnionFind from tqdm import tqdm def flip(bit): return '0' if bit=='1' else '1' def getNeiborhood(bits): for i in range(len(bits)): yield bits[:i] + (flip(bits[i]),) + bits[i+1:] for i, j in itertools.permutations(range(len(bits)), 2): if i < j: yield bits[0:i] + (flip(bits[i]),) + bits[i+1:j] + (flip(bits[j]),) + bits[j+1:] def Clustering(nodes): UnionNodes = UnionFind(nodes.keys()) for node in tqdm(nodes): for neighbour in getNeiborhood(node): if neighbour not in nodes: continue if not UnionNodes.connected(node, neighbour): UnionNodes.union(node, neighbour) return UnionNodes if __name__ == "__main__": txtFile = './clustering_big.txt' data = collections.defaultdict() with open(txtFile, 'r') as f: for line in f.readlines()[1:]: nums = line.split() # data.append(tuple(nums)) data[tuple(nums)] = tuple(nums) # print(data[:5]) # cluster1 = Cluster(data) # print(cluster1.clustering()) unionNodes = Clustering(data) print(unionNodes.n_comps)
PHP
UTF-8
2,611
2.640625
3
[]
no_license
<div id="page"> <div id="contenu"> <div class="box"> <?php // si la variable $_REQUEST['Pra_Num'] est vide c'est qu'il s'agit d'un nouvel Praticien à créer if(!empty($_REQUEST['Pra_Num'])) { // si on demande une modification d'un Praticien $LePraticien=Praticien::findById($_REQUEST['Pra_Num']); // trouve le Praticien et on renvoie un objet Praticien } $lesTypePraticiens=TypePraticien::getAllTP(); ?> <h2>Fiche Praticien</h2> <section> <form action="index.php?uc=GestionPraticiens&action=VerifForm" method="POST"> <input type="hidden" name="Pra_Num" value='<?php if(!empty($_REQUEST['Pra_Num'])){echo $LePraticien->getIdP();}?>'> <label for="nomPrat"><font color="#A52A2A">Nom</font></label> <input type="text" name="nomPrat" id="nomPrat" value="<?php if(!empty($_REQUEST['Pra_Num'])){echo $LePraticien->getNom();} ?>"><br><br> <label for="TypePrat"><font color="#A52A2A">Type du praticien</font></label> <select name="TypePrat" id="TypePrat" value="<?php if(!empty($_REQUEST['Pra_Num'])){echo $LePraticien->getTypeP();} ?>"> <?php foreach($lesTypePraticiens as $TypePraticien) { echo "<option value=". $TypePraticien->getIdTP() ." "; if(!empty($_REQUEST['Typ_Code']) && ($_REQUEST['Typ_Code'])== $TypePraticien->getIdTP()){ echo "selected"; } echo ">".$TypePraticien->getLibelleTP() ."</option>"; } ?> </select><br><br> <label for="AdressePrat"><font color="#A52A2A">Adresse</font></label> <input type="text" name="AdressePrat" id="AdressePrat" value="<?php if(!empty($_REQUEST['Pra_Num'])){echo $LePraticien->getAdresse();} ?>"><br><br> <label for="CPPrat"><font color="#A52A2A">Code postal</font></label> <input type="text" name="CPPrat" id="CPPrat" value="<?php if(!empty($_REQUEST['Pra_Num'])){echo $LePraticien->getCP();} ?>"><br><br> <label for="VillePrat"><font color="#A52A2A">Ville</font></label> <input type="text" name="VillePrat" id="VillePrat" value="<?php if(!empty($_REQUEST['Pra_Num'])){echo $LePraticien->getVille();} ?>"><br><br> <label for="CoefnotorietePrat"><font color="#A52A2A">Coefficient de notoriété</font></label> <input type="text" name="CoefnotorietePrat" id="CoefnotorietePrat" value="<?php if(!empty($_REQUEST['Pra_Num'])){echo $LePraticien->getCoef();} ?>"><br><br><br><br> <input type="submit" value="<?php if(!empty($_REQUEST['Pra_Num'])){echo "Modifier le praticien";}else{echo "Ajouter le praticien";} ?>"/> </form> </section> </div> </div> <br class="clearfix" /> </div>
TypeScript
UTF-8
384
2.515625
3
[]
no_license
export class LogService{ constructor(){ } log(info:string):void{ console.log(info) } } export class UseValueService{ log(info:string):void{ console.log(info) } } export class UseFactroryService{ log(message:string){ console.log(message); } } export class LogStringTokenService{ constructor(){ } log(info:string):void{ console.log(info) } }
SQL
UTF-8
442
3.1875
3
[]
no_license
DROP TABLE IF EXISTS USER_SEARCH; DROP TABLE IF EXISTS USER_SEARCH_BY_RESULT; CREATE TABLE USER_SEARCH ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(250) NOT NULL, created_date timestamp , search_result VARCHAR(250) NOT NULL ); CREATE TABLE USER_SEARCH_BY_RESULT ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(250) NOT NULL, created_date timestamp without time zone, search_result VARCHAR(250) NOT NULL );
Python
UTF-8
1,301
3.109375
3
[ "MIT" ]
permissive
import csv import argparse import glob def run(folder: str, column: str, value): files = [i for i in glob.glob(f'{folder}/*.csv')] if not input(f'Adding column {column} with value {value} to {len(files)} files in folder {folder}. Continue? [y/n]') == 'y': return for file in files: run_file(file, column, value) def run_file(file: str, column: str, value): rows = [] with open(file, encoding='utf-8-sig') as csvfile: reader = csv.DictReader(csvfile) for row in reader: assert not row.get('iteration'), f'Row in file {file} already has column {column}' rows.append(row) assert len(rows) > 0 for row in rows: row[column] = value with open(file, encoding='utf-8-sig', mode='w') as csvfile: keys = rows[0].keys() writer = csv.DictWriter(csvfile, fieldnames=keys) writer.writeheader() writer.writerows(rows) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--folder', '-f', dest='folder', required=True) parser.add_argument('--column', '-c', dest='column', required=True) parser.add_argument('--value', '-v', dest='value', required=True) args = parser.parse_args() run(args.folder, args.column, args.value)
Java
UTF-8
4,219
2.421875
2
[ "MIT" ]
permissive
package com.tags.jsf.form; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.faces.component.FacesComponent; import javax.faces.component.UIComponentBase; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import com.classes.BeanImplementation; import com.ui.ApiUi; @FacesComponent(createTag = true, namespace="http://www.edunola.com.ar/uicomponents", tagName="radioFull", value="radioFull") public class RadioFull extends UIComponentBase{ private String label; private String id= ""; private String name; private Object value; private boolean inline= false; private String typeError; private String size = "md"; private Object options; private String methodValue; private String methodLabel; @Override public String getFamily() { return "EnolaUIServices"; } @SuppressWarnings("unchecked") @Override public void encodeBegin(FacesContext context) throws IOException { ApiUi api= ApiUi.getInstance(); //Armo un mapa con los valores de configuracion del Componente Map<String, Object> valores= new HashMap<String, Object>(); valores.put("config.seccion", "cabecera"); valores.put("config.label", this.getLabel()); if(this.getTypeError() != null){valores.put("config.typeError", this.getTypeError());} valores.put("config.size", this.getSize()); //Opciones del Radio String componentes= ""; int numero= 0; Collection<Object> opciones= (Collection<Object>) this.getOptions(); for(Object opcion: opciones){ Object optLabel= BeanImplementation.executeMethodGet(opcion, this.getMethodLabel()); Object optValue= BeanImplementation.executeMethodGet(opcion, this.getMethodValue()); Map<String, Object> valoresOpt= new HashMap<String, Object>(); valoresOpt.put("config.label", optLabel); valoresOpt.put("config.name", name); valoresOpt.put("datos.value", optValue); if(this.isInline()){ valoresOpt.put("config.inline", "si"); }else{ valoresOpt.put("config.inline", "no"); } valoresOpt.put("config.id", this.getId() + Integer.toString(numero)); numero++; if(this.getValue().equals(optValue)){ valoresOpt.put("config.checked", "si"); } else{ valoresOpt.put("config.checked", "no"); } componentes += api.imprimirComponente("radio_option", valoresOpt); } valores.put("components", componentes); ResponseWriter writer = context.getResponseWriter(); writer.write(api.imprimirComponente("radio", valores)); } @Override public void encodeEnd(FacesContext context) throws IOException { ApiUi api= ApiUi.getInstance(); //Armo un mapa con los valores de configuracion del Componente Map<String, Object> valores= new HashMap<String, Object>(); valores.put("config.seccion", "pie"); ResponseWriter writer = context.getResponseWriter(); writer.write(api.imprimirComponente("radio", valores)); } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public boolean isInline() { return inline; } public void setInline(boolean inline) { this.inline = inline; } public String getTypeError() { return typeError; } public void setTypeError(String typeError) { this.typeError = typeError; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public Object getOptions() { return options; } public void setOptions(Object options) { this.options = options; } public String getMethodValue() { return methodValue; } public void setMethodValue(String methodValue) { this.methodValue = methodValue; } public String getMethodLabel() { return methodLabel; } public void setMethodLabel(String methodLabel) { this.methodLabel = methodLabel; } }
Python
UTF-8
818
2.671875
3
[]
no_license
# takes a list of protein sequences and determines their orthogroup ids #with python/2.7.8 #takes two files, source of fasta and output import urllib, json, time, sys from Bio import SeqIO urlbase = "http://www.orthodb.org/blast?" outfile = open(sys.argv[2], "w", 0) level = "level=7434" #Aculeata count = 1 start = time.time() for rec in SeqIO.parse(sys.argv[1], "fasta"): while True: try: response = urllib.urlopen(urlbase + level + "&seq=" + str(rec.seq).replace("*","")) data = response.read() parsedData = json.loads(data) except: print "http error" time.sleep(2) else: break if parsedData['data']: outfile.write(rec.id + "\t" + ",".join(parsedData['data']) + "\n") count += 1 if count % 100 == 0: print("%i %.2f" % (count, time.time() - start)) start = time.time()
Markdown
UTF-8
7,159
2.953125
3
[ "MIT" ]
permissive
--- layout: article title: AE 484 - Finite Element Methods aside: toc: true sidebar: nav: docs-en categories: department_elective ae-484 permalink: /course_reviews/:categories tags: structures theory project --- # Autumn 2019 ### Prof. PJ Guruprasad **Author**: Sakshi Dayal **Pre-requisite courses**: [AE 227](/course_reviews/second_year/ae-227), AE 238 **Pre-requisite skills**: Basic MATLAB coding. (Code template was given, you need to just complete missing sections according to the question) **Course Content**: - Basics of finite element method (for motivation) - Standard discrete spring-mass-damper system - Variational methods of approximation (derivations) - Rayleigh- Ritz method and Method of Weighted Residuals - Weak Forms of Finite Element Approximation - 1D, 2D, 3D FEM models (bar, Euler-Bernoulli beam, Timoshenko beam) - Reduced Numerical integration - Introduction to finite element method in dynamics and vibrations - Computer implementation of the finite element models **Motivation to take up the course**: I had been using ANSYS and other simulation software mindlessly, but during my intern I realised we must know the background algorithms to avoid committing blunders. Also, FEM is an integral part of structures and if one is seeking to do projects or pursue career in this field, one will definitely require basic FEM knowledge. --- **Information about Projects/Assignments**: Two quizzes (10% each) Assignments (10%) Midsem (30%) Endsem (40%) This was declared in the beginning of the course, but changed drastically as semester proceeded. Weightage for assignments was increased and there was no midsem. Assignments are given a week in advance and have deadline a day prior to quiz. Completing and understanding each concept covered in the assignment is beneficial for quiz preparation. Quizzes are quite straightforward, mostly based on tutorial problems covered in class. Endsem was of medium difficulty. Formulae are provided during exams, no need of memorizing, just knowing how to attempt and reduce the question is important. There is a lot of scope of doing silly mistakes, so make sure you complete the questions till the very end while practicing. **Quizzes/Midsem/Endsem papers Difficulty**: 2/5 **Overall Course Difficulty**: Moderate **Average Time Commitment**: (Apart from lectures and tutorials) Less than 3 hrs **Attendance Policy**: There was no attendance policy, but it is recommended to attend lectures (especially tutorials) --- **General funda**: Attempt tutorial questions and assignments on your own, and till the very last step. Use a calculator and discover your own tricks to solve questions in less time and with more accuracy. **Grading stats**: | AA | 4 | | AB | 16 | | BB | 11 | | BC and below | 14 | | FR | 1 | **Professor's Teaching Style**: Asking doubts personally from the professor helps a lot. Raise questions and ask to repeat if you don't understand some step. Reading and attempting derivations by oneself using lecture notes is helpful. **Should you do this course?**: Anyone in third year or above can take this course. One should be comfortable with numerical methods, structure courses, and basic MATLAB coding. Scoring 8-9 is easy if you follow the course regularly, a 10 needs extra efforts. But for the utility of the course content, I highly recommend taking up this course, you won't regret. --- # Autumn 2022 ### Prof. Amuthan Ramabathiran **Author**: Vishnu Sankar **Pre-requisite skills**: Python programming, Basic Calculus **Course Content**: - Part 1 - 1D FEM - Basic FEM algorithm for second order ODEs. - Implementation of FEM in Python. - Introduction to Sobolev spaces. - Modern mathematical perspective of FEM. - A-priori and a-posteriori error estimates. - Part 2 - FEM for 2D elliptic PDEs - Variational theory of elliptic PDEs. - Abstract FE methodology. - Introduction to Fenics. - Application to heat conduction and elasticity using Fenics - Part 3 - Advanced Topics - Decriminalizing variational crimes. - Mixed finite elements: application to the Stokes problem. - Locking phenomenon. - Relationship between P1 finite elements and ReLU Deep Neural Networks. - FEM for parabolic PDEs **Motivation to take up the course**: Wanted to expand my knowledge of solving PDEs and wanted to experience one of the kind teaching style of Prof. Amuthan once again (first being AE 102) --- **Information about Projects/Assignments**: - Assignments - 20% - Midsem - 30% - Endsem - 50% - Project (optional) - 10% - Class wiki: Scribe for each lecture (optional) - 2% for each **Quizzes/Midsem/Endsem papers Difficulty**: 4/5 **Projects/Assignments Difficulty**: 4/5 --- **General funda**: This course presents a new way of abstract thinking that you might have hardly encountered before in any of the core/elective courses, so you need to put in some effort to get hold of the mathematical jargons and abstract thinking. The midsem is a pure programming, open book & open internet exam for 3 hrs. Assignments also involve fair amount of programming. The endsem exam is a mix of both numerical problems and programming. Soon after the midsem, professor Amuthan introduces you to a python framework called FEMTO (which he is currently developing). The course is fast paced after midsems, and you need to catch up to his teaching, devote enough time to understand OOPs concepts in Python and his code FEMTO. This is inevitable as you will have to use FEMTO in the assignments and endsem exams. The prof is chill with the grading, but you need to work towards it. Try to scribe as many class wiki's as possible as you will understand concepts better when you write them down for others to understand (and also you get bonus 2% for each class wiki) **Professor's Teaching Style**: Prof Amuthan's teaching is so fluid and immersive, this course is pretty mathematical in nature, but the Prof makes it quite simple to understand. Thankfully, he doesn't grill you with such mathematical questions in the exams. He conducted three demo lectures on advanced topics (not for exams/evaluation purpose): Introduction to open-source FEM packages such as FREEFEM and Fenics, Application of FEM to fluid problems, and relationship between FEM and ReLU Deep Neural Networks. The prof is also very accommodating of student requests such as deadline extensions etc. You also get to taste Prof. Amuthan's humor sense at time :) **Should you do this course?**: Anyone interested in solving PDEs through numerical computations in general can take up this course. The framework can be used for both Fluids and Structures, though in industry it is widely used only for structures problems. Recent research in the topic in the Fluid community involve hybrid FEM and FVM methods for fluid problems. If you want to get a sneak peek of modern mathematical formulation to solve PDEs/ODEs along with an immersive hands on Python programming experience, you should definitely take this course. **References**: - Claes Johnson - Numerical Solutions Of Partial Differential Equations By The Finite Element Method - Johnson - Numerical Solutions of PDE by FEM ---
Ruby
UTF-8
199
3.1875
3
[]
no_license
def is_integer? self.to_i.to_s == self end def isIPv4Address(inputString) inputString.count('.') == 3 && inputString.split('.').all? { |s| s.is_integer? && s.to_i >= 0 && s.to_i < 256 } end
JavaScript
UTF-8
1,322
2.546875
3
[ "MIT" ]
permissive
var test = require('tape') var FauxDOMRequest = require('./index') var successful = require('./dummy/successful') var erroneous = require('./dummy/erroneous') test('default state', function (assert) { var request = new FauxDOMRequest assert.equal(request.readyState, 'pending', 'readyState is "pending"') assert.equal(request.onerror, null, 'onerror is null') assert.equal(request.onsuccess, null, 'onsuccess is null') assert.equal(request.error, null, 'error is null') assert.equal(request.result, undefined, 'result is undefined') assert.end() }) test('successful request', function (assert) { assert.plan(4) var request = successful() request.onsuccess = function () { assert.pass('onsuccess was called') assert.equal(this.readyState, 'done', 'readyState is "done"') assert.equal(this.result, 'Great job!', 'result set') assert.equal(this.error, null, 'error is null') } }) test('erroneous request', function (assert) { assert.plan(5) var request = erroneous() request.onerror = function () { assert.pass('onerror was called') assert.equal(this.readyState, 'done', 'readyState is "done"') assert.equal(this.result, undefined, 'result is undefined') assert.ok(this.error, 'error is set') assert.equal(this.error.name, 'NO_GO', 'error.name set') } })
Java
UTF-8
8,853
2.234375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package VIEW; import CONTROLLER.Controle; import MODEL.ClientesBEAN; import static java.lang.Thread.sleep; import java.util.logging.Level; import java.util.logging.Logger; public class EditarClientes extends javax.swing.JInternalFrame { public EditarClientes() { initComponents(); jLabel4.setVisible(false); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { alterar = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); textNome = new javax.swing.JTextField(); textCPF = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); textId = new javax.swing.JTextField(); buscar = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); setClosable(true); setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); alterar.setText("Alterar"); alterar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { alterarActionPerformed(evt); } }); jLabel2.setText("Nome:"); jLabel3.setText("CPF:"); textNome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textNomeActionPerformed(evt); } }); jLabel1.setText("Id:"); textId.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textIdActionPerformed(evt); } }); buscar.setText("Buscar"); buscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buscarActionPerformed(evt); } }); jLabel4.setText("Alterado com sucesso!"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(50, 50, 50) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3) .addComponent(jLabel1) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textCPF, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textNome, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(textId, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(buscar)))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(alterar) .addGap(84, 84, 84)))) .addGroup(layout.createSequentialGroup() .addGap(90, 90, 90) .addComponent(jLabel4))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(54, 54, 54) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(textId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(buscar)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(textNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(textCPF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(41, 41, 41) .addComponent(alterar) .addGap(18, 18, 18) .addComponent(jLabel4) .addContainerGap(34, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void alterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_alterarActionPerformed Controle control = new Controle(); ClientesBEAN cliente = new ClientesBEAN(textNome.getText(), textCPF.getText()); control.addCliente(cliente); jLabel4.setVisible(true); }//GEN-LAST:event_alterarActionPerformed private void textNomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textNomeActionPerformed // TODO add your handling code here: }//GEN-LAST:event_textNomeActionPerformed private void textIdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textIdActionPerformed // TODO add your handling code here: }//GEN-LAST:event_textIdActionPerformed private void buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscarActionPerformed Controle control = new Controle(); ClientesBEAN cliente = new ClientesBEAN(null, null); if(textId.getText()!=null){ cliente = control.findCliente(Integer.parseInt(textId.getText())); }else{ cliente = control.findIdClienteNome(textNome.getText()); } textId.setText(Integer.toString(cliente.getIdCliente())); textNome.setText(cliente.getNome()); textCPF.setText(cliente.getCPF()); }//GEN-LAST:event_buscarActionPerformed private void sleepLabel(){ jLabel4.setVisible(false); try { sleep(2000); } catch (InterruptedException ex) { Logger.getLogger(CadastrarClientes.class.getName()).log(Level.SEVERE, null, ex); } } private static EditarClientes instance = null; public static EditarClientes getInstance() { if (instance == null) { instance = new EditarClientes(); Interface.getInstance().getDesktop().add(instance); } return instance; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton alterar; private javax.swing.JButton buscar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JTextField textCPF; private javax.swing.JTextField textId; private javax.swing.JTextField textNome; // End of variables declaration//GEN-END:variables }
Markdown
UTF-8
4,578
3
3
[]
no_license
+++ comments = true date = "2015-04-03" draft = false image = "" menu = "" share = true slug = "make-some-joy-on-phaser-stick" tags = ["game", "development", "es6", "javaScript", "phaser", "guide", "tutorial"] title = "A Virtual Joystick for Phaser" excerpt = 'So I wrote my own Virtual Joystick Plugin for the HTML5 game engine Phaser. That may sound stupid now, but at that time @photostorm didn’t release his official plugin yet. Still, it’s a $20 value there.' +++ So I needed a *Virtual Joystick* plugin (kinda) a few weeks ago. I found [phaser-touch-control-plugin](https://github.com/eugenioclrc/phaser-touch-control-plugin), but I want the joystick to stay in one place on the screen. So I wrote my own Virtual Joystick Plugin. That may sound stupid now, but at that time *@photostorm* didn’t release his [official plugin](http://phaser.io/shop/plugins/virtualjoystick) yet. Still, it’s a $20 value there. **For a quick demo, check out the Youtube video at the bottom of this post.** Here is my design: {{< figure src="/img/1-MOCWHqW8lCMOF3YOuZY9_w.png" >}} 1. A **background** for the joystick (the grey box) to show the players where to put their finger. {{< highlight js "linenos=inline" >}} class Joystick extends Phaser.Sprite { constructor(x, y) { super(game, 0, 0, 'background'); this.anchor.setTo(0.5, 0.5); } } {{< /highlight >}} 2. A *draggable sprite* for the **pin** (the red box) which players can, duh, drag. Here, `pin.input.enableDrag` is called with first param `true` so that the pin is always *centered* at your finger tip. {{< highlight js "linenos=inline" >}} constructor(x, y) { ... let pin = game.add.sprite(0, 0, 'pin'); pin.anchor.setTo(0.5, 0.5); pin.inputEnabled = true; pin.input.enableDrag(true); this.addChild(pin); this.pin = pin; } {{< /highlight >}} 3. Event `onDragStop`: The pin returns to the center of the background. {{< highlight js "linenos=inline" >}} constructor(x, y) { ... pin.events.onDragStop.add(this.onDragStop, this); ... } onDragStop(){ this.pin.position.setTo(0, 0); } {{< /highlight >}} 4. A restriction `maxDistance` to prevent the pin from going outside of the background (like in the picture below). If the background is a circle, this is normally the radius, meaning half of the background image width. The check happens at event `onDragUpdate`. {{< figure src="/img/1-GGn274e5_Gy_Fe1Q4y_wZQ.png" >}} {{< highlight js "linenos=inline" >}} constructor(x, y) { ... this.maxDistance = this.width/2; pin.events.onDragUpdate.add(this.onDragUpdate, this); ... } onDragUpdate(){ let {pin, maxDistance} = this; var distance = pin.getMagnitude(); if (distance > maxDistance) { pin.setMagnitude(maxDistance); } } {{< /highlight >}} --- There are two problems: 1. Event `onDragUpdate`: if `distance` is larger than `maxDistance`, the pin position is changed and not at player finger anymore. 2. In other game, players can start dragging from anywhere on the background of the joystick and the pin jumps at it immediately. Here, players have to actually start dragging at the pin position. To solve this, I added a transparent layer to act as the draggable, and use the pin only for indication of position. {{< figure src="/img/1-7uYh6KEiMyim_lhPJSxswg.png" >}} 1. Add a transparent `dragger` and move `dragging` events to `dragger` {{< highlight js "linenos=inline" >}} constructor(x, y) { ... let dragger = this.dragger = game.add.sprite(0, 0, null); dragger.anchor.setTo(0.5, 0.5); dragger.width = dragger.height = this.width; dragger.inputEnabled = true; dragger.input.enableDrag(true); this.addChild(dragger); dragger.events.onDragStop.add(this.onDragStop, this); dragger.events.onDragUpdate.add(this.onDragUpdate, this); } onDragStop(){ this.dragger.position.setTo(0, 0); this.pin.position.setTo(0, 0); } {{< /highlight >}} 2. The pin's position then would be set based on the dragger's position and `maxDistance`. {{< highlight js "linenos=inline" >}} onDragUpdate(){ let {pin, dragger, maxDistance} = this; var distance = dragger.getMagnitude(); pin.position.copyFrom(dragger); if (distance > maxDistance) { pin.setMagnitude(maxDistance); } } {{< /highlight >}} Check out the full source code on this [gist](https://gist.github.com/netcell/9083b5cef97125128420), and see this Virtual Joystick in action in my development footage for Sword of Vendetta: Dojo’s Last Blood. {{< youtube r-rhHbcNb0g >}}
JavaScript
UTF-8
1,544
2.890625
3
[ "MIT" ]
permissive
var subDays = require('date-fns/src/sub_days'); var subMonths = require('date-fns/src/sub_months'); var isWithinRange = require('date-fns/src/is_within_range'); var parseDate = require('date-fns/src/parse'); var dateAgoToken = /ago$/; var dateAgoDelimeterToken = /[ .]+/; var daysUnitToken = /(days?|d)/; var weeksUnitToken = /(weeks?|w)/; var monthsUnitToken = /(months?|m)/; var yearsUnitToken = /(years?|y)/; var parseDateOption = function(dateStr, today) { today = today || new Date(); if (dateAgoToken.test(dateStr)) { var dateArray = dateStr.split(dateAgoDelimeterToken); var numericValue = parseFloat(dateArray[0]); var unit = dateArray[1]; if (daysUnitToken.test(unit)) { return subDays(today, numericValue); } else if (weeksUnitToken.test(unit)) { return subDays(today, numericValue * 7); } else if (monthsUnitToken.test(unit)) { return subMonths(today, numericValue); } else if (yearsUnitToken.test(unit)) { return subMonths(today, numericValue * 12); } else { return parseDate(dateStr); } } else { return parseDate(dateStr); } }; var isReviewedRecently = function(todo, options) { if (!todo.isReviewed) { return false; } var today = new Date(); var sinceDate = options.since ? parseDateOption(options.since, today) : subDays(today, options.days || 14); var untilDate = options.until ? parseDateOption(options.until, today) : today; return isWithinRange(todo.reviewedAt, sinceDate, untilDate); }; module.exports = isReviewedRecently;
Markdown
UTF-8
2,527
2.90625
3
[]
no_license
# Article P 17 § 1er. - Lors des conférences faites accessoirement dans les salles de réunion, les sièges doivent être reliés entre eux par rangées au moyen d'un système d'attache rigide. Chaque rangée doit, en outre, être fixée solidement à ses deux extrémités au sol ou aux parois, soit rendue solidaire d'une ou plusieurs autres rangées de manière à constituer un bloc difficile à renverser ou à déplacer. Dans ce cas, les tringles de fixation perpendiculaires aux rangées doivent être appliquées au niveau du sol et ne pas avoir plus de 0,20 mètre d'épaisseur avec profil arrondi, pour empêcher toute chute de spectateurs. § 2. - Toutes les places doivent être desservies par des dégagements perpendiculaires ou parallèles aux rangées de sièges ayant au moins une unité de passage. Cette largeur doit aller en augmentant vers la sortie à raison d'une unité de passage par 100 personnes ou fraction de 100 personnes susceptibles de les utiliser. Le nombre et la disposition de ces dégagements sont conditionnés par la nécessité d'assurer une prompte évacuation des auditeurs. Ils doivent être établis de manière que, pour atteindre un dégagement, chaque personne ne soit pas obligée de passer devant un nombre de sièges supérieur à 7 (donnant ainsi des rangées de 16 sièges au maximum entre deux dégagements). § 3. - Les rangées de sièges doivent être disposées de façon à laisser entre elles un espace libre suffisant. Dans tous les cas, cet espace doit permettre le passage facile d'un gabarit de 0,35 mètre de front affectant la forme d'un parallélépipède rectangle ayant comme autres dimensions 0,20 mètre d'épaisseur et, approximativement, 1,20 mètre de hauteur. Si les sièges se relèvent automatiquement, leur fonctionnement doit toujours être assuré. L'essai du gabarit doit être fait soit entre rangées de sièges relevés, si les dossiers sont fixes, soit entre une rangée de sièges relevés et une rangée de dossiers inclinés dans leur position d'occupation, si ces derniers sont mobiles. § 4. - Les sièges situés en bordure des dégagements doivent être alignés le long de ces derniers ou tout au moins ne pas former de redans susceptibles d'accrocher les auditeurs se dirigeant vers les sorties. Cette disposition ne s'oppose pas à l'installation de sièges en quinconce. § 5. - Aucune barre ou obstacle quelconque ne doit être placé dans les rangs des sièges ni dans les passages de circulation desservant des rangs.
C
UTF-8
4,894
2.609375
3
[]
no_license
/* ============================================================== Name : sensor.c Copyright : Copyright (C) 早稲田大学マイクロマウスクラブ Description : センサ関連の関数たちです. 更新履歴 2016/1/29 山上 コメント追加、get_wall_info関数内の始めの pins_write関数の第3引数を6からLED_NUMに変更 2016/2/24 山上 2016年度用にピン設定を変更 ============================================================== */ /*ヘッダファイルの読み込み*/ #include "global.h" //+++++++++++++++++++++++++++++++++++++++++++++++ //get_base // 制御用の基準値を取得する // 引数:なし // 戻り値:理想的な値を取得できたか 1:できた 0:できなかった //+++++++++++++++++++++++++++++++++++++++++++++++ unsigned char get_base() { unsigned char res = 0; //理想的な値を取得できたか ms_wait(10); //----制御用の基準を取得---- // base_l = ad_l - WALL_OFFSET; //現在の左側のセンサ値で決定 // base_r = ad_r - WALL_OFFSET; //現在の右側のセンサ値で決定 //----基準が理想的だとLED点滅---- if((-50 < (int)(base_l - base_r)) && ((int)(base_l - base_r) < 50)){ //左右で差が50以下である場合 pin_write(DISP_LEDS[0], 0x0); //0番目のLEDを消灯 pins_write(DISP_LEDS, 0x0f, LED_NUM); //LEDを全点灯 pins_write(DISP_LEDS, 0x00, LED_NUM); //LEDを全消灯 res = 1; //resを1に }else{ } uart_printf("base:%d, %d\r\n", base_r, base_l); return res; //理想的な値を取得できたかを返す } //+++++++++++++++++++++++++++++++++++++++++++++++ //get_wall_info // 壁情報取得を取得する // 引数:なし // 戻り値:なし //+++++++++++++++++++++++++++++++++++++++++++++++ void get_wall_info() { unsigned char tmp = 0; //点灯させるLEDの場所 //----壁情報の初期化---- wall_info = 0x00; //壁情報を初期化 pins_write(DISP_LEDS, 0, LED_NUM); //LEDを全消灯 //----前壁を見る---- if(wall_ff.dif > wall_ff.threshold){ //AD値が閾値より大きい(=壁があって光が跳ね返ってきている)場合 wall_info |= 0x88; //壁情報を更新 tmp = 0x06; //1番目と2番目のLEDを点灯させるよう設定 } //----右壁を見る---- if(wall_r.dif > wall_r.threshold){ //AD値が閾値より大きい(=壁があって光が跳ね返ってきている)場合 wall_info |= 0x44; //壁情報を更新 tmp |= 0x01; //0番目のLEDを点灯させるよう設定 } //----左壁を見る---- if(wall_l.dif > wall_l.threshold){ //AD値が閾値より大きい(=壁があって光が跳ね返ってきている)場合 wall_info |= 0x11; //壁情報を更新 tmp |= 0x08; //3番目のLEDを点灯させるよう設定 } pins_write(DISP_LEDS, tmp, LED_NUM); //LEDを点灯させる } void enc_test(){ reset_distance(); time = 0; R_PG_Timer_StartCount_MTU_U0_C1(); R_PG_Timer_StartCount_MTU_U0_C2(); R_PG_Timer_StartCount_CMT_U1_C2(); while(1){ /* totalR_mm += -DIA_WHEEL_mm * (DIA_PINI_mm / DIA_SQUR_mm) * 2 * Pi * (dif_pulse_r % 4096) / 4096; totalL_mm += -DIA_WHEEL_mm * (DIA_PINI_mm / DIA_SQUR_mm) * 2 * Pi * (dif_pulse_l % 4096) / 4096; */ uart_printf("R_distance:%4lf L_distance:%4lf\r\n",encoder_r.distance, encoder_l.distance); ms_wait(500); } } void sensor_start(){ R_PG_Timer_StartCount_MTU_U0_C1(); //エンコーダ左右 R_PG_Timer_StartCount_MTU_U0_C2(); R_PG_Timer_StartCount_CMT_U0_C1(); //壁センサ用LED起動タイマ R_PG_Timer_StartCount_CMT_U1_C2(); //エンコーダ処理,PID計算用タイマ } void sensor_stop(){ R_PG_Timer_HaltCount_MTU_U0_C1(); R_PG_Timer_HaltCount_MTU_U0_C2(); R_PG_Timer_HaltCount_CMT_U0_C1(); R_PG_Timer_HaltCount_CMT_U1_C2(); pin_write(PE0,0); pin_write(PE1,0); pin_write(PE2,0); pin_write(PE3,0); pin_write(PE4,0); melody(c6,1000); } void sensor_check(){ MF.FLAG.CTRL = 1; R_PG_Timer_StartCount_CMT_U0_C1(); get_base(); while(1){ pins_write(DISP_LEDS, 0, LED_NUM); //pins_write()はport.cに関数定義あり uart_printf("ad_l: %4d ad_fl:%4d ad_ff:%4d ad_fr:%4d ad_r:%4d \r\n", wall_l.dif, wall_fl.dif, wall_ff.dif, wall_fr.dif, wall_r.dif); //uart_printf(" | dif_l: %4d dif_r:%4d\r\n", wall_r., dif_r); //----LEDが4つの場合---- if(wall_fr.dif > wall_fr.threshold){ // ここ、ad_lになってましたよ!! pin_write(DISP_LEDS[0], ON); //pin_write()はport.cに関数定義あり } if(wall_r.dif > wall_r.threshold){ pin_write(DISP_LEDS[1], ON); } if(wall_l.dif > wall_l.threshold){ pin_write(DISP_LEDS[2], ON); } if(wall_fl.dif > wall_fl.threshold){ pin_write(DISP_LEDS[3], ON); } ms_wait(1000); } MF.FLAG.CTRL = 0; }
C
UTF-8
6,615
2.75
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/time.h> #define num_mem_block 1000 #define mem_block_size 1048576 #define NUM_THREADS 1 int z=0,y=0; struct mem { long t; }; struct arr { long f1,f2; }; struct arr ar1[10],ar2[10]; void func(char** m) //int mem_block_size { //char** m = mg; struct timeval start,end; int i; char* temp; gettimeofday(&start, 0x0); for(i = 0;i < num_mem_block;i++) { temp = strchr(m[i], '1'); } for(i = 0;i < num_mem_block;i++) { memset(m[i], '0', mem_block_size); } gettimeofday(&end,NULL); /*printf("in func \n start time %ld msec\n",start.tv_sec*1000000+start.tv_usec); printf("end time %ld msec\n",end.tv_sec*1000000+end.tv_usec); */ long diff = (end.tv_sec-start.tv_sec)*1000000 + (end.tv_usec-start.tv_usec); printf("diff in msec %ld\n",diff); double f1=(double)mem_block_size*(double)num_mem_block; double f2=(double)diff/1000000.00; double f3=f1/f2; //f3=f3/1000000.00; ar1[z].f1=(start.tv_sec)*1000000 + start.tv_usec; ar1[z].f2=(end.tv_sec)*1000000 + end.tv_usec; z++; pthread_exit(NULL); } void randfunc(char** m) //int mem_block_size { //char** m = mg; struct timeval start,end; long i, *ran; char* temp; time_t t; srand((unsigned)time(&t)); ran = (long*)malloc(sizeof(long) * num_mem_block); for(i = 0;i < num_mem_block;i++) { ran[i] = rand() % num_mem_block; } gettimeofday(&start, 0x0); for(i = 0;i < num_mem_block;i++) { temp = strchr(m[ran[i]], '1'); } for(i = 0;i < num_mem_block;i++) { memset(m[ran[i]], '0', mem_block_size); } gettimeofday(&end,NULL); /*printf("in func \n start time %ld msec\n",start.tv_sec*1000000+start.tv_usec); printf("end time %ld msec\n",end.tv_sec*1000000+end.tv_usec); */ long diff = (end.tv_sec-start.tv_sec)*1000000 + (end.tv_usec-start.tv_usec); printf("diff in msec %ld\n",diff); double f1=(double)mem_block_size*(double)num_mem_block; double f2=(double)diff/1000000.00; double f3=f1/f2; //f3=f3/1000000.00; ar2[y].f1=(start.tv_sec)*1000000 + start.tv_usec; ar2[y].f2=(end.tv_sec)*1000000 + end.tv_usec; y++; pthread_exit(NULL); } void* mem_test(void* arg) { struct mem mem_para = *((struct mem*)arg); long id = mem_para.t; //long num_mem_block = mem_para.num_mem_block; //long mem_block_size = mem_para.mem_block_size; char** mem_char; mem_char = (char**)malloc(sizeof(char*) * num_mem_block); long i; for(i = 0;i < num_mem_block;i++) { mem_char[i] = (char*)malloc(mem_block_size); } for(i = 0;i < num_mem_block;i++) { memset(mem_char[i], '0', mem_block_size - 1); mem_char[i][mem_block_size - 1] = '1'; } func(mem_char); for(i = 0;i < num_mem_block;i++) { free(mem_char[i]); } free(mem_char); return NULL; } void* mem_test1(void* arg) { struct mem mem_para = *((struct mem*)arg); long id = mem_para.t; //long num_mem_block = mem_para.num_mem_block; //long mem_block_size = mem_para.mem_block_size; char** mem_char; mem_char = (char**)malloc(sizeof(char*) * num_mem_block); long i; for(i = 0;i < num_mem_block;i++) { mem_char[i] = (char*)malloc(mem_block_size); } for(i = 0;i < num_mem_block;i++) { memset(mem_char[i], '0', mem_block_size - 1); mem_char[i][mem_block_size - 1] = '1'; } randfunc(mem_char); for(i = 0;i < num_mem_block;i++) { free(mem_char[i]); } free(mem_char); return NULL; } void main() { int j=0; int i=0; struct timeval start,end,start1,end1; int c; pthread_t threads[NUM_THREADS]; int rc; void *status; long t; gettimeofday(&start,NULL); for(t=0; t<NUM_THREADS; t++) { struct mem *m1=(struct mem *)malloc(sizeof(struct mem *)); m1->t=t; //strncpy(m1->mem_char,mem,mem_block_size); printf("In main: creating thread %ld\n", t); rc = pthread_create(&threads[t], NULL,mem_test, (void *)m1); if (rc) { printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } for(t=0;t<NUM_THREADS;t++) { pthread_join(threads[t],&status); } gettimeofday(&end, NULL); /* printf("in main\n start time %ld\n",start.tv_sec*1000000+start.tv_usec); printf("end time %ld\n",end.tv_sec*1000000+end.tv_usec); long diff = (end.tv_sec-start.tv_sec)*1000000 + (end.tv_usec-start.tv_usec); double d=(double)diff/1000000.0; printf("diff in micro sec %lf\n",d); double f1=(((double)mem_block_size*(double)num_mem_block)/NUM_THREADS)/(double)d; printf(" \n the thoughput %lf\n",f1); */ /* for(i=0;i<NUM_THREADS;i++) { printf("the first loop flops is %ld\n",ar1[i].f1); printf("the second loop flops is %ld\n",ar1[i].f2); }*/ long s1,e1; s1=ar1[0].f1; e1=ar1[0].f2; for(j=1;j<NUM_THREADS;j++) { if(ar1[j].f1<s1) s1=ar1[j].f1; if(ar1[j].f2>e1) e1=ar1[j].f2; } printf("in loops\n"); printf("lowest startime is %ld msec\n",s1); printf("highest endtime is %ld msec\n",e1); double d1=((double)(e1-s1))/1000000.0; printf("%ld\n",e1-s1); printf("time difference in sec %lf\n",d1); double f2=(((double)mem_block_size*(double)num_mem_block/(double)NUM_THREADS))/(double)d1; f2=f2/1000000.0; printf(" the thoughput %lf\n",f2); printf(" \n\n\n random calculation\n\n\n"); gettimeofday(&start1,NULL); for(t=0; t<NUM_THREADS; t++) { struct mem *m1=(struct mem *)malloc(sizeof(struct mem *)); m1->t=t; //strncpy(m1->mem_char,mem,mem_block_size); printf("In main: creating thread %ld\n", t); rc = pthread_create(&threads[t], NULL,mem_test1, (void *)m1); if (rc) { printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } for(t=0;t<NUM_THREADS;t++) { pthread_join(threads[t],&status); } gettimeofday(&end1, NULL); //printf("in main\n start time %ld\n",start1.tv_sec*1000000+start1.tv_usec); //printf("end time %ld\n",end1.tv_sec*1000000+end1.tv_usec); /*long diff3 = (end1.tv_sec-start1.tv_sec)*1000000 + (end1.tv_usec-start1.tv_usec); double d3=(double)diff3/1000000.0; printf("diff in micro sec %lf\n",d3); double f3=(((double)mem_block_size*(double)num_mem_block)/NUM_THREADS)/(double)d3; printf(" \n the thoughput %lf\n",f3); */ /* for(i=0;i<NUM_THREADS;i++) { printf("the first loop flops is %ld\n",ar1[i].f1); printf("the second loop flops is %ld\n",ar1[i].f2); }*/ long s,e; s=ar2[0].f1; e=ar2[0].f2; for(j=1;j<NUM_THREADS;j++) { if(ar2[j].f1<s) s=ar2[j].f1; if(ar2[j].f2>e) e=ar2[j].f2; } printf("in loops\n"); printf("lowest startime is %ld msec\n",s); printf("highest endtime is %ld msec\n",e); double d4=((double)(e-s))/1000000.0; printf("%ld\n",e-s); printf("time difference in sec %lf\n",d4); double f4=(((double)mem_block_size*(double)num_mem_block/(double)NUM_THREADS))/(double)d4; f4=f4/1000000.0; printf(" the thoughput %lf\n",f4); pthread_exit(NULL); }
Java
UTF-8
1,263
2.1875
2
[ "Apache-2.0" ]
permissive
/* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ing.data.cassandra.jdbc; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.UUID; /** * JDBC description of {@code TIMEUUID} CQL type (corresponding Java type: {@link UUID}). * <p>CQL type description: version 1 UUID only.</p> */ public class JdbcTimeUUID extends AbstractJdbcUUID { /** * Gets a {@code JdbcTimeUUID} instance. */ public static final JdbcTimeUUID instance = new JdbcTimeUUID(); JdbcTimeUUID() { } public UUID compose(@NonNull final Object obj) { return UUID.fromString(obj.toString()); } public Object decompose(@NonNull final UUID value) { return value.toString(); } }