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
Shell
UTF-8
9,466
3.203125
3
[]
no_license
#!/bin/bash -l #------------------------------------------------------------------------------- wkdir="$(cd "$( dirname "$0" )" && pwd)" cd ${wkdir} myname=$(basename "$0") myname1=${myname%.*} . admin.rc || exit $? #------------------------------------------------------------------------------- function unlock () { if (($(cat $lockfile) == $$)); then rm -f $lockfile fi } trap unlock EXIT #------------------------------------------------------------------------------- download_parse_conf () { mkdir -p $outdir/exp rsync -aLvz --remove-source-files ${r_url}:${r_rundir}/exp/ $outdir/exp # parse ... } download () { istime="$TIME" istimef="$(date -ud "$istime" +'%Y%m%d%H%M%S')" iatime="$(date -ud "$LCYCLE second $istime" +'%Y-%m-%d %H:%M:%S')" iatimef="$(date -ud "$iatime" +'%Y%m%d%H%M%S')" while ((istimef <= ETIMEf)); do ssh ${r_url} "cd ${r_outdir}/${istimef}/log && tar --remove-files -czf scale_init.tar.gz scale_init" ssh ${r_url} "cd ${r_outdir}/${istimef}/log && tar --remove-files -czf scale.tar.gz scale" ssh ${r_url} "cd ${r_outdir}/${iatimef}/log && tar --remove-files -czf obsope.tar.gz obsope" ssh ${r_url} "cd ${r_outdir}/${iatimef}/log && tar --remove-files -czf letkf.tar.gz letkf" ssh ${r_url} "cd ${r_outdir}/${iatimef} && tar --remove-files -czf obsgues.tar.gz obsgues" mkdir -p $outdir/${istimef}/hist rsync -av --remove-source-files ${r_url}:${r_outdir}/${istimef}/hist/meanf/ $outdir/${istimef}/hist/meanf rsync -av --remove-source-files ${r_url}:${r_outdir}/${istimef}/hist/[0-9]* $outdir/${istimef}/hist mkdir -p $outdir/${iatimef}/gues rsync -av --remove-source-files ${r_url}:${r_outdir}/${iatimef}/gues/mean/ $outdir/${iatimef}/gues/mean rsync -av --remove-source-files ${r_url}:${r_outdir}/${iatimef}/gues/meanf/ $outdir/${iatimef}/gues/meanf rsync -av --remove-source-files ${r_url}:${r_outdir}/${iatimef}/gues/sprd/ $outdir/${iatimef}/gues/sprd rsync -av --remove-source-files ${r_url}:${r_outdir}/${iatimef}/gues/[0-9]* $outdir/${iatimef}/gues mkdir -p $outdir/${iatimef}/anal rsync -av ${r_url}:${r_outdir}/${iatimef}/anal/mean/ $outdir/${iatimef}/anal/mean rsync -av --remove-source-files ${r_url}:${r_outdir}/${iatimef}/anal/sprd/ $outdir/${iatimef}/anal/sprd # if (($(date -ud "${iatime}" +'%k') == 0)); then ## if (($(date -ud "${iatime}" +'%j') % 5 == 1 && $(date -ud "${iatime}" +'%k') == 0)); then rsync -av ${r_url}:${r_outdir}/${iatimef}/anal/[0-9]* $outdir/${iatimef}/anal # fi mkdir -p $outdir/${istimef}/log rsync -av --remove-source-files ${r_url}:${r_outdir}/${istimef}/log/scale_init.tar.gz $outdir/${istimef}/log rsync -av --remove-source-files ${r_url}:${r_outdir}/${istimef}/log/scale.tar.gz $outdir/${istimef}/log mkdir -p $outdir/${iatimef}/log rsync -av --remove-source-files ${r_url}:${r_outdir}/${iatimef}/log/obsope.tar.gz $outdir/${iatimef}/log rsync -av --remove-source-files ${r_url}:${r_outdir}/${iatimef}/log/letkf.tar.gz $outdir/${iatimef}/log rsync -av --remove-source-files ${r_url}:${r_outdir}/${iatimef}/obsgues.tar.gz $outdir/${iatimef} mkdir -p $outdir/${istimef}/anal/mean rsync -av --remove-source-files ${r_url}:${r_outdir}/${istimef}/anal/mean/init_ocean.pe*.nc $outdir/${istimef}/anal/mean ssh ${r_url} "rm -r ${r_outdir}/${istimef}/anal/[0-9]*" if (($(date -ud "${FCST_TIME}" +'%Y%m%d%H%M%S') >= istimef)); then ssh ${r_url} "rm -r ${r_outdir}/${istimef}/anal/mean" fi ssh ${r_url} "find ${r_outdir}/${istimef} -depth -type d -empty -exec rmdir {} \;" ssh ${r_url} "find ${r_outdir}/${iatimef} -depth -type d -empty -exec rmdir {} \;" ssh ${r_url} "rm -r ${r_wrfdir_da}/${istimef}" ssh ${r_url} "rm ${r_obsdir}/obs_${iatimef}.dat" istime="$(date -ud "$LCYCLE second $istime" +'%Y-%m-%d %H:%M:%S')" istimef="$(date -ud "$istime" +'%Y%m%d%H%M%S')" iatime="$(date -ud "$LCYCLE second $istime" +'%Y-%m-%d %H:%M:%S')" iatimef="$(date -ud "$iatime" +'%Y%m%d%H%M%S')" done now="$(date -u +'%Y-%m-%d %H:%M:%S')" echo "$now [DONE] $TIMEPRINT - Download and remove remote files (background job completed)" >> $logfile } #------------------------------------------------------------------------------- now="$(date -u +'%Y-%m-%d %H:%M:%S')" if [ ! -s "$timefile" ]; then echo "$now [ERR ] Cannot find previous model time." >> $logfile exit fi if [ -e "$lockfile" ]; then echo "$now [PREV]" >> $logfile exit else echo $$ >> $lockfile fi PREVIOUS_TIME="$(cat $timefile)" TIME="$(date -ud "${PREVIOUS_TIME}" +'%Y-%m-%d %H:%M:%S')" TIMEf="$(date -ud "$TIME" +'%Y%m%d%H%M%S')" ATIME="$(date -ud "$LCYCLE second $TIME" +'%Y-%m-%d %H:%M:%S')" ATIMEf="$(date -ud "$ATIME" +'%Y%m%d%H%M%S')" if [ -s "$wkdir/admin_fcst.time" ]; then FCST_TIME="$(cat "$wkdir/admin_fcst.time")" fi TIMEstop="$(date -ud "$((LCYCLE * (MAX_CYCLE-1))) second $TIME" +'%Y-%m-%d %H:%M:%S')" if [ -s "$timestopfile" ]; then TIMEstoptmp="$(cat $timestopfile)" if (($(date -ud "$TIMEstoptmp" +'%s') < $(date -ud "$TIMEstop" +'%s'))); then TIMEstop="$TIMEstoptmp" fi fi if (($(date -ud "$TIME" +'%s') > $(date -ud "$TIMEstop" +'%s'))); then now="$(date -u +'%Y-%m-%d %H:%M:%S')" echo "$now [STOP] $ATIMEf" >> $logfile exit fi #------------------------------------------------------------------------------- now="$(date -u +'%Y-%m-%d %H:%M:%S')" echo "$now [TRY ] $ATIMEf" >> $logfile n=0 istime="$TIME" istimef="$(date -ud "$istime" +'%Y%m%d%H%M%S')" iatime="$(date -ud "$LCYCLE second $istime" +'%Y-%m-%d %H:%M:%S')" iatimef="$(date -ud "$iatime" +'%Y%m%d%H%M%S')" while ((istimef <= $(date -ud "$TIMEstop" +'%Y%m%d%H%M%S') || n == 0)); do if [ ! -s "$wrfdir/$(date -ud "$istime" +'%Y%m%d%H')/mean/wrfout_${istimef}" ] || [ ! -s "$wrfdir/$(date -ud "$iatime" +'%Y%m%d%H')/mean/wrfout_${iatimef}" ] || [ ! -s "$wrfdir/$(date -ud "$iatime" +'%Y%m%d%H')/mean/wrfout_$(date -ud "$LCYCLE second $iatime" +'%Y%m%d%H%M%S')" ]; then if ((n == 0)); then echo "$now [WAIT] $iatimef - Model files are not ready." >> $logfile exit else break fi fi if [ ! -s "$obsdir/$(date -ud "$iatime" +'%Y%m%d%H')/obs_${iatimef}.dat" ]; then if ((n == 0)); then echo "$now [WAIT] $iatimef - Observation files are not ready." >> $logfile exit else break fi fi n=$((n+1)) istime="$(date -ud "$LCYCLE second $istime" +'%Y-%m-%d %H:%M:%S')" istimef="$(date -ud "$istime" +'%Y%m%d%H%M%S')" iatime="$(date -ud "$LCYCLE second $istime" +'%Y-%m-%d %H:%M:%S')" iatimef="$(date -ud "$iatime" +'%Y%m%d%H%M%S')" done ETIME="$(date -ud "- $LCYCLE second $istime" +'%Y-%m-%d %H:%M:%S')" ETIMEf="$(date -ud "$ETIME" +'%Y%m%d%H%M%S')" EATIME="$(date -ud "$LCYCLE second $ETIME" +'%Y-%m-%d %H:%M:%S')" EATIMEf="$(date -ud "$EATIME" +'%Y%m%d%H%M%S')" NCYCLE=$n if [ "$TIMEf" = "$ETIMEf" ]; then TIMEPRINT="$ATIMEf" else TIMEPRINT="${ATIMEf}-${EATIMEf}" fi #------------------------------------------------------------------------------- rm -f $outfile now="$(date -u +'%Y-%m-%d %H:%M:%S')" echo "$now [TRAN] $TIMEPRINT - Upload files" >> $logfile istime="$TIME" istimef="$(date -ud "$istime" +'%Y%m%d%H%M%S')" iatime="$(date -ud "$LCYCLE second $istime" +'%Y-%m-%d %H:%M:%S')" iatimef="$(date -ud "$iatime" +'%Y%m%d%H%M%S')" while ((istimef <= ETIMEf)); do mkdir -p $tmpdir/${istimef}/mean rm -fr $tmpdir/${istimef}/mean/* ln -s $wrfdir/$(date -ud "$istime" +'%Y%m%d%H')/mean/wrfout_${istimef} $tmpdir/${istimef}/mean ln -s $wrfdir/$(date -ud "$iatime" +'%Y%m%d%H')/mean/wrfout_${iatimef} $tmpdir/${istimef}/mean ln -s $wrfdir/$(date -ud "$iatime" +'%Y%m%d%H')/mean/wrfout_$(date -ud "$LCYCLE second $iatime" +'%Y%m%d%H%M%S') $tmpdir/${istimef}/mean rsync -avL $tmpdir/${istimef} ${r_url}:${r_wrfdir_da} >> $outfile rsync -av $obsdir/$(date -ud "$iatime" +'%Y%m%d%H')/obs_${iatimef}.dat ${r_url}:${r_obsdir}/obs_${iatimef}.dat >> $outfile rm -fr $tmpdir/${istimef}/mean/* rmdir $tmpdir/${istimef}/mean rmdir $tmpdir/${istimef} istime="$(date -ud "$LCYCLE second $istime" +'%Y-%m-%d %H:%M:%S')" istimef="$(date -ud "$istime" +'%Y%m%d%H%M%S')" iatime="$(date -ud "$LCYCLE second $istime" +'%Y-%m-%d %H:%M:%S')" iatimef="$(date -ud "$iatime" +'%Y%m%d%H%M%S')" done success=0 ntry=0 while ((success == 0)) && ((ntry < MAX_TRY)); do ntry=$((ntry+1)) total_sec=$(date -ud "1970-01-01 ${WTIME_L[$ntry]}" +'%s') WTIME_L_use=$(date -ud "$((total_sec * NCYCLE)) second 1970-01-01 00:00:00" +'%H:%M:%S') now="$(date -u +'%Y-%m-%d %H:%M:%S')" echo "$now [RUN ] $TIMEPRINT/$ntry" >> $logfile ssh ${r_url} "cd ${r_rundir} && ./admin.sh cycle ${TIMEf} ${ETIMEf} ${TIME_DT[$ntry]} ${TIME_DT_DYN[$ntry]} ${NNODES[$ntry]} $WTIME_L_use" res=$? if ((res == 0)); then success=1 else now="$(date -u +'%Y-%m-%d %H:%M:%S')" echo "$now [ERR ] $TIMEPRINT/$ntry - Exit code: $res" >> $logfile if ((res >= 100 && res <= 110)); then download_parse_conf fi sleep 10s fi done if ((success == 1)); then now="$(date -u +'%Y-%m-%d %H:%M:%S')" echo "$now [TRAN] $TIMEPRINT - Download and remove remote files (background job)" >> $logfile download_parse_conf download >> $outfile 2>&1 & now="$(date -u +'%Y-%m-%d %H:%M:%S')" echo "$now [DONE] $TIMEPRINT" >> $logfile echo "$EATIME" > $timefile else echo "$now [FAIL] $TIMEPRINT - All trials failed" >> $logfile fi
C#
UTF-8
3,129
2.59375
3
[]
no_license
using System.Collections.Generic; using System.Linq; using Teashop.Backend.Application.Commons.Models; using Teashop.Backend.Domain.Product.Entities; using Teashop.Backend.UI.Api.Product.Models; namespace Teashop.Backend.UI.Api.Product.Mappings { public class ProductMapper { public PresentationalProduct MapToPresentational(ProductEntity product) { return new PresentationalProduct { Id = product.ProductId, ProductNumber = product.ProductNumber, Name = product.Name, Price = product.Price, QuantityPerPrice = product.QuantityPerPrice, ImagePath = product.ImagePath, Description = product.Description, BrewingInfo = MapToPresentational(product.BrewingInfo), Categories = product.ProductCategories .Select(pc => pc.Category.Name) .ToArray() }; } public ProductEntity MapFromPresentational(PresentationalProduct presentationalProduct) { return new ProductEntity { ProductId = presentationalProduct.Id, Name = presentationalProduct.Name, Price = presentationalProduct.Price, QuantityPerPrice = presentationalProduct.QuantityPerPrice }; } public PresentationalBrewingInfo MapToPresentational(BrewingInfo brewingInfo) { if (brewingInfo == null) return null; return new PresentationalBrewingInfo { WeightInfo = brewingInfo.WeightInfo, TemperatureInfo = brewingInfo.TemperatureInfo, TimeInfo = brewingInfo.TimeInfo, NumberOfBrewingsInfo = brewingInfo.NumberOfBrewingsInfo }; } public GetProductsBySpecificationPaginatedResponse MapToGetProductsBySpecificationResponse(PaginatedList<ProductEntity> result) { return new GetProductsBySpecificationPaginatedResponse { PageIndex = result.PageIndex, PageSize = result.PageSize, PagesInTotal = result.PagesInTotal, TotalCount = result.TotalCount, Products = MapToMultipleMinimized(result.Items) }; } public List<MinimizedPresentationalProduct> MapToMultipleMinimized(List<ProductEntity> products) { return products .Select(product => MapToMinimized(product)) .ToList(); } public MinimizedPresentationalProduct MapToMinimized(ProductEntity product) { return new MinimizedPresentationalProduct { Id = product.ProductId, ProductNumber = product.ProductNumber, Name = product.Name, Price = product.Price, QuantityPerPrice = product.QuantityPerPrice, ImagePath = product.ImagePath, }; } } }
JavaScript
UTF-8
426
2.84375
3
[]
no_license
import { DateTime } from 'luxon'; // Returns a formatted date based on time information and a format specifier const formatDate = (timestamp, timezone, format) => { const date = DateTime.fromSeconds(timestamp).setZone(timezone); if (format in date) { return date[format]; } // if not found in date instance use format from DateTime return date.toLocaleString(DateTime[format]); }; export default formatDate;
C++
UTF-8
280
3.28125
3
[]
no_license
#include "iostream.h" class A { int *p; public: A() { p = new int; } int *G() { return p; } void F(A &); ~A() { cout << "Destruyendo...\n"; delete p; } }; void A::F(A &c) { (*c.p)++; } main() { A b; int *q = b.G(); *q = 10; b.F(b); cout << *b.G() << endl; }
Python
UTF-8
3,096
2.734375
3
[]
no_license
# -*- coding: utf-8 -*- import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier import matplotlib.pyplot as plt import seaborn as sns #% matplotlib inline mydataset=pd.read_csv("city_hour.csv") mydataset.interpolate(limit_direction="both",inplace=True) mydataset['BTX']=mydataset['Benzene']+mydataset['Toluene']+mydataset['Xylene'] mydataset['Nitrogen_compounds']=mydataset['NO']+mydataset['NO2']+mydataset['NOx']+mydataset['NH3'] #print(mydataset.head(4)) mydataset.drop(['Benzene','Toluene','Xylene','Datetime'],axis=1,inplace=True) mydataset.drop(['NO','NOx','NO2','NH3'],axis=1,inplace=True) #print(mydataset.head(1)) mydataset.set_index('City',inplace=True) cities_undertaken=['Delhi'] df=mydataset[['AQI','AQI_Bucket']] mydataset.drop(['AQI','AQI_Bucket'],axis=1,inplace=True) mydataset['AQI']=df['AQI'] #mydataset['AQI_Bucket']=df['AQI_Bucket'] dataset_UP=mydataset.loc[cities_undertaken] # Adding extra col to divide as classes column_name='AQI' conditions=[dataset_UP[column_name]>400,(dataset_UP[column_name]<400) & (dataset_UP[column_name]>300), (dataset_UP[column_name]<300) &(dataset_UP[column_name]>200), (dataset_UP[column_name]<200)&(dataset_UP[column_name]>100), (dataset_UP[column_name]<100)&(dataset_UP[column_name]>50),(dataset_UP[column_name]<50)] classes=["severe","verypoor","poor","moderate","satisfactory","good"] dataset_UP["classes_col"]=np.select(conditions,classes,default="moderate") #sns.pairplot(dataset_UP,hue="AQI") print(dataset_UP.columns) X=dataset_UP.iloc[:,:-2] Y=dataset_UP.iloc[:,8] scaler=StandardScaler() scaler.fit(X) scaled_features=scaler.transform(X) scaled_X=pd.DataFrame(scaled_features,columns=X.columns) print(Y.head()) # Splitting into training and test dataset X_train,X_test,Y_train,Y_test=train_test_split(scaled_X,Y,test_size=0.2,random_state=10) #Splitting into validation dataset #X_train,X_val,Y_train,Y_val=train_test_split(X_train,Y_train,test_size=0.25,random_state=10) #print(dataset_UP.shape,X_train.shape,X_val.shape,X_test.shape) #knn algo knn=KNeighborsClassifier(n_neighbors=1) knn.fit(X_train,Y_train) prediction=knn.predict(X_test) from sklearn.metrics import classification_report,confusion_matrix print(confusion_matrix(Y_test,prediction)) print(classification_report(Y_test,prediction)) error_rate=[] for i in range(1,21): knn=KNeighborsClassifier(n_neighbors=i) knn.fit(X_train,Y_train) prediction_i=knn.predict(X_test) error_rate.append(np.mean(prediction_i!=Y_test)) plt.figure(figsize=(10,10)) plt.plot(range(1,21),error_rate,color="blue",linestyle="dashed",marker="o",markerfacecolor="red",markersize=10) plt.title("Errorrate Vs K") plt.xlabel("K") plt.ylabel("Error_rate") knn=KNeighborsClassifier(n_neighbors=7) knn.fit(X_train,Y_train) prediction=knn.predict(X_test) print(confusion_matrix(Y_test,prediction)) print(classification_report(Y_test,prediction)) distance_metrics="euclideandistance"
Markdown
UTF-8
2,474
2.921875
3
[ "Apache-2.0" ]
permissive
# Proyecto Podcast [Proyecto Podcast](https://ezeholz.github.io/Acamica/primerProyecto/) busca acaparar los conocimientos que aprendimos en la primera parte del curso con respecto a la maquetación en HTML utilizando CSS, o en mi caso SCSS Fecha de inicio del trabajo: 07/11/19\ Fecha de entrega del trabajo: 19/12/19 ### To Do - [ ] Mejorar la presentación - [ ] Rehacer utilizando valores relativos - [ ] Rehacer haciendo uso de clases y SASS en la totalidad del proyecto - [ ] \(Posible) Rehacer cambiando la temática ## Infografía Para mi, en todo trabajo que se haga, es importante anotar infografía que haya servido para realizarlo.\ A modo de resúmen, sirve también para que a futuro se pueda consultar. ### Referencias * [MDN](https://developer.mozilla.org) * [W3Schools](https://www.w3schools.com) * [CodePen](https://codepen.io/) * [FontAwesome](https://fontawesome.com) * [Google Fonts](https://fonts.google.com/) * [CSS Tricks](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) ### Artículos * [Pure CSS checkbox toggle menu](https://stackoverflow.com/questions/23823514/pure-css-checkbox-toggle-menu) * [How do I create a parallelogram shape in CSS with a straight side](https://stackoverflow.com/questions/25993033/how-do-i-create-a-parallelogram-shape-in-css-with-a-straight-side) * [Superponiendo Divs mediante CSS](https://blog.evidaliahost.com/superponiendo-divs-mediante-css/) * [Check checkbox on click href and on click checkbox](https://stackoverflow.com/questions/38323752/check-checkbox-on-click-href-and-on-click-checkbox) * [Multiple two class selectors in SASS](https://stackoverflow.com/questions/18561547/multiple-two-class-selectors-in-sass) ## Licencia Este programa se hizo y se presentó a la tutoría de [Acámica](https://www.acamica.com), el fin de este proyecto fue demostrar el conocimiento aprendido en la carrera Fullstack que tuve el honor de cursar. >Copyright 2019 Ezequiel G. Holzweissig > >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.
Java
UTF-8
1,650
3.078125
3
[]
no_license
package buncoplus; import framework.*; /** * Instancie les joueurs et les dés pour BuncoPlus. */ public class FabriqueBuncoplus extends Fabrique { private final int NBRE_JOUEURS = 5; private final int NBRE_DES = 3; private static CollectionJoueurs collectionJoueurs; private static CollectionDes collectionDes; public FabriqueBuncoplus(Jeu jeu) { demarrerJeu(jeu); } @Override public CollectionJoueurs creerJoueurs() { Joueur[] listeJoueurs = new Joueur[NBRE_JOUEURS]; collectionJoueurs = new CollectionJoueurs(listeJoueurs); for(int i = 0; i < listeJoueurs.length; i++) { String playerNum = Integer.toString(i+1); //ex nom: player1, player2 collectionJoueurs.ajouterJoueur(new Joueur("PLAYER_"+playerNum), i); } return collectionJoueurs; } @Override public CollectionDes creerDes() { De[] listeDes = new De[NBRE_DES]; collectionDes = new CollectionDes(listeDes); for(int i = 0; i < listeDes.length; i++) { int deID = i+1; collectionDes.ajouterDe(new De(6, deID), i); } return collectionDes; } public int getNBRE_JOUEURS() { return NBRE_JOUEURS; } public int getNBRE_DES() { return NBRE_DES; } public static void setCollectionDes(CollectionDes collectionDes) { FabriqueBuncoplus.collectionDes = collectionDes; } public static CollectionJoueurs getCollectionJoueurs() { return collectionJoueurs; } public static CollectionDes getCollectionDes() { return collectionDes; } }
Markdown
UTF-8
966
2.53125
3
[]
no_license
## Месяца того же в 18-й, память святых мучеников Платона и Романа <*p. 97 / 296 / 295*> Поется все, как и на всякий день: стихиры же и канон. И читается тогда мучение святого Платона и похвала Златоуста о святом Романе. --- *Подобает знать*, что в 9-ю неделю Евангелий от Луки, когда читается Евангелие, начало: **Во оно время человеку богату етеру** <*Лк.12:16; зач. 66*>, читается с середины в ту неделю слово из обычных, святого Василия о том: **Разорю житниця моя**, начало: **Сугуб ведение напасти**. [← 17-е](11_17_AST.ru.md) | [Ноябрь](README.md#18-й) | [20-е →](11_20_AST.ru.md)
Java
UTF-8
3,245
2.0625
2
[]
no_license
package com.authright.happyPrime.config.appconfig; import com.authright.happyPrime.config.propertyconfig.RestTemplatePropConfig; import com.authright.happyPrime.handler.HttpClientResponseErrorHandler; import com.google.common.collect.Lists; import org.apache.http.client.HttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import org.springframework.http.client.BufferingClientHttpRequestFactory; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import java.util.List; @Configuration @EnableConfigurationProperties(RestTemplatePropConfig.class) @ComponentScan(value = "com.authright.happyPrime") public class RestTemplateConfig { @Autowired private RestTemplatePropConfig restTemplatePropConfig; @Bean("randomGeneratorRestTemplate") @Scope("prototype") public RestTemplate getRandomGeneratorRestTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new HttpClientResponseErrorHandler()); BufferingClientHttpRequestFactory bufferingClientHttpRequestFactory = new BufferingClientHttpRequestFactory(httpRequestFactory()); restTemplate.setRequestFactory(bufferingClientHttpRequestFactory); List<ClientHttpRequestInterceptor> interceptors = Lists.newArrayList(new LogRequestResponseFilter()); restTemplate.setInterceptors(interceptors); restTemplate.setInterceptors(interceptors); return restTemplate; } @Bean public ClientHttpRequestFactory httpRequestFactory() { HttpComponentsClientHttpRequestFactory httpClientRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient()); httpClientRequestFactory.setConnectTimeout(restTemplatePropConfig.getConnectTimeOut()); httpClientRequestFactory.setReadTimeout(restTemplatePropConfig.getReadTimeOut()); return httpClientRequestFactory; } @Bean public HttpClient httpClient() { final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(restTemplatePropConfig.getPool().getSize()); connectionManager.setDefaultMaxPerRoute(restTemplatePropConfig.getPool().getMaxPerRoute()); return HttpClientBuilder .create() .setConnectionManager(connectionManager) .build(); } @Autowired public void setRestTemplatePropConfig(RestTemplatePropConfig restTemplatePropConfig) { this.restTemplatePropConfig = restTemplatePropConfig; } }
PHP
UTF-8
680
2.875
3
[]
no_license
<?php namespace App\Services\ItemsFormatter; use App\Item; use Illuminate\Database\Eloquent\Collection; /** * Formats items of the menu. * * @package App\Services\ItemsFormatter */ interface ItemsFormatter { /** * Returns a nested array of items in the format specified by the task docs. * * @param Collection $items * @param int|null $parentId * @return array */ public function toNestedArray(Collection $items, ?int $parentId = null): array; /** * Formats an item and its children into a nested array. * * @param Item $item * @return array */ public function itemToNestedArray(Item $item): array; }
Markdown
UTF-8
1,807
2.671875
3
[ "CC0-1.0" ]
permissive
## Welcome to my learning notes pages. 各种markdown的笔记。 ### Vue学习笔记 - [Vue技术要点笔记-快速入门](vue/Vue技术要点笔记-快速入门.md) - [Vue技术要点笔记-组件](vue/Vue技术要点笔记-组件.md) ### Java学习笔记 - [69道Spring面试题和答案](java/69道Spring面试题和答案.md) - [Spring Bean生命周期图](java/Spring%20Bean生命周期.png) - [Spring AOP定义详解](java/Spring%20AOP定义详解.md) - [java/spring-@import和@bean应用详解](java/spring-@import和@bean应用详解.md) - [ImportBeanDefinitionRegistrar动态注册bean](java/ImportBeanDefinitionRegistrar动态注册bean.md) - [dobbo服务Reference的服务注册过程图](java/dobbo服务Reference的服务注册过程图.jpg) ### Mysql DB笔记 - [高性能MySQL笔记1](db/高性能MySQL笔记1.md) - [MySql常用30种SQL查询语句优化方法](db/MySql常用30种SQL查询语句优化方法.pdf) ### Markdown语法提示 Markdown is a lightweight and easy-to-use syntax for styling your writing. It includes conventions for ```markdown Syntax highlighted code block # Header 1 ## Header 2 ### Header 3 - Bulleted - List 1. Numbered 2. List **Bold** and _Italic_ and `Code` text [Link](url) and ![Image](src) ``` For more details see [GitHub Flavored Markdown](https://guides.github.com/features/mastering-markdown/). ### Jekyll Themes Your Pages site will use the layout and styles from the Jekyll theme you have selected in your [repository settings](https://github.com/Seanxq/mdnotes/settings). The name of this theme is saved in the Jekyll `_config.yml` configuration file. Whenever you commit to this repository, GitHub Pages will run [Jekyll](https://jekyllrb.com/) to rebuild the pages in your site, from the content in your Markdown files.
Java
UTF-8
8,457
2
2
[]
no_license
package controllers; import bussiness.licences.ILicencesService; import bussiness.user.IActivateUserService; import bussiness.user.ISaleDepartmentService; import bussiness.user.IUserInfoService; import bussiness.user.impl.UserInfoService; import com.google.gson.reflect.TypeToken; import models.iquantCommon.*; import play.Logger; import play.data.binding.As; import play.libs.F; import util.GsonUtil; import util.Page; import javax.inject.Inject; import java.lang.reflect.Type; import java.util.List; /** * User: 刘建力(liujianli@gtadata.com)) * Date: 13-6-28 * Time: 上午9:59 * 功能描述: 用户信息API */ public class UserInfoCt extends BaseController { @Inject static IUserInfoService userInfoService; @Inject static IActivateUserService activateUserService; @Inject static ISaleDepartmentService saleDepartmentService; @Inject static ILicencesService licencesService; /** * 根据账号查询用户信息 * @param account 账号 */ public static void fetchUserByAcccount(String account) { UserInfo userInfo = userInfoService.findByAccount(account); responseJSON(userInfo); } public static void checkSumValid(String account){ boolean flag = false; UserInfo userInfo = userInfoService.findByAccount(account); if(userInfo!=null){ flag = licencesService.isCheckSumValid(userInfo.uuid,userInfo.id,userInfo.account,userInfo.email,userInfo.checkSum); } responseJSON(flag); } /** * 更改用户密码 * @param uid * @param newPwd */ public static void updateUserPWD(long uid, String newPwd){ Boolean success = userInfoService.updateUserPwd(uid, newPwd); responseJSON(success); } /** * 待激活用户 * * @param pageNo 页码 * @return _1 列表list _2 page对象 */ public static void activateUsersList(int pageNo){ String body = fetchBody(); AvtivatePar ap = GsonUtil.createWithoutNulls().fromJson(body,AvtivatePar.class); F.T2<List<ActivateUserDto>,Page> result = activateUserService.userList(ap, pageNo); responseJSON(result._1,result._2); } /** * 激活用户 * * @param pageNo 页码 * @return _1 列表list _2 page对象 */ public static void usersList(int pageNo){ String body = fetchBody(); AvtivatePar ap = GsonUtil.createWithoutNulls().fromJson(body,AvtivatePar.class); F.T2<List<ActivateUserDto>,Page> result = activateUserService.users(ap, pageNo); responseJSON(result._1,result._2); } /** * 到期用户 * * @param pageNo 页码 * @return _1 列表list _2 page对象 */ public static void dueUsersList(int pageNo){ String body = fetchBody(); AvtivatePar ap = GsonUtil.createWithoutNulls().fromJson(body,AvtivatePar.class); F.T2<List<ActivateUserDto>,Page> result = activateUserService.dueUsers(ap, pageNo); responseJSON(result._1,result._2); } /** * 查询所有的部门信息 * @return */ public static void findAllDepartment(){ List<SaleDepartMentDto> list = saleDepartmentService.findAll(); responseJSON(list); } /** * 根据用户ID 查询用户的角色信息 * * @param uid * @return */ public static void findUserRoleInfoById(long uid){ List<UserRoleDto> list = userInfoService.findUserRoleInfoById(uid); responseJSON(list); } /** * 根据角色ID查询菜单 * * @param rid * @return */ public static void findRoleFunctionInfo(long rid){ List<FunctionInfo> list = UserInfoService.findRoleFunctionInfo(rid); responseJSON(list); } /** * 根据用户ID查询用户信息 * * @param uid * @return */ public static void findUserInfoById(long uid){ UserInfo userInfo = userInfoService.findUserById(uid); responseJSON(userInfo); } /** * 根据用户ID查询 用户的菜单 * * @param uid * @return */ public static void findUserFunctionInfoById(long uid){ List<FunctionInfoDto> list = userInfoService.findUserFunctionInfoById(uid); responseJSON(list); } /** * 修改用户基本信息 * * @return */ public static void updateUserInfo(){ String body = fetchBody(); UserInfoDto userInfoDto = GsonUtil.createWithoutNulls().fromJson(body,UserInfoDto.class); Boolean flag = userInfoService.updateUserInfo(userInfoDto); responseJSON(flag); } /* public static void fetchFunctionInfo(){ }*/ /** * 根据email查找用户信息 * @param email */ public static void findUserByEmail(String email){ UserInfoDto userInfoDto = userInfoService.findUserByEmail(email); responseJSON(userInfoDto); } /** * 批量删除用户(软删除) * @param ids */ public static void delUserById(String ids){ userInfoService.delUser(ids); responseJSON(true); } /** * 批量修改用户状态 * @param ids 用户id 用逗号分隔 * @param status */ public static void userStateModifyById(@As(",")String[] ids ,int status){ userInfoService.userStateModify(ids,status); responseJSON(true); } /** * 到期用户延期 * * @param strId * @param delaydate */ public static void userdelayById(@As(",")String[] strId, String delaydate){ userInfoService.userdelay(strId,delaydate); responseJSON(true); } /** * 批量插入用户信息 * */ public static void addUserBatch(){ String body = fetchBody(); Type type = new TypeToken<List<UserInfoDto>>() {}.getType(); List<UserInfoDto> userList = GsonUtil.createWithoutNulls().fromJson(body, type); List<Long> longList = null; try { longList = userInfoService.addUserBatch(userList); } catch (Exception e) { e.printStackTrace(); Logger.error(e, "程序异常:%s", e.getMessage()); responseError(); } responseJSON(longList); } /** * 获得用户数据权限信息 * @param id 用户ID */ public static void fetchUserDataInfoById(long id){ List<UserDataDto> list = userInfoService.findUserDataInfoByUid(id); responseJSON(list); } /** * 查看用户信息 * @param uid */ public static void fetchPersonalmodify(long uid) { UserInfoDto userInfoDto = userInfoService.personalmodify(uid); responseJSON(userInfoDto); } /** * 更新用户信息 * @param uid */ public static void updatePersonalmodify(long uid) { String body = fetchBody(); UserInfoDto userInfoDto = GsonUtil.createWithoutNulls().fromJson(body, UserInfoDto.class); boolean flag = userInfoService.updateUserInfo(userInfoDto, uid); responseJSON(flag); } /** * 根据uid找密码 * @param password * @param uid */ public static void findPwdById(String password, long uid) { boolean flag = userInfoService.findPwdById(password, uid); responseJSON(flag); } /** * 检查email是否存在 * @param newEmail * @param selfEmail */ public static void checkEmail(String newEmail, String selfEmail) { UserInfoDto userInfoDto = userInfoService.checkEmail(newEmail, selfEmail); responseJSON(userInfoDto); } /** * 注册用户 * @return 是否成功 */ public static void addUser(){ String body = fetchBody(); UserRegisterDto userRegisterDto = GsonUtil.createWithoutNulls().fromJson(body, UserRegisterDto.class); boolean flag = userInfoService.addUser(userRegisterDto); responseJSON(flag); } public static void fetchAllDepartment() { List<SaleDepartment> list = userInfoService.fetchAllDepartment(); responseJSON(list); } /** * 根据token查询该用户权限到期时间 * @param token * @return */ public static void fetchEndDateByToken(String token){ UserInfo userInfo = userInfoService.fetchEndDate(token); responseJSON(userInfo); } }
Python
UTF-8
135
3.390625
3
[]
no_license
def faktoriyel(sayi): if sayi==1: return 1 else: return sayi * faktoriyel(sayi-1) print(faktoriyel(6))
Shell
UTF-8
2,611
3.40625
3
[ "MIT" ]
permissive
#!/bin/bash # # GMT_Graph.sh # # Copyright 2011 Francisco Hernandez <FJHernandez89@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # ##---Variables--- ARGS=3 ACARG=$# T01=$1 E_BADARGS=65 #---Output Files--- Odx=$( echo $1 | sed 's/.dx/X.ps/g') Ody=$( echo $2 | sed 's/.dy/Y.ps/g') Odz=$( echo $3 | sed 's/.dz/Z.ps/g') #---Verify Arguments--- if [ "$ACARG" -ne "$ARGS" ] then echo "Usage: 'GMT_Graph.sh' DxFile DyFile DzFile" exit $E_BADARGS fi #---Define Ranges--- XxMin=$(awk 'min=="" || $1 < min {min=$1} END{ print min -1}' $1) XxMax=$(awk 'max=="" || $1 > max {max=$1} END{ print max +1}' $1) XyMin=$(awk 'min=="" || $2 < min {min=$2} END{ print min -1}' $1) XyMax=$(awk 'max=="" || $2 > max {max=$2} END{ print max +1}' $1) YxMin=$(awk 'min=="" || $1 < min {min=$1} END{ print min -1}' $2) YxMax=$(awk 'max=="" || $1 > max {max=$1} END{ print max +1}' $2) YyMin=$(awk 'min=="" || $2 < min {min=$2} END{ print min -1}' $2) YyMax=$(awk 'max=="" || $2 > max {max=$2} END{ print max +1}' $2) ZxMin=$(awk 'min=="" || $1 < min {min=$1} END{ print min -1}' $3) ZxMax=$(awk 'max=="" || $1 > max {max=$1} END{ print max +1}' $3) ZyMin=$(awk 'min=="" || $2 < min {min=$2} END{ print min -1}' $3) ZyMax=$(awk 'max=="" || $2 > max {max=$2} END{ print max +1}' $3) RanX="-R$XxMin/$XxMax/$XyMin/$XyMax" RanY="-R$YxMin/$YxMax/$YyMin/$YyMax" RanZ="-R$ZxMin/$ZxMax/$ZyMin/$ZyMax" Scal="-Jx.5" #---Creating Graphs--- echo "Creating Graphs" psbasemap $Scal $RanX -B:"# of Day":a5f5g1/:"NS-Disp (cm)":a5f5g1 -K > $Odx psbasemap $Scal $RanY -B:"# of Day":a5f5g1/:"EW-Disp (cm)":a5f5g1 -K > $Ody psbasemap $Scal $RanZ -B:"# of Day":a5f5g1/:"Vetical-Disp (cm)":a5f5g1 -K > $Odz psxy $1 $Scal $RanX -Sc.1 -Wthicker,255/0/0 -O >> $Odx psxy $2 $Scal $RanY -Sc.1 -Wthicker,255/0/0 -O >> $Ody psxy $3 $Scal $RanZ -Sc.1 -Wthicker,255/0/0 -O >> $Odz
Java
UTF-8
828
2.8125
3
[]
no_license
package model; import java.math.BigInteger; /** * * @author Admin */ public class ProductToCart { private ProductWithMaterial productWithMaterial; private int quantity; public ProductToCart() { } public ProductWithMaterial getProductWithMaterial() { return productWithMaterial; } public void setProductWithMaterial(ProductWithMaterial productWithMaterial) { this.productWithMaterial = productWithMaterial; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public String getSubTotal() { BigInteger productPrice = new BigInteger(productWithMaterial.getProductPrice()); return productPrice.multiply(BigInteger.valueOf(quantity)).toString(); } }
Python
UTF-8
1,901
3.0625
3
[]
no_license
import csv import datetime as dt import sqlalchemy as db from sqlalchemy.orm import sessionmaker # импортируем классы Book и Base из файла database_setup.py from database_setup import User, Author, Book, Base engine = db.create_engine('postgresql+psycopg2://books:bNcO9ypR@192.168.1.120:5432/books') # Свяжим engine с метаданными класса Base, # чтобы декларативы могли получить доступ через экземпляр DBSession Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # Экземпляр DBSession() отвечает за все обращения к базе данных # и представляет «промежуточную зону» для всех объектов, # загруженных в объект сессии базы данных. session = DBSession() def selectOrCreateAuthor(aname): ret=session.query(Author).filter_by(name=aname).first() if ret is None: a=Author(name=aname) session.add(a) session.commit() id=a.id return id else: return ret.id def selectOrCreateBook(title,isbn,year,author_name): au_id=selectOrCreateAuthor(author_name) b=Book(title=title,isbn=isbn,year=year,author_id=au_id) ret=session.query(Book).filter_by(isbn=isbn).first() if ret is None: session.add(b) session.commit() return b.id else: return ret.id def loadData(fname): with open(fname,newline='') as fin: reader=csv.DictReader(fin) counter=0 for row in reader: y=dt.datetime(int(row['year']),1,1) r=selectOrCreateBook(row['title'],row['isbn'],y,row['author']) if r: counter+=1 return counter def main(): c=loadData('books.csv') print(c) if __name__=='__main__': main()
C#
UTF-8
1,471
2.640625
3
[]
no_license
using SkiaSharp; using SkiaSharp.Views.Forms; using Xamarin.Forms; namespace BottlesApp.Views { public partial class UserPage : ContentPage { public UserPage() { InitializeComponent(); } private void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args) { int size = 240; SKImageInfo info = args.Info; SKSurface surface = args.Surface; SKCanvas canvas = surface.Canvas; Color currColor = Color.FromHex("edefee"); using (SKPaint paintShader = new SKPaint()) { paintShader.Shader = SKShader.CreateRadialGradient( new SKPoint(info.Width / 2, info.Height / 2), size, new SKColor[] { SKColors.Black, SKColors.Black, SKColors.Gray, currColor.ToSKColor() }, null, SKShaderTileMode.Repeat); canvas.DrawCircle(info.Width / 2, info.Height / 2, size, paintShader); } currColor = Color.FromHex("d2e8eb"); SKPaint paint = new SKPaint { Style = SKPaintStyle.Fill, Color = currColor.ToSKColor() }; canvas.DrawCircle(info.Width / 2, info.Height / 2 - 20, size - 15, paint); } } }
JavaScript
UTF-8
551
2.578125
3
[]
no_license
// simple server 'use strict'; const http = require('http'); const fs = require('fs'); const port = 8080; const path = require('path'); const getContent = (req, res) => { let url; if (req.url === '/' || req.url === '/index.html') url = 'index.html'; else if (req.url === '/js/main.js') url = 'js/main.js'; else return; fs.readFile(url, 'utf-8', (err, content) => { res.end(content); }); }; const server = http.createServer(getContent); server.listen(port, () => { console.log('started'); });
TypeScript
UTF-8
414
3.046875
3
[]
no_license
export enum Pawns { pawn = "PAWN", rook = "ROOK", knight = "KNIGHT", king = "KING", queen = "QUEEN", bishop = "BISHOP", } export interface Cell { player?: Turn; taken: boolean; pawn: Pawns | null; id: number; } export type Grid = Cell[]; export type State = { grid: Grid; gameResult: null | string; gameFinished: boolean; }; export enum Turn { WHITE = "WHITE", BLACK = "BLACK", }
JavaScript
UTF-8
360
3.3125
3
[]
no_license
function addStuff() { var add = 2+2; document.getElementById("math").innerHTML = "It's " + add + "!"; } function subStuff() { var subtract = 8-3; document.getElementById("math").innerHTML = subtract; } function modStuff() { var modulus = 29%7; document.getElementById("mod").innerHTML = -modulus; } window.alert(Math.random() * 100);
Java
UTF-8
914
2.25
2
[ "Apache-2.0" ]
permissive
package com.github.braisdom.objsql.sample.controllers; import com.github.braisdom.objsql.sample.ResponseObject; import com.github.braisdom.objsql.sample.model.Product; import com.github.braisdom.objsql.sql.SQLSyntaxException; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.sql.SQLException; import java.util.List; @RestController public class ProductsController { @GetMapping("/products/calculate_sl_sply") public ResponseObject calculateSlSply(@RequestParam("begin") String begin, @RequestParam("end") String end) throws SQLException, SQLSyntaxException { List<Product> productSLSply = Product.calProductSPLYAndLP(begin, end); return ResponseObject.createSuccessResponse(productSLSply); } }
TypeScript
UTF-8
617
2.828125
3
[]
no_license
import { v4 as uuidv4 } from 'uuid'; import { Id } from '@domainTypes/Id'; describe('Id type', () => { it('create a new Id', () => { const id = new Id; expect(id.getValue()).toMatch(Id.validationRegex); }); it('create a new id from uuid v4', () => { const uuid = uuidv4(); const id = new Id(uuid); expect(id.getValue()).toBe(uuid); }); it('throw an error when create the Id from a invalid uuid', () => { const invalidUuidv4 = 'cb3b5c32-f791-72d2-8667-5d0c66a8190cZ'; expect(() => new Id(invalidUuidv4)) .toThrowError(new Error(`The id ${invalidUuidv4} is a invalid uuid v4`)); }); });
Markdown
UTF-8
2,385
3.53125
4
[ "MIT" ]
permissive
# single_instance `yba::single_instance` is a really small single-header library to assist you in making a single-instance program. This may be used for URL handlers, or application that needs to make sure only one instance of it is running. This library is compatible with Windows, and any UNIX platform supporinng the `shm_open`, `mmap`, `munmap`, `ftruncate`, `shm_unlink` and `close` systemcalls. ## How to Add the `inlcude` directory of this repository to your compiler search path. On UNIX you will need to link to `pthread` and `rt`. The `yba::single_instance` is the main type of this library. ```cpp yba::single_instance(int argc, char* argv[], const char* unqiue_name, yba::single_instance::argument_handler& handler = nullptr); ``` Its constructor takes the command line arguments of the application (that may be forwarded to the first instance of the program), a unique identifier string, and optionally a pointer to an `argument_handler` sturcture. The pointer `handler` has to be an address of an instance of a type that inherits from `argument_handler` ```cpp struct argument_handler { virtual void operator()(int argc, char* argv[]) {} }; ``` Example: ```cpp struct my_handler : yba::single_instance::argument_handler { void operator()(int argc, char* argv[]) final { std::printf("Received %d arguments\n", argc); for(int i = 0; i < argc; ++i) { std::printf("argv[%d] = \"%s\"\n", i, argv[i]); } } }; int main(int argc, char* argv[]) { my_handler handler; yba::single_instance instance(argc, argv, "test_server", &handler); // Calling this permit you to perform the check to know if this program is the original instance, // or not. if(instance.check_single_instance()) { std::printf("this program is the original instance.\n"); } else { std::printf("this program is another instance of the same program.\n"); // Calling this function will send the list of arguments passed form the // 2nd instance of the program to the orignal instance. // // In the orignal instance of the program, my_handler::operator() will be called with // *this program*'s `argc` and `argv` instance.forward_arguments(); return 0; } while(true) { /* this is the original instance doing it's work here */ } return 0; } ```
PHP
UTF-8
4,765
3.34375
3
[]
no_license
<?php class Post { //DB stuff private $conn; private $table = 'post'; //post props public $id; public $title; public $writer; public $content; public $published_date; //constructor public function __construct($db){ $this->conn = $db; $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $uri = explode( '/', $uri ); $id = null; if (isset($uri[2])) { $id = $uri[2]; } $this->id = $id; } //get posts public function get() { //create query $query = 'SELECT * FROM post'; //prepare statement $stmt = $this->conn->prepare($query); //exeCUTE $stmt->execute(); return $stmt; } public function get_single() { //create query $query = 'SELECT * FROM post WHERE id = ? LIMIT 0,1'; //prepare statement $stmt = $this->conn->prepare($query); // Bind ID $stmt->bindParam(1, $this->id); //exeCUTE $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); // Set properties $this->id = $row['id']; $this->title = $row['title']; $this->writer = $row['writer']; $this->content = $row['content']; $this->published_date = $row['published_date']; } // POST public function post() { $query = 'INSERT INTO post SET title = :title, writer = :writer, content = :content'; //prepare statement $stmt = $this->conn->prepare($query); // Clean data $this->title = htmlspecialchars(strip_tags($this->title)); $this->writer = htmlspecialchars(strip_tags($this->writer)); $this->content = htmlspecialchars(strip_tags($this->content)); // Bind data $stmt->bindParam(':title', $this->title); $stmt->bindParam(':writer', $this->writer); $stmt->bindParam(':content', $this->content); //exeCUTE if ($stmt->execute()){ return true; } else { printf("Error: %s.\n", $stmt->error); return false; } } // Update POST public function update() { $query = 'SELECT * FROM post WHERE id = :id'; //prepare statement $stmt = $this->conn->prepare($query); $stmt->bindParam(':id', $this->id); $stmt->execute(); if (!($stmt -> fetch())) { print_r(json_encode( array('message' => 'Wrong ID'))); } else { $query = 'UPDATE post SET title = :title, writer = :writer, content = :content WHERE id = :id'; //prepare statement $stmt = $this->conn->prepare($query); // Clean data $this->title = htmlspecialchars(strip_tags($this->title)); $this->writer = htmlspecialchars(strip_tags($this->writer)); $this->content = htmlspecialchars(strip_tags($this->content)); // Bind data $stmt->bindParam(':id', $this->id); $stmt->bindParam(':title', $this->title); $stmt->bindParam(':writer', $this->writer); $stmt->bindParam(':content', $this->content); //exeCUTE if ($stmt->execute()){ return true; } else { printf("Error: %s.\n", $stmt->error); return false; } } } // DELETE data public function delete() { $query = 'DELETE FROM post WHERE id = :id'; $stmt = $this->conn->prepare($query); // Clean data $this->id = htmlspecialchars(strip_tags($this->id)); // Bind ID $stmt->bindParam(':id', $this->id); //exeCUTE if ($stmt->execute()){ return true; } else { printf("Error: %s.\n", $stmt->error); return false; } } } ?>
Python
UTF-8
3,109
4
4
[]
no_license
''' Created on Mar 1, 2021 @author: rashmeade22 ''' one = 'Pick a number. 1, 4, 5, or 8: ' two = 'Pick a number. 2, 3, 7, or 9: ' def SecondNumber(first_number, color): # main code first_number = int(first_number) color = int(color) if (color % 2) == 0 and (first_number % 2) == 0: while True: second_number = input(one) if second_number != '1' and second_number != '4' and second_number != '5' and second_number != '8': continue else: break elif (color % 2) == 0 and (first_number % 2) != 0: while True: second_number = input(two) if second_number != '2' and second_number != '3' and second_number != '7' and second_number != '9': continue else: break elif (color % 2) != 0 and (first_number % 2) == 0: while True: second_number = input(two) if second_number != '2' and second_number != '3' and second_number != '7' and second_number != '9': continue else: break elif (color % 2) != 0 and (first_number % 2) != 0: while True: second_number = input(one) if second_number != '1' and second_number != '4' and second_number != '5' and second_number != '8': continue else: break return int(second_number) def Outcome(second_number): if second_number == 1: outcome = ('') elif second_number == 2: outcome = ('') elif second_number == 3: outcome = ('') elif second_number == 4: outcome = ('') elif second_number == 5: outcome = ('') elif second_number == 9: outcome = ('') elif second_number == 7: outcome = ('') elif second_number == 8: outcome = ('') return outcome def main(): fortune = True while fortune: color = input("Pick a color. 1) for red; 2) for blue; 3) for green; 4) for yellow: ") if color == '1' or color == '3': while True: first_number = input(two) if first_number != '2' and first_number != '3' and first_number != '7' and first_number != '9': continue else: second_number = SecondNumber(first_number, color) print(Outcome(second_number)) fortune = False break elif color == '2' or color == '4': while True: first_number = input(one) if first_number != '1' and first_number != '4' and first_number != '5' and first_number != '8': continue else: second_number = SecondNumber(first_number, color) print(Outcome(second_number)) fortune = False break if __name__ == '__main__': main()
Java
UTF-8
526
2.75
3
[]
no_license
package com.shijin.learn.controller.dao; public class Animal { private int id; private String name; //name public Animal() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return new StringBuilder().append(name).append("[").append(id).append("]").toString(); } }
Shell
UTF-8
3,976
3.90625
4
[]
no_license
#!/bin/bash GREEN='\033[0;32m' RED='\033[0;31m' BOLD='\033[1m' DIM='\033[2m' RESET='\033[0m' # Check if the current folder contains .git folder and is active GIT repo if [[ -z $(git rev-parse --is-inside-work-tree 2> /dev/null || false) ]]; then echo -e "${RED}Your not in a GIT repository${RESET}" exit 1; fi echo -e "${GREEN}Enter new tag version${RESET} (e.g. 1.0.1 or 1.1.2)" printf "> " read VERSION echo echo -e "${GREEN}Enter new dependency version${RESET} (e.g. 1.0.* or 1.1.* or ^1.1.2)" echo -e "${DIM}Version for dependencies as composer allows.${RESET}" printf "> " read DEPENDENCIES_VERSION # Check if the current branch is master CURRENT_BRANCH=$(git rev-parse --symbolic-full-name --abbrev-ref HEAD) if [[ $CURRENT_BRANCH == 'master' ]]; then MERGE_INTO_MASTER=false else echo echo -e "${GREEN}Do you want to merge current branch \"$CURRENT_BRANCH\" into the master?${RESET} (y|Y|n|N) default: n" printf "> " read -n 1 -r MERGE_INTO_MASTER fi # Want to merge current branch into the master branch? # This is usefull incase from develop to master if [[ $MERGE_INTO_MASTER =~ ^[Yy]$ ]]; then echo echo -e "${GREEN}Do you want to update composer.json dependencies section to dev-master?${RESET} (y|Y|n|N) default: n " printf "> " read -n 1 -r UPDATE_DEPENDENCIES_FOR_MERGE echo echo "Lets start the process" echo echo "Pull latest changes of the branch: $CURRENT_BRANCH" git pull origin $CURRENT_BRANCH >/dev/null 2>/dev/null if [[ $UPDATE_DEPENDENCIES_FOR_MERGE =~ ^[Yy]$ ]]; then sed "s/[(bp|qq).laravel.(.*)\":\s\"]dev-$CURRENT_BRANCH[\"]/\"dev-master\"/g" composer.json > tmp.json && mv tmp.json composer.json git commit -am "Changed composer.json dependencies to dev-master" >/dev/null 2>/dev/null fi else echo echo "Lets start the process" echo fi # Suspress output: >/dev/null 2>/dev/null # Get latest version from master echo "Fetch latest versions and commits from origin: master" git fetch origin >/dev/null 2>/dev/null git checkout master >/dev/null 2>/dev/null git pull origin master >/dev/null 2>/dev/null if [[ $MERGE_INTO_MASTER =~ ^[Yy]$ ]]; then git merge $CURRENT_BRANCH if [[ -n $(git ls-files --unmerged) ]]; then echo echo -e "${RED}Please fix the merge conflicts first and run again.${RESET}" exit 1; fi fi echo "Create new version: $VERSION" # Open composer.json and rename all bp.laravel.* dev-master to a version sed "s/[(bp|qq).laravel.(.*)\":\s\"]dev-master[\"]/\"$DEPENDENCIES_VERSION\"/g" composer.json > tmp.json && mv tmp.json composer.json sed "s/ - Unreleased//g" CHANGELOG.md > bck_CHANGELOG.md && mv bck_CHANGELOG.md CHANGELOG.md # Ask if you want to update the composer.lock / dependencies echo echo -e "${GREEN}Want to update the composer.lock dependencies from the dev-master?${RESET} (y|Y|n|N) default: n " printf "> " read -n 1 -r UPDATE_DEPENDENCIES echo echo # update dependencies to version number if [[ $UPDATE_DEPENDENCIES =~ ^[Yy]$ ]]; then echo "Update dependencies to latest versions" composer update --no-dev >/dev/null 2>/dev/null fi # commit the updated version numbers in composer.json git commit -am "Release version $VERSION" >/dev/null 2>/dev/null # create tags and remove old once git tag -d $VERSION >/dev/null 2>/dev/null git tag $VERSION >/dev/null 2>/dev/null # Push commit and tags to the server git push origin master >/dev/null 2>/dev/null git push origin --tags --force >/dev/null 2>/dev/null echo "Push new version to remote" echo "Create new dev-master based on $VERSION" # Create develop version sed "s/[(bp|qq).laravel.(.*)\":\s\"]$DEPENDENCIES_VERSION[\"]/\"dev-master\"/g" composer.json > tmp.json && mv tmp.json composer.json # Push commit to the sever git commit -am "Create dev-master version based on $VERSION." >/dev/null 2>/dev/null echo "Push the new dev-master version to remote" git push origin master
Python
UTF-8
1,192
3.03125
3
[]
no_license
#coding:utf-8 import pandas as pd import numpy as np #保存特征重要性 def feature_important(bst, filepath): feature_score = bst.get_fscore() feature_score = sorted(feature_score.items(), key=lambda x:x[1],reverse=True) x1 = [] x2 = [] for (key,value) in feature_score: x1.append(key) x2.append(value) feat_im = pd.DataFrame({"feature_name":x1, "score":x2}) feat_im.to_csv(filepath, index=False) #删除重复的列 def remove_dupl_col(df): # remove duplicated columns remove = [] c = df.columns for i in range(len(c)-1): #print "col:", i v = df[c[i]].values for j in range(i+1,len(c)): if np.array_equal(v,df[c[j]].values): remove.append(c[j]) df.drop(remove, axis=1, inplace=True) print remove return df, remove #删除只有一个值的列 def remove_cons_col(df): # remove constant columns remove = [] for col in df.columns: if np.array(df[col]).std() == 0: # < 0.1: remove.append(col) df.drop(remove, axis=1, inplace=True) print remove return df, remove
Markdown
UTF-8
2,182
2.609375
3
[]
no_license
# [打个分] 常凯申同志泥潭各位打几分啊? > tid: `21838621` 用户ID: `43242861` 发布时间: `2020-05-21 11:13:00` > 毛主席定调七分功,三分过。那常凯申呢?我给打个三分功,七分过,应该很合理吧? ---------- > `2.楼` 用户ID: `12165189` 发布时间: `2020-05-21 11:14:00` > 七三分你来了? ---------- > `3.楼` 用户ID: `43242861` 发布时间: `2020-05-21 11:14:00` > <b>Reply to [pid=423699818,21838621,1]Reply[/pid] Post by [uid=35141573]满地打滚自干五[/uid] (2020-05-21 11:13)</b><br/><br/>所以你的分是0功10过咯 ---------- > `4.楼` 用户ID: `60075523` 发布时间: `2020-05-21 11:14:00` > [quote][tid=21838621]Topic[/tid] <b>Post by [uid=43242861]2fsheep[/uid] (2020-05-21 11:13):</b><br/><br/>毛主席定调七分功,三分过。那常凯申呢?我给打个三分功,七分过,应该很合理吧?[/quote]毛主席7分功3分过是你定的呀,牛逼 ---------- > `5.楼` 用户ID: `39470791` 发布时间: `2020-05-21 11:15:00` > 功:日记写的好。<br/>过:这里放不下。 ---------- > `7.楼` 用户ID: `974879` 发布时间: `2020-05-21 11:16:00` > 给10不给0? ---------- > `9.楼` 用户ID: `43242861` 发布时间: `2020-05-21 11:16:00` > <b>Reply to [pid=423700195,21838621,1]Reply[/pid] Post by [uid=60075523]有态度的虚空行者[/uid] (2020-05-21 11:14)</b><br/><br/>我认错了,我也是听别人说的。我收回给毛主席的打分,各位还是回到主题啊,常凯申同志打几分啊 ---------- > `10.楼` 用户ID: `28427104` 发布时间: `2020-05-21 11:16:00` > 能给负分么? ---------- > `11.楼` 用户ID: `26847411` 发布时间: `2020-05-21 11:17:00` > 你竟敢不空一格? ---------- > `13.楼` 用户ID: `42741914` 发布时间: `2020-05-21 11:17:00` > 1分功9分过 ---------- > `15.楼` 用户ID: `4949184` 发布时间: `2020-05-21 11:18:00` > 我给2分,其中一分给微操 ---------- > `16.楼` 用户ID: `40608817` 发布时间: `2020-05-21 11:19:00` > 花园口决堤,单这一条,不可能高于0分 ----------
Java
UTF-8
2,107
2.703125
3
[]
no_license
package com.stewesho.ninjaboi; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.physics.box2d.Body; public class Shuriken{ private Texture spritesheet; private Sprite sprite; private float angle; private float speed; private long lifespan; //seconds private long startTime; private long elapsedLifetime; //seconds private boolean isDead; private Body body; //physics body for collision public Shuriken(float x, float y, float angle){ this.spritesheet = new Texture("art/weapons.png"); this.sprite = new Sprite(this.spritesheet, 0, 0, 16, 16); this.sprite.setPosition(x, y); this.angle = angle; this.speed = 750; this.lifespan = 3; this.startTime = System.currentTimeMillis(); this.isDead = false; this.body = NinjaBoiBreakOut.physicsManager.createShurikenBody(x, y); Gdx.app.log("shuriken", "spawned at (" + x + ", " + y + ")"); } public void draw(SpriteBatch batch){ this.sprite.rotate(10); this.sprite.draw(batch); } public void move(){ float deltaX = this.speed * MathUtils.cosDeg(this.angle) * Gdx.graphics.getDeltaTime(); float deltaY = this.speed * MathUtils.sinDeg(this.angle) * Gdx.graphics.getDeltaTime(); this.sprite.translate(deltaX, deltaY); this.body.setTransform(this.sprite.getX()+8, this.sprite.getY()+8, 0); this.elapsedLifetime = (System.currentTimeMillis() - this.startTime)/1000; //get time lasted if (this.elapsedLifetime > this.lifespan || this.body.getUserData() == "dead") this.isDead = true; } public boolean isDead(){ return isDead; } public Body getBody(){ return body; } public void killBody(){ NinjaBoiBreakOut.physicsManager.world.destroyBody(body); body.setUserData(null); body = null; } }
Python
UTF-8
3,834
2.546875
3
[]
no_license
import tensorflow as tf #from tensorflow.keras.layers.experimental import preprocessing import numpy as np #for upscaling #from tensorflow_examples.models.pix2pix import pix2pix #from IPython.display import clear_output import matplotlib.pyplot as plt import cv2 #The second way to define a model #1. create input layer: inputs = Input(input_size) #2> Sequentially define next layer based on previous layer # --> nextlayer = e.g Conv2D()(previous layer) #finally define model: model = Model(input = inputs, output = last layer) # Here is the implementation of Unet, by nttuan8.com #https://nttuan8.com/bai-12-image-segmentation-voi-u-net/ inputs = Input(input_size) conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs) conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1) pool1 = MaxPooling2D(pool_size=(2, 2))(conv1) conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1) conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2) pool2 = MaxPooling2D(pool_size=(2, 2))(conv2) conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2) conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3) pool3 = MaxPooling2D(pool_size=(2, 2))(conv3) conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3) conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4) drop4 = Dropout(0.5)(conv4) pool4 = MaxPooling2D(pool_size=(2, 2))(drop4) conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4) conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5) drop5 = Dropout(0.5)(conv5) up6 = Conv2D(512, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(drop5)) merge6 = concatenate([drop4,up6], axis = 3) conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge6) conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6) up7 = Conv2D(256, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv6)) merge7 = concatenate([conv3,up7], axis = 3) conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge7) conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7) up8 = Conv2D(128, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv7)) merge8 = concatenate([conv2,up8], axis = 3) conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge8) conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8) up9 = Conv2D(64, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv8)) merge9 = concatenate([conv1,up9], axis = 3) conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge9) conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9) conv9 = Conv2D(2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9) conv10 = Conv2D(1, 1, activation = 'sigmoid')(conv9) model = Model(input = inputs, output = conv10) model.compile(optimizer = Adam(lr = 1e-4), loss = 'binary_crossentropy', metrics = ['accuracy'])
TypeScript
UTF-8
501
2.625
3
[]
no_license
import {Category} from '../../categories/shared/category'; export class Location { name: string; address: string; coordinates: string; category: Category; id: number; private readonly locations: number[]; constructor(data: Partial<Location>) { Object.assign(this, data); this.id = new Date().getTime(); } w get latitude(): number { return Number(this.coordinates.split(',')[0]); } get longitude(): number { return Number(this.coordinates.split(',')[1]); } }
Java
UTF-8
2,185
2.328125
2
[ "Apache-2.0" ]
permissive
package com.huaweicloud.sdk.dli.v1.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Objects; /** * Request Object */ public class ListResourcesRequest { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "kind") private String kind; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "tags") private String tags; public ListResourcesRequest withKind(String kind) { this.kind = kind; return this; } /** * Get kind * @return kind */ public String getKind() { return kind; } public void setKind(String kind) { this.kind = kind; } public ListResourcesRequest withTags(String tags) { this.tags = tags; return this; } /** * Get tags * @return tags */ public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } @Override public boolean equals(java.lang.Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } ListResourcesRequest that = (ListResourcesRequest) obj; return Objects.equals(this.kind, that.kind) && Objects.equals(this.tags, that.tags); } @Override public int hashCode() { return Objects.hash(kind, tags); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ListResourcesRequest {\n"); sb.append(" kind: ").append(toIndentedString(kind)).append("\n"); sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
Markdown
UTF-8
988
2.609375
3
[]
no_license
# Esame 2021/07/19 SPA Questo documento serve a spiegare nel dettaglio come far partire l'applicativo ### Requisiti per il funzionamento dell'applicativo: - `Node.js` scaricare ed installare da [Node.js](https://nodejs.org/). scaricare la versione `LTS` e seguire i passaggi per l'installazione. - Scaricare json-server dopo aver installato node aprendo un terminale e digitando `npm i -g json-server` - Un broswer ##### Passaggi per il funzionamento dell'applicativo: - Scaricare il codice da github (se si scarica il file zip, scompattarlo) - Aprire il `terminale` all'interno della cartella scaricata - Da terminale entrare nella cartella myapp - Digitare sul terminale `npm i` (nel caso non funzioni bisogna controllare che node sia installato) - Dopo digitare `npm run serve` - Aprire un altro `terminale` all'interno della cartella scaricata - Digitare `json-server` --watch db.json - Aprire il `broswer` (preferibilmente chrome) e recarsi all'indirizzo `http://localhost:8080/`
Java
UTF-8
6,863
2.0625
2
[]
no_license
package com.hanglinpai.util; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.util.Log; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.hanglinpai.R; import com.hanglinpai.app.AppApplication; import com.hanglinpai.widget.CommonDialog; import com.yuyh.library.imgsel.ImageLoader; import com.yuyh.library.imgsel.ImgSelActivity; import com.yuyh.library.imgsel.ImgSelConfig; /** * Created by EWorld on 2017/10/27. */ public class SystemUtils { private static CommonDialog dialog; public static void startToSettingAuth(Context context){ dialog = new CommonDialog(context, "提示", "您的应用缺少定位权限,请到系统设置收到开启", "确定", "取消", new CommonDialog.DialogClickListener() { @Override public void onDialogClick() { SystemUtils.getAppDetailSettingIntent(AppApplication.getInstance()); dialog.dismiss(); } }); dialog.show(); } public static void startToSettingAuth(Context context,String text){ if(dialog!=null&&dialog.isShowing()){ return; } dialog = new CommonDialog(context, "提示", text, "确定", "取消", new CommonDialog.DialogClickListener() { @Override public void onDialogClick() { SystemUtils.getAppDetailSettingIntent(AppApplication.getInstance()); dialog.dismiss(); } }); dialog.show(); } public static void dismissDioalog(){ if(dialog!=null&&dialog.isShowing()){ dialog.dismiss(); return; } } public static void getAppDetailSettingIntent(Context context) { Intent localIntent = new Intent(); localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (Build.VERSION.SDK_INT >= 9) { localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS"); localIntent.setData(Uri.fromParts("package", context.getPackageName(), null)); } else if (Build.VERSION.SDK_INT <= 8) { localIntent.setAction(Intent.ACTION_VIEW); localIntent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails"); localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName()); } context.startActivity(localIntent); } // 两次点击按钮之间的点击间隔不能少于5000毫秒 private static final int MIN_CLICK_DELAY_TIME = 3000; private static long lastClickTime; public static boolean isFastClick() { boolean flag = false; Log.i("999","999999"); long curClickTime = System.currentTimeMillis(); if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) { flag = true; } lastClickTime = curClickTime; return flag; } // 两次点击按钮之间的点击间隔不能少于5000毫秒 private static final int MIN_CLICK_DELAY_TIME2 = 1000; private static long lastClickTime2; public static boolean isFastClickMonth() { boolean flag = false; Log.i("999","999999"); long curClickTime = System.currentTimeMillis(); if ((curClickTime - lastClickTime2) >= MIN_CLICK_DELAY_TIME2) { flag = true; } lastClickTime2 = curClickTime; return flag; } // 选择多张照片 public static void SelectMulti(Activity context,int hasNum) { // 自定义图片加载器 ImageLoader loader = new ImageLoader() { @Override public void displayImage(Context context, String path, ImageView imageView) { // TODO 在这边可以自定义图片加载库来加载ImageView,例如Glide、Picasso、ImageLoader等 Glide.with(context).load(path).into(imageView); } }; // 自由配置选项 ImgSelConfig config = new ImgSelConfig.Builder(context, loader) // 是否多选 .multiSelect(true) // “确定”按钮背景色 .btnBgColor(Color.parseColor("#FFFFFF")) // “确定”按钮文字颜色 .btnTextColor(R.color.firstColor) // 返回图标ResId .backResId(R.mipmap.back) // 标题 .title("图片") // 标题文字颜色 .titleColor(R.color.firstColor) .backResId(R.mipmap.back) // TitleBar背景色 .titleBgColor(Color.parseColor("#FFFFFF")) // 裁剪大小。needCrop为true的时候配置 .cropSize(1, 1, 200, 200) .needCrop(false) // 第一个是否显示相机 .needCamera(true) .rememberSelected(false) // 最大选择图片数量 .maxNum(3-hasNum) .build(); // 跳转到图片选择器 ImgSelActivity.startActivity(context, config, 1); } // 选择单张照片 public static void SelectSinge(Activity context,int a,int b) { // 自定义图片加载器 ImageLoader loader = new ImageLoader() { @Override public void displayImage(Context context, String path, ImageView imageView) { // TODO 在这边可以自定义图片加载库来加载ImageView,例如Glide、Picasso、ImageLoader等 Glide.with(context).load(path).into(imageView); } }; // 自由配置选项 ImgSelConfig config = new ImgSelConfig.Builder(context, loader) // 是否多选 .multiSelect(false) // “确定”按钮背景色 .btnBgColor(Color.parseColor("#FFFFFF")) // “确定”按钮文字颜色 .btnTextColor(R.color.firstColor) // 返回图标ResId // 标题 .title("图片") .backResId(R.mipmap.back) // 标题文字颜色 .titleColor(R.color.firstColor) // TitleBar背景色 .titleBgColor(Color.parseColor("#FFFFFF")) // 裁剪大小。needCrop为true的时候配置 .cropSize(a, b, a*8, b*8) .needCrop(true) // 第一个是否显示相机 .needCamera(true) // 最大选择图片数量 .maxNum(1) .build(); // 跳转到图片选择器 ImgSelActivity.startActivity(context, config, 1); } }
JavaScript
UTF-8
1,604
2.96875
3
[]
no_license
import React, {Component} from 'react'; import PropTypes from 'prop-types'; import NewsItem from './NewsItem'; import NewsForm from './NewsForm'; class News extends Component { static propTypes = { news: PropTypes.array.isRequired, name: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]).isRequired }; //component'de name gelmezse default hasan verilecek. static defaultProps = { name : "hasan" }; //js expression yazabilirsin. render(){ const title = "react js"; const description = "react description" let nameElement = <div>demircan</div> console.log(this.props.addNews); const elements = this.props.news.map(news => <NewsItem key = {news.id} newsData = {news} /> ) return( <div> { elements } {this.props.name} <NewsForm addNews={this.props.addNews}/> </div> ) } } export default News; /* 1. uzun yol. {2 + 2 === 4 ? "evet" : "hayır"} {nameElement} <NewsItem //diger component'lere veri taşımak için title = {title} description = {description} /> <NewsItem title = {title} description = {description}/> <NewsItem title = {news[2].title} description = {news[2].description}/> */
JavaScript
UTF-8
10,462
2.75
3
[]
no_license
function GIF() { this.width = 0; this.height = 0; this.nFrames = 0; this.buffer = []; this.version = ""; this.pos = 0; // Current Pos this.fileSize = 0; // Stores the File Size this.gloColTable = []; // Global Color Table this.dictColor = {}; // Dictonary of colors with respective index this.pixelAspectRatio = 0; // Pixel aspect ratio this.bgIndex = 0; // Background Index this.delay = 0; // Delay Time this.transFlag = false; // Transparent Flag this.transIndex = 0;// Transparent Index this.images = []; this.appName = ""; // Application name this.tmpind = 0; // Temp image Index this.comments = []; // Array of all comments } GIF.prototype.constructor = GIF; // Function convert bits array to decimal no GIF.prototype.bitsNum = ba => { console.log(ba) ba.reduce(function (s, n) { return s * 2 + n; }, 0); } // Function to convert byte to bit GIF.prototype.byteBit = function () { var byt = this.buffer[this.pos], tmp = []; for (var i = 7; i >= 0; i--) tmp.push(!!(byt & 1 << i)); this.pos += 1; return tmp; } // Function to check whether it is a valid gif GIF.prototype.isValidFile = function () { this.pos += 3; return ((this.buffer[0] === 71 && this.buffer[1] === 73 && this.buffer[2] === 70 && this.buffer[this.buffer.length - 1] == 59)); } // Function read unsigned int GIF.prototype.getUint16 = function () { var tmp = this.buffer[this.pos + 1] << 8 | this.buffer[this.pos]; this.pos += 2; return tmp; } // Function Convert integer to little endian GIF.prototype.litEnd = function (int) { return [int & 0xFF, int >> 8]; } // Function read current gif version GIF.prototype.readVersion = function () { this.version = String.fromCharCode(this.buffer[this.pos]); this.version += String.fromCharCode(this.buffer[this.pos + 1]); this.version += String.fromCharCode(this.buffer[this.pos + 2]); this.pos += 3; } // Read Current Byte and increase the pos GIF.prototype.readByte = function () { return this.buffer[this.pos++]; } GIF.prototype.rgbHex = function (c) { return '#' + c.r.toString(16) + c.g.toString(16) + c.b.toString(16); } // parse Color Table GIF.prototype.parseColTable = function (tsize) { if (tsize == 0) return; var table = []; for (var i = 0; i < tsize; i++) table.push({ r: this.readByte(), g: this.readByte(), b: this.readByte() }) return table; } // Parse Graphics Control Extension GIF.prototype.parseGrapConExt = function () { this.readByte(); // Block Size var packedField = this.byteBit(); this.transFlag = packedField[7]; this.delay = this.getUint16(); this.transIndex = this.readByte(); this.readByte(); // Block terminator } // GIF.prototype.readSubBlock = function (){ var size,data = ''; do{ size = this.readByte(); for (var i=0;i<size;i++) data += String.fromCharCode(this.readByte()); }while(size != 0) return data; } // Parse Image GIF.prototype.parseImg = function () { // Parse The Image Descriptor First var left = this.getUint16(); var top = this.getUint16(); var w = this.getUint16(); var h = this.getUint16(); var packedField = this.byteBit(); /// Parse the Local table if Exist var locTable = undefined; if (packedField[0]) { var tsize = (+packedField[5]) * 4 + (+packedField[6]) * 2 + (+packedField[7]); tsize = (1 << (tsize + 1)); locTable = this.parseColTable(tsize); } if (packedField[1]) console.log("x"); this.images.push({ w, h, top, left, locTable, data: undefined, transFlag: undefined, delay: undefined, transIndex: undefined }); } // GIF LZW Decoder GIF.prototype.LZWDecode = function (minCodeSize, data, shape) { data.shift(); // Number of Bytes var pos = 0; var readCode = function (size) { var code = 0; for (var i = 0; i < size; i++) { if (data[(pos >> 3)] & (1 << (pos & 7))) { code |= 1 << i; } pos++; } return code; }; var output = []; var clearCode = 1 << minCodeSize; var eoiCode = clearCode + 1; var codeSize = minCodeSize + 1; var dict = []; var clear = function () { dict = []; codeSize = minCodeSize + 1; for (var i = 0; i < clearCode; i++) { dict[i] = [i]; } dict[clearCode] = []; dict[eoiCode] = null; }; var code; var last; while (true) { last = code; code = readCode(codeSize); if (code === clearCode) { clear(); continue; } if (code === eoiCode) break; if (code < dict.length) { if (last !== clearCode) { dict.push(dict[last].concat(dict[code][0])); } } else { if (code !== dict.length) throw new Error('Invalid LZW code.'); dict.push(dict[last].concat(dict[last][0])); } output.push.apply(output, dict[code]); if (dict.length === (1 << codeSize) && codeSize < 12) { codeSize++; } } var tmpCan = document.createElement('canvas'); tmpCan.width = shape.w; tmpCan.height = shape.h; console.log(output.length) var imgData = tmpCan.getContext('2d').getImageData(0, 0, shape.w, shape.h); for (var i = 0; i < imgData.data.length / 4; i++) { imgData.data[4 * i] = this.gloColTable[output[i]].r; imgData.data[4 * i + 1] = this.gloColTable[output[i]].g; imgData.data[4 * i + 2] = this.gloColTable[output[i]].b; imgData.data[4 * i + 3] = 255; } tmpCan.getContext('2d').putImageData(imgData, 0, 0); var tmpImg = new Image(); tmpImg.src = tmpCan.toDataURL('image/png') document.body.appendChild(tmpImg) return tmpImg; } // Parsing Image data GIF.prototype.parseImgData = function (shape) { var minCodeSize = this.readByte(); var data = []; while (true) { var tmpB = this.readByte(); if (tmpB == 0) break; data.push(tmpB); } return this.LZWDecode(minCodeSize, data, shape); } // Parse Application Extension GIF.prototype.parseAppExt = function () { var size = this.readByte(); for (var i = 0; i < size; i++) this.appName += String.fromCharCode(this.readByte()); if (this.appName == "NETSCAPE2.0") { this.readByte();// 03 this.readByte();// 01 this.getUint16(); // Iterations this.readByte(); // Block terminator }else { // Unknown Application while (this.readByte() != 0); } } // Parse Comment Extension GIF.prototype.parseComment = function (){ var size = this.readByte(),tmp=""; for (var i=0;i<size;i++) tmp += String.fromCharCode(this.readByte()); this.comments.push(tmp); while(this.readByte() != 0); // Block terminator } GIF.prototype.parsePlainText = function (){ var skip = this.readByte(); for (var i=0;i<skip;i++) this.readByte(); while (this.readByte() != 0); } GIF.prototype.loadFile = function (filename) { var h = new XMLHttpRequest(); h.overrideMimeType('text/plain; charset=x-user-defined'); h.onload = e => { this.fileSize = h.responseText.length; for (var i = 0; i < h.responseText.length; i++) this.buffer.push((h.responseText.charCodeAt(i) & 0xFF)); this.buffer = new Uint8Array(this.buffer); if (!this.isValidFile()) throw new Error("File is Not a Gif"); this.readVersion(); this.width = this.getUint16(); this.height = this.getUint16(); var packedField = this.byteBit(); this.bgIndex = this.readByte(); this.pixelAspectRatio = this.readByte(); /// (N + 15) / 64 for all N<>0. if (packedField[0]) { var tsize = (+packedField[5]) * 4 + (+packedField[6]) * 2 + (+packedField[7]); tsize = (1 << (tsize + 1)); this.gloColTable = this.parseColTable(tsize); console.log(this.pos) } var cnt = 0; while (this.pos < this.fileSize) { var tmpBy = this.readByte(); ++cnt; // if (tmpBy == 59) break; if (tmpBy == 33) { var ss = this.readByte(); if (ss == 249) this.parseGrapConExt(); else if (ss == 0xFF) this.parseAppExt(); else if (ss == 0x01) this.parsePlainText(); else if (ss == 0xFE) this.parseComment(); } else if (tmpBy == 44) { // console.log(this.pos) // this.parseImg(); } } this.show(); console.log(this) }; h.onerror = function () { }; h.open('GET', filename, true); h.send(); } GIF.prototype.saveOriginal = fileName => { var blob = new Blob([new Uint8Array(this.buffer)], { type: "image/gif" }); var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = fileName; link.click(); } GIF.prototype.show = function () { var canvas = document.createElement("canvas"); canvas.width = this.width; canvas.height = this.height; document.body.appendChild(canvas); var ctx = canvas.getContext("2d"); // ctx.drawImage(this.images[0].data, 0, 0); } GIF.prototype.addImage = function () { } GIF.prototype.createImage = function () { var tmpbuffer = []; var x = "GIF89a"; var w = 1; var h = 1; for (var i = 0; i < x.length; i++) tmpbuffer.push(x.charCodeAt(i)); tmpbuffer.push(...this.litEnd(w)); tmpbuffer.push(...this.litEnd(h)); tmpbuffer.push(";".charCodeAt(0)); console.log(tmpbuffer); // var blob = new Blob([new Uint8Array(tmpbuffer)], { type: "image/gif" }); // var link = document.createElement('a'); // link.href = window.URL.createObjectURL(blob); // link.download = fileName; // link.click(); } function Load() { var g = new GIF(); g.loadFile("demo.gif"); // g.createImage(); // var x = "#4 #1 #6 #6 #2 #9 #9 #7 #8 #10 #2 #12 #1 #14 #15 #6 #0 #21 #0 #10 #7 #22 #23 #18 #26 #7 #10 #29 #13 #24 #12 #18 #16 #36 #12 #5".trim().split(' '); // x = x.reverse(); // for (var i = 0; i < x.length; i++) { // x[i] = parseInt(x[i].replace("#", "")).toString(2); // } // var str = x.join(''); // console.log(str); }
Swift
UTF-8
519
2.796875
3
[]
no_license
// // Secret.swift // MarvelApp // // 17/04/2020. // // import Foundation import CryptoKit struct Secret { static private let privateKey = "23ec56ac540c405b94063afddc79bcda1fcac842" static let publicKey = "ee77e6d97c8a8329dce2c8bff21d88c1" static let ts = String(Date().timeIntervalSince1970) static var md5: String { let digest = Insecure.MD5.hash(data: "\(ts)\(privateKey)\(publicKey)".data(using: .utf8) ?? Data()) return digest.map { String(format: "%02hhx", $0) }.joined() } }
SQL
UTF-8
405
3.4375
3
[]
no_license
-- Health Facts Diabetes, Dx + labs + meds -- Only diagnostic ICD-9-CM codes (Volume 2). -- Diabetes Codes: 250.*, includes Diabetes Mellitus type-1 and type-2 -- Here we select type-1 assuming "juvenile" is in all descriptions. -- SELECT dm.medication_id, dm.generic_name, dm.brand_name, dm.ndc_code, dm.route_description FROM hf_d_medication dm WHERE LOWER(dm.generic_name) LIKE 'insulin%' ; --
Java
UTF-8
1,094
2.53125
3
[]
no_license
package ex.db2.product.domain; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import javax.persistence.*; import java.util.Date; @Slf4j @Entity @Getter @ToString @NoArgsConstructor public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @Setter private Integer price; private Date updatedAt; public Product(String name, Integer price) { this.name = name; this.price = price; } @PrePersist private void prePersist() { log.warn("prePersist() start"); this.updatedAt = new Date(); log.warn("prePersist() end"); } @PreUpdate private void preUpdate() { log.warn("preUpdate() start"); this.updatedAt = new Date(); log.warn("preUpdate() end"); } @PostUpdate private void postUpdate() { log.warn("postUpdate() start"); this.updatedAt = new Date(); log.warn("postUpdate() end"); } }
Markdown
UTF-8
10,031
3.84375
4
[ "Apache-2.0" ]
permissive
> ## 顺序容器概述 * string和vector将元素保存在连续的内存空间中,用下标计算地址非常快,但是在中间位置插入删除元素很耗时,因为在一次插入或删除后要移动插入或删除位置之后的所有元素,添加一个元素有时还需要分配额外的存储空间,此时每个元素都要移动到新的存储空间中 * list和forward_list在任何位置的插入删除都很快速,但不支持随机访问,只能遍历整个容器,与vector、deque和array相比这两个容器的额外开销也很大 * deque支持快速随机访问,在中间位置插入删除代价可能很高,但在两端很快,与list或forward_list相当 * 迭代器范围由一对迭代器begin、end表示,它们指向同一容器,迭代器范围中的元素为`[begin,end)`范围中所有元素,这个范围称为左闭合区间 * **标准库使用左闭合范围是因为它有三种方便的性质** * begin == end,范围为空 * begin != end,范围至少包含一个元素 * begin递增若干次可以使begin == end ```cpp while (begin != end) { *begin = val; ++begin; } ``` * **size类型为size_type**,一种无符号整数,迭代器类型分为**iterator和const_iterator**,要专门得到**const_iterator**则可以使用**cbegin和cend**,如果需要元素类型可以使用**value_type** ```cpp vector<int>::size_type iter; vector<int>::iterator iter; // 一般用auto获取类型 auto iter = v.begin(); ``` * **begin是被重载过的,实际有两个名为begin的成员,一个是const成员返回const_iterator,另一个则是非常量**。rbegin和rend类似 ```cpp list <string>::iterator it1 = a.begin(); list <string>::const_iterator it2 = a.begin(); auto it3 = a.begin(); // 仅当a是const时it是const_iterator auto it4 = a.cbegin(); // it4是const_iterator ``` > ## 容器定义和初始化 ```cpp C c; C c1(c2); C c1 = c2; C c {a, b, c...}; C c = {a, b, c}; C c(b, e); C seq(n); // seq包含n个元素,这些元素进行了值初始化 // 此构造函数是explicit的 C seq(n, t); // seq包含n个值初始化为t的元素 ``` * 要用一个容器拷贝给另一个,两个容器的类型和元素类型必须匹配,但是当**传递迭代器参数拷贝一个范围**时则无此要求,只要能转换要拷贝的元素类型就行 ```cpp vector <const *char> articles = { "a", "an", "the"}; forward_list <string> words(articles.begin(),articles.end()); ``` > ## 容器赋值 ```cpp c1 = c2; c = {a, b, c...}; swap(c1, c2); // 除array外,swap并未进行拷贝删除插入,只是交换容器内部数据结构 c1.swap(c2); // 比从c2向c1拷贝元素快得多 // assign不适用array和关联容器 seq.assign(b, e); seq.assign(il); // 将seq中的元素替换为初始化列表il中的元素 seq.assign(n, t); ``` * swap只是交换两个容器的内部数据结构,元素本身并未交换 ```cpp vector<string> v1(10); // 10个元素的vector vector<string> v2(20); // 20个元素的vector swap(v1, v2); // 交换后v1包含20个元素,v2包含10个 ``` * 两个容器要用关系运算进行比较则其元素类型要支持所需运算符 ```cpp if (c1 < c2) // c1和c2的类型必须支持<比较操作,否则错误 ``` > ## 添加元素 * 添加元素会改变容器大小,array不支持,forward_list有自己专有的insert和emplace且不支持`push_back`和`emplace_back`,vector和string不支持`push_front`和`emplace_front` ```cpp c.push_back(t); // push_back会创建一个局部临时对象并压入容器 c.emplace_back(args); // emplace_back在容器管理的内存中直接创建对象 // emplace的参数根据元素类型变化,参数必须与元素类型的构造函数匹配 c.push_front(t); c.emplace_front(args); // 以上四条返回void c.insert(p, t); c.emplace(p, args); // 以上两条返回新添加元素的迭代器 c.insert(p, n, t); c.insert(p, b, e); //不能是自身的迭代器,c.b,c.e c.insert(p, il); // il是花括号包围的元素值列表 // 以上三条返回指向新添加的第一个元素的迭代器,若添加内容为空则返回p ``` * 向vector、string、deque插入元素会使所有指向容器的迭代器、引用、指针失效 ```cpp list <string> lst; auto iter = lst.begin(); while(cin >> word) iter = lst.insert(iter, word); // insert返回的迭代器指向新元素 // 等价于调用push_front ``` > ## 访问元素 * 访问元素返回的是引用,容器是const对象则返回const引用,一般用auto保存返回值 ```cpp c.back(); // 返回尾元素引用,c为空则行为未定义 c.front(); // 返回首元素引用,c为空则行为未定义 c[n]; // n>c.size()则函数行为未定义 c.at(n); // 如果下标越界则抛出out_of_range异常 ``` * 对空容器调用front和back等于使用越界的下标,是严重的错误 ```cpp if (!c.empty()) { c.front() = 42; auto &v = c.back(); v = 1024; auto v2 = c.back(); // v2不是引用,只是c.back()的一个拷贝 v2 = 0; // v2未改变c中的元素 } ``` > ## 删除元素 * 删除元素会改变容器大小,array不支持,forward_list有特殊版本的`erase`且不支持`pop_back`,vector和string不支持`pop_front` ```cpp c.pop_back(); // 返回void,c为空则行为未定义 c.pop_front(); // 同上 c.erase(p); // 返回p后一个位置迭代器,p为尾后迭代器则行为未定义 c.erase(b, e); // 返回最后一个被删元素之后的迭代器,若e是尾后迭代器则返回尾后迭代器 c.clear(); // 删除所有元素,返回void ``` * forward_list的插入删除 ```cpp lst.before_begin(); // 返回首元素之前不存在的迭代器,此迭代器不能解引用 lst.cbefore_begin(); // 在p之后的位置插入元素,返回指向最后一个插入元素的迭代器,未插入则返回p // p为尾后迭代器则行为未定义 lst.insert_after(p, t); lst.insert_after(p, n, t); lst.insert_after(p, b, e); // b和e不能指向lst内 lst.insert_after(p, il); emplace_after(p, args); // 删除p指向位置之后的元素,返回指向被删元素之后的迭代器 // 若p指向尾元素或是尾后迭代器则行为未定义 lst.erase_after(p); lst.erase_after(b, e); ``` > ## 改变容器大小 ```cpp c.resize(n); // 缩小则丢弃多出的元素,扩大则对新元素进行值初始化 c.resizie(n, t); // 扩大则值初始化为t ``` * 容器操作使迭代器失效,每次进行改变操作后要重新定位迭代器,不要保存end返回的迭代器 * 容器的size是已经保存的元素数,capacity是在不分配新的内存空间的前提下最多能保存的元素数 > ## 容器适配器 * 标准库定义了三个容器适配器:`stack`、`queue`、`priority_queue`,每个适配器定义两个构造函数,默认构造函数创建一个空对象,接受一个容器的构造函数拷贝该容器来初始化适配器 ```cpp // 假设deq是一个deque<int> stack <int> stk(deq); // 从deq拷贝元素到stk ``` * 默认stack和queue基于deque实现,priority_queue基于vector,可以在创建时将一个命名的顺序容器作为第二个参数类型来重载默认类型。queue也可以用list或vector实现,priority_queue也可以用deque实现 ```cpp stack <string, vector <string>> str_stk; stack <string, vector <string>> str_stk(sevc); ``` * stack ```cpp s.empty(); s.size(); s.pop(); // 删除栈顶元素,不返回该元素值 s.push(item); // 入栈(会创建临时量) s.emplace(args); // 直接构造元素入栈(无临时量) s.top(); ``` * queue和priority_queue ```cpp q.empty(); q.size(); q.pop(); // 返回但不删除queue首元素或priority_queue最高优先级元素 q.front(); // 返回但不删除首元素或尾元素 q.back(); // 只适用queue q.top(); // 只适用priority_queue,返回但不删除最高优先级元素 q.push(item); // queue末尾或priority_queue中恰当位置创建一个元素 q.emplace(args); ``` > ## 链表实现约瑟夫生死游戏 * n个人排成一个环,依次编号为1到n,指定一个起始数字开始计数,数到死亡数字的人出列,再从下一个人开始重新计数,直到剩下指定数量的生还人数为止 ```cpp #include <iostream> #include <list> using namespace std; const int n = 30; // 总人数 const int m = 9; // 死亡数字 const int k = 1; // 起始数字 const int s = 15; // 生还人数 void del(list<int>&v, int m, int k, int s) { auto it = v.begin(); for (int i = 0; i < k - 1; ++i) { ++it; if (it == v.end()) it = v.begin(); } while (v.size() > s) { for (int i = 0; i < m - 1; ++i) { ++it; if (it == v.end()) it = v.begin(); } cout << "del:" << *it << endl; it = v.erase(it); if (it == v.end()) it = v.begin(); } } int main() { list<int> v; for (int i = 1; i <= n; ++i) v.push_back(i); del(v, m, k, s); for (auto x : v) cout << x << ' '; } ``` * 不使用std::list的实现 ```cpp #include <iostream> using namespace std; const int n = 30; // 总人数 const int m = 9; // 死亡数字 const int k = 1; // 起始数字 const int s = 15; // 生还人数 struct Node{ Node* next; int val; }; int main() { Node* head = new Node; head->val = 1; head->next = NULL; Node* cur = head; for (int i = 2; i <= n; ++i) { Node* node = new Node; node->val = i; node->next = NULL; cur->next = node; cur = node; } cur->next = head; cur = head; for (int i = 0; i < k - 1; ++i) { cur = cur->next; } int cnt = n; while (cnt > s) { for (int i = 0; i < m - 2; ++i) { cur = cur->next; } if (cur->next == head) head = head->next; cur->next = cur->next->next; cur = cur->next; --cnt; } cur = head; for (int i = 0; i < s; ++i) { cout << cur->val << " "; cur = cur->next; } } ```
Markdown
UTF-8
4,323
3.40625
3
[]
no_license
## Assignment: Please create a tool that can send shipment notifications as text messages. All of the functionality you create must be exposed through a single front-end interface. It must interact with back-end API’s to perform its functions. The main flows to implement are: - A user can choose a particular product and save a draft of a shipping notification for that product. For purposes of this assignment, we want to be able to create different shipping notifications for different products. There can be multiple draft message for a product or one per product, that is up to you. - A user can also look up draft versions of these text messages that have been saved, and click a button to actually send one of them to a number (which they provide at the time of sending). Additional details under “User Flows.” ## Evaluation Criteria: - Learning & implementing new frameworks / languages - Speed / Resourcefulness - Working within a broad spec / autonomous decision making - Quality given the amount of time taken (it would be reasonable to submit a medium-quality solution that you were able to do quickly) ## Tooling: Please use the following technologies. If you are unfamiliar with them, learn the minimum required to get the job done. When you send in your assignment, you can tell us which ones you had to learn from scratch and we will take that into account. - Flask (Python) to create the API endpoints - Connect to DB using SQLAlchemy or pure SQL - PostgreSQL database - ReactJS Front-end (or Flask HTML) - It is totally fine to use only pure HTML (via Flask) if you are unfamiliar with front-end technologies. There is room on our team for pure backend developers. But if you have front-end skills you can show them here. - Twilio to send text messages (if for some reason you can’t create a trial account for free credit, let us know) This does not need to be deployed and available to the internet as long as it can be run locally. The assignment should utilize Docker Compose in order to run locally on any setup. ## User Flows: - Users should be able to query a list of available product_ids - Users should be able to create and save a message for a product - Saving a message requires a product_id to be attached to the message and should throw an error otherwise For example, the message object might look like ``` { "message" : "Some string", "Product_id":1 } ``` - Users should be able to view messages for a product - Users should be able to send messages for a product - This should utilize the Twilio API -- use a Twilio trial account, it is OK if the message does not send to outside / non-whitelisted numbers. ## Getting Setup: There are 2 folders contained with this homework: **`api`** The `api` folder houses the `Dockerfile` to build and run the `Flask` application against the `db`. It contains a bootstrapped `Flask` object and `Flask-SQLAlchemy` already setup to work with the larger `docker-compose.yml` file of this homework. **`app`** The `app` folder will house your frontend code and contains a `Dockerfile` that installs `package.json` with `npm` (or `yarn` if you uncomment it) and then executes `npm start` (or `yarn start`). The package.json does not currently exist (you will have to generate it with any packages you want) and the `docker-compose.yml` will startup the entire application folder when run. Be sure, whatever framework you use, you're able to start the frontend application on port 3000 or you'll need to update the `app/Dockerfile` and `docker-compose.yml` for your frontend port. __Note:__ If you'd like to use `yarn` instead of `npm`, open the `app/Dockerfile` and swap `npm install --silent` with `yarn install --silent` ### Running the Environment Once you've created a `package.json` in the `app` folder, you're ready to run the `docker-compose` environment. By default, when running the `docker-compose` of this repo, the ports will map as follows: - `api` - Port 5000 - `db` - Port 5432 - `app` - Port 3000 Running the environment is now as easy as `docker compose up`. - Visit `http://localhost:5000/health-check` to verify the api is working. - Visit `http://localhost:3000` to see your frontend application ## Comments: Project not fully completed, clone repo for base then modify as you wish!
C++
UTF-8
2,277
2.75
3
[]
no_license
#include "circle.h" BBox Circle::object_bound() const { return BBox(Point3(-m_r,-m_r,0),Point3(m_r,m_r,0)); } void Circle::copyToMesh(TriangleMesh* msh_) { double inR_ = m_r/(double)m_loops; int loops_ = m_loops-1; double deltaSlicesAng_ = 0.0174532925*(double)360.0/(double)m_slices; double deltaR_ = (m_r-inR_)/(double)loops_; double angle_,cosAng_,sinAng_; double x_ , y_; x_ = inR_; y_ = 0; for(int j=0 ; j<= loops_ ; j++ ) // circle { Vertex* vrt_ = new Vertex(0,x_+deltaR_*j,0); msh_->vertexList().push_back(vrt_); } for(int i=1 ; i<m_slices ; i++) { for(int j=0 ; j<= loops_ ; j++) { Vertex* vr1_ = msh_->vertexList()[j]; angle_ = (double)(i)*deltaSlicesAng_; cosAng_ = cos(angle_); sinAng_ = sin(angle_); y_ = vr1_->y()*cosAng_; x_ = vr1_->y()*sinAng_; msh_->vertexList().push_back(new Vertex(x_,y_,0)); } } for(int i=1 ; i< m_slices ; i++) // height { for(int j=0 ; j<= loops_-1 ; j++ ) // circle { Vertex* v1_ = msh_->vertexList()[ (i-1)*(loops_+1)+j+1]; Vertex* v2_ = msh_->vertexList()[ (i-1)*(loops_+1)+j]; Vertex* v3_ = msh_->vertexList()[ i*(loops_+1)+j+1]; Vertex* v4_ = msh_->vertexList()[ i*(loops_+1)+j]; Triangle* tr1_ = new Triangle(v1_,v2_,v3_); Triangle* tr2_ = new Triangle(v2_,v4_,v3_); msh_->faceList().push_back(tr1_); msh_->faceList().push_back(tr2_); } } for(int j=0 ; j<= loops_-1 ; j++ ) // circle { Vertex* v1_ = msh_->vertexList()[ (m_slices-1)*(loops_+1)+j+1]; Vertex* v2_ = msh_->vertexList()[ (m_slices-1)*(loops_+1)+j]; Vertex* v3_ = msh_->vertexList()[ j+1]; Vertex* v4_ = msh_->vertexList()[ j]; Triangle* tr1_ = new Triangle(v1_,v2_,v3_); Triangle* tr2_ = new Triangle(v2_,v4_,v3_); msh_->faceList().push_back(tr1_); msh_->faceList().push_back(tr2_); } Vertex* root_ = new Vertex(0,0,0); for(int i=1 ; i< m_slices ; i++) // height { Vertex* v1_ = msh_->vertexList()[(i-1)*m_loops]; Vertex* v2_ = msh_->vertexList()[i*m_loops]; msh_->faceList().push_back(new Triangle(root_,v2_,v1_)); } Vertex* v1_ = msh_->vertexList()[0]; Vertex* v2_ = msh_->vertexList()[(m_slices-1)*m_loops]; msh_->faceList().push_back(new Triangle(root_,v1_,v2_)); msh_->vertexList().push_back(root_); msh_->calculatebounds(); }
Python
UTF-8
2,351
3.25
3
[ "BSD-3-Clause" ]
permissive
# -*- coding: utf-8 -*- neutral = [ #'Se abre el ascensor y hay un programador dentro, le preguntan: - Sube o baja? A lo que el programador responde: - Si.', 'Se abre el ascensor y hay un programador dentro, le preguntan: - Sube o baja? A lo que el programador responde: - Si.', #'Que le dice un bit al otro? Nos vemos en el bus.', 'Que le dice un bit al otro? Nos vemos en el bus.', 'Atracador: El dinero o la vida! Programador: Lo siento, soy programador. Atracador: Y? Programador: No tengo dinero ni vida.', 'Que es un terapeuta? - 1024 Gigapeutas', 'Cuantos programadores hacen falta para cambiar una bombilla? - Ninguno, porque es un problema de hardware.', 'Se abre el telon, aparece un informatico y dice: que habeis tocado que no se cierra el telon!', '- ...fallece una persona mientras estudiaba en la biblioteca - Que estaba estudiando? - La API de Windows.', 'Que le dice un GIF a un JPG? -Animate hombre...', 'Que dice un informatico que se esta ahogando en la playa?: F1, F1!', 'Solo hay 10 tipos de personas en el mundo, las que entienden binario y las que no.', 'Solo hay 10 tipos de personas en el mundo: las que entienden trinario, las que no, y las que lo confunden con binario.', 'Una mujer dice a su marido informatico: - Ve al supermercado y trae una barra de pan, y si hay huevos, doce. Trajo doce barras de pan.', 'Quien demonios es el general Failure, y que hace intentando leer de mi disco duro?', 'En que se diferencian Windows y un virus? En que el virus funciona, y es gratis.' ] adult = [ #'Que es una mujer objeto? Un instancia de una mujer con clase', #'- Cuantos dalmatas habia en la peli? - 101. - Por el culo te la hinco!', #'Encuentran programador muerto en la ducha con un bote de champu: "enjabonar, aclarar y vuelta a empezar"', #'Esto es un mainframe que le dice a un PC: "tan pequeno y ya "computas"?' 'Que es una mujer objeto? Un instancia de una mujer con clase', '- Cuantos dalmatas habia en la peli? - 101. - Por el culo te la hinco!', 'Encuentran programador muerto en la ducha con un bote de champu: "enjabonar, aclarar y vuelta a empezar"', 'Esto es un mainframe que le dice a un PC: "tan pequeno y ya "computas"?' ] jokes_es = { 'neutral': neutral, 'adult': adult, 'all': neutral + adult, }
C++
BIG5
233
2.6875
3
[]
no_license
//arr_glo.cpp #include <iostream.h> //cout #include <conio.h> //getch() int a[5]; //}Cܼ void main() { for (int i=0;i<5;i++) cout << a[i] << ' '; //CLa}C cout << endl; getch(); //Ȱ }
Java
UTF-8
955
2.09375
2
[]
no_license
package vip.pryun.dikas.admin.conf; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /** * @author 59941 * @date 2019/5/30 10:55 */ @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { /* http.authorizeRequests() .anyRequest().authenticated(); */ } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/admin/**"); } }
Python
UTF-8
1,343
2.890625
3
[]
no_license
import json import sys import time #print(sys.argv) if len(sys.argv) < 4: print('Usage: python replace_id.py INPUT_JSON_FILE -sSTART_FRAME -eEND_FRAME') print('Example: python replace_id.py ch5.json -s2703 -e3603') exit() for arg in sys.argv: if arg.startswith('-s'): start = int(arg[2:]) elif arg.startswith('-e'): stop = int(arg[2:]) else: input_file_name = arg output_file_name = 'replaced_' + input_file_name person = {} find = input('Enter ID to find: ') replace = input('Replace ID %d with: ' % find) exec_start = time.time() with open(input_file_name, 'r') as data_file: data = json.load(data_file) output_data = [] changes = 0 for aClass in data: print(aClass['class'] + ', ' + aClass['filename']) interest = range(start, stop+1) for i, aFrame in enumerate(aClass['frames']): if aFrame['num'] in interest: for j, aNote in enumerate(aFrame['annotations']): if aNote['id'] == find: aClass['frames'][i]['annotations'][j]['id'] = replace changes += 1 output_data.append(aClass) print('replaced in %d locations' % changes) with open(output_file_name, 'w') as output_file: print('writing output file') json.dump(output_data, output_file, sort_keys=True, indent=4) print('done in %ss' % (time.time() - exec_start))
PHP
UTF-8
609
2.546875
3
[ "BSD-2-Clause" ]
permissive
<?php $version['update_required'] = false; function getCurrentVersion() { global $settings; $dbh = $settings->getDatabase(); $statement = $dbh->prepare('SELECT current FROM dbversion'); if ($statement && $statement->execute()) { $result = $statement->fetch(PDO::FETCH_ASSOC); return $result['current']; } else { return 0; } } function getAvailableVersion() { return (int) file_get_contents(BASE.'/updates/version.txt'); } function isUpdateRequired() { return getAvailableVersion() > getCurrentVersion(); } if ($settings->getDatabase()) { $version['update_required'] = isUpdateRequired(); }
C++
UTF-8
514
2.546875
3
[]
no_license
/* *Autor:Diego Silva *Data:10/11/2018 *Descrição:Biblioteca para sensor RGB * */ #ifndef SensorRGB_h #define SensorRGB_h #include <Arduino.h> class SensorRGB{ public: //declarando métodos de entra para seta portas SensorRGB(int P1, int P2, int P3); int getportA(void); int getportB(void); int getportC(void); //decalrando métodos para retorna de portas int CheckInputGreen(); int CheckInputYellow(); int CheckInputBlue(); private: int _pA; int _pB; int _pC; }; #endif
Java
UTF-8
1,341
2.203125
2
[]
no_license
package com.punjabivideostatus.latestsong.gettersetter; public class Item_category { String cid; String category_name; String category_image_thumb; String language; String type_layout; public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public String getCategory_name() { return category_name; } public void setCategory_name(String category_name) { this.category_name = category_name; } public String getCategory_image_thumb() { return category_image_thumb; } public void setCategory_image_thumb(String category_image_thumb) { this.category_image_thumb = category_image_thumb; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getType_layout() { return type_layout; } public void setType_layout(String type_layout) { this.type_layout = type_layout; } public String toString() { return "ClassPojo [cid = " + this.cid + ", category_name = " + this.category_name + ", category_image_thumb = " + this.category_image_thumb + ", language = " + this.language + ", type_layout = " + this.type_layout + "]"; } }
Python
UTF-8
571
2.71875
3
[]
no_license
import pyodbc def fetch_data(): conn = pyodbc.connect('DRIVER={SQL Server};SERVER=pocserver007.database.windows.net;DATABASE=POC;UID=demo;PWD=User@2021') cursor = conn.cursor() cursor.execute("SELECT * FROM dbo.Transactions") for row in cursor.fetchall(): print(",".join(list(row))) break conn.commit() cursor.close() conn.close() return (",".join(list(row))) global list1 list1 = ["Ram","Lal"] def count(): return " ".join(list1)
Java
UTF-8
1,780
2.6875
3
[]
no_license
package wangleijin; import javax.swing.*; import java.awt.*; public class DisplayJFream extends JFrame { private LeftJpanel leftJpanel; private southJpanel southJpanel; private northJpanel northJpanel; private String sql = "SELECT goodsID AS 商品编号,type AS 类型,name AS 名称,price AS 价格,number AS 数量\n" + "FROM goods"; //JFream程序主窗口 public DisplayJFream(){ super("201700800377 王蕾锦"); this.setSize(800,600); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.southJpanel = new southJpanel(); this.northJpanel = new northJpanel(sql); this.leftJpanel = new LeftJpanel(northJpanel); JPanel rightJpanel = new JPanel(new BorderLayout()); rightJpanel.add(northJpanel,BorderLayout.CENTER); rightJpanel.add(southJpanel,BorderLayout.SOUTH); this.add(new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,leftJpanel,rightJpanel)); this.pack(); this.setVisible(true); } public static void main(String[] args) { new DisplayJFream(); } } //下面是数据库的创建语句 /* CREATE DATABASE MyDB ON PRIMARY ( NAME = 'mydb_data', FILENAME = '/root/Sql/mydb_data.mdf', SIZE = 5MB, MAXSIZE = 50MB, FILEGROWTH = 5% ) LOG ON ( NAME = 'mydb_log', FILENAME = '/root/Sql/mydb_log.ldf', SIZE = 5MB, MAXSIZE = 50MB , FILEGROWTH = 5% ) USE MyDB CREATE TABLE goods ( goodsID NVARCHAR(8) PRIMARY KEY , type NVARCHAR(4), name NVARCHAR(10), price FLOAT, number INT ) */
Markdown
UTF-8
7,578
3.453125
3
[ "CC-BY-3.0", "MIT" ]
permissive
--- layout: default title: Priority+ Navigation name: NavPriority description: Mobile navigation is often treated as show / hide only. Usability tests suggest that user experience can be improved by using a priority menu. NavPriority plugin adjust wide navigation to fit the viewport of any device. --- ### Bootstrap Priority Navbar Responsive menu with many items is very challenging to design and code. Priority+ pattern solves problems with much needed space when you really care about multi device usability. If you want to know more about priority+ patterns, let us recommend you great article [Revisiting the priority pattern](http://bradfrost.com/blog/post/revisiting-the-priority-pattern/) by [Brad Frost](https://twitter.com/brad_frost). PriorityNav plugin checks available space and rearranges menu accordingly. When there is not enough space, overflowing items are stored in dropdown menu labelled "More". Plugin lets you customize a few options, so it suits your needs. <div class="sw-example sw-example-resizable" id="navbar-priority-1"> <div class="sw-resizable"> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="collapsed navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-9" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="#" class="navbar-brand">BBC</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-9" data-nav="priority-1"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">UK</a></li> <li><a href="#">World</a></li> <li><a href="#">Sport</a></li> <li><a href="#">Opinion</a></li> <li><a href="#">Culture</a></li> <li><a href="#">Business</a></li> <li><a href="#">Lifestyle</a></li> <li><a href="#">Fashion</a></li> <li><a href="#">Environment</a></li> <li><a href="#">Tech</a></li> <li><a href="#">Travel</a></li> </ul> </div> </div> </nav> </div> </div> ~~~html <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="collapsed navbar-toggle" data-toggle="collapse" data-target="#sw-example-navbar" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="#" class="navbar-brand">BBC</a> </div> <div class="collapse navbar-collapse" id="sw-example-navbar" data-nav="priority"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">UK</a></li> <li><a href="#">World</a></li> <li><a href="#">Sport</a></li> <li><a href="#">Opinion</a></li> <li><a href="#">Culture</a></li> <li><a href="#">Business</a></li> <li><a href="#">Lifestyle</a></li> <li><a href="#">Fashion</a></li> <li><a href="#">Environment</a></li> <li><a href="#">Tech</a></li> <li><a href="#">Travel</a></li> </ul> </div> </div> </nav> ~~~ NavPriority does have just one requirement, it has to be simple `<ul>` list wrapped in a resizable container. The plugin is initialized by calling `window.navPriority('[data-nav="priority-1"]')` with DOM selector as first argument and optional parameters as second argment. ~~~html window.navPriority('[data-nav="priority-1"]') ~~~ ### Custom Priority Navbar NavPriority plugin is not dependant on any framework, however, if you want to used it with your own styles, make sure the navigation container is resizable. <div class="sw-example sw-example-resizable" id="navbar-priority-2"> <div class="sw-resizable"> <nav class="sw-example-menu" data-nav="priority-2"> <ul> <li class="active"><a href="#">Home</a></li> <li><a href="#">UK</a></li> <li><a href="#">World</a></li> <li><a href="#">Sport</a></li> <li><a href="#">Opinion</a></li> <li><a href="#">Culture</a></li> <li><a href="#">Business</a></li> <li><a href="#">Lifestyle</a></li> <li><a href="#">Fashion</a></li> <li><a href="#">Environment</a></li> <li><a href="#">Tech</a></li> <li><a href="#">Travel</a></li> </ul> </nav> </div> </div> ~~~html <nav class="sw-example-menu" data-nav="priority-2"> <ul> <li class="active"><a href="#">Home</a></li> <li><a href="#">UK</a></li> <li><a href="#">World</a></li> <li><a href="#">Sport</a></li> <li><a href="#">Opinion</a></li> <li><a href="#">Culture</a></li> <li><a href="#">Business</a></li> <li><a href="#">Lifestyle</a></li> <li><a href="#">Fashion</a></li> <li><a href="#">Environment</a></li> <li><a href="#">Tech</a></li> <li><a href="#">Travel</a></li> </ul> </nav> ~~~ ### Responsivity In case you want to use different navigation types for different screen sizes, f.e. mobile vs. desktop, you can use small utility BreakpointSwitcher to turn priority nav on / off. Example implementation used in this demo: ~~~html var bs = BreakpointSwitcher.create({ '768px': function(enter) { if (enter) { window.navPriority('[data-nav="priority-1"]', { containerSelector: null, containerWidthOffset: 70, }); window.navPriority('[data-nav="priority-2"]') } else { window.navPriority('[data-nav="priority-1"]', 'destroy'); window.navPriority('[data-nav="priority-2"]', 'destroy'); } } }); ~~~ You need to specify breakpoint, when the navigation is supposed to be enabled or disabled. When the view meets the condition, the navigation is enabled. BreakpointSwitcher uses `window.matchMedia` to test the viewport. You can use `px` or `em` based breakpoints. ### Plugin Options This table gives you a quick overview of NavPriority options. <div class="table-responsive sw-table"> <table class="table table-bordered"> <thead> <tr> <th style="width: 200px">Name</th> <th style="width: 200px">Default</th> <th>Usage</th> </tr> </thead> <tbody> <tr> <td><strong>dropdownLabel</strong></td> <td><code>'More <i class="caret"></i>'</code></td> <td>Change label of the menu to your context.</td> </tr> <tr> <td><strong>dropdownMenuClass</strong></td> <td><code>'dropdown-menu dropdown-menu-right'</code></td> <td>Classes for custom styling of the dropdown menu.</td> </tr> <tr> <td><strong>dropdownMenuTemplate</strong></td> <td><i class="text-muted">see the source</i></td> <td>You can change code of the dropdown menu, but it is not recommended.</td> </tr> <tr> <td><strong>containerWidthOffset</strong></td> <td><code>70</code></td> <td>Offset is substracted from container width.</td> </tr> </tbody> </table> </div>
Java
UTF-8
1,432
2.859375
3
[]
no_license
package lintcode._101_200._115; public class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { // write your code int rows = obstacleGrid.length; if ( rows == 0 ) { return 0; } int cols = obstacleGrid[0].length; int[][] dp = new int[rows][cols]; if ( obstacleGrid[0][0] == 1 ) { dp[0][0] = 0; } else { dp[0][0] = 1; } for (int i = 1; i < cols; i++) { if ( obstacleGrid[0][i] == 1 ) { dp[0][i] = 0; }else { dp[0][i] = dp[0][i-1]; } } for (int i = 1; i < rows; i++) { if ( obstacleGrid[i][0] == 1 ) { dp[i][0] = 0; }else { dp[i][0] = dp[i-1][0]; } } for (int i = 1; i < rows; i++) { for (int j = 1; j < cols; j++) { if ( obstacleGrid[i][j] == 1 ) { dp[i][j] = 0; }else { dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } } return dp[rows-1][cols-1]; // System.out.println(Arrays.deepToString(dp)); } public static void main(String[] args) { Solution solution = new Solution(); int[][] ss = new int[2][2]; solution.uniquePathsWithObstacles(ss); } }
Python
UTF-8
4,314
3.09375
3
[]
no_license
from random import shuffle # import os import player class Blackjack: # Game Vars __fresh_deck = [] __deck = [] __players = [] # Round vars __pot = {} __hands = {} __totals = {} def __init__(self, starting_score): for i in range(1, 14): if i == 1: card = "A" elif i == 11: card = "J" elif i == 12: card = "Q" elif i == 13: card = "K" else: card = i self.__fresh_deck.append(tuple([card, "♠"])) self.__fresh_deck.append(tuple([card, "♣"])) self.__fresh_deck.append(tuple([card, "♥"])) self.__fresh_deck.append(tuple([card, "♦"])) self.shuffle_deck() self.add_player("Dealer", starting_score, True) def remove_player(self, i): del self.__players[i] def remove_hand(self, i): del self.__hands[i] def get_players(self): return self.__players def get_player(self, i): return self.__players[i] def shuffle_deck(self): self.__deck = list(self.__fresh_deck) shuffle(self.__deck) def get_deck(self): return self.__deck def add_player(self, name, starting_score, is_robot=False): self.__players.append(player.Player(name, starting_score, is_robot)) def deal(self, bet): # print("Deck length before: " + str(len(self.__deck))) if len(self.__deck) < 21: # print("Shuffling deck...") self.shuffle_deck() # print("Deck length after: " + str(len(self.__deck))) # os.system("pause") for p in self.__players: if (p.get_score() - bet) < 0: raise ValueError("Not enough chips!") for p in self.__players: p.change_score(-bet) self.__pot[self.__players.index(p)] = bet self.__hands[self.__players.index(p)] = [self.__deck.pop(), self.__deck.pop()] def get_hands(self, get_all=False): helper = {} for key, value in self.__hands.items(): if self.__players[key].is_robot(): if get_all: helper[key] = value else: helper[key] = value[1:] else: helper[key] = value return helper def get_hand(self, i): return self.__hands[i] def get_score(self, h): score = [0] for card in self.__hands[h]: if card[0] in ("J", "Q", "K"): score[0] += 10 if len(score) == 2: score[1] += 10 if score[1] > 21: del score[1] elif card[0] == "A": if len(score) == 1: if (score[0] + 11) <= 21: score.append(score[0]+11) else: if (score[1] + 11) <= 21: score[1] += 11 elif (score[1] + 1) <= 21: score[1] += 1 else: del score[1] score[0] += 1 else: score[0] += card[0] if len(score) == 2: score[1] += card[0] if score[1] > 21: del score[1] return score def hit(self, h): if len(self.__deck) == 0: self.shuffle_deck() self.__hands[h].append(self.__deck.pop()) if self.get_score(h)[0] > 21: return True else: return False def robo(self, h): while True: score = self.get_score(h) # print(self.__players[h].get_name()) # print(score) if len(score) == 2: if score[1] <= 16: self.hit(h) else: break elif score[0] <= 16: self.hit(h) else: break if self.get_score(h)[0] > 21: return True else: return False def double_down(self, idx): if ((self.__players[idx].get_score() - (self.__pot[idx])) < 0) or ((self.__players[0].get_score() - (self.__pot[idx])) < 0): raise ValueError("Not enough chips!") self.__players[idx].change_score(-(self.__pot[idx]*2)) self.__players[0].change_score(-(self.__pot[idx] * 2)) self.__pot[0] += self.__pot[idx] self.__pot[idx] *= 2 def check_winner(self): winner = [[0], 0] for idx in self.__hands.keys(): score = self.get_score(idx) if (len(score) == 2) and (score[1] <= 21): if score[1] == winner[1]: winner[0].append(idx) elif winner[1] < score[1]: winner[1] = score[1] winner[0] = [idx] elif score[0] <= 21: if score[0] == winner[1]: winner[0].append(idx) elif winner[1] < score[0]: winner[1] = score[0] winner[0] = [idx] total = 0 for chips in self.__pot.values(): total += chips if len(winner[0]) > 1: total = total/len(winner[0]) for w in winner[0]: self.__players[w].change_score(round(total, 2)) else: self.__players[winner[0][0]].change_score(round(total, 2)) self.__pot = {} return {'winner': winner[0], 'score': winner[1], 'total': round(total, 2)}
Python
UTF-8
937
2.984375
3
[]
no_license
__author__ = 'Kirby' if __name__ == "__main__": fr = open("A-large.in", "r") fw = open("so2.out", "w") T = int(fr.readline()) for i in range(1, T+1): [Smax, S_vec] = fr.readline().split() Smax = int(Smax) S_vec = map(int, list(S_vec)) # General Algorithm: # Friends = 0 # Scan the list accumulating the number of people at each shyness level until 0 people are at a level. # If the accumulator <= index, friends and accumulator += index - accumulator + 1. Continue scanning. friends = 0 accumulator = 0 for level in range(0, Smax+1): if S_vec[level] == 0 and accumulator <= level: incr = level - accumulator + 1 friends += incr accumulator += incr else: accumulator += S_vec[level] fw.write("Case #{0}: {1}\n".format(i, friends))
PHP
UTF-8
2,544
3.734375
4
[]
no_license
<?php function z1($a){ if ($a >= 0 && $a <= 100){ echo "liczba $a znajduje sie w przedziale 0-100 <br>"; } else { echo "liczba $a poza przedzialem <br>"; } } function z2($a){ if (($a >= 0 && $a <= 100) || ($a >= 200 && $a <= 1000)){ echo "liczba $a znajduje sie w przedziale 0-100 lub 200-1000 <br>"; } else { echo "liczba $a jest poza przedzialem <br>"; } } function z3($a, $b){ if ($b != 0 ){ $dzielenie = $a / $b; echo "wynik dzielenia to: $dzielenie <br>"; } else echo "nie dziel przez $b <br>"; } function z4($a, $b, $c){ $odejmowanie = $b - $c; if ($odejmowanie != 0 ){ $dzielenie = $a / $odejmowanie; echo "wynik dzialania to: $dzielenie <br>"; } else echo "nie dziel przez $odejmowanie <br>"; } function z5($a){ if ($a < 0) { $a *= -1; if ($a >= 0 && $a <= 10) echo "wartosc bezwgledna jest z zakresu 0-10<br>"; else echo "nie jest z zakresu 0-10<br>"; } } function z6($a, $b){ $suma = $a + $b; if ($suma > 100) echo "suma jest wieksza od 100<br>"; else echo "suma mniejsza od 100 <br>"; } function z7($a){ if ($a < 0){ $a *= -1; echo "wartosc bezwzgledna to $a <br>"; } else echo "wartosc bezwzgledna to $a<br>"; } function z8($a){ if ($a > -10 && $a < 10){ if ($a < 0){ $a *= -1; echo "wartosc bezwzgledna to $a <br>"; } else echo "wartosc bezwzgledna to $a<br>"; } else echo "liczba poza przedzialem<br>"; } function z9($a){ if ($a == 10 || $a == 20 || $a == 30){ echo "wartosc to 10, 20 lub 30 <br>"; } else echo "zla wartosc <br>"; } function z10($a){ if ($a % 2 == 0) echo "liczba $a jest podzielna przez 2<br>"; else echo "liczba $a nie jest podzielna przez 2<br>"; } z1(5); z2(150); z3(120,17); z4(10,6,4); z5(-8); z6(100,5); z7(-19); z8(80); z9(20); z10(443); ?>
Markdown
UTF-8
3,810
2.578125
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: Connect CEF data to Azure Sentinel Preview| Microsoft Docs description: Learn how to connect CEF data to Azure Sentinel. services: sentinel documentationcenter: na author: yelevin manager: rkarlin editor: '' ms.service: azure-sentinel ms.subservice: azure-sentinel ms.devlang: na ms.topic: conceptual ms.tgt_pltfrm: na ms.workload: na ms.date: 11/26/2019 ms.author: yelevin --- # Connect your external solution using Common Event Format When you connect an external solution that sends CEF messages, there are three steps to connecting with Azure Sentinel: STEP 1: [Connect CEF by deploying the agent](connect-cef-agent.md) STEP 2: [Perform solution-specific steps](connect-cef-solution-config.md) STEP 3: [Verify connectivity](connect-cef-verify.md) This article describes how the connection works, provides prerequisites and gives you the steps for deploying the agent on security solutions that send Common Event Format (CEF) messages on top of Syslog. > [!NOTE] > Data is stored in the geographic location of the workspace on which you are running Azure Sentinel. In order to make this connection, you need to deploy an agent on a dedicated Linux machine (VM or on premises) to support the communication between the appliance and Azure Sentinel. The following diagram describes the setup in the event of a Linux VM in Azure. ![CEF in Azure](./media/connect-cef/cef-syslog-azure.png) Alternatively, this setup will exist if you use a VM in another cloud, or an on-premises machine. ![CEF on premises](./media/connect-cef/cef-syslog-onprem.png) ## Security considerations Make sure to configure the machine's security according to your organization's security policy. For example, you can configure your network to align with your corporate network security policy and change the ports and protocols in the daemon to align with your requirements. You can use the following instructions to improve your machine security configuration:  [Secure VM in Azure](../virtual-machines/linux/security-policy.md), [Best practices for Network security](../security/fundamentals/network-best-practices.md). To use TLS communication between the security solution and the Syslog machine, you will need to configure the Syslog daemon (rsyslog or syslog-ng) to communicate in TLS: [Encrypting Syslog Traffic with TLS -rsyslog](https://www.rsyslog.com/doc/v8-stable/tutorials/tls_cert_summary.html), [Encrypting log messages with TLS –syslog-ng](https://support.oneidentity.com/technical-documents/syslog-ng-open-source-edition/3.22/administration-guide/60#TOPIC-1209298). ## Prerequisites Make sure the Linux machine you use as a proxy is running one of the following operating systems: - 64-bit - CentOS 6 and 7 - Amazon Linux 2017.09 - Oracle Linux 6 and 7 - Red Hat Enterprise Linux Server 6 and 7 - Debian GNU/Linux 8 and 9 - Ubuntu Linux 14.04 LTS, 16.04 LTS and 18.04 LTS - SUSE Linux Enterprise Server 12 - 32-bit - CentOS 6 - Oracle Linux 6 - Red Hat Enterprise Linux Server 6 - Debian GNU/Linux 8 and 9 - Ubuntu Linux 14.04 LTS and 16.04 LTS - Daemon versions - Syslog-ng: 2.1 - 3.22.1 - Rsyslog: v8 - Syslog RFCs supported - Syslog RFC 3164 - Syslog RFC 5424 Make sure your machine also meets the following requirements: - Permissions - You must have elevated permissions (sudo) on your machine. - Software requirements - Make sure you have Python running on your machine ## Next steps In this document, you learned how to connect CEF appliances to Azure Sentinel. To learn more about Azure Sentinel, see the following articles: - Learn how to [get visibility into your data, and potential threats](quickstart-get-visibility.md). - Get started [detecting threats with Azure Sentinel](tutorial-detect-threats.md).
Java
UTF-8
1,152
2.078125
2
[]
no_license
package com.codegym.services.impl; import com.codegym.models.Payment; import com.codegym.repositories.PaymentRepository; import com.codegym.services.PaymentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class PaymentServiceImpl implements PaymentService { @Autowired private PaymentRepository paymentRepository; @Override public Iterable<Payment> findAll() { return paymentRepository.findAll(); } @Override public Iterable<Payment> findAllByStatus(String status) { return paymentRepository.findAllByStatus(status); } @Override public Optional<Payment> findById(Long id) { return paymentRepository.findById(id); } @Override public List<Payment> findAllByUserId(Long id) { return paymentRepository.findAllByUserId(id); } @Override public void save(Payment payment) { paymentRepository.save(payment); } @Override public void remove(Long id) { paymentRepository.deleteById(id); } }
Java
UTF-8
608
2.46875
2
[]
no_license
package com.quickblox.task; import com.quickblox.task.http.HttpServerFuture; public class Main { public static void main(String[] args) { Server serverFuture = new HttpServerFuture(); if (args.length == 2 && args[0].equals("-p")) { try { serverFuture.setPort(Integer.parseInt(args[1])); } catch (NumberFormatException e) { System.out.println("Incorrect param please try again.."); } } else { System.out.println("Incorrect param please try again.."); } serverFuture.run(); } }
Python
UTF-8
3,831
2.734375
3
[ "SunPro", "BSD-2-Clause", "MIT" ]
permissive
import functools import textwrap from typing import Any from typing import Callable from typing import Optional from typing import TYPE_CHECKING from typing import TypeVar import warnings from optuna.exceptions import ExperimentalWarning if TYPE_CHECKING: from typing_extensions import ParamSpec FT = TypeVar("FT") FP = ParamSpec("FP") CT = TypeVar("CT") _EXPERIMENTAL_NOTE_TEMPLATE = """ .. note:: Added in v{ver} as an experimental feature. The interface may change in newer versions without prior notice. See https://github.com/optuna/optuna/releases/tag/v{ver}. """ def _validate_version(version: str) -> None: if not isinstance(version, str) or len(version.split(".")) != 3: raise ValueError( "Invalid version specification. Must follow `x.y.z` format but `{}` is given".format( version ) ) def _get_docstring_indent(docstring: str) -> str: return docstring.split("\n")[-1] if "\n" in docstring else "" def experimental_func( version: str, name: Optional[str] = None, ) -> "Callable[[Callable[FP, FT]], Callable[FP, FT]]": """Decorate function as experimental. Args: version: The first version that supports the target feature. name: The name of the feature. Defaults to the function name. Optional. """ _validate_version(version) def decorator(func: "Callable[FP, FT]") -> "Callable[FP, FT]": if func.__doc__ is None: func.__doc__ = "" note = _EXPERIMENTAL_NOTE_TEMPLATE.format(ver=version) indent = _get_docstring_indent(func.__doc__) func.__doc__ = func.__doc__.strip() + textwrap.indent(note, indent) + indent @functools.wraps(func) def wrapper(*args: Any, **kwargs: Any) -> "FT": warnings.warn( "{} is experimental (supported from v{}). " "The interface can change in the future.".format( name if name is not None else func.__name__, version ), ExperimentalWarning, stacklevel=2, ) return func(*args, **kwargs) return wrapper return decorator def experimental_class( version: str, name: Optional[str] = None, ) -> "Callable[[CT], CT]": """Decorate class as experimental. Args: version: The first version that supports the target feature. name: The name of the feature. Defaults to the class name. Optional. """ _validate_version(version) def decorator(cls: "CT") -> "CT": def wrapper(cls: "CT") -> "CT": """Decorates a class as experimental. This decorator is supposed to be applied to the experimental class. """ _original_init = getattr(cls, "__init__") _original_name = getattr(cls, "__name__") @functools.wraps(_original_init) def wrapped_init(self: Any, *args: Any, **kwargs: Any) -> None: warnings.warn( "{} is experimental (supported from v{}). " "The interface can change in the future.".format( name if name is not None else _original_name, version ), ExperimentalWarning, stacklevel=2, ) _original_init(self, *args, **kwargs) setattr(cls, "__init__", wrapped_init) if cls.__doc__ is None: cls.__doc__ = "" note = _EXPERIMENTAL_NOTE_TEMPLATE.format(ver=version) indent = _get_docstring_indent(cls.__doc__) cls.__doc__ = cls.__doc__.strip() + textwrap.indent(note, indent) + indent return cls return wrapper(cls) return decorator
Python
UTF-8
4,170
2.921875
3
[]
no_license
import numpy as np import shared import math """ Function to run problem one solution and generate the heat maps. @param article_path: path to articles file @param label_path: path to mapping of articles to groups @param groups_path: path to file mapping of group ids to names @param output_path: output perfix for heatmaps """ def main(article_path="./Data/data50.csv", label_path="./Data/label.csv", groups_path="./Data/groups.csv", output_path="./Heatmap"): shared.setup(article_path, label_path, groups_path) group_list = list(shared.group_id_to_articles.keys()) group_names = [shared.group_id_to_name[gid] for gid in group_list] num_groups = len(group_list) jacc_similarity_vals = np.zeros((num_groups, num_groups)) l2_similarity_vals = np.zeros((num_groups, num_groups)) cos_similarity_vals = np.zeros((num_groups, num_groups)) print("Comparing groupings") # Leverage symmetric property of underlying similarity functions for a runtime optimization to avoid unnecessary iterations for ind in range(num_groups): for ind_two in range(ind, num_groups): num_completed_iters = ind end_val = num_groups - (num_completed_iters - 1) current_iters = (ind_two + 1) - ind print("\tComparing group {0} of 210".format(int((num_completed_iters * (num_groups + end_val)/2) + current_iters))) jacc_similarity, l2_similarity, cos_similarity = similarity(shared.group_id_to_articles[group_list[ind]], shared.group_id_to_articles[group_list[ind_two]]) jacc_similarity_vals[ind, ind_two] = jacc_similarity l2_similarity_vals[ind, ind_two] = l2_similarity cos_similarity_vals[ind, ind_two] = cos_similarity # set inverse values jacc_similarity_vals[ind_two, ind] = jacc_similarity l2_similarity_vals[ind_two, ind] = l2_similarity cos_similarity_vals[ind_two, ind] = cos_similarity print("Plotting Jaccard heatmap") shared.makeHeatMap(jacc_similarity_vals, group_names, output_path, "Jaccard") print("Plotting L2 heatmap") shared.makeHeatMap(l2_similarity_vals, group_names, output_path, "L2", round='%.1f') print("Plotting Cosine heatmap") shared.makeHeatMap(cos_similarity_vals, group_names, output_path, "Cosine") print("Completed plotting") """ Function to generate similarity metrics between two article groups. @param article_list_one: Articles from one group to compare @param article_list_two: Articles from another group to compare the first list to @return: Returns a three-tuple of averaged similarities for all three similarity metrics, across all articles in each group. """ def similarity(article_list_one, article_list_two): counter = 0 jaccard = 0.0 l2 = 0.0 cos = 0.0 for article_one in article_list_one: for article_two in article_list_two: if (article_one.id == article_two.id and article_one.group_id == article_two.group_id): continue jacc_min_sum = 0.0 jacc_max_sum = 0.0 l2_diff_sum = 0.0 cos_prod_sum = 0.0 cos_x_sum = 0.0 cos_y_sum = 0.0 for word in set(article_one.word_counts.keys()).union(set(article_two.word_counts.keys())): xi = article_one.get_count(word) yi = article_two.get_count(word) # Jaccard summation jacc_min_sum += min(xi, yi) jacc_max_sum += max(xi, yi) # L2 summation l2_diff_sum += math.pow((xi-yi), 2) # Cosine summation cos_prod_sum += xi * yi cos_x_sum += math.pow(xi, 2) cos_y_sum += math.pow(yi, 2) # compute jaccard jaccard += jacc_min_sum/jacc_max_sum # compute l2 l2 += math.sqrt(l2_diff_sum) * -1.0 # compute cosine cos += cos_prod_sum / (math.sqrt(cos_x_sum) * math.sqrt(cos_y_sum)) counter += 1 return jaccard/counter, l2/counter, cos/counter if __name__ == '__main__': main()
SQL
UTF-8
8,955
3.359375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version phpStudy 2014 -- http://www.phpmyadmin.net -- -- 主机: localhost -- 生成日期: 2019 年 02 月 24 日 15:13 -- 服务器版本: 5.5.53 -- PHP 版本: 5.4.45 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- 数据库: `mall` -- -- -------------------------------------------------------- -- -- 表的结构 `admin` -- CREATE TABLE IF NOT EXISTS `admin` ( `admin_id` int(10) NOT NULL AUTO_INCREMENT COMMENT '管理员id', `adminname` varchar(45) NOT NULL COMMENT '管理员姓名', `password` varchar(45) NOT NULL COMMENT '设置密码', `password2` varchar(45) NOT NULL COMMENT '确认密码', PRIMARY KEY (`admin_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ; -- -- 转存表中的数据 `admin` -- INSERT INTO `admin` (`admin_id`, `adminname`, `password`, `password2`) VALUES (1, '尼古拉斯', 'f379eaf3c831b04de153469d1bec345e', 'f379eaf3c831b04de153469d1bec345e'), (2, '小仙女', 'e10adc3949ba59abbe56e057f20f883e', 'e10adc3949ba59abbe56e057f20f883e'), (3, '琳达Linda', 'be13b093d53644bc3b88dc76f278d574', 'be13b093d53644bc3b88dc76f278d574'), (4, '曹操', '202cb962ac59075b964b07152d234b70', '202cb962ac59075b964b07152d234b70'); -- -------------------------------------------------------- -- -- 表的结构 `product` -- CREATE TABLE IF NOT EXISTS `product` ( `product_id` int(10) NOT NULL AUTO_INCREMENT COMMENT '商品id', `productname` varchar(60) NOT NULL COMMENT '商品名称', `introduction` varchar(60) NOT NULL COMMENT '商品简介', `price` float(12,2) NOT NULL COMMENT '价格', `sort_id` int(10) NOT NULL, `image` varchar(60) NOT NULL COMMENT '图片路径', PRIMARY KEY (`product_id`), KEY `sort_id` (`sort_id`), KEY `productname` (`productname`), KEY `price` (`price`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=24 ; -- -- 转存表中的数据 `product` -- INSERT INTO `product` (`product_id`, `productname`, `introduction`, `price`, `sort_id`, `image`) VALUES (2, '格子少女连帽羽绒服', '春季连帽新款,值得这个价!', 30000.98, 1, '格子连帽羽绒服.jpg'), (3, '镂空宽松针织衫', '春季新款', 200.00, 1, '镂空宽松针织衫.jpg'), (4, '米色中长裙', '春季新款', 300.00, 1, '米色中长裙.jpg'), (5, '复古短袖连衣裙', '亚麻褶皱,灰常显瘦', 400.00, 1, '复古短袖连衣裙.jpg'), (6, '白色纯棉男士T恤', '适合男士内搭', 100.00, 1, '白色纯棉男士T恤.jpg'), (7, '飞行员夹克', '加厚棉衣,正品潮牌,还是情侣款哦', 300.00, 1, '飞行员夹克.jpg'), (8, '经典皮夹克', '进口羊皮,经典品质', 1500.00, 1, '经典皮夹克.jpg'), (9, '双面羊绒大衣', '帅气青年的选择', 800.00, 1, '双面羊绒大衣.jpg'), (11, '长筒系带靴', '不过膝盖的平底长筒骑士靴', 200.00, 2, '长筒系带靴.jpg'), (14, '红色拉杆箱', '复古防刮,旅行必备', 300.00, 2, '红色拉杆箱.jpg'), (16, '棕色宽松休闲长袖衬衣外套', '潮流青年的选择', 15000.77, 1, '棕色宽松休闲长袖衬衣外套.jpg'), (17, '自由呼吸2019新款运动服套装女春秋宽松韩版坠感阔腿裤卫衣两件套 粉末蓝 L(女)', '一起享受自由生活', 234.00, 1, '2e4270421560d706.jpg'), (18, '一米阳光很仙的小个子打底连衣裙女2018新款韩版气质大摆红色长裙 枣红色 M', '生机新春热情似火', 3432.00, 1, 'd03876644bef4727.jpg'), (19, '自由呼吸运动服套装女春秋季2019新款韩版连帽阔腿裤休闲装两件套 红色 L', '为了让美丽优雅的你喜欢,简单纯粹也能张扬个性', 3432.00, 1, '1f8d4849358b4021.jpg'), (20, '牛津大学箱包旗舰店 小学生书包', '镇店爆款 减负护脊防水', 199.00, 2, '360截图168409278813790.jpg'), (21, 'UNIVERSITY OF OXFORD多功能多层笔袋铅笔收纳袋 文具盒 X5621 深蓝', '千锤百炼,都拆不散我和你的上学时光', 50.00, 2, '8ba3672fbe104be4.jpg'), (22, '安特丽五色箱包 20英寸', '闪耀品质,时尚五色,轻盈耐用', 399.00, 2, '360截图165405286911496.jpg'), (23, '佐卡伊白18K金钻石吊坠', '手工制作的贵金属材质,可定制', 522678.09, 3, '佐卡伊白18K金钻石吊坠.png'); -- -------------------------------------------------------- -- -- 表的结构 `register` -- CREATE TABLE IF NOT EXISTS `register` ( `id` int(10) NOT NULL AUTO_INCREMENT, `username` varchar(45) NOT NULL, `gender` varchar(15) NOT NULL, `email` varchar(45) NOT NULL, `password` varchar(45) NOT NULL, `password2` varchar(45) NOT NULL, PRIMARY KEY (`id`), KEY `username` (`username`), KEY `username_2` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=19 ; -- -- 转存表中的数据 `register` -- INSERT INTO `register` (`id`, `username`, `gender`, `email`, `password`, `password2`) VALUES (3, '尼古拉斯', '男', '666666@qq.com', 'f379eaf3c831b04de153469d1bec345e', 'f379eaf3c831b04de153469d1bec345e'), (4, '小仙女', '女', '123456@qq.com', 'e10adc3949ba59abbe56e057f20f883e', 'e10adc3949ba59abbe56e057f20f883e'), (5, '小飞龙', '', '', 'd41d8cd98f00b204e9800998ecf8427e', 'd41d8cd98f00b204e9800998ecf8427e'), (6, '', '', '', 'd41d8cd98f00b204e9800998ecf8427e', 'd41d8cd98f00b204e9800998ecf8427e'), (7, '小飞龙', '男', '123', '202cb962ac59075b964b07152d234b70', 'caf1a3dfb505ffed0d024130f58c5cfa'), (8, '阿江', '', '', 'd41d8cd98f00b204e9800998ecf8427e', 'd41d8cd98f00b204e9800998ecf8427e'), (9, '阿江', '女', '393848733@qq.com', '202cb962ac59075b964b07152d234b70', 'caf1a3dfb505ffed0d024130f58c5cfa'), (10, '胡铁花', '男', '4646464@163.com', 'edee198e26c06ab8134917781cb55ca7', '1c44feda75820f0dc6673915a4d27644'), (11, '花蝴蝶', '男', '4646464@163.com', 'edee198e26c06ab8134917781cb55ca7', 'edee198e26c06ab8134917781cb55ca7'), (12, '琳达Linda', '女', '123456777@qq.com', 'be13b093d53644bc3b88dc76f278d574', 'be13b093d53644bc3b88dc76f278d574'), (13, '曹操', '男', '123@qq.com', '202cb962ac59075b964b07152d234b70', '202cb962ac59075b964b07152d234b70'), (14, '狗蛋', '男', '123456@qq.com', 'e10adc3949ba59abbe56e057f20f883e', 'e10adc3949ba59abbe56e057f20f883e'), (15, '小明同学', '男', 'xxxxxx@qq.com', 'dad3a37aa9d50688b5157698acfd7aee', 'dad3a37aa9d50688b5157698acfd7aee'), (16, '石头', '男', 'xxxxxx@qq.com', 'dad3a37aa9d50688b5157698acfd7aee', 'dad3a37aa9d50688b5157698acfd7aee'), (17, 'GG江', 'female', '393848733@qq.com', '25f9e794323b453885f5181f1b624d0b', '25f9e794323b453885f5181f1b624d0b'), (18, '阿江二号', 'female', '123456@qq.com', 'e10adc3949ba59abbe56e057f20f883e', 'e10adc3949ba59abbe56e057f20f883e'); -- -------------------------------------------------------- -- -- 表的结构 `shoppingcart` -- CREATE TABLE IF NOT EXISTS `shoppingcart` ( `cart_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '购物车明细id', `product_id` int(11) NOT NULL COMMENT '商品id', `unitprice` float(12,2) NOT NULL COMMENT '单价', `count` int(45) NOT NULL COMMENT '数量', `username` varchar(45) NOT NULL, PRIMARY KEY (`cart_id`), KEY `unitprice` (`unitprice`), KEY `product_id` (`product_id`), KEY `username` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=17 ; -- -- 转存表中的数据 `shoppingcart` -- INSERT INTO `shoppingcart` (`cart_id`, `product_id`, `unitprice`, `count`, `username`) VALUES (5, 5, 400.00, 5, '尼古拉斯'), (9, 2, 30000.98, 1, '尼古拉斯'), (10, 3, 200.00, 1, '尼古拉斯'), (11, 4, 300.00, 2, '尼古拉斯'), (12, 21, 50.00, 1, 'GG江'), (13, 20, 199.00, 6, '尼古拉斯'), (14, 21, 50.00, 5, '尼古拉斯'), (15, 11, 200.00, 10, '尼古拉斯'), (16, 23, 522678.09, 6, '尼古拉斯'); -- -------------------------------------------------------- -- -- 表的结构 `sort` -- CREATE TABLE IF NOT EXISTS `sort` ( `sort_id` int(10) NOT NULL AUTO_INCREMENT, `sortname` varchar(45) NOT NULL, PRIMARY KEY (`sort_id`), KEY `sort_id` (`sort_id`), KEY `sortname` (`sortname`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ; -- -- 转存表中的数据 `sort` -- INSERT INTO `sort` (`sort_id`, `sortname`) VALUES (6, '图书音像'), (4, '家用电器'), (3, '珠宝手表'), (5, '生鲜水果'), (1, '男装女装'), (2, '鞋靴箱包'); -- -- 限制导出的表 -- -- -- 限制表 `product` -- ALTER TABLE `product` ADD CONSTRAINT `product_ibfk_2` FOREIGN KEY (`sort_id`) REFERENCES `sort` (`sort_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- 限制表 `shoppingcart` -- ALTER TABLE `shoppingcart` ADD CONSTRAINT `shoppingcart_ibfk_4` FOREIGN KEY (`product_id`) REFERENCES `product` (`product_id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `shoppingcart_ibfk_5` FOREIGN KEY (`unitprice`) REFERENCES `product` (`price`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `shoppingcart_ibfk_6` FOREIGN KEY (`username`) REFERENCES `register` (`username`) ON DELETE CASCADE ON UPDATE CASCADE; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
C++
UTF-8
934
3.4375
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; /** * Record and retrieve name and scores. */ int main(){ vector<string> names; vector<int> scores; cout << "Enter name and score separated by space. Stop by entering: \"NoName 0\" \n"; int score; string name; while(cin>>name>>score && name != "NoName"){ names.push_back(name); scores.push_back(score); } // Retrieve score from records. cout << "\nEnter score to retrieve names with that score.\n"; while(cin >> score){ bool found = false; for(int i = 0; i <= scores.size(); i++){ if(score == scores[i]){ cout << names[i] << '\n'; found = true; } } if(!found){ cout << "No one has a score of " << score << '\n'; } } return 0; }
C#
UTF-8
580
2.515625
3
[ "MIT" ]
permissive
using Newtonsoft.Json; using SquidsMovieApp.Data.Utilities.Parsers.Models; using System.Collections.Generic; using System.IO; namespace SquidsMovieApp.Data.Utilities.Parsers { public class Parser { public ICollection<MovieParsedModel> ParseMovies(string path) { return JsonConvert.DeserializeObject<List<MovieParsedModel>>(File.ReadAllText(path)); } public ActorParsedModel ParseParticipantBio(string participant) { return JsonConvert.DeserializeObject<ActorParsedModel>(participant); } } }
Java
UTF-8
2,358
2.59375
3
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
package org.pac4j.oauth.profile.facebook.converter; import org.pac4j.core.profile.converter.AttributeConverter; import org.pac4j.core.util.Pac4jConstants; import org.pac4j.oauth.profile.facebook.FacebookRelationshipStatus; /** * This class converts a String into a FacebookRelationshipStatus. * * @author Jerome Leleu * @since 1.0.0 */ public final class FacebookRelationshipStatusConverter implements AttributeConverter { /** {@inheritDoc} */ @Override public FacebookRelationshipStatus convert(final Object attribute) { if (attribute != null) { if (attribute instanceof String) { var s = ((String) attribute).toLowerCase(); s = s.replaceAll("_", " "); s = s.replaceAll("'", Pac4jConstants.EMPTY_STRING); if ("single".equals(s)) { return FacebookRelationshipStatus.SINGLE; } else if ("in a relationship".equals(s)) { return FacebookRelationshipStatus.IN_A_RELATIONSHIP; } else if ("engaged".equals(s)) { return FacebookRelationshipStatus.ENGAGED; } else if ("married".equals(s)) { return FacebookRelationshipStatus.MARRIED; } else if ("its complicated".equals(s)) { return FacebookRelationshipStatus.ITS_COMPLICATED; } else if ("in an open relationship".equals(s)) { return FacebookRelationshipStatus.IN_AN_OPEN_RELATIONSHIP; } else if ("widowed".equals(s)) { return FacebookRelationshipStatus.WIDOWED; } else if ("separated".equals(s)) { return FacebookRelationshipStatus.SEPARATED; } else if ("divorced".equals(s)) { return FacebookRelationshipStatus.DIVORCED; } else if ("in a civil union".equals(s)) { return FacebookRelationshipStatus.IN_A_CIVIL_UNION; } else if ("in a domestic partnership".equals(s)) { return FacebookRelationshipStatus.IN_A_DOMESTIC_PARTNERSHIP; } } else if (attribute instanceof FacebookRelationshipStatus) { return (FacebookRelationshipStatus) attribute; } } return null; } }
Ruby
UTF-8
2,224
2.890625
3
[]
no_license
require 'nuvi/unzipper' require 'nuvi/zip_downloader' require 'nuvi/zip_index' require 'logger' require 'redis' module Nuvi extend self def start(base_url) # Get the list of zip files from the HTTP directory index = ZipIndex.new(base_url) zip_urls = index.zip_urls logger.debug("Found #{zip_urls.count} zip files") zip_urls.each { |zip| process(zip) } end def process(zip) # Save the zip file to a tmp directory zip_file = downloader.download(zip) # Extract the zip file and get the target directory xml_files_directory = unzipper.unzip(zip_file) xmls = Dir[File.join(xml_files_directory, '*.xml')] # Process file by file and count the new items new_items = xmls.map { |xml_file| process_xml(xml_file) }.compact.inject(:+) logger.info("Added #{new_items} new items to the NEWS_XML list") # Cleanup the zip files FileUtils.rm_rf(xml_files_directory) # Do not delete the zip file. # Since the software has to be run multiple times, and the zip files are # quite large, it is nice to have a local cache. # The ZipDownloader class does nothing when the zip file is already there. # File.delete(zip_file) end # How it works: # The NEWS_XML redis list contains all the XML file contents processed # without duplicates. # To avoid duplicates we mantain a redis set of the file hashes. If the # hash is not in the set, it is added and the file content is added to # the NEWS_XML list. # # Returns true if the news item is a new entry def process_xml(xml_file) hash = File.basename(xml_file, '.xml') # sadd returns true if the element was not in the set if redis.sadd('NEWS_HASHES', hash) content = File.read(xml_file) redis.rpush('NEWS_XML', content) true end end def redis @redis ||= Redis.new(host: redis_host, port: redis_port) end def logger @logger ||= Logger.new(STDOUT) end def downloader @downloader ||= ZipDownloader.new end def unzipper @unzipper ||= Unzipper.new end attr_writer :redis_host, :redis_port def redis_host @redis_host ||= 'localhost' end def redis_port @redis_port ||= 6379 end end
PHP
UTF-8
492
2.546875
3
[]
no_license
<?php class Content { private $blogid; public function __construct($id) { $this->blogid=$id; } // public function getContent() { //sql $sql='select blogsContent from blogs where blogsId=:id'; // $conmand=Yii::app()->db->createCommand($sql); // $conmand->bindParam(':id',$this->blogid); // $result=$conmand->queryScalar(); $url=Yii::app()->request->baseUrl; $newresult=str_ireplace('upload/', $url.'/upload/', $result); return $newresult; } } ?>
TypeScript
UTF-8
1,618
2.671875
3
[]
no_license
import { Message } from "discord.js"; function i18n(key: string, message: Message, ...args: any[]) { return getValue(key, "en", args); } function getValue(key: string, lang: string, args: any[]) { if (lang === "qqx") { console.log(args); if (args.length == 0) { return `(${key})`; } else { let qqx = `(${key}: `; for(let i = 0; i < args.length; i++){ qqx += args[i]; if(i != args.length - 1){ qqx += ", "; } } qqx += ")"; return qqx; } } let langfile = require(`./i18n/${lang}.json`); if (typeof langfile[key] === "undefined") { langfile = require("./i18n/en.json"); if (typeof langfile[key] === "undefined") { return key; } } let value: string = langfile[key]; if (args.length > 0) { for (let i = 0; i < args.length; i++){ value = value.replace(new RegExp(`\\$${i+1}`,"g"), args[i]); } } if (value.includes("{{PLURAL:")){ let found: any = [...value.matchAll(/{{PLURAL:(\d+)\.?\d?\|(.*)}}/g)][0]; found[2] = found[2].split("|"); if(found[2].length === 1){ return value = value.replace(/{{PLURAL:\d+\.?\d?\|.*}}/, found[2][0]); } if(found[1] === "1"){ return value = value.replace(/{{PLURAL:\d+\.?\d?\|.*}}/, found[2][0]); } else{ return value = value.replace(/{{PLURAL:\d+\.?\d?\|.*}}/, found[2][1]); } } return value; } export { i18n };
Markdown
UTF-8
1,567
2.640625
3
[]
no_license
# TilerService Docker A dockerized image of the [TilerService](https://github.com/maritime-web/TilerService). ## Prerequisites * Docker * A file called application.properties * A license key for MapTiler Pro ## Configuration The application.properties file must at least contain the following lines: mapTiler.license = <license key for MapTiler Pro> mapTiler.arguments = <arguments for MapTiler Pro> tiles.hostDirectory = <the absolute path to the directory where images to be tiled are stored> The variable `tracing` can be set to `false` to disable detailed tracing. It is by default set to `true`. ## Execution Before you run the container you must pull the image for the [MapTiler Pro container](https://hub.docker.com/r/klokantech/maptiler/), [TileServer](https://hub.docker.com/r/klokantech/tileserver-php/) and [Satellite Consumer](https://github.com/maritime-web/Satellite-Consumer): docker pull klokantech/maptiler docker pull klokantech/tileserver-php docker pull dmadk/satellite-consumer:latest docker pull dmadk/satellite-consumer:newest To run the container you can do it the following way: docker run --name tiler-service -v /var/run/docker.sock:/var/run/docker.sock \ -v $HOME/data:/data/tiles \ -v <where you stored application.properties>/application.properties:/data/properties/application.properties \ dmadk/tiler-service The reason why the container needs to mount the Docker socket is because it needs to be able to start MapTiler Pro and the satellite image consumer in seperate containers.
Python
UTF-8
558
2.859375
3
[ "MIT" ]
permissive
import tensorflow as tf from PIL import Image import numpy as np def process_image(image_path): #open image from path dir and convert it to numpy array im = Image.open(image_path) image = np.asarray(im) #pre-procesing image and normalize it image_size = 224 image = tf.convert_to_tensor(image) image = tf.cast(image, tf.float32) image = tf.image.resize(image, (image_size, image_size)) image /= 255 image = image.numpy() #add dimension image = np.expand_dims(image, axis = 0) return image
JavaScript
UTF-8
826
2.53125
3
[]
no_license
const Koa = require("koa"); const app = new Koa(); const Route = require("koa-router"); const route = new Route(); const redis = require("redis"); const client = redis.createClient(6999, "127.0.0.1"); // 客户端实例 app.use(async (ctx) => { const start = new Date().getTime(); const questPromise = new Promise((resolve, reject) => { client.get("hello", function (err, data) { // 加 1 存进去 client.set("hello", Number(data) + 1, function (err, obj) { resolve(Number(data) + 1); }); }); }); const counts = await questPromise.then((args) => { return args; }); const end = new Date().getTime(); ctx.body = "当前访问次数:" + counts + ",本次访问用时:" + (end - start) + "ms,时间:" + new Date(); }); app.listen(8089);
Java
UTF-8
3,325
2.453125
2
[ "Apache-2.0" ]
permissive
package Tables; import java.sql.SQLException; import java.util.ArrayList; import classes.Ability; /* * @author Nikola Corkovic - cnik996@gmail.com * @version beta 1.0 */ public class NapadiDBL { static int duzinaListeImenaNapada = 5; //Broj napada ne prelazi 5 static ArrayList<String> ListaImenaNapada = new ArrayList<String>(duzinaListeImenaNapada); public static Ability pullNapadiV2 (String izabranoImeNapada, int idNinje) throws SQLException { String imeNapada = izabranoImeNapada; // int redniBroj = izabraniRedniBrojNinje; kad vratis objekat prilepi //int idNinje = Main.fight.getTeam().get_ninjas().get(redniBroj).getIdNinje(); //int redniBrojAbility = izabraniAbility; Ability abil = new Ability(); while (ConnectionDBL.rs.next()) { if (ConnectionDBL.rs.getInt(34) == (idNinje)) { if (ConnectionDBL.rs.getString(2).equals(imeNapada)) { abil.setName(ConnectionDBL.rs.getString(2)); abil.setTaijutsu(ConnectionDBL.rs.getDouble(3)); abil.setNinjutsu(ConnectionDBL.rs.getDouble(4)); abil.setBukijutsu(ConnectionDBL.rs.getDouble(5)); abil.setElement(ConnectionDBL.rs.getDouble(6)); abil.setGen(ConnectionDBL.rs.getDouble(7)); abil.setStamina(ConnectionDBL.rs.getDouble(8)); abil.setAttack(ConnectionDBL.rs.getDouble(9)); abil.setBukiRec(ConnectionDBL.rs.getDouble(10)); abil.setBukiBoost(ConnectionDBL.rs.getDouble(11)); abil.setCritChance(ConnectionDBL.rs.getDouble(12)); abil.setCritStrike(ConnectionDBL.rs.getDouble(13)); abil.setReroll(ConnectionDBL.rs.getDouble(14)); abil.setEndurance(ConnectionDBL.rs.getDouble(15)); abil.setFatigue(ConnectionDBL.rs.getDouble(16)); abil.setTaiImmunity(ConnectionDBL.rs.getDouble(17)); abil.setNinImmunity(ConnectionDBL.rs.getDouble(18)); abil.setBukiImmunity(ConnectionDBL.rs.getDouble(19)); abil.setAttackImmunity(ConnectionDBL.rs.getDouble(20)); abil.setGenImmunity(ConnectionDBL.rs.getDouble(21)); abil.setPoisonImmunity(ConnectionDBL.rs.getDouble(22)); abil.setPoison(ConnectionDBL.rs.getDouble(23)); abil.setGuard(ConnectionDBL.rs.getDouble(24)); abil.setAbsorb(ConnectionDBL.rs.getDouble(25)); abil.setLvl5Death(ConnectionDBL.rs.getDouble(26)); abil.setGenAct(ConnectionDBL.rs.getDouble(28)); abil.setGenMast(ConnectionDBL.rs.getDouble(29)); abil.setGenRec(ConnectionDBL.rs.getDouble(30)); abil.setGenAbs(ConnectionDBL.rs.getDouble(31)); abil.setGenLearn(ConnectionDBL.rs.getDouble(32)); abil.setGenCopy(ConnectionDBL.rs.getDouble(33)); } } } return abil; } public static void insertAbilityNamesIntoArray (int izabraniNinja) throws SQLException { //int izabranNinja = izabraniNinja; //int idNinje2 = Main.fight.getTeam().get_ninjas().get(izabranNinja).getIdNinje(); int indeks = 0; while (ConnectionDBL.rs.next()) { if (ConnectionDBL.rs.getInt(34) == (izabraniNinja)) { ListaImenaNapada.add(indeks,ConnectionDBL.rs.getString(2)); indeks++; } } } /** * @return listaImenaNapada */ public static ArrayList<String> getListaImenaNapada() { return ListaImenaNapada; } /** * @param listaImenaNapada set */ public static void setListaImenaNapada(ArrayList<String> listaImenaNapada) { ListaImenaNapada = listaImenaNapada; } }
Java
UTF-8
3,665
2.171875
2
[]
no_license
package me.weekbelt.naverreservation.web.controller; import com.fasterxml.jackson.databind.ObjectMapper; import me.weekbelt.naverreservation.web.dto.display.DisplayInfoResponse; import me.weekbelt.naverreservation.web.dto.product.ProductDto; import me.weekbelt.naverreservation.web.dto.product.ProductResponse; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import java.nio.charset.Charset; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @SpringBootTest @AutoConfigureMockMvc class ProductApiControllerTest { @Autowired MockMvc mockMvc; @Autowired ObjectMapper objectMapper; @DisplayName("전시 상품 목록을 4개씩 두번째 페이지 조회") @Test void getProducts() throws Exception { String requestUri = "/api/products"; MvcResult mvcResult = mockMvc.perform(get(requestUri) .param("categoryId", "1") .param("start", "4")) .andDo(print()) .andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); String content = response.getContentAsString(Charset.defaultCharset()); ProductResponse productResponse = objectMapper.readValue(content, ProductResponse.class); assertThat(productResponse.getTotalCount()).isEqualTo(10); List<ProductDto> items = productResponse.getItems(); assertThat(items.size()).isEqualTo(4); assertThat(items.get(0).getDisplayInfoId()).isEqualTo(5); assertThat(items.get(0).getProductId()).isEqualTo(5); assertThat(items.get(1).getDisplayInfoId()).isEqualTo(6); assertThat(items.get(1).getProductId()).isEqualTo(6); assertThat(items.get(2).getDisplayInfoId()).isEqualTo(7); assertThat(items.get(2).getProductId()).isEqualTo(7); assertThat(items.get(3).getDisplayInfoId()).isEqualTo(8); assertThat(items.get(3).getProductId()).isEqualTo(8); } @DisplayName("상품 상세 정보 조회") @Test void getProduct() throws Exception { String requestUri = "/api/products/{displayInfoId}"; Long displayInfoId = 1L; MvcResult mvcResult = mockMvc.perform(get(requestUri, displayInfoId)) .andDo(print()) .andExpect(jsonPath("displayInfo").exists()) .andExpect(jsonPath("productImages").exists()) .andExpect(jsonPath("displayInfoImage").exists()) .andExpect(jsonPath("comments").exists()) .andExpect(jsonPath("averageScore").exists()) .andExpect(jsonPath("productPrices").exists()) .andReturn(); String content = mvcResult.getResponse().getContentAsString(Charset.defaultCharset()); DisplayInfoResponse displayInfoResponse = objectMapper.readValue(content, DisplayInfoResponse.class); assertThat(displayInfoResponse.getDisplayInfo().getDisplayInfoId()) .isEqualTo(displayInfoId); } }
Java
UTF-8
6,510
2.84375
3
[]
no_license
import java.io.*; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; public class ServerThread implements Runnable { private final String hash; private final int stringLength; private final int port; private byte nextDiapason = 0; public ServerThread(int port, String hash, int stringLength) { this.hash = hash; this.stringLength = stringLength; this.port = port; } @Override public void run() { try (ServerSocket serverSocket = new ServerSocket(port)) { System.out.println("Server starting in " + port + " port."); HashMap<InetAddress, ArrayList<DiapasonInfo>> clients = new HashMap<>(); while (true) { Socket socket = serverSocket.accept(); try (InputStream inputStream = socket.getInputStream(); DataInputStream dataInputStream = new DataInputStream(inputStream); OutputStream outputStream = socket.getOutputStream()) { while (true) { int size = dataInputStream.readInt(); int type = inputStream.read(); System.out.println("type:" + type); switch (type) { case Protocol.FIST_REQUEST_TYPE: outputStream.write(createMessageWithHash()); break; case Protocol.DIAPASON_REQUEST_TYPE: ArrayList<DiapasonInfo> array = clients.get(socket.getInetAddress()); if(nextDiapason != Protocol.LAST_DIAPASON + 1) if (array == null) { array = new ArrayList<>(); array.add(new DiapasonInfo(nextDiapason)); clients.put(socket.getInetAddress(), array); } else { array.add(new DiapasonInfo(nextDiapason)); } outputStream.write(createMessageWithDiapason()); break; case Protocol.RESULT_TYPE: ArrayList<DiapasonInfo> diapasons = clients.get(socket.getInetAddress()); DiapasonInfo info = diapasons.get(diapasons.size() - 1); int count = dataInputStream.readInt(); byte[] result = new byte[size - Protocol.INT_SIZE]; inputStream.read(result); if (count != 0) { info.setResults(getStringArrayListFromResult(count, result)); } } printClientList(clients); } } catch (EOFException | UnknownProtocolException ignored) { } } } catch (IOException e) { e.printStackTrace(); } } private void printClientList(HashMap<InetAddress, ArrayList<DiapasonInfo>> clients) { for (InetAddress inetAddress : clients.keySet()) { System.out.println(inetAddress + ":"); for (DiapasonInfo diapasonInfo : clients.get(inetAddress)) { System.out.print("\t" + diapasonInfo.getDiapason() + ": "); if (diapasonInfo.getResults() != null) { for (String s : diapasonInfo.getResults()) { System.out.print(s + " "); } System.out.println(); } else { System.out.println("null"); } } } } private ArrayList<String> getStringArrayListFromResult(int count, byte[] result) throws UnknownProtocolException { ArrayList<String> strings = new ArrayList<>(count); int byteInString = (stringLength / 4) + 1; String tmpStr = ""; String str = ""; int bigPart = stringLength / 4; int symbolsInSmallPart = stringLength % 4; for (int s = 0; s < count; s++) { for (int k = 0; k < bigPart; k++) { for (int j = 0; j < 4; j++) { byte b = (byte) ((result[k + s*byteInString] >> j * 2) & 3); tmpStr += Protocol.byteToChar(b); } str += (new StringBuilder(tmpStr).reverse().toString()); tmpStr = ""; } for (int i = 0; i < symbolsInSmallPart; i++) { byte b = (byte) ((result[bigPart] >> i * 2) & 3); tmpStr += Protocol.byteToChar(b); } str += (new StringBuilder(tmpStr).reverse().toString()); tmpStr = ""; strings.add(str); str = ""; } for (String string : strings) { System.out.println("strings: " + string); } return strings; } private byte[] createMessageWithDiapason() { if (nextDiapason != Protocol.LAST_DIAPASON) { ByteBuffer byteMessageBuffer = ByteBuffer.allocate(Protocol.BUF_SIZE); byteMessageBuffer.putInt(1); byteMessageBuffer.put(Protocol.NEW_DIAPASON_TYPE); byteMessageBuffer.put(nextDiapason); nextDiapason++; return Arrays.copyOf(byteMessageBuffer.array(), Protocol.PREFIX_SIZE + 1); } else { ByteBuffer byteMessageBuffer = ByteBuffer.allocate(Protocol.BUF_SIZE); byteMessageBuffer.putInt(0); byteMessageBuffer.put(Protocol.DIAPASONS_ENDED_TYPE); return Arrays.copyOf(byteMessageBuffer.array(), Protocol.PREFIX_SIZE); } } private byte[] createMessageWithHash() { ByteBuffer byteMessageBuffer = ByteBuffer.allocate(Protocol.BUF_SIZE); int size = Protocol.INT_SIZE + hash.getBytes().length; byteMessageBuffer.putInt(size); byteMessageBuffer.put(Protocol.HASH_ANSWER_TYPE); byteMessageBuffer.putInt(stringLength); byteMessageBuffer.put(hash.getBytes()); return Arrays.copyOf(byteMessageBuffer.array(), Protocol.PREFIX_SIZE + size); } }
Python
UTF-8
4,653
2.828125
3
[ "MIT" ]
permissive
import types try: import unittest2 as unittest except ImportError: import unittest from marnadi.utils import Lazy try: str = unicode except NameError: pass _test_tuple = ('foo', 'bar') _test_list = ['foo', 'bar'] _test_set = set(_test_tuple) _test_dict = {'foo': 'bar'} _test_str = 'foo' _test_bytes = b'foo' _test_true = True _test_false = False def _test_function(*args, **kwargs): return args, kwargs class _TestClass: pass _test_instance = _TestClass() class LazyTestCase(unittest.TestCase): def test_lazy_true(self): lazy_true = Lazy('%s._test_true' % __name__) self.assertTrue(lazy_true) def test_lazy_false(self): lazy_true = Lazy('%s._test_false' % __name__) self.assertFalse(lazy_true) def test_lazy_tuple(self): lazy_tuple = Lazy('%s._test_tuple' % __name__) self.assertTupleEqual(_test_tuple, tuple(lazy_tuple)) def test_length_of_lazy_tuple(self): lazy_tuple = Lazy('%s._test_tuple' % __name__) self.assertEqual(2, len(lazy_tuple)) def test_lazy_list(self): lazy_list = Lazy('%s._test_list' % __name__) self.assertListEqual(_test_list, list(lazy_list)) def test_lazy_set(self): lazy_set = Lazy('%s._test_set' % __name__) self.assertSetEqual(_test_set, set(lazy_set)) def test_lazy_dict(self): lazy_dict = Lazy('%s._test_dict' % __name__) self.assertDictEqual(_test_dict, dict(lazy_dict)) def test_lazy_str(self): lazy_str = Lazy('%s._test_str' % __name__) self.assertEqual(_test_str, str(lazy_str)) def test_lazy_bytes(self): lazy_bytes = Lazy('%s._test_bytes' % __name__) self.assertEqual(_test_bytes, bytes(lazy_bytes)) def test_lazy_isinstance(self): lazy_instance = Lazy('%s._test_instance' % __name__) self.assertIsInstance(lazy_instance, _TestClass) def test_lazy_class_instance(self): lazy_class = Lazy('%s._TestClass' % __name__) self.assertIsInstance(lazy_class(), _TestClass) def test_lazy_function__no_args(self): lazy_function = Lazy('%s._test_function' % __name__) self.assertEqual(lazy_function(), ((), {})) def test_lazy_function__args(self): lazy_function = Lazy('%s._test_function' % __name__) self.assertEqual( lazy_function('foo', 'bar'), (('foo', 'bar'), {}), ) def test_lazy_function__kwargs(self): lazy_function = Lazy('%s._test_function' % __name__) self.assertEqual( lazy_function(foo='bar'), ((), {'foo': 'bar'}), ) def test_lazy_function__args_kwargs(self): lazy_function = Lazy('%s._test_function' % __name__) self.assertEqual( lazy_function('foo', 'bar', foo='bar'), (('foo', 'bar'), {'foo': 'bar'}), ) def test_lazy__explicit_class(self): self.assertIs(_TestClass, Lazy(_TestClass)) def test_lazy__explicit_function(self): self.assertIs(_test_function, Lazy(_test_function)) def test_lazy__explicit_instance(self): self.assertIs(Lazy(_test_instance), _test_instance) def test_lazy__explicit_dict(self): self.assertIs(_test_dict, Lazy(_test_dict)) def test_lazy__explicit_list(self): self.assertIs(_test_list, Lazy(_test_list)) def test_lazy__explicit_tuple(self): self.assertIs(_test_tuple, Lazy(_test_tuple)) def test_lazy__explicit_set(self): self.assertIs(_test_set, Lazy(_test_set)) def test_lazy__explicit_none(self): self.assertIsNone(Lazy(None)) def test_lazy__explicit_lazy(self): lazy = Lazy('%s._test_instance' % __name__) self.assertIs(lazy, Lazy(lazy)) def test_lazy__explicit_lazy_str(self): lazy_str = Lazy('%s._test_str' % __name__) self.assertIs(lazy_str, Lazy(lazy_str)) def test_lazy__module(self): lazy = Lazy(__name__) self.assertIsInstance(lazy, types.ModuleType) self.assertEqual(__name__, lazy.__name__) def test_lazy__module_from_package(self): lazy = Lazy('marnadi.wsgi') self.assertIsInstance(lazy, types.ModuleType) self.assertEqual('marnadi.wsgi', lazy.__name__) def test_lazy__package(self): lazy = Lazy('marnadi') self.assertIsInstance(lazy, types.ModuleType) self.assertEqual('marnadi', lazy.__name__) def test_lazy__package_from_package(self): lazy = Lazy('marnadi.http') self.assertIsInstance(lazy, types.ModuleType) self.assertEqual('marnadi.http', lazy.__name__)
C
UTF-8
1,467
2.765625
3
[]
no_license
/* ** process_file.c for asm in /home/keyrise/Work/Repositories/Epitech/CPE/CPE_2015_corewar/asm/srcs/process/ ** ** Made by Buyumad Anas ** Login <buyuma_a@anas.buyumad@epitech.eu> ** ** Started on Wed Mar 23 15:17:48 2016 Buyumad Anas ** Last update Sun Mar 27 03:14:32 2016 Buyumad Anas */ #include <stdlib.h> #include "asm.h" int call_lp(t_asm *data, t_line *line, char *line_s, int nb_line) { line->nb_line = nb_line; if (check_label(data->labels, nb_line) == SUCCESS) line->is_label = true; else line->is_label = false; if (parser(line, line_s) == ERROR) return (ERROR); if (line_assigner(data->labels, data->instructions, line) == ERROR) return (ERROR); if (line_lexer(data->instructions, line) == ERROR) return (ERROR); return (SUCCESS); } int process_line(t_asm *data, char *line_s, int nb_line) { t_line *line; t_line *tmp; if ((line = malloc(sizeof(t_line))) == NULL) return (ERROR); line->next = NULL; if (call_lp(data, line, line_s, nb_line) == ERROR) return (ERROR); if (data->lines == NULL) data->lines = line; else { tmp = data->lines; while (tmp->next != NULL) tmp = tmp->next; tmp->next = line; } return (SUCCESS); } int process_file(int fd, t_asm *data) { char *line; int nb_line; nb_line = 0; while ((line = get_next_line(fd)) != NULL) { if (process_line(data, line, nb_line) == ERROR) return (ERROR); nb_line += 1; free(line); } return (SUCCESS); }
Swift
UTF-8
1,067
2.859375
3
[]
no_license
// // ViewController.swift // MInhas_Anotacoes // // Created by Max Mendes on 16/05/19. // Copyright © 2019 Curso iOS. All rights reserved. // import UIKit class ViewController: UIViewController { let textKey:String = "userText" @IBOutlet weak var textArea: UITextView! @IBAction func btnSave(_ sender: Any) { if let text = textArea.text{ UserDefaults.standard.set(text, forKey: textKey) view.endEditing(true) } } override var prefersStatusBarHidden: Bool{ return true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } func loadText() -> String{ if let textLoaded = UserDefaults.standard.object(forKey: textKey){ return textLoaded as! String } return "" } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. textArea.text = loadText() print(textArea) } }
Rust
UTF-8
2,516
2.75
3
[ "CC0-1.0" ]
permissive
extern crate sophia; use std::collections::HashSet; use std::error::Error; use sophia::graph::{inmem::FastGraph, *}; use sophia::parser::turtle; use sophia::term::TermKind; use sophia::term::{RcTerm, TTerm}; use sophia::triple::stream::TripleSource; use sophia::triple::Triple; fn render_graph(graph: &FastGraph) -> Result<(), Box<dyn Error>> { let mut indivs = HashSet::new(); let mut literals = HashSet::new(); let mut preds = HashSet::new(); for triple in graph.triples() { let triple = triple?; // triple.s() is a reference, lifing only as long as `triple` // i.e. until the end of the iteration, // i.e. not long enough to be safely stored in `indivs` // (which will still exist after the end of the loop). // // Therefore, we must make a self-contained copy of the term. // By self-contained, I mean a term that we own (so that we can move it into `indivs`) // and that owns its own underlying data. // Since FastGraph uses RcTerms, and those are clonable, // we achieve that by simply cloning the terms. indivs.insert(triple.s().clone()); // Let's do the same for predicate and object. preds.insert(triple.p().clone()); let obj: RcTerm = triple.o().clone(); match obj.kind() { TermKind::Iri => { indivs.insert(obj); } TermKind::Literal => { literals.insert(obj); } TermKind::BlankNode => {} TermKind::Variable => {} }; } println!( "{} individuals, {} predicates, {} literals", indivs.len(), preds.len(), literals.len() ); Ok(()) } fn main() -> Result<(), Box<dyn Error>> { #[allow(unused_variables)] let data1 = "@base <http://example.org/> . @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . @prefix foaf: <http://xmlns.com/foaf/0.1/> . <http://www.w3.org/2001/sw/RDFCore/ntriples/> rdf:type foaf:Document ; <http://purl.org/dc/terms/title> \"N-Triples\"@en-US ; foaf:maker _:art ."; #[allow(unused_variables)] let data2 = "<http://www.w3.org/2001/sw/RDFCore/ntriples/> <http://xmlns.com/foaf/0.1/maker> _:art . _:art <http://xmlns.com/foaf/0.1/name> \"Art Barstow\" ."; let data = data2; let graph: FastGraph = turtle::parse_str(data).collect_triples().unwrap(); render_graph(&graph) }
JavaScript
UTF-8
545
2.71875
3
[]
no_license
{ function name(type) { if (type == "A") { console.log("A"); } if (type == "B") { console.log("B"); } if (type == "C") { console.log("C"); } } function calculate(type, cb) { const strategies = { A: function () { console.log("A"); cb(); }, B: function () { console.log("B"); cb(); }, C: function () { console.log("C"); cb(); }, }; return strategies[type]; } } { }
C++
UHC
269
2.890625
3
[]
no_license
#pragma once #include <iostream> #define STACK_MAX_DATA_COUNT 10 class Stack { public: int myData[STACK_MAX_DATA_COUNT] = { 0 }; // ͸ 迭 void Push(); int Pop(); int Count(); void PrintStackData(); private: int dataCount = -1; };
Python
UTF-8
3,992
2.640625
3
[]
no_license
#!/usr/bin/python import cv import numpy as np import random import time from scipy.cluster.vq import kmeans, vq num_texcels = 16 num_hist = 7 window_size = 5 W1 = 0.5 W2 = 1.0 W3 = 0.5 def flatten( features ): return features.reshape( [features.shape[0] * features.shape[1], features.shape[2]] ) def compute_features( image ): result = np.zeros( image.shape[:2] + (11, ), np.float32 ) for i in xrange( 1, image.shape[0] - 2 ): for j in xrange( 1, image.shape[1] - 2 ): result[i, j, 0] = W1 * image[i, j, 0] result[i, j, 1] = W2 * image[i, j, 1] result[i, j, 2] = W2 * image[i, j, 2] l1 = image[i, j, 0] * 1. result[i, j, 3] = W3 * ( l1 - image[i - 1, j - 1, 0] ) result[i, j, 4] = W3 * ( l1 - image[i , j - 1, 0] ) result[i, j, 5] = W3 * ( l1 - image[i + 1, j - 1, 0] ) result[i, j, 6] = W3 * ( l1 - image[i - 1, j, 0] ) result[i, j, 7] = W3 * ( l1 - image[i + 1, j, 0] ) result[i, j, 8] = W3 * ( l1 - image[i - 1, j + 1, 0] ) result[i, j, 9] = W3 * ( l1 - image[i , j + 1, 0] ) result[i, j, 10] = W3 * ( l1 - image[i + 1, j + 1, 0] ) return result def compute_texcels( features, k = 16 ): centroids, distortion = kmeans( flatten( features ), k ) return centroids def integral_image( image ): result = image * 0 for i in xrange( image.shape[0] ): for j in xrange( image.shape[1] ): r = image[i, j] if i > 0: r += result[i - 1, j] if j > 0: r += result[i, j - 1] if i > 0 and j > 0: r -= result[i - 1, j - 1] result[i, j] = r return result def compute_histogram_features( labels, k = 16, window = 8 ): integrals = np.zeros( labels.shape[:2] + (k, ), np.float32 ) for i in xrange( k ): integrals[:, :, i] = integral_image( ( labels == i ) * 1.0 ) result = np.zeros( labels.shape[:2] + (k, ), np.float32 ) for i in xrange( window, labels.shape[0] - window - 1 ) : for j in xrange( window, labels.shape[1] - window - 1 ) : result[i, j] = integrals[i + window, j + window] +\ integrals[i, j] -\ integrals[i + window, j] -\ integrals[i, j + window] return result def cluster_histograms( features, k = 16 ): centroids, distortion = kmeans( flatten( features ), k ) return centroids def create_palette( colors = 16 ): samples = np.random.randint( 256, size = ( 1000, 3 ) ) palette, _ = kmeans( samples, colors ) return palette image = cv.LoadImageM( "img/lobby1.jpg" ) cielab = cv.CreateMat( image.rows, image.cols, image.type ) cv.CvtColor( image, cielab, cv.CV_RGB2Lab ) print "Computing features" t = time.time() features = compute_features( np.asarray( cielab ) ) t = time.time() - t print "%f seconds" % t print "Computing texcels" t = time.time() texcels = compute_texcels( features, num_texcels ) t = time.time() - t print "%f seconds" % t print "Labeling" t = time.time() labels, _ = vq( flatten( features ), texcels ) labels = labels.reshape( [cielab.rows, cielab.cols] ).astype( np.int8 ) t = time.time() - t print "%f seconds" % t print "Computing histograms" t = time.time() h_features = compute_histogram_features( labels, num_texcels, window_size ) t = time.time() - t print "%f seconds" % t print "Clustering histograms" t = time.time() h_codebook = cluster_histograms( h_features, num_hist ) t = time.time() - t print "%f seconds" % t print "Labeling" t = time.time() h_labels, _ = vq( flatten( h_features ), h_codebook ) h_labels = h_labels.reshape( [cielab.rows, cielab.cols] ).astype( np.int8 ) t = time.time() - t print "%f seconds" % t palette = create_palette( num_hist ) output = np.zeros( [cielab.rows, cielab.cols, 3] ).astype( np.int8 ) for k in xrange( num_hist ): output[h_labels == k] = palette[k] label_img = cv.fromarray( output ) cv.NamedWindow( "Original" ) cv.ShowImage( "Original", image ) cv.NamedWindow( "Segmented" ) cv.ShowImage( "Segmented", label_img ) cv.WaitKey( 0 )
Python
UTF-8
169
3.34375
3
[]
no_license
media = int(input("Média: ")) if (media >= 70): print('Que bom') print('passou') print('legal') else: print('Que pena') print('não passou') print('chore')
Java
UTF-8
13,599
2.59375
3
[]
no_license
package com.optimization; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.awt.event.ActionListener; import java.sql.DriverManager; import java.awt.event.ActionEvent; import java.awt.*; import java.sql.*; public class PrioritySelection extends JFrame{ JComboBox jcSolution, jcOperationalization; JButton btnSetParameters,btnConfirm,btnGenerateOrderedPairs,btnContinueWithAll; JSpinner jsPriority; JTable jtSolutions; int prevprio=0,id=0; CopyOnWriteArrayList<Solution>unorderedSolution, orderedSolution; CopyOnWriteArrayList<OrderedPairs>orderedPairsList; DefaultComboBoxModel opmodel; ArrayList<String>dupselectedSolutionArrayList; Connection con=null; Statement stmt=null; ResultSet rs=null; public PrioritySelection(ArrayList<String>selectedSolutionArrayList) { setSize(600,600); setTitle("Optimization Framework"); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); setLayout(null); unorderedSolution=new CopyOnWriteArrayList<>(); orderedSolution=new CopyOnWriteArrayList<>(); orderedPairsList=new CopyOnWriteArrayList<>(); DefaultComboBoxModel nfrmodel= new DefaultComboBoxModel(); opmodel= new DefaultComboBoxModel(); dupselectedSolutionArrayList=new ArrayList(); for(String s:selectedSolutionArrayList) { dupselectedSolutionArrayList.add(s); } // DB Connection String String drivername="com.microsoft.sqlserver.jdbc.SQLServerDriver"; try { Class.forName(drivername); String db="jdbc:sqlserver://localhost:1433;user=sa;password=cmsa019;databaseName=OptimizationDB"; con=DriverManager.getConnection(db); System.out.println("Driver loaded successfully"); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // String[]ops={"Operationalization 1","Operationalization 2","Operationalization 3", "Operationalization 4", "Operationalization 5"}; // for (String value : ops) { // opmodel.addElement(value); // } // Adding Solution Combobox jcSolution=new JComboBox(); for (int i = 0; i < selectedSolutionArrayList.size(); i++) { nfrmodel.addElement(selectedSolutionArrayList.get(i)); } jcSolution.setModel(nfrmodel); jcSolution.setBounds(10,10, 150,30); add(jcSolution); // Adding Spinner priority SpinnerModel value = new SpinnerNumberModel(5, //initial value 1, //minimum value 10, //maximum value 1); //step jsPriority=new JSpinner(value); jsPriority.setBounds(180,10,50,30); add(jsPriority); // Adding Operationalization Combobox // Collect Operationalizations from database and add to opmodel jcOperationalization=new JComboBox(); jcOperationalization.setBounds(250,10,150,30); //jcOperationalization.setModel(opmodel); add(jcOperationalization); // Adding btnConfirm btnConfirm=new JButton("Confirm"); btnConfirm.setBounds(415,10,100,30); add(btnConfirm); // Adding btnGenerateOrderedPairs System.out.println("Generate Solution"); btnGenerateOrderedPairs=new JButton("Generate Solution"); btnGenerateOrderedPairs.setBounds(100,520,200,30); add(btnGenerateOrderedPairs); // // Adding btnContinueWithAll // // btnContinueWithAll=new JButton("Find Optimal Solution"); // btnContinueWithAll.setBounds(320, 520,200,30); // add(btnContinueWithAll); // Adding Table JPanel jp=new JPanel(); jp.setBounds(30,300,500,200); String []col={"NFR","Priority","Operationalization"}; String [][]data=null; DefaultTableModel model = new DefaultTableModel(data,col); jtSolutions=new JTable(model); jtSolutions.setBounds(30,300, 500,200); //jtSolutions.setPreferredScrollableViewportSize(new Dimension(450,363)); jtSolutions.setFillsViewportHeight(true); JScrollPane js=new JScrollPane(jtSolutions); js.setVisible(true); jp.add(js); add(jp); // Adding Onselect event of NFR combobox jcSolution.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { String item=jcSolution.getSelectedItem().toString(); System.out.println(item +" is selected"); if(item!=null) { populateFromDB(item); } } catch(Exception ex) { System.err.println("Error Occurred!! "+ex.toString()); } } }); // Add item to table row event btnConfirm.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { DefaultTableModel model = (DefaultTableModel)jtSolutions.getModel(); String NFR=jcSolution.getSelectedItem().toString(); String p = jsPriority.getValue().toString(); String op=jcOperationalization.getSelectedItem().toString(); int pr=Integer.parseInt(p); prevprio=pr; Object []o = new Object[3]; o[0]=NFR; o[1]=p; o[2]=op; model.addRow(o); nfrmodel.removeElement(NFR); Solution sl=new Solution(); // SL id++; sl.setId(id); sl.setNFR(NFR); sl.setPriority(pr); sl.setOperationalization(op); unorderedSolution.add(sl); // JOptionPane.showMessageDialog(null, "Please give priority greater than "+prevprio, "Failure", JOptionPane.ERROR_MESSAGE); } }); // Adding event to Generate Ordered pairs Button btnGenerateOrderedPairs.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { makeOrderedSolution(unorderedSolution); } }); // btnContinueWithAll.addActionListener(new ActionListener() { // // @Override // public void actionPerformed(ActionEvent arg0) { // findOperationalizations(); // // } // }); } // End of constructor // Convert Unordered solution to Ordered Solution public void makeOrderedSolution(CopyOnWriteArrayList<Solution> solutionlist) { int status=0; int id=0; CopyOnWriteArrayList<Solution>orderedsolutionlist=new CopyOnWriteArrayList<>(); while(!solutionlist.isEmpty()) { for(Solution s : solutionlist) { status=0; int prio1=s.getPriority(); for(Solution s2: solutionlist) { int prio2=s2.getPriority(); if(prio1<=prio2) { } else { status=1; } } if(status==0) { id++; s.setId(id); orderedsolutionlist.add(s); solutionlist.remove(s); } } } for(Solution s:orderedsolutionlist) { System.out.println(s.getId()+" "+s.getNFR()+" "+s.getPriority()+" "+s.getOperationalization()); } createOrderedPairs(orderedsolutionlist); } // Creating Ordered Pairs public void createOrderedPairs(CopyOnWriteArrayList<Solution> solutionlist) { int id=0; for(Solution s : solutionlist) { int firstid=s.getId(); for(Solution s2:solutionlist) { int secondid=s2.getId(); if(firstid<secondid) { id++; OrderedPairs op=new OrderedPairs(); op.setId(id); op.setOp1prio(s.getPriority()); op.setOp2prio(s2.getPriority()); op.setOperationalization1(s.getOperationalization()); op.setOperationalization2(s2.getOperationalization()); orderedPairsList.add(op); } } } System.out.println("=================== Ordered Pairs========================"); for(OrderedPairs op:orderedPairsList) { System.out.println(op.getOperationalization1()+" "+op.getOperationalization2()); } calculateQualityFunction(orderedPairsList,solutionlist); // calling mean normalized priority // int a[]={4,5}; // double w=calculateMeanNormalizedPriority(a); // System.out.println("Mean normalized priority of "+4+" and "+5+" is "+w); } // populate Operationalizations from DB public void populateFromDB(String NFRName) { try { stmt=con.createStatement(); rs=stmt.executeQuery("select Operationalization from TblOperationalization where NFRName='"+NFRName+"' "); int i=0; ArrayList<String>opslist=new ArrayList<>(); while(rs.next()) { opslist.add(rs.getString(1)); //System.out.println(rs.getString(1)); } opmodel=new DefaultComboBoxModel<>(); for (String value : opslist) { opmodel.addElement(value); } jcOperationalization.setModel(opmodel); } catch(Exception e) { e.printStackTrace(); } } public double calculateMeanNormalizedPriority(int []priorities) { int priosum=0; for(int i=0;i<priorities.length;i++) { priosum=priosum+priorities[i]; } int p=priorities.length*10; double k=((double)priosum/((double)p)); //System.out.println(k); double w=1-k; return w; } public void calculateQualityFunction(CopyOnWriteArrayList<OrderedPairs> orderedpairlist, CopyOnWriteArrayList<Solution> solutionlist) { CopyOnWriteArrayList<ParametersOfOrderedPairs>paramOrderedpairlist=new CopyOnWriteArrayList<>(); for(OrderedPairs op:orderedpairlist) { String op1=op.getOperationalization1(); String op2=op.getOperationalization2(); try { // finding NFR for op1 String NFR1=""; stmt=con.createStatement(); rs=stmt.executeQuery("select NFRName from TblOperationalization where Operationalization='"+op1+"' "); while(rs.next()) { NFR1=rs.getString(1); } rs.close(); // finding NFR for op2 String NFR2=""; stmt=con.createStatement(); rs=stmt.executeQuery("select NFRName from TblOperationalization where Operationalization='"+op2+"' "); while(rs.next()) { NFR2=rs.getString(1); } rs.close(); System.out.println("NFR1 is "+NFR1+" NFR2 is "+NFR2); // finding threshold for NFR(op1) and NFR(op2) double threshold=0.00; stmt=con.createStatement(); rs=stmt.executeQuery("select Threshold from TblThreshold where NFR1='"+NFR1+"' and NFR2='"+NFR2+"'"); while(rs.next()) { threshold=rs.getDouble(1); } System.out.println("Threshold is "+threshold); // Finding combined contribution double combinedcontribution=0.00; stmt=con.createStatement(); rs=stmt.executeQuery("select CombinedContribution from TblCombinedContribution where Operationalization1='"+op1+"' and Operationalization2='"+op2+"'"); while(rs.next()) { combinedcontribution=rs.getDouble(1); } rs.close(); System.out.println("Combined contribution is "+combinedcontribution); // Calculating Mean Normalized priority int prio1=op.getOp1prio(); int prio2=op.getOp2prio(); int p[]={prio1,prio2}; double mnp=calculateMeanNormalizedPriority(p); System.out.println("MNP is "+mnp); // Calculating Del conflict deviation double del=threshold-combinedcontribution; // Calculating BigDel Conflict function double bigdel=0.00; if(del>0) { bigdel=mnp*del; } else { bigdel=0.00; } ParametersOfOrderedPairs pop=new ParametersOfOrderedPairs(); pop.setNFR1(NFR1); pop.setNFR2(NFR2); pop.setOp1(op1); pop.setOp2(op2); pop.setThreshold(threshold); pop.setCombinedcontribution(combinedcontribution); pop.setDelta(del); pop.setBigdel(bigdel); pop.setOp1prio(prio1); pop.setOp2prio(prio2); paramOrderedpairlist.add(pop); } catch(Exception e) { System.err.println(e.toString()); } } QualityFunction(paramOrderedpairlist,solutionlist); } // Quality function implementation public void QualityFunction(CopyOnWriteArrayList<ParametersOfOrderedPairs>poplist, CopyOnWriteArrayList<Solution>solutionlist) { double w3=0.00; int sumprio=0; int no_of_sol=solutionlist.size(); for(Solution s:solutionlist) { sumprio=sumprio+s.getPriority(); } w3 = 1-((double)sumprio/((double)no_of_sol*10)); System.out.println("W3 is "+w3); double sigma3=0.00; for(ParametersOfOrderedPairs pop:poplist) { double cc=pop.getCombinedcontribution(); double bigdel=pop.getBigdel(); sigma3=sigma3+(cc-bigdel); } double roh=sigma3*w3; System.out.println("===============Quality function value is =========== "+roh); JOptionPane.showMessageDialog(null, "Quality function value is "+roh, "Success", JOptionPane.INFORMATION_MESSAGE); } // Finding all operationalizations for list of NFRs // public void findOperationalizations() // { // // for(String s:dupselectedSolutionArrayList) // { // System.out.println(s); // } // } }
JavaScript
UTF-8
1,091
2.53125
3
[]
no_license
const {user} = require('../models/user'); const {ValidationUserField} = require('../validation/UserFieldValidation'); const {validationAndGetValidDataForUpdate} = require('../validation/validationHelper'); const createUserValid = (req, res, next) => { const validationFields = new ValidationUserField(res, next); const {firstName, lastName, email, phoneNumber, password} = req.body; const newUser = {...user}; delete newUser.id; newUser.firstName = validationFields.firstName(firstName); newUser.lastName = validationFields.lastName(lastName); newUser.email = validationFields.email(email); newUser.phoneNumber = validationFields.phoneNumber(phoneNumber); newUser.password = validationFields.password(password); req.body = newUser; next(); } const updateUserValid = (req, res, next) => { const validationFields = new ValidationUserField(res, next); req.body = validationAndGetValidDataForUpdate(validationFields, req.body, user); next(); } exports.createUserValid = createUserValid; exports.updateUserValid = updateUserValid;
C++
UTF-8
1,129
2.765625
3
[]
no_license
#include <iostream> #include <algorithm> #include <cstring> using namespace std; inline int pos(int m, int n, int i, int j, int k, int l) { return i * n * m * n + j * m * n + k * n + l; } int main() { int m, n; cin >> m >> n; ++m, ++n; int *matrix = new int[m * n]; int *dp = new int[m * n * m * n]; memset(dp, 0, sizeof(int) * m * n * m * n); for (int i = 1; i < m; ++i) for (int j = 1; j < n; ++j) cin >> matrix[i * n + j]; for (int i = 1; i < m; ++i) { for (int j = 1; j < n; ++j) { for (int k = 1; k < m; ++k) { for (int l = 1; l < n; ++l) { dp[pos(m, n, i, j, k, l)] = max( max(dp[pos(m, n, i - 1, j, k - 1, l)], dp[pos(m, n, i - 1, j, k, l - 1)]), max(dp[pos(m, n, i, j - 1, k - 1, l)], dp[pos(m, n, i, j - 1, k, l - 1)]) ) + matrix[i * n + j] + ((i != k || j != l) ? matrix[k * n + l] : 0); } } } } cout << dp[m * n * m * n - 1] << endl; return 0; }
Java
UTF-8
1,097
3.3125
3
[]
no_license
package creatingapolygon; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Polygon; import javafx.stage.Stage; public class CreatingAPolygon extends Application { @Override public void start(Stage primaryStage) { //Creating a Polygon Polygon polygon = new Polygon(); //Adding coordinates to the polygon polygon.getPoints().addAll(new Double[]{ 300.0, 50.0, 450.0, 150.0, 300.0, 250.0, 150.0, 150.0, }); //Creating a Group object Group root = new Group(polygon); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage primaryStage.setTitle("Drawing a Polygon"); //Adding scene to the stage primaryStage.setScene(scene); //Displaying the contents of the stage primaryStage.show(); } public static void main(String[] args) { launch(args); } }
C++
UTF-8
3,004
3.265625
3
[]
no_license
class Operator : public Node { struct Twin { //std::shared_ptr<Node> _left; //std::shared_ptr<Node> _right; //std::unique_ptr<Node> _left; //std::unique_ptr<Node> _right; Node* _left; Node* _right; } twin ; const std::function<Operator**(const Symbol) > setS = [&](const Symbol s){ symbol = s; _state ++; std::cout << "setSymbol!!" << std::endl; //std::cout << pp << std::endl; return pp; }; const std::function<Operator**(const Symbol) > addL = [&](const Symbol s) { if(true){ //twin._left.reset( new Constant() ); twin._left = new Constant(); } else { //twin._left.reset( new Constant() ); } twin._left->symbol = s; //twin._left->parent._mom.reset(this); std::cout << "addLeft!!" << std::endl; _state ++; return pp; }; const std::function<Operator**(const Symbol) > addR = [&](const Symbol s){ _state ++; //twin._right.reset( new Constant() ); twin._right = new Constant(); twin._right->symbol = s; //twin._right->parent._mom.reset(this); std::cout << "addRight!!" << std::endl; return pp; }; const std::function<Operator**(const Symbol) > downL = [&](const Symbol s ){ _state ++; //twin._left.reset( new Operator() ); twin._left = new Operator(); //Operator* a = static_cast<Operator*>(twin._left); std::cout << "downLeft!!" << std::endl; return twin._left->pp; }; const std::function<Node**(const Symbol) > downR = [&] (const Symbol s ){ _state ++; twin._right.reset( new Operator() ); std::cout << "downRight!!" << std::endl; return twin._right->pp; }; const std::function<Operator**(const Symbol) > uP = [&](const Symbol s ){ std::cout << "up!!" << std::endl; return nullptr; }; public: /* pointer and pointer of pointer should be single */ Operator* p; Operator** pp;/* indirection for creating stack pointer */ Operator(){ p = this; std::cout << this << "/" << p << std::endl; pp = &p; std::cout << this << "/" << p << "/" << pp << std::endl; }; Operator** expR(const Symbol& t){ //std::cout << "stateB" << _state << std::endl; std::string res = Grammer::get(_state,t.token); //std::cout << "stateA" << _state << std::endl; if(res == "set_symbol"){ return setS(t); // symbol = t; // std::cout << symbol.value << std::endl; // _state++; } else if(res == "add_left"){ return addL(t); } else if( res == "add_right" ) { return addR(t); } else if( res == "down_left" ){ return downL(t); } else if( res == "down_right" ){ return downR(t); } else if(res == "up") { return uP(t); } }; };
Java
UTF-8
648
2.125
2
[]
no_license
package com.transmilenio.transmisurvey.http; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class API { // public static final String BASE_URL = "http://10.0.2.2:8080/TmAPI/"; public static final String BASE_URL = "http://35.226.255.51:8080/TmAPI/"; private static Retrofit retrofit = null; public static Retrofit getApi(){ if(retrofit == null ){ retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } }
Java
UTF-8
1,339
1.992188
2
[ "Apache-2.0" ]
permissive
package io.semla; import io.semla.cache.Cache; import com.decathlon.tzatziki.steps.EntitySteps; import io.semla.datasource.MysqlDatasource; import io.semla.util.Maps; import org.junit.BeforeClass; import org.junit.ClassRule; import org.testcontainers.containers.JdbcDatabaseContainer; import org.testcontainers.containers.MySQLContainer; import java.util.TimeZone; import static io.semla.datasource.Datasource.Configuration.generic; public class MysqlTest extends DatasourceSuite { @ClassRule public static JdbcDatabaseContainer<?> container = new MySQLContainer<>("mysql:8.0.18") .withTmpFs(Maps.of("/var/lib/mysql", "rw")); @BeforeClass public static void init() { MysqlDatasource.Configuration mysql = MysqlDatasource.configure() .withJdbcUrl(container.getJdbcUrl() + "?serverTimezone=" + TimeZone.getDefault().getID()) .withUsername(container.getUsername()) .withPassword(container.getPassword()) .withAutoCreateTable(true); EntitySteps.setDefaultCache(binder -> binder.bind(Cache.class).to(mysql.asCache(entityModel -> mysql.create(entityModel, getNext(entityModel.tablename())))) ); EntitySteps.setDefaultDatasource(generic(entityModel -> mysql.create(entityModel, getNext(entityModel.tablename())))); } }
Python
UTF-8
1,107
3.328125
3
[]
no_license
# Python3 code to demonstrate # getting numbers from string # using re.findall() import re def To_Num(text): # using re.findall() # getting numbers from string temp = re.findall(r'\d+\.?\d*', text) res = list(map(float, temp)) # print result return res[0] def To_Storage(text): # using re.findall() # getting numbers from string temp = text.split(' ') # print result return temp[0] def To_Date(text): regex = re.compile( '(?=((?:(?:[0][1-9]|[1-2][0-9]|3[0-1]|[1-9])[/\-,.]?(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*[/\-,.]?(?:19|20)?\d{2}(?!\:)|' '(?:19|20)?\d{2}[/\-,.]?(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*[/\-,.]?(?:[0][1-9]|[1-2][0-9]|3[0-1]|[1-9])|' '(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*[/\-,.]?(?:[0][1-9]|[1-2][0-9]|3[0-1]|[1-9])[/\-,.]?(?:19|20)\d{2}(?!\:)|' '(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*[/\-,.]?(?:[0][1-9]|[1-2][0-9]|3[0-1]|[1-9])[/\-,.]?\d{2})))' ) return(sum([regex.findall(x) for x in text],[]))
PHP
UTF-8
2,824
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; use NotificationChannels\Twitter\TwitterChannel; use NotificationChannels\Twitter\TwitterStatusUpdate; use NotificationChannels\FacebookPoster\FacebookPosterChannel; use NotificationChannels\FacebookPoster\FacebookPosterPost; use App\Blog; class BlogPublished extends Notification { use Queueable; /** * Create a new notification instance. * * @return void */ public function __construct() { // } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { return ['mail',TwitterChannel::class,FacebookPosterChannel::class]; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $message = ""; $image = ""; if($notifiable instanceof Blog) { $blog = (Blog)$notifiable; $message = $blog->heading; $image = $blog->photo; return (new MailMessage) ->line($message) ->action('New Blog Published', url('/').'/blog/'.$blog->slug) ->line('You can click on the link to read the full article'); } return null; } public function toTwitter($notifiable) { $message = ""; $image = ""; if($notifiable instanceof Blog) { $blog = (Blog)$notifiable; $message = $blog->heading; $image = $blog->photo; return (new TwitterStatusUpdate($message))->withImage(url('/').'/images/blog/'.$image); } return null; } /** * Get the Facebook post representation of the notification. * * @param mixed $notifiable. * @return \NotificationChannels\FacebookPoster\FacebookPosterPost */ public function toFacebookPoster($notifiable) { $message = ""; $image = ""; if($notifiable instanceof Blog) { $blog = (Blog)$notifiable; $message = $blog->heading; $image = $blog->photo; return (new FacebookPosterPost($message))->withLink(url('/').'/blog/'.$blog->slug); } return null; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ // ]; } }
Java
UTF-8
5,150
2.453125
2
[]
no_license
package com.example.myapplication.controller.music; import android.app.Service; import android.content.Intent; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import com.example.myapplication.model.Track; import java.io.IOException; import java.util.ArrayList; public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener{ private MediaPlayer mediaPlayer; private final IBinder mBinder = new MusicBinder(); private ArrayList<Track> mTracks; private Track song; private int currentTrack; private MusicCallback callback; public void setCallback(MusicCallback callback){ this.callback = callback; } @Override public void onCompletion(MediaPlayer mp) { } @Override public boolean onError(MediaPlayer mp, int what, int extra) { return false; } @Override public void onPrepared(MediaPlayer mp) { } public class MusicBinder extends Binder { public MusicService getService(){ return MusicService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public boolean onUnbind(Intent intent) { mediaPlayer.stop(); mediaPlayer.release(); stopSelf(); onDestroy(); return false; } @Override public void onCreate() { super.onCreate(); currentTrack = 0; mediaPlayer = new MediaPlayer(); this.callback = callback; initMediaPlayer(); } private void initMediaPlayer(){ // Let playback continue when the device continue idle //mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); //Interface Implemented in the Class mediaPlayer.setOnPreparedListener(this); mediaPlayer.setOnCompletionListener(this); mediaPlayer.setOnErrorListener(this); } public void setTracks(ArrayList<Track> tracks, int currentTrack){ mTracks = tracks; this.currentTrack = currentTrack; updateTrackUI(); playSong(); } public ArrayList<Track> getTracks(){ return mTracks; } public void setTrack(Track song){ this.song = song; } public Track getTrack(){ return song; } public void playSong() { mediaPlayer.reset(); //Fetch the song buffer it and play it Track track = mTracks.get(currentTrack); try { mediaPlayer.setDataSource(track.getUrl()); } catch (IOException e) { e.printStackTrace(); } mediaPlayer.prepareAsync(); mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { callback.updateMaxSeekBar(mediaPlayer.getDuration()); playAudio(); } }); } public void updateTrack(int offset) { currentTrack = ((currentTrack+offset)%(mTracks.size())); currentTrack = currentTrack >= mTracks.size() ? 0:currentTrack; currentTrack = currentTrack < 0 ? (mTracks.size()-1):currentTrack; String newUrl = mTracks.get(currentTrack).getUrl(); try { playSong(); } catch(Exception e) { } //Update view updateTrackUI(); } public void updateTrackUI(){ setTrack(mTracks.get(currentTrack)); callback.setSongID(currentTrack); callback.showShrinkedBar(true); callback.updateLikeButton(mTracks.get(currentTrack).isLiked()); callback.updateSongTitle(mTracks.get(currentTrack).getName()); callback.updateSongImage(mTracks.get(currentTrack).getThumbnail()); callback.updateSeekBar(mediaPlayer.getCurrentPosition()); callback.updateArtist(mTracks.get(currentTrack).getUserLogin()); callback.updateSongURL(mTracks.get(currentTrack).getUrl()); } public void seekTo(int newPosition){ mediaPlayer.seekTo(newPosition); } public void previousSong(){ //TODO: Update View currentTrack -= 1; } public void nextSong(){ currentTrack += 1; } public int getCurrentPosition(){ return mediaPlayer.getCurrentPosition(); } public MediaPlayer getMediaPlayer(){ return mediaPlayer; } public Track getCurrentTrack() { return mTracks.size() > 0 ? mTracks.get(currentTrack):null; } public void playAudio() { mediaPlayer.start(); callback.updateSeekBar(mediaPlayer.getCurrentPosition()); callback.updatePlayPauseButton(true); } public void pauseAudio() { mediaPlayer.pause(); callback.updateSeekBar(mediaPlayer.getCurrentPosition()); callback.updatePlayPauseButton(false); } }
Java
UTF-8
1,036
2.0625
2
[]
no_license
package com.tc.autobim.controller; import com.tc.autobim.domain.model.*; import com.tc.autobim.repository.IHouseRepository; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/UserConfig") public class UserConfigController { @Autowired private IHouseRepository repository; @PostMapping public HouseModel postUserConfig(@RequestBody UserConfigModel userConfigModel) { Optional<HouseModel> house=repository.findById(userConfigModel.getHouseId()); HouseModel houseModel=house.get(); return houseModel; } }
Java
UTF-8
4,790
2.609375
3
[]
no_license
package com.plan.respository.webutil.factory; import org.apache.kafka.clients.producer.*; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.Future; public class MyProducer{ public static void main(String[] args) { /* //创建Kafka生产者的配置信息 Properties properties = new Properties(); //指定连接的Kafka集群 properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"newyear:9092"); //ACK应答级别 properties.put(ProducerConfig.ACKS_CONFIG,"all"); //重试次数 properties.put(ProducerConfig.RETRIES_CONFIG,6); //批次大小 properties.put(ProducerConfig.BATCH_SIZE_CONFIG,16384); //等待时间 properties.put(ProducerConfig.LINGER_MS_CONFIG,10); //RecordAccumulator缓冲区大小 properties.put(ProducerConfig.BUFFER_MEMORY_CONFIG,33554432); //key,value的序列化类 properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer"); properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");*/ ArrayList<String> list = new ArrayList<>(); //创建生产者对象 KafkaProducer<String, String> producer = new KafkaProducer<>(getProperty("newyear:9092","all",3,16384,33554432,10,"com.plan.respository.webutil.factory.partitioner.OurPartition",list)); //发送数据 for (int i = 0; i < 10; i++) { //不带回调的生产者 // producer.send(new ProducerRecord<>("first","producer---"+i)); //带回调的生产者 Future<RecordMetadata> second = producer.send(new ProducerRecord<>("second", "happynewyear" + i), new Callback() { @Override public void onCompletion(RecordMetadata metadata, Exception exception) { if (exception == null) { System.out.println(metadata.offset() + "========" + metadata.partition()); } else { exception.printStackTrace(); } } }); try { //同步发送的方式 RecordMetadata recordMetadata = second.get(); }catch (Exception e){ e.printStackTrace(); } //另外一种写法 producer.send(new ProducerRecord<>("second", "happynewyear" + i),((metadata, exception) -> { if(exception == null){ System.out.println(metadata.partition()+"---"+metadata.offset()); }else { exception.printStackTrace(); } })); } //关闭资源 producer.close(); } /** * 配置Kafka的信息 * @param bootstrapServer 指定连接的Kafka集群 * @param ack ACK应答级别 * @param reties 重试次数 * @param bachesize 批次大小 * @param buffermemery RecordAccumulator缓冲区大小 * @param lingerms 等待时间 * @param partitioner 指定分区的全类名 * @param list 拦截器的全类名的集合 * @return 具体的配置信息 */ public static Properties getProperty(String bootstrapServer, String ack, int reties, int bachesize, int buffermemery, int lingerms, String partitioner, List<String> list){ Properties properties = new Properties(); //ACK应答级别 properties.put(ProducerConfig.ACKS_CONFIG,ack); //指定连接的Kafka集群 properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,bootstrapServer); //重试次数 properties.put(ProducerConfig.RETRIES_CONFIG,reties); //批次大小 properties.put(ProducerConfig.BATCH_SIZE_CONFIG,bachesize); //RecordAccumulator缓冲区大小 properties.put(ProducerConfig.BUFFER_MEMORY_CONFIG,buffermemery); //等待时间 properties.put(ProducerConfig.LINGER_MS_CONFIG,lingerms); //key,value的序列化类 properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer"); properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer"); //指定自定义分区 properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG,partitioner); //添加拦截器 properties.put(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG,list); return properties; } }
Python
UTF-8
1,068
2.578125
3
[]
no_license
from bs4 import BeautifulSoup import requests import random import re def scraping(): ng_list = ["the bridge"] html = requests.get('https://thebridge.jp/') soup = BeautifulSoup(html.text, "html.parser") article = soup.find(class_="articles") title = article.find(class_="entry-title").string for i in ng_list: if i in title: return reporter = '' try: reporter = soup.find(class_="text-muted").text reporter = reporter[4:] except: print("reporter not found") image = soup.find(class_="entry-thumbnail") image = image.a.get("style") url = article.a.get("href") html = requests.get(url) soup = BeautifulSoup(html.text, "html.parser") soup = soup.find(class_="post-body") text = ''.join([s.text for s in soup.find_all("p")]) return {'article_text':text,'article_title':title, 'article_url':url,'article_reporter':reporter.split('\n')[0], 'site_name':'the_bridge','article_image': image.split('url(')[1][:-1]} if __name__ == "__main__": print(scraping())
Markdown
UTF-8
6,354
2.953125
3
[ "Apache-2.0" ]
permissive
--- layout: work-with-us-layout title: Qualitative Researcher role: <b> Role </b> <br><br> We are looking for a full-time Social Science Researcher to join our team at Fields of View. You will be required to work with qualitative social data. You must have proficiency in qualitative research methodologies and must also possess a working ability to interpret quantitative data. You will be expected to apply a range of qualitative analytical methods and techniques, including designing of analytical frameworks, executing research projects, analysing and reporting results in various media. <br> <br> We are a multi-disciplinary organisation working in diverse subject matters such as urban planning, energy systems, local governance, climate change, law and justice, housing, etc. Therefore, you must be able to apply research methods in designing studies and analysing data across domain areas. <br> <br> Being a research organisation, we encourage all our researchers to explore new avenues of both research and practice. The candidate will be working in an interdisciplinary team, and has to communicate and work with people from different backgrounds. The ability to simultaneously work on multiple projects and to rapidly switch contexts is non-negotiable. <br> <br> This is a full-time role and will be based in Bangalore, India. responsibilities: <b> Responsibilities </b> <br> <ul> <li>Undertake secondary data collection using public data sources such as Census of India, World Bank, etc. </li> <li> Execute research projects from start to finish, including collecting, cleaning, processing, analysing and publishing data </li> <li> Independently develop framework of analyses for consolidated primary or secondary data </li> <li> Coordinate with stakeholders for data collection and sharing </li> <li> Communicate research processes and results to audiences from diverse backgrounds </li> <li> Manage projects and team towards the project outcomes </li> <li> Writing up research results in the form of journal articles, conference papers, blogs, or white papers </li> </ul> skills: <b> Required Skills </b> <br> <ul> <li> A Master’s degree in any of the social sciences, including sociology, economics, anthropology, law, public policy, psychology, statistics or in equivalent fields. </li> <li> Prior experience in field research, either in conducting surveys or ethnographic research </li> <li> Proficiency in qualitative data analysis software such as NVivo, Atlas.ti and data visualisation software such as Tableau or other applications. </li> <li> Managing databases, cleaning and presenting data in statistical packages of choice. </li> <li> Experience in organising and facilitating Focus Group Discussions (FGDs) </li> <li> Developing and writing case studies </li> <li> Experience in project management and liaising with project partners </li> <li> Simultaneously working on multiple projects </li> <li> Quickly switching contexts </li> <li> Independently planning and managing your work </li> <li> Applying research methods to different subject areas </li> </ul> additionalSkills: <b> Preferred Skills </b> <ul> <li> Designing primary data collection proposals, including accounting for ethical, privacy and method-specific considerations </li> <li> Proficiency in one or more Indian languages such as Kannada, Tamil, or Hindi </li> <li> Experience in diverse data collection methods such as games, oral histories, online surveys, social media, etc. </li> <li> Experience working with government stakeholders </li> <li> Ability to interpret quantitative data and identify emerging trends for analysis </li> </ul> whyWorkForFov: <b>Why Work at Fields of View</b> <br> <ul> <li> We pride ourselves in building a collaborative and open environment around our work in building tools for inclusive public policy. This is your chance to become an addition to our coveted multidisciplinary team, that houses individuals from different backgrounds scaling from Journalism to Game Design to Law. </li> <li> We have collaborations with Indian and international universities, and you get access to cutting edge research in data and policy. </li> <li> Depending on your interest, you will contribute to research papers that will be published in major journals. </li> <li> Your work will contribute to real-world applications in addressing social problems. </li> <li> High levels of ownership as part of a small, growing team. </li> <li> We have a generous leave and work-from-home policy and are committed to building an organisational culture of collaboration and trust. </li> <li> We are a non-profit organisation and an equal opportunity employer. We are committed to a safe and vibrant workplace, and highly encourage applications from people from diverse caste, gender, ethnic and religious identities. </li> </ul> applicationProcess: <b> How To Apply </b> <br><br> If this sounds interesting or exciting to you, please write to work@fieldsofview.in with your CV, a writing sample and a thoughtful cover letter stating why you want to work with us in this role. <br><br> <b> Application Process </b> <br><ol> <li> &nbsp;We will review your application and, upon shortlisting it, set up a quick phone call. The phone call acts as a good way to introduce yourself and for us to let you know a bit more about our work. </li> <li> &nbsp;Having successfully gone through the phone call stage, we will provide you with an assignment. The assignment will involve a cross section of the kind of work you'll do with us. You take as much time as you want to complete the assignment, but we've noted that it takes on average about 7 days to finish. </li> <li> &nbsp;If we like your approach to the assignment, we invite you to spend two days with us. You can pepper us with more questions and get to know the rest of the team. You will also be provided a follow-up task to be performed during those 2 days. Once this is done, and if you like us and we like you, we will extend an offer within a week's time. </li> </ol> notes: <b>Other Notes</b> <br> <ul> <li>Fields of View is a non-profit organisation.</li> <li>The position is based in Bangalore</li> <li>Our office is in JP Nagar, close to Rangashankara</li></ul> ide: Qualitative Researcher tag: Qualitative Researcher category: jd permalink: /projects/work-with-us/qualitativeresearcher/ ---
Markdown
UTF-8
3,004
2.984375
3
[]
no_license
# CSAPP_Study ------ ### 作者:冰红茶 ### 参考书籍:《Computer Systems A Programmer’s Perspective(3rd)》 ------   正式开始CSAPP了,有点儿小兴奋。据说这本书是国外许多著名大学的经典教材,深入讲解了计算机系统的底层原理,包括编码,汇编软件,指令,存储器层次结构,虚拟内存等。看完应该会很有收益,那事不宜迟,正式开始吧^_ ^ 参考机:Intel Core i7 Haswell   ## [链接:https://github.com/hblvsjtu/CSAPP_Study/blob/master/Computer%20Systems%20A%20Programmer%E2%80%99s%20Perspective(3rd).pdf](https://github.com/hblvsjtu/CSAPP_Study/blob/master/Computer%20Systems%20A%20Programmer%E2%80%99s%20Perspective(3rd).pdf) ## 目录 ## Computer Systems 1 ## A Programmer’s Perspective(3rd) 1 ## 一、 计算机系统漫游 1 ## 1.1 位+上下文 1 ### 1.2 编译系统(Compilation System) 1 ### 1.3 系统的硬件组成 2 ### 1.4 不同层次的储存设备 2 ### 1.5 操作系统管理硬件 3 ### 1.6 Amdahl定律 4 ## 二、 程序结构和执行 4 ### 2.1 字数据的大小 4 ### 2.2 寻址和字节顺序 4 ### 2.3 补码 5 ### 2.4 拓展一个数字的位表示 6 ### 2.5 整数运算 6 ## 三、 程序的机器级表示 8 ### 3.1 基础知识 9 ### 3.2 汇编代码格式 9 ### 3.3 寻址方式 10 ### 3.4 基本操作 11 ### 3.5 条件码 15 ### 3.6 跳转 16 ### 3.7 循环 19 ### 3.8 switch多重分支 19 ### 3.9 过程 21 ### 3.10 数组的分配和访问 22 ## 四、 处理器体系结构 24 ### 4.1 Y86-64指令集体体系结构 24 ### 4.2 逻辑设计和硬件控制语言HCL 28 ### 4.3 Y86-64的顺序实现 29 ### 4.4 流水线的通用原理 31 ### 4.5 SQE+重新安排计算阶段 32 ## 五、 优化程序性能 32 ### 5.1 优化编译器的能力和局限性 32 ### 5.2 表示程序性能 33 ### 5.3 优化性能 33 ### 5.4 理解现代处理器 34 ### 5.5 处理器操作的抽象模型 35 ### 5.6 循环展开 35 ### 5.7 提高并行性 36 ### 5.8 重新结合变换 37 ### 5.9 向量指令 38 ### 5.10 一些限制的因素 38 ### 5.11 程序剖析 38 ## 六、 存储器层次结构 39 ### 6.1 存储技术 39 ### 6.2 访问主存 40 ### 6.3 磁盘存储 41 ### 6.4 局部性locality 42 ### 6.5 缓存 43 ### 6.6 高速缓存存储器 44 ## 七、 链接 45 ### 7.1 学习链接的作用 45 ### 7.2 编译器驱动程序 46 ### 7.3 静态链接和目标文件 46 ### 7.4 符号和符号表 48 ### 7.5 符号解析 48 ### 7.6 与静态库链接 48 ### 7.7 动态链接共享库 49 ### 7.8 库打桩机制 49 ## 八、 异常控制流 49 ### 8.1 库打桩机制 49 ## 九、 虚拟内存 49 ### 9.1 定义和功能 49 ### 9.2 地址空间 50 ### 9.3 虚拟内存作为缓存的工具 50 ### 9.4 虚拟内存作为内存管理的工具 51 ### 9.5 虚拟内存作为内存保护的工具 52 ### 9.6 地址翻译 52 ### 9.7 内存映射 55
JavaScript
UTF-8
729
3.828125
4
[]
no_license
const peso1 = 1.0 const peso2 = Number('2.0') console.log(peso1, peso2) console.log(Number.isInteger(peso1)) // Verificando se a variável é um inteiro const avaliacao1 = 9.567 const avaliacao2 = 6.547 const total = avaliacao1 * peso1 + avaliacao2 * peso2 const media = total / (peso1 + peso2) console.log(media.toFixed(2)) // toFixed = funçao de quantas casas decimais após a vírgula /* console.log(media.toString()) // transforma o valor em uma string */ console.log(media.toString(2)) // transforma o valor em binário console.log(media.toString(16)) // transforma o valor em hexadecimal console.log(typeof media) // tipo da media console.log(typeof Number) // Number com N maiúsuculo é uma função, não um tipo
Ruby
UTF-8
333
3.140625
3
[]
no_license
puts "Salut, bienvenue dans ma super pyramide ! Combien d'étages veux-tu ?" print "> " stage=gets.chomp.to_i a=0 until (stage <= 25 && stage > 0) puts "Veuillez entrer un nombre compris entre 1 et 25" print "> " stage=gets.chomp.to_i end puts "Voici la pyramide :" until a>stage do puts "#"*a a+=1 end