code
stringlengths
0
29.6k
language
stringclasses
9 values
AST_depth
int64
3
30
alphanumeric_fraction
float64
0.2
0.86
max_line_length
int64
13
399
avg_line_length
float64
5.02
139
num_lines
int64
7
299
source
stringclasses
4 values
package com.fichajespi.dto.converter; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fichajespi.dto.entity.FichajeDto; import com.fichajespi.dto.entity.FichajeDtoReqRes; import com.fichajespi.entity.Fichaje; import com.fichajespi.entity.Usuario; import com.fichajespi.entity.enums.TipoFichaje; import com.fichajespi.service.FichajeService; import com.fichajespi.service.UsuarioService; @Component public class FichajeDtoConverter { @Autowired private UsuarioService service; @Autowired private FichajeService fichajeService; public FichajeDto inverseTransform(Fichaje f) { return null; } public Fichaje transform(FichajeDtoReqRes dto) { Fichaje f = new Fichaje(); f.setHora(dto.getHora()); f.setDia(dto.getDia()); Usuario usuario = service .findByNumero(dto.getNumeroUsuario()) .orElse(null); f.setUsuario(usuario); f.setTipo(dto.getTipo()); f.setOrigen(dto.getOrigen()); return f; } public FichajeDtoReqRes fichar(FichajeDtoReqRes fichajeDto) { fichajeDto.setHora(LocalTime.now()); fichajeDto.setDia(LocalDate.now()); Fichaje fichaje = transform(fichajeDto); Usuario usuario = fichaje.getUsuario(); if (usuario != null) { boolean workingState = usuario.getWorking(); if (workingState) fichaje.setTipo(TipoFichaje.SALIDA.toString()); // fichaje.setTipo("SALIDA"); else fichaje.setTipo(TipoFichaje.ENTRADA.toString()); // fichaje.setTipo("ENTRADA"); usuario.setWorking(!workingState); StringBuilder sb = new StringBuilder(); sb.append(fichaje.getDia()); sb.append(" "); DateTimeFormatter myTime = DateTimeFormatter.ofPattern("HH:mm:ss"); sb.append(myTime.format(fichaje.getHora())); sb.append(" - "); sb.append(fichaje.getTipo()); usuario.setUltimoFichaje(sb.toString()); service.save(usuario); fichaje.setUsuario(usuario); fichajeService.save(fichaje); fichajeDto .setNombreUsuario(fichaje.getUsuario().getNombreEmpleado()); fichajeDto.setHora(fichaje.getHora()); fichajeDto.setTipo( fichaje.getUsuario().getWorking() ? "entrada" : "salida"); return fichajeDto; } return null; } }
java
12
0.746173
70
26.034483
87
starcoderdata
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bremersee.profile.business; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.bremersee.profile.AbstractComponentImpl; import org.springframework.security.acls.domain.BasePermission; import org.springframework.security.acls.domain.GrantedAuthoritySid; import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.Sid; /** * @author */ public abstract class AbstractServiceImpl extends AbstractComponentImpl { MutableAcl initAcl(Object entity) { return initAcl(entity, null, null, false); } MutableAcl initAcl(Object entity, String owner) { return initAcl(entity, owner, null, false); } @SuppressWarnings("WeakerAccess") MutableAcl initAcl(Object entity, String owner, Acl parent, boolean entriesInheriting) { Validate.notNull(entity, "Entity must not be null."); final ObjectIdentity objectIdentity; if (entity instanceof ObjectIdentity) { objectIdentity = (ObjectIdentity) entity; } else { objectIdentity = getObjectIdentityRetrievalStrategy().getObjectIdentity(entity); } MutableAcl acl = getAclService().createAcl(objectIdentity); final Sid ownerSid; if (StringUtils.isBlank(owner) && parent != null) { ownerSid = parent.getOwner(); } else { ownerSid = new PrincipalSid(StringUtils.isBlank(owner) ? getSystemName() : owner); } acl.setOwner(ownerSid); if (parent != null) { acl.setParent(parent); acl.setEntriesInheriting(entriesInheriting); } if (!entriesInheriting) { for (final String roleName : getAdminAndSystemRoleNames()) { final GrantedAuthoritySid roleSid = new GrantedAuthoritySid(roleName); acl.insertAce(acl.getEntries().size(), BasePermission.ADMINISTRATION, roleSid, true); acl.insertAce(acl.getEntries().size(), BasePermission.CREATE, roleSid, true); acl.insertAce(acl.getEntries().size(), BasePermission.DELETE, roleSid, true); acl.insertAce(acl.getEntries().size(), BasePermission.READ, roleSid, true); acl.insertAce(acl.getEntries().size(), BasePermission.WRITE, roleSid, true); } } return getAclService().updateAcl(acl); } void deleteAcls(Object entity, boolean deleteChildren) { Validate.notNull(entity, "Entity must not be null."); if (entity instanceof ObjectIdentity) { getAclService().deleteAcl((ObjectIdentity) entity, deleteChildren); } else { getAclService().deleteAcl(getObjectIdentityRetrievalStrategy().getObjectIdentity(entity), deleteChildren); } } }
java
15
0.691715
118
38.923077
91
starcoderdata
def get_queryset(self): # Oracle and Django don't play nice with JSON. This makes filtering by an array of tags difficult. # We comma separate the tags provided in the ?tags query parameter (ex: ?tags=a,b,c). tags = [x for x in self.request.GET.get('tags', '').split(',')] # filter out an empty strings tags = pydash.without(tags, '') matches = [] params = { 'owner': self.request.user.profile, } exclude_params = { 'id__in': [] } matches = Notification.objects.filter(owner=self.request.user.profile).values() # This is inefficient, but we have to fetch all notifications to find out which ones have the requested tags. if tags: matchesClone = pydash.filter_(matches, lambda x: set(tags).issubset(set(x['tags'] or []))) matchesClone = pydash.map_(matchesClone, 'id') # Only append to params if tags exists, so that we don't inadvertently pass an empty array params['id__in'] = matchesClone # Don't show notifications for handshakes that are in an unrevealed bid cycle for x in matches: try: meta = pydash.get(x, 'meta') or '{}' meta = json.loads(meta) bidcycle_id = pydash.get(meta, 'bidcycle_id') cycles = BidHandshakeCycle.objects.filter(cycle_id=bidcycle_id) if cycles.first(): cycle = cycles.first() allowed_date = cycle.handshake_allowed_date if allowed_date: if allowed_date > maya.now().datetime(): exclude_params['id__in'].append(pydash.get(x, 'id')) except Exception as e: logger.error(f"{type(e).__name__} at line {e.__traceback__.tb_lineno} of {__file__}: {e}") queryset = Notification.objects.filter(**params).exclude(**exclude_params) self.serializer_class.prefetch_model(Notification, queryset) return queryset
python
19
0.563394
117
43.659574
47
inline
using System.Threading.Tasks; namespace Sid.MailKit.Abstractions { public interface IMailSender { Task SendEmailAsync(string subject, string content, params string[] tos); Task SendEmailAsync(MailMessage mailMessage); Task SendEmailAndReturnAsync(string subject, string content, params string[] tos); Task SendEmailAndReturnAsync(MailMessage mailMessage); } }
c#
9
0.749455
115
29.6
15
starcoderdata
vpActivityConfig::~vpActivityConfig() { // Write out any config changes made by the user. if (this->Internal->Dirty) { this->WriteActivityTypes(); } this->ActivityTypeRegistry->UnRegister(0); delete this->Internal; }
c++
8
0.687764
51
20.636364
11
inline
package main import ( "flag" "fmt" "log" "net/http" "os" ) var ( listen = flag.String("listen", GetPort(), "listen address") dir = flag.String("dir", ".", "directory to serve") ) // GetPort: Get the Port from the environment so we can run on Heroku func GetPort() string { var port = os.Getenv("PORT") // Set a default port if there is nothing in the environment if port == "" { port = "8080" fmt.Println("INFO: No PORT environment variable detected, defaulting to " + port) } return ":" + port } func main() { flag.Parse() log.Printf("listening on %q...", *listen) log.Fatal(http.ListenAndServe(*listen, http.FileServer(http.Dir(*dir)))) }
go
13
0.659544
83
20.9375
32
starcoderdata
package pro.haichuang.framework.base.config.mvc; import cn.hutool.core.date.DatePattern; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.converter.Converter; import java.math.BigInteger; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Date; /** * Jackson自动配置 * * {@code Jackson} 的常用功能 * 已默认配置的如下: * * BigInteger} 自动序列化为 {@link String} 字符串 * Long} 自动序列化为 {@link String} 字符串 * Date} 自动序列化为 {@code yyyy-MM-dd HH:mm:ss} 字符串 * LocalDateTime} 自动序列化为 {@code yyyy-MM-dd HH:mm:ss} 字符串 * LocalDate} 自动序列化为 {@code yyyy-MM-dd} 字符串 * LocalTime} 自动序列化为 {@code HH:mm:ss} 字符串 * * {@link Jackson2ObjectMapperBuilderCustomizer} 的原因是默认 {@code Jackson} 已存在一些默认配置内容, * 通过此种方式可以实现在不修改默认配置的情况下插入我们自定义的配置 * * @author JiYinchuan * @see WebMvcConfig * @since 1.1.0.211021 */ @Configuration(proxyBeanMethods = false) public class JacksonConfig { @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return jacksonObjectMapperBuilder -> { jacksonObjectMapperBuilder.serializerByType(BigInteger.class, new ToStringSerializer()); jacksonObjectMapperBuilder.serializerByType(Long.class, new ToStringSerializer()); jacksonObjectMapperBuilder.serializerByType(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN))); jacksonObjectMapperBuilder.serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN))); jacksonObjectMapperBuilder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN))); jacksonObjectMapperBuilder.deserializerByType(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN))); jacksonObjectMapperBuilder.deserializerByType(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN))); jacksonObjectMapperBuilder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN))); }; } /** * LocalDateTime自定义转换器 * * @author JiYinchuan * @since 1.1.0.211021 */ public static class LocalDateTimeConverter implements Converter<String, LocalDateTime> { @Override public LocalDateTime convert(String s) { return LocalDateTime.parse(s, DatePattern.NORM_DATETIME_FORMATTER); } } /** * LocalDate自定义转换器 * * @author JiYinchuan * @since 1.1.0.211021 */ public static class LocalDateConverter implements Converter<String, LocalDate> { @Override public LocalDate convert(String s) { return LocalDate.parse(s, DatePattern.NORM_DATE_FORMATTER); } } /** * LocalTime自定义转换器 * * @author JiYinchuan * @since 1.1.0.211021 */ public static class LocalTimeConverter implements Converter<String, LocalTime> { @Override public LocalTime convert(String s) { return LocalTime.parse(s, DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)); } } }
java
16
0.720286
115
38.752294
109
starcoderdata
/* * Create by BobEve on 17-12-18 上午11:40 * Copyright (c) 2017. All rights reserved. * * Last modified 17-12-18 上午11:40 */ package bob.eve.walle.mvp.model.bean.zhihu; /** * Created by Bob on 17/12/18. */ public class ZhihuEditor { /** * url : http://www.zhihu.com/people/deng-ruo-xu * bio : 好奇心日报 * id : 82 * avatar : http://pic2.zhimg.com/d3b31fa32_m.jpg * name : 邓若虚 */ private String url; private String bio; private int id; private String avatar; private String name; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getBio() { return bio; } public void setBio(String bio) { this.bio = bio; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
java
8
0.639409
50
13.926471
68
starcoderdata
import React from 'react' import PropTypes from 'prop-types' const Header = (props) => ( <header id="header" style={props.timeout ? {display: 'none'} : {}}> <div className="logo"> <div className="content"> <div className="inner"> graduated from Duke University in 2019, and I'm working at Facebook in Washington, D.C. as a software engineer. href="https://www.facebook.com/ben.hubsch" target="_blank" rel="noopener noreferrer">Facebook href="https://www.instagram.com/sw33tb3n/" target="_blank" rel="noopener noreferrer">Instagram href="https://www.linkedin.com/in/benhubsch/" target="_blank" rel="noopener noreferrer">LinkedIn href="https://github.com/benhubsch" target="_blank" rel="noopener noreferrer">Github href="mailto: target="_blank" rel="noopener noreferrer">Email ) Header.propTypes = { timeout: PropTypes.bool } export default Header
javascript
10
0.567044
136
40.266667
30
starcoderdata
package com.inner.lovetao.search.mvp.presenter; import android.app.Application; import com.inner.lovetao.config.ConfigInfo; import com.inner.lovetao.core.TaoResponse; import com.inner.lovetao.search.mvp.contract.SearchResultContract; import com.inner.lovetao.tab.bean.ProductItemBean; import com.jess.arms.di.scope.ActivityScope; import com.jess.arms.http.imageloader.ImageLoader; import com.jess.arms.integration.AppManager; import com.jess.arms.mvp.BasePresenter; import com.jess.arms.utils.RxLifecycleUtils; import java.util.List; import javax.inject.Inject; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import me.jessyan.rxerrorhandler.core.RxErrorHandler; import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber; import me.jessyan.rxerrorhandler.handler.RetryWithDelay; /** * desc: * Created by xcz */ @ActivityScope public class SearchResultPresenter extends BasePresenter<SearchResultContract.Model, SearchResultContract.View> { @Inject RxErrorHandler mErrorHandler; @Inject Application mApplication; @Inject ImageLoader mImageLoader; @Inject AppManager mAppManager; @Inject ImageLoader imageLoader; @Inject public SearchResultPresenter(SearchResultContract.Model model, SearchResultContract.View rootView) { super(model, rootView); } /** * 获取推荐类型 * @param pageNum * @param title */ public void getSearchData(int pageNum, String title){ mModel.getSearchData(pageNum, ConfigInfo.PAGE_SIZE,title) .subscribeOn(Schedulers.io()) .doOnSubscribe(disposable -> mRootView.showLoading()) .retryWhen(new RetryWithDelay(1, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔 .observeOn(AndroidSchedulers.mainThread()) .doFinally(()->mRootView.hideLoading()) .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用Rxlifecycle,使Disposable和Activity一起销毁 .subscribe(new ErrorHandleSubscriber { @Override public void onNext(TaoResponse listTaoResponse) { if(listTaoResponse.isSuccess()){ mRootView.getSearchResultData(listTaoResponse.getData()); }else { mRootView.showMessage(listTaoResponse.getMessage()); } } }); } /** * 获取销量和最新 * @param pageNum * @param title * @param sortName */ public void getSearchDataForSort(int pageNum, String title,String sortName){ mModel.getSearchSortData(pageNum, ConfigInfo.PAGE_SIZE,title,sortName) .subscribeOn(Schedulers.io()) .doOnSubscribe(disposable -> mRootView.showLoading()) .retryWhen(new RetryWithDelay(1, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔 .observeOn(AndroidSchedulers.mainThread()) .doFinally(()->mRootView.hideLoading()) .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用Rxlifecycle,使Disposable和Activity一起销毁 .subscribe(new ErrorHandleSubscriber { @Override public void onNext(TaoResponse listTaoResponse) { if(listTaoResponse.isSuccess()){ mRootView.getSearchResultData(listTaoResponse.getData()); }else { mRootView.showMessage(listTaoResponse.getMessage()); } } }); } /** * 获取价格排序(升序和降序) * @param pageNum * @param title * @param sortName * @param sortOrder */ public void getSearchDataForSorts(int pageNum, String title,String sortName,String sortOrder){ mModel.getSearchSortsData(pageNum, ConfigInfo.PAGE_SIZE,title,sortName,sortOrder) .subscribeOn(Schedulers.io()) .doOnSubscribe(disposable -> mRootView.showLoading()) .retryWhen(new RetryWithDelay(1, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔 .observeOn(AndroidSchedulers.mainThread()) .doFinally(()->mRootView.hideLoading()) .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用Rxlifecycle,使Disposable和Activity一起销毁 .subscribe(new ErrorHandleSubscriber { @Override public void onNext(TaoResponse listTaoResponse) { if(listTaoResponse.isSuccess()){ mRootView.getSearchResultData(listTaoResponse.getData()); }else { mRootView.showMessage(listTaoResponse.getMessage()); } } }); } public ImageLoader getImageLoader(){ return imageLoader; } @Override public void onDestroy() { super.onDestroy(); this.mErrorHandler = null; this.mAppManager = null; this.mImageLoader = null; this.mApplication = null; } }
java
19
0.62952
113
38.07971
138
starcoderdata
<style type="text/css"> hr.style1{ border:none; border-left:1px solid hsla(200, 10%, 50%,100); height:100vh; width:1px; } <div class="bread_parent"> <ul class="breadcrumb"> href="<?php echo base_url('backend/superadmin/dashboard');?>"><i class="icon-home"> Dashboard href="<?php echo base_url('backend/products/variation_themes'); ?>">Product Variation Theme Product Variation Theme <div class="col-sm-12"> <div class="panel-body"> <form role="form" class="form-horizontal tasi-form" action="<?php echo current_url()?>" enctype="multipart/form-data" method="post"> <?php echo $this->session->flashdata('msg_error');?> <header class="panel-heading colum"><i class="fa fa-angle-double-right"> Variation Theme information : <div class="form-group"> <label class="col-md-2 control-label">Variation Theme Title <span class="mandatory">* <div class="col-md-9"> <input type="text" placeholder="Variation Theme Title" class="form-control" name="product_theme_title" value="<?php if(set_value('product_theme_title')) echo set_value('product_theme_title'); else if($variation_themes->product_theme_title) echo $variation_themes->product_theme_title; ?>" > <span class="error"><?php echo form_error('product_theme_title'); ?> <div class="form-group"> <label class="col-md-2 control-label">Category <span class="mandatory">* <div class="col-md-9"> <select name="category" class="form-control main-search-catg" onchange="getAttrDataUsingCategory(this.value)"> <option value="">--Select Category-- <?php $cate=''; if(!empty($_GET['category'])) $cate=$_GET['category']; else $cate = $variation_themes->category; echo getcategoryDropdown($cate); ?> <span class="error"><?php echo form_error('category'); ?> <div class="form-group atrributeData" style="<?php if($variation_themes->attributes){ ?>display: block;<?php }else{ ?>display: none;<?php } ?>"> <label class="col-md-2 control-label">Choose Atrribute <span class="mandatory">* <div class="col-md-9 attributesUsingCat"> <?php echo getAttributeInfoUsingCat($variation_themes->category, $variation_themes->attributes); ?> <span class="error"><?php echo form_error('attributesUsingCat[]'); ?> <div class="form-group"> <label class="col-md-2 control-label">Status <span class="mandatory">* <div class="col-md-9"> <select class="form-control" name="status" > <option value="1" <?php if(set_value('status')==1) echo 'selected'; else if($variation_themes->status==1) echo 'selected' ?> >Active <option value="2" <?php if(set_value('status')==2) echo 'selected'; else if($variation_themes->status==2) echo 'selected' ?> >Inactive <span class="error"><?php echo form_error('status'); ?> <div class="form-actions fluid"> <div class="col-md-offset-2 col-md-10"> <button class="btn btn-primary" type="submit">Submit <a class="btn btn-danger" href="<?php echo base_url()?>backend/products/variation_themes">Back <!-- END FORM--> var SITE_URL = "<?php echo base_url(); ?>"; function getAttrDataUsingCategory(category){ if(category){ $(".atrributeData").show(); $.ajax({ url: SITE_URL+'backend/products/getAttrDataUsingCategory', type: 'POST', data: { catID : category, attributes : "" }, cache: false, success:function(result){ var data = JSON.parse(result); $('.attributesUsingCat').html(data.optionData); }, }); }else{ $(".atrributeData").hide(); } }
php
9
0.537952
382
45.316832
101
starcoderdata
/** * @package EntegreJS * @subpackage Bootstrap * @author * @copyright 2016 * @license MIT */ E.bootstrap.div = class extends E.bootstrap.node { constructor( attr, children ) { super( null, 'div', attr, children ); } column( m, s ) { if( !E.empty( m ) ) { m = m.toString().toLowerCase(); if( E.bootstrap.conf.columns.includes( m ) ) { s = parseInt( s ); if( s >= 1 && s <= 12 ) { this.attr( 'class', `${m}-${s}` ); } } } return this; } offset( m, s ) { if( !E.empty( m ) ) { m = m.toString().toLowerCase(); if( E.bootstrap.conf.columns.includes( m ) ) { s = parseInt( s ); if( s >= 1 && s <= 12 ) { this.attr( 'class', `${m}-offset-${s}` ); } } } return this; } };
javascript
11
0.5199
50
18.142857
42
starcoderdata
protected override async void Run() { var globalConfig = Silo.CurrentSilo.OrleansConfig.Globals; if (!globalConfig.HasMultiClusterNetwork) return; var myClusterId = globalConfig.ClusterId; while (router.Running) { try { await Task.Delay(period); if (!router.Running) break; logger.Verbose("GSIP:M running periodic check (having waited {0})", period); // examine the multicluster configuration var config = Silo.CurrentSilo.LocalMultiClusterOracle.GetMultiClusterConfiguration(); if (config == null || !config.Clusters.Contains(myClusterId)) { // we are not joined to the cluster yet/anymore. // go through all owned entries and make them doubtful // this will not happen under normal operation // (because nodes are supposed to shut down before being removed from the multi cluster) // but if it happens anyway, this is the correct thing to do var allEntries = router.DirectoryPartition.GetItems(); var ownedEntries = FilterByMultiClusterStatus(allEntries, GrainDirectoryEntryStatus.Owned) .Select(kp => Tuple.Create(kp.Key, kp.Value.Instances.FirstOrDefault())) .ToList(); logger.Verbose("GSIP:M Not joined to multicluster. Make {0} owned entries doubtful {1}", ownedEntries.Count, logger.IsVerbose2 ? string.Join(",", ownedEntries.Select(s => s.Item1)) : ""); await router.Scheduler.QueueTask( () => RunBatchedDemotion(ownedEntries), router.CacheValidator.SchedulingContext ); } else { // we are joined to the multicluster. // go through all doubtful entries and broadcast ownership requests for each // take them all out of the list for processing. List<GrainId> grains; lock (lockable) { grains = doubtfulGrains; doubtfulGrains = new List<GrainId>(); } // filter logger.Verbose("GSIP:M retry {0} doubtful entries {1}", grains.Count, logger.IsVerbose2 ? string.Join(",", grains) : ""); var remoteClusters = config.Clusters.Where(id => id != myClusterId).ToList(); await router.Scheduler.QueueTask( () => RunBatchedActivationRequests(remoteClusters, grains), router.CacheValidator.SchedulingContext ); } } catch (Exception e) { logger.Error(ErrorCode.GlobalSingleInstance_MaintainerException, "GSIP:M caught exception", e); } } }
c#
27
0.48766
211
47.057143
70
inline
public void start() { vertx.createHttpServer() .requestHandler(req -> VertxCloudEvents.create().rxReadFromRequest(req) .subscribe((receivedEvent, throwable) -> { if (receivedEvent != null) { // extract the data/double out of the cloudevent: // I got a cloud Event: Echo that final Double val = Double.parseDouble(receivedEvent.getData().get().toString()); // reading multiplication factor final Double multiplicationFactor = getMultiplicationFactor(); // apply the math final Double result = val * multiplicationFactor; // return result as plain text response... req.response() .putHeader(HttpHeaders.CONTENT_LENGTH, HttpHeaders.createOptimized(String.valueOf(result.toString().length()))) .putHeader(HttpHeaders.CONTENT_TYPE, HttpHeaders.createOptimized("text/plain")) .setStatusCode(200) .end(result.toString()); } else { // error if no cloud event is there // 500 does also prevent a reply in Knative; req.response() .setChunked(true) .putHeader(HttpHeaders.CONTENT_TYPE, HttpHeaders.createOptimized("text/plain")) .setStatusCode(500) .end("nope"); } })) .rxListen(8080) .subscribe(server -> { System.out.println("Server running!"); }); }
java
28
0.417228
151
53.710526
38
inline
#! /usr/bin/env python """ Generate dummy LHE events designed to be showered and make one visible jet in the detector. """ import argparse,numpy,logging logger = logging.getLogger(__name__) def main(): logging.basicConfig(level=logging.INFO) ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("-n",'--numevents', dest="nevts", default=1000, type=int, help="number of events to generate") ap.add_argument('-N','--numfiles',dest='nfiles',default=1,type=int,help='number of files to produce, each with nevts inside.') ap.add_argument("-o",'--outfile-base', dest="output_base", default="events", help="base filename for output event files") ap.add_argument('-e','--ecm',dest='ecm',type=float,default=13000.,help='Center of Mass energy: Units are GeV') ap.add_argument('-a','--eta-max',dest='eta_max',type=float,default=1.5,help='particles are generated within -eta_max and eta_max.') ap.add_argument('-b','--min-e',dest='min_e',type=float,default=100.,help='particles are generated within energy min_e and max_e: Units are GeV') ap.add_argument('-c','--max-e',dest='max_e',type=float,default=1000.,help='particles are generated within energy min_e and max_e: Units are GeV') ap.add_argument('-r','--numpy-seed',dest='numpy_seed',type=int,default=0,help='random number seed to start with') ap.add_argument('-q','--quark-flavor',dest='quark_flavor',type=int,default=5,help='quark flavor in output, 5=bottom, 4=charm, 3=strange, 2=down, 1=up') args = ap.parse_args() logger.info('nevts: %s',args.nevts) logger.info('nfiles: %s',args.nfiles) logger.info('output_base: %s',args.output_base) logger.info('ecm: %s',args.ecm) logger.info('eta_max: %s',args.eta_max) logger.info('min_e: %s',args.min_e) logger.info('max_e: %s',args.max_e) logger.info('numpy_seed: %s',args.numpy_seed) logger.info('quark_flavor: %s',args.quark_flavor) numpy.random.seed(args.numpy_seed) head = """\ <LesHouchesEvents version="1.0"> <!-- File generated with lhegun by --> 2212 2212 {energy:.8E} {energy:.8E} -1 -1 -1 -1 3 1 1E+09 0.0 0.0 12345 """.format(energy=args.ecm/2.) for i in range(args.nfiles): # make a filenames if args.nfiles > 1: outputfilename = args.output_base + ('_%08d.lhe' % i) else: outputfilename = args.output_base + '.lhe' with open(outputfilename, "w") as f: f.write(head) import random, math for i in range(args.nevts): ## Set up for flat sampling of eta and eta = numpy.random.uniform(-args.eta_max, args.eta_max) phi = numpy.random.uniform(0, 2*numpy.pi) energy = numpy.random.uniform(args.min_e, args.max_e) ## Translate coords to x,y,z,t theta = 2*numpy.arctan(numpy.exp(-eta)) pz = energy * numpy.cos(theta) pperp = energy * numpy.sin(theta) px = pperp * numpy.cos(phi) py = pperp * numpy.sin(phi) ## Assemble convenience tuples mom = (px, py, pz, energy) amom = (-px, -py, -pz, -energy) s = """\ 4 12345 1.00E+00 {p[3]:.8E} -1.00E+00 -1.00E-01 21 -1 0 0 511 514 0.00E+00 0.00E+00 {p[3]:.8E} {p[3]:.8E} 0.00E+00 0.00E+00 9.00E+00 {quark_flavor} -1 0 0 514 0 0.00E+00 0.00E+00 {q[3]:.8E} {p[3]:.8E} 0.00E+00 0.00E+00 9.00E+00 {quark_flavor} 1 1 2 511 0 {p[0]:.8E} {p[1]:.8E} {p[2]:.8E} {p[3]:.8E} 0.00E+00 0.00E+00 9.00E+00 12 1 1 2 0 0 {q[0]:.8E} {q[1]:.8E} {q[2]:.8E} {p[3]:.8E} 0.00E+00 0.00E+00 9.00E+00 q=amom,quark_flavor=args.quark_flavor) f.write(s + "\n") f.write(" if __name__ == '__main__': main()
python
17
0.578802
154
45.952941
85
starcoderdata
/* Copyright 2021 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package handlers import ( "net/http" "vitess.io/vitess/go/vt/vtadmin/rbac" ) // NewAuthenticationHandler returns an http middleware that invokes the given // authenticator and calls the next handler in the middleware chain, with the // authenticated actor added to the request context. // // If the authenticator returns an error, then the overall http request is // failed with an Unauthorized code. func NewAuthenticationHandler(authenticator rbac.Authenticator) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { actor, err := authenticator.AuthenticateHTTP(r) if err != nil { http.Error(w, err.Error(), http.StatusUnauthorized) return } next.ServeHTTP(w, r.WithContext(rbac.NewContext(r.Context(), actor))) }) } }
go
22
0.765271
97
32.113636
44
starcoderdata
<?php namespace Service\Balance\Model; class MovementType { public const IN = 'in'; public const OUT = 'out'; }
php
6
0.645161
32
10.363636
11
starcoderdata
def __init__(self, parent): super().__init__(parent) self.base_path_out = ( "work/{{mapper}}.{var_caller}.{{cancer_library}}/out/" "{{mapper}}.{var_caller}.{{cancer_library}}{ext}" ) # Build shortcut from cancer bio sample name to matched tumor sample self.cancer_ngs_library_to_sample_pair = OrderedDict() for sheet in self.parent.shortcut_sheets: self.cancer_ngs_library_to_sample_pair.update( sheet.all_sample_pairs_by_tumor_dna_ngs_library ) # Build shortcut from library name to donor. self.donor_to_cancer_ngs_libraries = OrderedDict() for sheet in self.parent.shortcut_sheets: for pair in sheet.all_sample_pairs_by_tumor_dna_ngs_library.values(): self.donor_to_cancer_ngs_libraries.setdefault(pair.donor.name, []) if pair.tumor_sample.name not in self.donor_to_cancer_ngs_libraries: self.donor_to_cancer_ngs_libraries[pair.donor.name].append( pair.tumor_sample.dna_ngs_library.name )
python
15
0.593474
84
53.047619
21
inline
void Pipeline::recompile(ShaderFile file) { this->file = file; //Destroy all resources allocated by pipeline device.destroyDescriptorSetLayout(descriptorSetLayout1); device.destroyDescriptorSetLayout(descriptorSetLayout2); device.destroyDescriptorSetLayout(descriptorSetLayout3); createDescriptorLayout(file.getProps()); rebuild(extent, renderpass); }
c++
8
0.752525
61
32.083333
12
inline
<?php /** * @package common.extensions.behaviors * @author * @version 1.0 * @modified_by * @modified_date 2013-05-29 */ class SoftDeleteBehavior extends CActiveRecordBehavior { /** * @var string */ public $flagField = 'is_deleted'; public $deletedAt = 'deleted_at'; public $deletedBy = 'deleted_by'; /** * @return CComponent */ public function remove() { $this->getOwner()->{$this->flagField} = 1; $this->getOwner()->{$this->deletedAt} = date('Y-m-d H:i:s'); $this->getOwner()->{$this->deletedBy} = Yii::app()->user->id; $this->getOwner()->save(); return $this->getOwner(); } // public function beforeFind($event) // { // // if ($this->getEnabled()) { // $criteria = new CDbCriteria; // $criteria->condition = "{$this->owner->tableAlias}.{$this->flagField} = 0"; // $this->owner->dbCriteria->mergeWith($criteria); // // } // } /** * @return CComponent */ public function restore() { $this->getOwner()->{$this->flagField} = 0; $this->getOwner()->save(); return $this->getOwner(); } /** * @return CComponent */ public function notRemoved() { $this->getOwner()->getDbCriteria()->mergeWith(array( 'condition'=>$this->flagField.' = 0', 'params'=>array(), )); return $this->getOwner(); /* $criteria = $this->getOwner()->getDbCriteria(); $criteria->compare('t.' . $this->flagField, 0); return $this->getOwner(); */ } /** * @return CComponent */ public function removed() { $this->getOwner()->getDbCriteria()->mergeWith(array( 'condition'=>$this->flagField.' = 1', 'params'=>array(), )); return $this->getOwner(); /* $criteria = $this->getOwner()->getDbCriteria(); $criteria->compare('t.' . $this->flagField, 1); return $this->getOwner(); */ } /** * @return bool */ public function isRemoved() { return (boolean)$this->getOwner()->{$this->flagField}; } }
php
14
0.507637
90
23.733333
90
starcoderdata
private async Task JoinQuitNotifications() { if (MainMenu.MiscSettingsMenu != null) { // Join/Quit notifications if (MainMenu.MiscSettingsMenu.JoinQuitNotifications && IsAllowed(Permission.MSJoinQuitNotifs)) { PlayerList plist = Players; Dictionary<int, string> pl = new Dictionary<int, string>(); foreach (Player p in plist) { pl.Add(p.Handle, p.Name); } await Delay(0); // new player joined. if (pl.Count > playerList.Count) { foreach (KeyValuePair<int, string> player in pl) { if (!playerList.Contains(player)) { Notify.Custom($"~g~<C>{GetSafePlayerName(player.Value)}</C>~s~ joined the server."); await Delay(0); } } } // player left. else if (pl.Count < playerList.Count) { foreach (KeyValuePair<int, string> player in playerList) { if (!pl.Contains(player)) { Notify.Custom($"~r~<C>{GetSafePlayerName(player.Value)}</C>~s~ left the server."); await Delay(0); } } } playerList = pl; await Delay(100); } } }
c#
25
0.360022
116
41.139535
43
inline
<?php namespace FS\Components\Migration; class BoxSplitDataMigration extends AbstractDataMigration { protected $migration_id = 'box_split_data_migration'; protected function update_fls_plugin_settings($option_key) { $settings = \get_option($option_key); if (!$settings || !isset($settings['enable_packing_api'])) { return true; } if ('yes' == $settings['enable_packing_api'] && isset($settings['default_package_box_split'])) { $settings['default_package_box_split'] = 'packing'; } unset($settings['enable_packing_api']); return \update_option($option_key, $settings); } }
php
14
0.617778
104
26
25
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace EnvironmentBuilder.Implementation.Json { internal static class JUtils { public static void ValidateGeneral(string exceptionMessage) { throw new JException(exceptionMessage??"Something went wrong in the Json engine"); } public static void ValidateOutOfBounds(string exceptionMessage = null) { throw new JException(exceptionMessage??"Reached an invalid control block."); } public static void ValidateChar(char? value, params char[] expected) { if (!value.HasValue || expected.All(x => x != value.Value)) throw new JException($"Invalid token. Expected any of '{string.Join(", ",expected.Select(x=>x.ToString()).ToArray())}', got '{(value.HasValue ? value.ToString() : "empty")}'."); } public static void ValidateChar(char? value, char expected, string exceptionMessage = null) { if(!value.HasValue || value != expected) throw new JException(exceptionMessage??$"Invalid token. Expected '{expected}', got '{(value.HasValue?value.ToString():"empty")}'."); } public static void ValidateChar(char? value, string exceptionMessage = null) { if (!value.HasValue) throw new JException(exceptionMessage ?? $"Invalid token. Expected a value, got empty."); } public static void ValidateNonEmpty(string value, string exceptionMessage = null) { if(string.IsNullOrEmpty(value)) throw new JException(exceptionMessage??"Expected non empty value."); } public static void ValidateInterCast { if (typeof(JNode).IsAssignableFrom(typeof(T))) throw new JException("Casting between node or self types is not allowed"); } public static object ConvertToType(object value, Type conversionType) { if (value == null) return null; if (value?.GetType()==conversionType) return value; if (conversionType.IsPrimitive) { return Convert.ChangeType(value, conversionType); } else if (conversionType == typeof(string)) { return value?.ToString() is string tx ? (string)tx : default; } else if (conversionType == typeof(DateTime)) { return DateTime.TryParse(value?.ToString(), out var r) ? (DateTime)(object)r : default; } return Activator.CreateInstance(conversionType); } public static bool CanConvertToType(object value, Type conversionType) { if (conversionType == null) { return false; } if (value == null) { return false; } IConvertible convertible = value as IConvertible; if (convertible == null) { return false; } return true; } public static bool ConformsToType value) { if (default(T) == null && value == null) return true; if (value is T) return true; return CanConvertToType(value, typeof(T)); } public static Type GetGenericTypeFromEnumerable { var o = typeof(T); if (o.IsGenericType && o.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { return o.GetGenericArguments()[0]; } return null; } public static Type GetGenericTypeFromEnumerable(Type o) { if (o.IsGenericType && o.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { return o.GetGenericArguments()[0]; } return null; } private static IDictionary<Type, MethodInfo> _methodCache=new Dictionary<Type, MethodInfo> { {typeof(JValueNode),typeof(JUtils) .GetMethods().FirstOrDefault(x=>x.Name==nameof(Cast) && x.IsPublic && x.IsStatic && x.GetParameters().Any(z=>z.ParameterType==typeof(JValueNode))) }, {typeof(JEnumerationNode),typeof(JUtils) .GetMethods().FirstOrDefault(x=>x.Name==nameof(Cast) && x.IsPublic && x.IsStatic && x.GetParameters().Any(z=>z.ParameterType==typeof(JEnumerationNode))) }, {typeof(JContentNode),typeof(JUtils) .GetMethods().FirstOrDefault(x=>x.Name==nameof(Cast) && x.IsPublic && x.IsStatic && x.GetParameters().Any(z=>z.ParameterType==typeof(JContentNode))) }, }; public static MethodInfo GetCastMethodForInputType { if (!_methodCache.ContainsKey(typeof(T))) return null; return _methodCache[typeof(T)]; } public static MethodInfo GetCastMethodForInputType(Type t) { if (!_methodCache.ContainsKey(t)) return null; return _methodCache[t]; } public static T Cast JContentNode node) { //case sensitive as per spec var keys = ((IDictionary<string, JNode>)node.Value).Keys; var t = typeof(T); var obj = Activator.CreateInstance foreach (var propertyInfo in t.GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(x => keys.Contains(x.Name))) { var nodex = node[propertyInfo.Name] as JNode; var targetType = propertyInfo.PropertyType; MethodInfo method = null; switch (nodex.Type) { case JNode.NodeType.Leaf: method = GetCastMethodForInputType break; case JNode.NodeType.Node: method = GetCastMethodForInputType break; case JNode.NodeType.Enumeration: method = GetCastMethodForInputType break; } var genericMethod = method.MakeGenericMethod(targetType); var result = genericMethod.Invoke(null, new object[] { nodex }); propertyInfo.SetValue(obj, result, null); } return (T)obj; } public static T Cast JValueNode node) { ValidateInterCast var actualValue = node.Value; if (actualValue is T t) return t; if (typeof(T).IsPrimitive) { if (actualValue == null && Nullable.GetUnderlyingType(typeof(T)) != null) return default; else return (T)Convert.ChangeType(actualValue, typeof(T)); }else if (typeof(T) == typeof(string)) { return actualValue?.ToString() is T tx?(T)tx:default; }else if (typeof(T) == typeof(DateTime)) { if (actualValue == null && Nullable.GetUnderlyingType(typeof(T)) != null) return default; return DateTime.TryParse(actualValue?.ToString(), out var r) ? (T)(object)r : default; } ValidateOutOfBounds($"Could not parse the value of type {typeof(T)}"); throw new NotImplementedException("This should never be hit. My mistake if it is."); } public static IEnumerable Cast JEnumerationNode node) { var list = node.Value as IEnumerable if (list == null || !list.Any()) return Enumerable.Empty if(!list.All(x=>ConformsToType ValidateGeneral("Cannot cast to enumeration of type {typeof(T)}. All of the items may not conform to the type."); return list.Select(x => { if (default(T) == null && x == null) return default; if (x is T a) return a; return (T)Convert.ChangeType(x.Value, typeof(T)); }); } } }
c#
25
0.528814
193
38.363636
220
starcoderdata
import { combineReducers } from 'redux' import { modalReducer as modal } from './modal/reducer' import { sidebarReducer as sidebar } from './sidebar/reducer' import { marketplaceReducer as marketplace } from './marketplace/reducer' export const uiReducer = combineReducers({ modal, sidebar, marketplace })
javascript
5
0.756303
73
28.75
12
starcoderdata
/** * API routes are only used for download and upload streams. * The main communication between the client (frontend) and the ServerQuery is * still handled by socket.io. */ const config = require("../config") const express = require("express") const router = express.Router() const jwt = require("jsonwebtoken") const {TeamSpeak} = require("ts3-nodejs-library") const {logger, whitelist} = require("../utils") const {Socket} = require("net") const Busboy = require('busboy') const Path = require("path") /** * Authenticate every request and try to connect to the ServerQuery. */ router.use(async (req, res, next) => { let {token, serverId} = req.cookies let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress let log = logger.child({client: ip}) res.locals.log = log try { let decoded = jwt.verify(token, config.secret) whitelist.check(decoded.host) let ServerQuery = await TeamSpeak.connect(decoded) await ServerQuery.execute("use", {sid: serverId}) res.locals.ServerQuery = ServerQuery log.info("API request authenticated") next() } catch(err) { next(err) } }) /** * Download file from the server. */ router.get("/download", async (req, res, next) => { let {path, name, cid} = req.query let {ServerQuery, log} = res.locals let receivedBytes = 0 let socket = new Socket() try { // Even on Windows TeamSpeak uses only POSIX specifc paths let {ftkey, port, size} = await ServerQuery.ftInitDownload({cid, name: Path.posix.join(path, name)}) socket.connect(port, ServerQuery.config.host) socket.on("connect", () => { res.setHeader("content-disposition", `attachment; filename=${name}`) res.setHeader("content-length", size) socket.write(ftkey) log.info(`Downloading File "${name}"`) socket.pipe(res) }) socket.on("end", async () => { socket.end() await ServerQuery.execute("quit") }) socket.on("error", async (err) => { socket.destroy() await ServerQuery.execute("quit") next(err) }) } catch(err) { next(err) } }) /** * Upload file to the server */ router.post("/upload", async (req, res, next) => { let {path, cid} = req.query let size = req.headers["content-length"] let {ServerQuery, log} = res.locals let busboy = new Busboy({headers: req.headers}) let socket = new Socket() try { busboy.on("file", async (fieldname, file, filename, encoding, mimetype) => { let {port, ftkey} = await ServerQuery.ftInitUpload({name: Path.posix.join(path, filename), cid, size}) socket.connect(port, ServerQuery.config.host) socket.on("connect", () => { socket.write(ftkey) log.info(`Uploading File "${filename}" to "${path}"`) file.pipe(socket) }) socket.on("error", async (err) => { socket.destroy() await ServerQuery.execute("quit") next(err) }) busboy.on("finish", async () => { log.info(`File "${filename}" successfully uploaded`) socket.end() await ServerQuery.execute("quit") res.sendStatus(200) }) }) req.pipe(busboy) } catch(err) { next(err) } }) /** * Handle errors. * This middleware needs to have 4 arguments in the callback function. * Otherwise express.js will not handle it as an error middleware. */ router.use((error, req, res, next) => { let {log} = res.locals log.error(error.message) res.status(400).send(error.message) }) module.exports = router
javascript
20
0.631814
108
22.227273
154
starcoderdata
static int si7210_pm_action(const struct device *dev, enum pm_device_action action) { int rc; switch (action) { case PM_DEVICE_ACTION_RESUME: /* Wake-up the chip */ rc = si7210_wakeup(dev); break; case PM_DEVICE_ACTION_SUSPEND: /* Put the chip into sleep mode */ rc = si7210_sleep(dev); break; default: return -ENOTSUP; } return rc; }
c
10
0.659341
53
17.25
20
inline
<?php namespace app\cmsv3\model; use think\Model; class Person extends Model { protected $table = 'person'; // 定义关联方法 // public function department() // { // // 用户HAS ONE档案关联 // return $this->belongsTo('Department') // ->bind([ // 'departmentName' => 'label', // '别名' => '字段名' // 'p_ids' => 'p_ids' // ]);; // } public function performance() { return $this->hasMany('Performance', 'belong_id', 'openid') ->order('pubdate DESC'); } }
php
11
0.509061
67
22.346154
26
starcoderdata
def parcels(self, node_list): """ Plots 3D parcels specified in the node_list. This function assumes the parcellation template has been loaded to the brain using brain.importISO. Note, values passed to this function should correspond with those in the iso image, not necessarily the node values. """ zero_arr = np.zeros(self.iso.shape) for n in node_list: n = float(n) # parcel files start from 1, zero is for background n_arr = np.ma.masked_where(self.iso != (n + 1), self.iso) n_arr.fill_value = 0.0 zero_arr = zero_arr + n_arr zero_arr.mask = None self.parcel_list = np.ma.masked_values(zero_arr, 0.0)
python
12
0.593875
81
38.578947
19
inline
package org.jcider.rest; import static spark.Spark.*; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import org.jcider.controllers.WRController; import org.jcider.indexer.ValueIndexEngine; import org.jcider.store.KeyStorage; public class RestInterface { //Initialize Sub System static int servicePort; static final KeyStorage ks = new KeyStorage(); static final ValueIndexEngine vie = new ValueIndexEngine(); public static void main( String[] args ){ Properties prop = new Properties(); try { prop.load(new FileInputStream("cider.conf")); servicePort = Integer.parseInt(prop.getProperty("servicePort")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Starting web server on port: " + servicePort); port(servicePort); /* * Java Spark is ok for proof of concept, but http://www.rapidoid.org/ is 50%+ faster if your going to stick with http proto * Adding ANYTHING creates overhead, the fact we are using http creates overhead, use a different protocol to reduce overhead * Using Rapidoid I seen test benchmarks up to ~98k/sec reads & ~75k/sec inserts, 2x what I was able to achieve with the Spark framework * However the Spark framework was easier to implement. If you desire to fork and switch to Rapidoid, the conversion is simple. * * User input is only lightly validated, its not robust WHAT SO EVER, see comment on overhead * In that same vein, there is NO authentication mechanism built into this code base * This is NOT production ready * * If Cider dies, any items waiting in the Lucene queue will be lost * WAL is disabled for MapDB, feel free to add it (its one line, see documentation for Mapdb). Will provide better redundancy if system dies for key store * * Remember to set -Xmx128M to reduce max head size, and increased memory allocation -XX:MaxDirectMemorySize=4G (up to you to tune params, see configuration) * * See Lucene documentation for query syntax * https://lucene.apache.org/core/2_9_4/queryparsersyntax.html#Fuzzy Searches * */ //Get Key Value get("/cache/:key", (req, res)->{ res.type("application/json"); return WRController.getData(req.params(":key")); }); //Put Key Value put("/cache", (req, res)->{ res.type("application/json"); return WRController.writeData(req.body()); }); //Delete Key Value delete("/cache/:key", (req, res)->{ res.type("application/json"); return WRController.deleteData(req.params(":key")); }); //Search for data in K/V space via values in "data" and/or "meta" data, advanced querying use Lucene query language post("/search", (req,res)->{ res.type("application/json"); return WRController.search(req.body()); }); } }
java
16
0.701832
161
36.316456
79
starcoderdata
import java.util.*; import java.util.function.*; import java.util.stream.*; import java.io.*; import java.math.*; public class LongestSubstringwithAtMostTwoDistinctCharacters { public int lengthOfLongestSubstringTwoDistinct(String s) { char[] chars = s.toCharArray(); int r = 0; int l = 0; Map<Character, Integer> existingCharsCounter = new HashMap<>(); int longest = 0; while (r < s.length()) { while (r < s.length() && (existingCharsCounter.size() < 2 || existingCharsCounter.containsKey(chars[r]))) { existingCharsCounter.merge(chars[r], 1, (oldV, v) -> oldV + v); r++; } longest = Math.max(longest, existingCharsCounter.entrySet().stream().mapToInt(e -> e.getValue()).sum()); while (existingCharsCounter.size() == 2) { existingCharsCounter.compute(chars[l], (k, v) -> --v == 0 ? null : v); l++; } } return longest; } }
java
17
0.552885
116
33.7
30
starcoderdata
var sockets_8h = [ [ "accept", "group__socket.html#gade2b17671b5a4b18e941fbf7e1060310", null ], [ "bind", "group__socket.html#ga4a88bb849aa7203b24bb245a193997a6", null ], [ "close", "group__socket.html#ga4ef17e85ec4d3acdcee5ce23f8ed93c4", null ], [ "closesocket", "group__socket.html#ga5a3eb971b466278ada4f7f87399a537c", null ], [ "connect", "group__socket.html#gae3d13671f622e17c17317c9a16dfd0ee", null ], [ "fcntl", "group__socket.html#gaaa2b0e00cab161fcc4b31ee0d06e7eb3", null ], [ "getpeername", "group__socket.html#ga33bf1b7f5b11de02d0db32531cd940b8", null ], [ "getsockname", "group__socket.html#gab096fb7dbc3f84be1699a87dce980f2f", null ], [ "getsockopt", "group__socket.html#gad2de02b35dbbf2334d1befb137ede821", null ], [ "inet_ntop", "group__socket.html#gaa40bf11abb409097e68aa3a6982eb52b", null ], [ "inet_pton", "group__socket.html#ga90d2b417d82e8da981c940a665324fd5", null ], [ "ioctl", "group__socket.html#ga50a83956bc3a96e6274a21ec0d4d6338", null ], [ "ioctlsocket", "group__socket.html#ga19e714443d0238cfd79b71059ec92378", null ], [ "listen", "group__socket.html#gae6e6de5a20bed9fc7078f0e6c9c4aca4", null ], [ "LWIP_TIMEVAL_PRIVATE", "sockets_8h.html#aaffd64f6887883ec6401e6bb684c40fa", null ], [ "poll", "group__socket.html#ga80ae38841b0e64e60618cd8bf857f617", null ], [ "read", "group__socket.html#ga822040573319cf87bfe6758d511be57f", null ], [ "readv", "group__socket.html#ga86788b3c690d38699fdbaea523ddec9d", null ], [ "recv", "group__socket.html#gadd7ae45df7c005619eb1126542231e9b", null ], [ "recvfrom", "group__socket.html#ga5e5f7bcda6562bae815e188ea1a81ecd", null ], [ "recvmsg", "group__socket.html#gaecfc7d524105e52604829c66ced752b8", null ], [ "select", "group__socket.html#gac332b9b9b2cd877a6189ef838de49e33", null ], [ "send", "group__socket.html#ga19024690fdfd3512d24dcaa9b80d24ed", null ], [ "sendmsg", "group__socket.html#gaad99bea090b1fe4743234fcee15a5d28", null ], [ "sendto", "group__socket.html#gaaa17499d76ef421821fe72fd29fe38f7", null ], [ "setsockopt", "group__socket.html#ga115d74cd1953e7bafc2e34157c697df1", null ], [ "shutdown", "group__socket.html#ga7d832f77cfad97cf901640f243c6e682", null ], [ "socket", "group__socket.html#ga862d8f4070c66dddb979540ce9ba6a83", null ], [ "write", "group__socket.html#ga0a651eb5fb5e6127f5e5153ce2251f3d", null ], [ "writev", "group__socket.html#ga697fd916a65a10b4dcb54b8199346fee", null ], [ "lwip_fcntl", "sockets_8h.html#ae84296093574ec746f8f88321356388f", null ], [ "lwip_listen", "sockets_8h.html#abee6ee286147cf334a1ba19f19b2e08b", null ], [ "lwip_shutdown", "sockets_8h.html#ade85c68b6673296c8fb67127b93fa4c1", null ], [ "lwip_socket_thread_cleanup", "sockets_8h.html#ab8cd92b10dbe3fb33da03faed1ea98a7", null ], [ "lwip_socket_thread_init", "sockets_8h.html#a0a250b3b4d1827e3a3661327f5e80ae0", null ] ];
javascript
3
0.733601
96
75.641026
39
starcoderdata
/** * * Test Git Hub and other if any related to project configuration. */ public class HelloWorld { public static void main(String[] args) { System.out.print("This is test"); } }
java
7
0.665254
66
20.545455
11
starcoderdata
package framework.utilities.swipe; import aquality.appium.mobile.actions.ITouchActions; import aquality.appium.mobile.application.AqualityServices; import aquality.appium.mobile.elements.interfaces.IElement; import framework.utilities.swipe.directions.EntireElementSwipeDirection; import framework.utilities.swipe.directions.EntireScreenDragDirection; import io.appium.java_client.MobileElement; import org.openqa.selenium.Dimension; import org.openqa.selenium.Point; import org.openqa.selenium.Rectangle; public final class SwipeElementUtils { private SwipeElementUtils() { } public static void swipeElementLeft(IElement element) { MobileElement mobileElement = element.getElement(); Point upperLeft = mobileElement.getLocation(); Dimension dimensions = mobileElement.getSize(); element.getTouchActions().swipe(new Point(upperLeft.x, upperLeft.y + dimensions.height / 2)); } public static void swipeElementDown(IElement element) { MobileElement mobileElement = element.getElement(); Point upperLeft = mobileElement.getLocation(); Dimension dimensions = mobileElement.getSize(); element.getTouchActions().swipe(new Point(upperLeft.x + dimensions.width / 2, upperLeft.y + dimensions.height)); } public static void swipeElementUp(IElement element) { MobileElement mobileElement = element.getElement(); Point upperLeft = mobileElement.getLocation(); Point center = mobileElement.getCenter(); element.getTouchActions().swipe(new Point(center.x, upperLeft.y)); } public static void swipeThroughEntireElementUp(IElement element) { MobileElement mobileElement = element.getElement(); Point upperLeft = mobileElement.getLocation(); Point center = mobileElement.getCenter(); Dimension dimensions = mobileElement.getSize(); ITouchActions touchActions = AqualityServices.getTouchActions(); touchActions.swipe(new Point(center.x, upperLeft.y + dimensions.height - 1), new Point(center.x, upperLeft.y - 1)); } public static void swipeFromLeftToRight(IElement element) { MobileElement mobileElement = element.getElement(); Rectangle rectangle = mobileElement.getRect(); element.getTouchActions().swipe(new Point(rectangle.x + rectangle.width - 1, mobileElement.getCenter().y)); } public static void swipeFromRightToLeft(IElement element) { element.getTouchActions().swipe(new Point(0, element.getElement().getCenter().y)); } /** * The method can be applied to every element with swiping support. * Swipe/scroll will be performed from one edge of the element to another. * * @param element element to be scrolled/swiped * @param entireElementSwipeDirection direction of the scroll/swipe */ public static void swipeThroughEntireElement(IElement element, EntireElementSwipeDirection entireElementSwipeDirection) { Direction direction = entireElementSwipeDirection.getSwipeDirection(element); AqualityServices.getTouchActions().swipe(direction.getFrom(), direction.getTo()); } /** * The method can be applied to every element with swiping/dragging support. * Swipe/drag will be performed from one edge of the screen to another. * * @param element element to be dragged/swiped * @param entireScreenDragDirection direction of the drag/swipe */ public static void dragElementThroughEntireScreen(IElement element, EntireScreenDragDirection entireScreenDragDirection) { Direction direction = entireScreenDragDirection.getDragDirection(element); AqualityServices.getTouchActions().swipe(direction.getFrom(), direction.getTo()); } }
java
12
0.73311
126
46.292683
82
starcoderdata
import test from 'ava' import m from '..' test('errors', async t => { await t.throwsAsync(() => m('hello'), /Expected a Array/) await t.throwsAsync(() => m(['en', 'ja'], 2), /Expected a string/) await t.throwsAsync(() => m(['en', 'ja'], 'app/', 2), /Expected a string/) })
javascript
13
0.575342
76
31.444444
9
starcoderdata
module.exports = { ROLE: { DRIVER: 'driver', ADMIN: 'admin' }, REQUEST: { UNLOCATED: 0, LOCATED: 1, RECEIVED: 2, MOVING: 3, COMPLETED: 4 }, PROCESS: { SENT: 0, REJECTED: 1, ACCEPTED: 2 }, RETRIES: 5000 }
javascript
8
0.542955
32
13.55
20
starcoderdata
#include #include std::optional calculo_que_puede_fallar(bool b) { if (b) { return "este es el resultado en caso de exito"; } else { return {}; } } auto main() -> int { std::optional result = calculo_que_puede_fallar(false); if (result == std::nullopt) { std::cout << "hubo un error" << std::endl; } else { std::cout << *result << std::endl; } }
c++
10
0.638581
69
20.47619
21
starcoderdata
<?php namespace Modules\Branch\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Routing\Controller; use Modules\Branch\Entities\Branch; class BranchController extends Controller { /** * Display a listing of Branch. */ public function index(Request $request) { $branch = Branch::where(function($query) use($request) { if($request->has('city_id')) { $query->where('city_id' , $request->city_id); } })->paginate(10); return responsejson(1 , 'ok' , $branch); } /** * Store a newly Branch. * @bodyParam name string required The name of the Branch. * @bodyParam open_time time required The time opening of the Branch. * @bodyParam close_time time required The time closeing of the Branch. * @bodyParam city_id int required The name of city the Branch was located. */ public function store(Request $request) { $data = $request->all(); $validator = validator()->make($data, [ 'name' => 'required|min:6', 'open_time' => 'required|date_format:H:i', 'close_time' => 'required|date_format:H:i|after:time_start', 'city_id' => 'required|numeric', ]); if ($validator->fails()) { return responsejson(1 , $validator->errors()->first() , $validator->errors()); } $branch = Branch::create($request->all()); $branch->save(); return responsejson(1 , 'OK' ,$branch); } /** * Show the Branch. * @bodyParam int $id required */ public function show($id) { $branch = Branch::find($id); if(! $branch) { return responsejson( 0 , 'OPPs' , 'There Is No Branch Request'); } return responsejson(1 , 'OK' , $branch); } /** * Update Branch. * @bodyParam name string required The name of the Branch. * @bodyParam open_time time required The time opening of the Branch. * @bodyParam close_time time required The time closeing of the Branch. * @bodyParam city_id int required The name of city the Branch was located. */ public function update(request $request , $id) { $branch = Branch::find($id); if (!$branch) { return responseJson(0 , 'OPPs' , 'There Is No Branch Request'); } $data = $request->all(); $validator = validator()->make($data, [ 'name' => 'required|min:6', 'open_time' => 'required|date_format:H:i', 'close_time' => 'required|date_format:H:i|after:time_start', 'city_id' => 'required|numeric', ]); if ($validator->fails()) { return responsejson(0 , $validator->errors()->first() , $validator->errors()); } $branch->update($data); return responsejson(1 , 'OK' , $branch); } /** * Remove the Branch. * @bodyParam int $id required */ public function destroy($id) { $branch = Branch::find($id); if (!$branch) { return responseJson(0 , 'OPPs' , 'There Is No Branch Request'); } $branch->delete(); return responseJson(1 , 'OK' , 'Deleted done successfully'); } }
php
21
0.518026
91
30.356522
115
starcoderdata
// Hyphenator (cmd ctrl alt h) @import 'js/utilities.js' /** * Hyphenation using Liang-Knuth algorithm. * version 0.1.2 (01.09.2010) * Copyright (C) 2008-2010 ( * * Web service's written by * Plugin's written by */ var onRun = function(context) { var selection = context.selection; var loop = [selection objectEnumerator] while (layer = [loop nextObject]) { if (!isText(layer)) continue; var url = "http://design-school.me/apps/hyphen/", body = "text=" + encodeURIComponent([layer stringValue]), result = getURLString(url, 'POST', body); [layer setStringValue: result ] // inject typographed text // rerender text layer var width = layer.absoluteRect().width(); [layer setTextBehaviour: 0] // Make it flexible: 1 — BCTextBehaviourFixedWidth [layer setTextBehaviour: 1] // Make it fixed back: 0 — BCTextBehaviourFlexibleWidth layer.absoluteRect().width = width; [layer adjustFrameToFit] } }
javascript
11
0.63129
92
28.567568
37
starcoderdata
#include "random.h" void Random::Init(unsigned int seed) { srand(seed); } double Random::Double(double min, double max) { double r = (double) rand() / RAND_MAX; return min + r * (max - min); } unsigned int Random::UInt(unsigned int min, unsigned int max) { unsigned int r = (unsigned int) rand() % (max - min + 1); return min + r; } int Random::Int(int min, int max) { int r = (int) rand() % (max - min + 1); return min + r; }
c++
9
0.603239
61
16.642857
28
starcoderdata
import styled from 'styled-components/native'; export const Container = styled.View` flex: 1; background: #FFFFFF; `; export const TodoFormContainer = styled.View` background: #FFFFFF; border-radius: 10px; padding: 10px; margin: 10px 20px 10px 20px; `; export const TodoInput = styled.TextInput.attrs({ placeholder: 'Insert ToDo' })` background-color: #FFFFFF; border-width: 2px; border-color: #141414; border-radius: 25px; margin: 10px 10px 10px 10px; padding-left: 10px; ` export const Send = styled.TouchableOpacity.attrs({ activeOpacity: 0.5, })` justify-content: center; background-color: #393f8f; margin: 0px 20px 0px 20px; min-height: 30px; border-radius: 25px; ` export const ButtonText = styled.Text` color: #FFFFFF; text-align: center; ` export const Title = styled.Text` color: #141414; text-align: center; font-size: 24px; font-weight: bold; `
javascript
10
0.702525
51
18.826087
46
starcoderdata
// Orphanet Disease Names Field Handler // Tagify Field handler with whitelist and Orphanet ajax var conclusion = document.querySelector("input[id=diagnostic]"); var conclusion_tag = new Tagify(conclusion, { enforceWhitelist: true, whitelist: [$("input[id=diagnostic]").val(), "UNCLEAR", "HEALTHY", "OTHER"], mode: "select", }); conclusion_tag.on("input", onInputConclusion); // Tagify AJAX Function to get a list of Orphanet names var myHeaders_orpha = new Headers({ apiKey: "impatient", }); var options_orpha = { headers: myHeaders_orpha, }; var delayTimer; function onInputConclusion(e) { conclusion_tag.whitelist = null; // reset the whitelist // show loading animation and hide the suggestions dropdown conclusion_tag.loading(true).dropdown.hide(); clearTimeout(delayTimer); delayTimer = setTimeout(function () { var value = e.detail.value; fetch( "https://api.orphacode.org/EN/ClinicalEntity/ApproximateName/" + value, options_orpha ) .then((RES) => RES.json()) .then(function (newWhitelist) { var terms_list = []; for (var i = 0; i < newWhitelist.length; i++) { terms_list.push( "ORPHA:" + newWhitelist[i]["ORPHAcode"] + " " + newWhitelist[i]["Preferred term"] ); } terms_list.push("UNCLEAR", "HEALTHY", "OTHER"); conclusion_tag.whitelist = terms_list; conclusion_tag.loading(false); conclusion_tag.dropdown.show(); // render the suggestions dropdown }); }, 700); }
javascript
24
0.640867
78
30.666667
51
starcoderdata
package com.kasperin.inventory_management.services; import com.kasperin.inventory_management.domain.enums.FoodType; import com.kasperin.inventory_management.domain.Items.ProcessedFood; import com.kasperin.inventory_management.repository.ItemsRepository.ProcessedFoodRepo; import com.kasperin.inventory_management.services.itemsServices.ProcessedFoodServiceImpl; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class ProcessedFoodServiceImplTest { public static final Long ID = 1L; public static final Long ID2 = 2L; public static final String NAME = "Chip"; public static final String NAME2 = "Burger"; public static final String BARCODE = "123456"; public static final String BARCODE2 = "789012"; public static final double PRICE = 1.9; public static final double PRICE2 = 1.9; public static final FoodType FOODTYPE = FoodType.VEGAN; public static final FoodType FOODTYPE2 = FoodType.NONVEGAN; @Mock ProcessedFoodRepo processedFoodRepository; @InjectMocks ProcessedFoodServiceImpl processedFoodService; @Test void save() throws Exception { //given ProcessedFood savedProcessedFood = new ProcessedFood(); savedProcessedFood.setId(ID); savedProcessedFood.setName(NAME); savedProcessedFood.setBarcode(BARCODE); savedProcessedFood.setPrice(PRICE); savedProcessedFood.setFoodType(FOODTYPE); when(processedFoodRepository.save(any())) .thenReturn(savedProcessedFood); ProcessedFood result = processedFoodService.save(savedProcessedFood); verify(processedFoodRepository).save(any()); assertEquals(savedProcessedFood, result); } // @Test // void findById() { // // given // ProcessedFood processedFood = new ProcessedFood(); // processedFood.setId(ID); // // when(processedFoodRepository.findById(anyLong())).thenReturn(Optional.of(processedFood)); // // // when // ProcessedFood result = processedFoodService.findById(ID).get(); // // // then // verify(processedFoodRepository).findById(eq(ID)); // // assertEquals(ID, result.getId()); // } /* @Test void findByName() { // given ProcessedFood processedFood = new ProcessedFood(); processedFood.setId(ID); processedFood.setName(NAME); when(processedFoodRepository.findByName(anyString())) .thenReturn(Optional.of(processedFood)); // when Optional result = processedFoodService .findByName(NAME); // then verify(processedFoodRepository).findByName(eq(NAME)); assertEquals(processedFood, result.get()); }*/ @Test void findAll() { // given List processedFoods = Arrays.asList(new ProcessedFood(), new ProcessedFood()); when(processedFoodRepository.findAll()).thenReturn(processedFoods); // when List result = processedFoodService.findAll(); // then verify(processedFoodRepository).findAll(); assertEquals(2, result.size()); } /*@Test void deleteById() throws Exception { // given ProcessedFood savedProcessedFood = new ProcessedFood(); savedProcessedFood.setId(ID); // savedProcessedFood.setName(NAME); // savedProcessedFood.setBarcode(BARCODE); // savedProcessedFood.setPrice(PRICE); // savedProcessedFood.setFoodType(FOODTYPE); processedFoodService.save(savedProcessedFood); // when processedFoodService.deleteById(ID); // then verify(processedFoodRepository, atLeastOnce()).deleteById(eq(ID)); }*/ }
java
13
0.692616
101
31.358779
131
starcoderdata
# Python implementation of Blynk program import blynklib import random BLYNK_AUTH = ' # initialise blynk blynk = blynklib.Blynk(BLYNK_AUTH) #initialise virtual pins temp_pin = 1 light_pin = 2 humidity_pin = 3 #initialise variables, need to be updated with real values temp = 23 light = 500 humidity = 20 READ_PRINT_MSG = "Temp: V{}, Light: V{}, Humidity: V{}" # register handler for virtual pin reading @blynk.handle_event('read V{1') def read_virtual_pin_handler(pin): print(READ_PRINT_MSG.format(temp_pin, light_pin, humidity_pin)) blynk.virtual_write(temp_pin, temp) blynk.virtual_write(light_pin, light) blynk.virtual_write(humidity_pin, humidity) ########################################################### # infinite loop that waits for event ########################################################### while True: blynk.run()
python
9
0.624711
67
24.470588
34
starcoderdata
<?php namespace NumenCode\Fundamentals\Classes; use UnexpectedValueException; use Backend\Facades\BackendAuth; class CmsPermissions { protected static $revokes = [ 'create' => [], 'update' => [], 'delete' => [], 'duplicate' => [], ]; public static function canCreate($controller) { return static::can('create', $controller); } public static function canUpdate($controller) { return static::can('update', $controller); } public static function canDelete($controller) { return static::can('delete', $controller); } public static function revokeCreate($group, $controller) { static::revoke('create', $group, $controller); } public static function revokeUpdate($group, $controller) { static::revoke('update', $group, $controller); } public static function revokeDelete($group, $controller) { static::revoke('delete', $group, $controller); } protected static function can($action, $controller) { static::validateAction($action); $controller = is_string($controller) ? $controller : get_class($controller); $groups = BackendAuth::getUser() ? BackendAuth::getUser()->groups->lists('code') : []; foreach ($groups as $group) { if (!empty(static::$revokes[$action][$group][$controller])) { return false; } } return true; } protected static function revoke($action, $group, $controller) { static::validateAction($action); if (is_array($group)) { return array_map(function ($group) use ($action, $controller) { static::revoke($action, $group, $controller); }, $group); } if (!isset(static::$revokes[$action][$group])) { static::$revokes[$action][$group] = []; } static::$revokes[$action][$group][$controller] = true; } protected static function validateAction($action) { if (!in_array($action, array_keys(static::$revokes))) { throw new UnexpectedValueException('Unexpected revoke type encountered: ' . $action); } } }
php
18
0.575501
97
25.72619
84
starcoderdata
import pymysql.cursors from django.conf import settings def yearning_op_add(username, nickname, email): connect = pymysql.connect( host=settings.Y_HOST, port=settings.Y_PORT, user=settings.Y_USER, password=settings.Y_PASSWORD, db=settings.Y_DATABASE, charset='utf8', cursorclass=pymysql.cursors.DictCursor ) try: with connect.cursor() as cursor: # 创建游标 # 插入数据 sql = "INSERT INTO `dba_audit`.`core_accounts`(`username`, `password`, `rule`, `department`, `real_name`, " \ "`email`, `is_read`) " \ "VALUES ('{username}', 'none', 'guest', 'all', '{nickname}', " \ "'{email}', 0);".format(username=username,nickname=nickname,email=email) print(sql) cursor.execute(sql) sql1 = "INSERT INTO `dba_audit`.`core_graineds`(`username`, `group`) " \ "VALUES ('{username}', '[\"DEV\",\"PROD\",\"Prod_RO\"]');".format(username=username) cursor.execute(sql1) except Exception as e: print(e) connect.rollback() # 事务回滚 connect.commit() connect.close() # 关闭数据库连接 def yearning_op_del(username): connect = pymysql.connect( host=settings.Y_HOST, port=settings.Y_PORT, user=settings.Y_USER, password= db=settings.Y_DATABASE, charset='utf8', cursorclass=pymysql.cursors.DictCursor ) try: with connect.cursor() as cursor: # 创建游标 sql = "DELETE FROM dba_audit.core_accounts WHERE username = '{username}'".format(username=username) cursor.execute(sql) sql1 = "DELETE FROM dba_audit.core_graineds WHERE username = '{username}'".format(username=username) cursor.execute(sql1) except Exception as e: print(e) connect.rollback() # 事务回滚 connect.commit() connect.close() # 关闭数据库连接
python
14
0.58226
121
33.220339
59
starcoderdata
__version__ = "3.8.0" __copyright__ = "(c) 2021 __license__ = "MIT"
python
4
0.609929
53
19.142857
7
starcoderdata
const types = require('../constants/ActionTypes'); const cacheUtils = require('../utils/cache'); const { CACHE_SIZE } = require('../constants/HomeConstants'); const cacheItemRequested = function (cacheKey) { return { type: types.QUERY_CACHE_ITEM_REQUESTED, key: cacheKey, }; }; const setCache = function (cache) { return { type: types.QUERY_SET_CACHE, cache, }; }; const clearCacheItems = function (cache, deviceType, ...rest) { return function (dispatch, getState) { dispatch(setCache(cacheUtils.filterCacheItems(cache, deviceType, ...rest))); }; }; const saveToCache = function (cache, cacheKey, data) { return function (dispatch, getState) { if (!cacheKey) return; if (Object.keys(cache).length >= CACHE_SIZE) { console.warn('Cache limit exceeded, making space by emptying LRU...'); const newCacheKeys = Object.keys(cache) .sort((a, b) => cache[b].counter - cache[a].counter) .filter((x, i) => i < Object.keys(cache).length - 1); const newCache = {}; newCacheKeys.forEach((key) => { newCache[key] = cache[key]; }); dispatch(setCache(newCache)); } dispatch({ type: types.QUERY_SAVE_TO_CACHE, key: cacheKey, data, }); }; }; const fetchFromCache = function (cache, cacheKey) { return function (dispatch, getState) { if (cache[cacheKey]) { dispatch(cacheItemRequested(cacheKey)); const { data } = cache[cacheKey]; return Promise.resolve(data); } return Promise.reject('notFound'); }; }; module.exports = { clearCacheItems, saveToCache, fetchFromCache, };
javascript
20
0.628415
80
23.58209
67
starcoderdata
package control; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; import model.Usuario; import view.manage.Escolheabre; import view.manage.escolhetimeabre; import view.manage.principalabre; import view.manage.realprincipalabre; public class EscolheModoController implements Initializable { @FXML private Label lbreal, lbtexto1, lbvirtual, lbtitulo, lbtexto2; @FXML private Button btreal, btvirtual; @FXML private ImageView ivfundo, ivreal, ivvirtual; @FXML private Pane panefrente, panefundo, panefrente2, panefundo2; private static Usuario usu; public static Usuario getUsu() { return usu; } public static void setUsu(Usuario usu) { EscolheModoController.usu = usu; } @Override public void initialize(URL url, ResourceBundle rb) { btvirtual.setOnMouseEntered(value->{ panefrente.setOpacity(0); ivvirtual.setOpacity(0); }); btvirtual.setOnMouseExited(value->{ panefrente.setOpacity(100); ivvirtual.setOpacity(100); }); btreal.setOnMouseEntered(value->{ panefrente2.setOpacity(0); ivreal.setOpacity(0); }); btreal.setOnMouseExited(value->{ panefrente2.setOpacity(100); ivreal.setOpacity(100); }); btvirtual.setOnMouseClicked(value->{ principalabre p1 = new principalabre(usu); Escolheabre e1 = new Escolheabre(usu); e1.fecharTela(); p1.abreTela(); }); btreal.setOnMouseClicked(value->{ if(usu.isModoreal() == true){ realprincipalabre r1 = new realprincipalabre(usu); Escolheabre m1 = new Escolheabre(usu); m1.fecharTela(); r1.abreTela(); }else{ escolhetimeabre e1 = new escolhetimeabre(usu); Escolheabre m1 = new Escolheabre(usu); m1.fecharTela(); e1.abreTela(); } }); } }
java
16
0.580472
72
28.2125
80
starcoderdata
package psarf // PsarPeriod represents the calculated Psar values for a given day type PsarPeriod struct { // implements ChartBar this is mainly just as a reference to the original // bar data ChartBar // naming schemes are loosly based on the formula itself. EP float64 AF float64 Sar float64 // This is the Sar value, the one you want SarEP float64 AFSarEP float64 // extLow is the extreme low of the last 2 lows // NOTE this is here for performance. This is a "cached" value. Lookups on // any dataset of more than a few bars becomes noticeable, and over a few // weeks it becomes nearly impossible extLow float64 } // ExtLow returns the extLow value (normally not a display value, but available // this way just in case) func (p *PsarPeriod) ExtLow() float64 { return p.extLow }
go
6
0.736342
79
29.071429
28
starcoderdata
import React from 'react'; import './CurrentWallet.css'; export const CurrentWallet = (props) => ( <div className="CurrentWallet"> Wallet {props.address} {props.balance} ETH );
javascript
6
0.613941
58
21
17
starcoderdata
namespace RichText.Queries { public class GetEpicsQuery { public string? BoardId { get; set; } } }
c#
8
0.608333
44
16.142857
7
starcoderdata
using ESFA.DC.ILR.ValidationService.Interface.Enum; namespace ESFA.DC.ILR.ValidationService.Data.External.ValidationErrors.Model { public class ValidationError { public string RuleName { get; set; } public Severity Severity { get; set; } public string Message { get; set; } } }
c#
11
0.704918
76
25.142857
14
starcoderdata
package iot import ( "encoding/json" "errors" "fmt" ) func (ya *YaClient) GetGroup(groupID string) (*IotGroupResponse, error) { var errMethodName = "[getDevices]" if groupID == "" { return nil, ErrorReturn(errMethodName, errors.New(" groupID not provided")) } body, err := ya.get(fmt.Sprintf(ya.config.IotUrl + "/v1.0/groups/" + groupID)) if err != nil { return nil, ErrorReturn(errMethodName, err) } var result IotGroupResponse if err = json.Unmarshal(body, &result); err != nil { return nil, ErrorReturn(errMethodName, err) } return &result, nil } func (ya *YaClient) SetActionToGroup(group Group) (*IotGroupResponse, error) { var errMethodName = "[setActionToGroup]" if err := group.Validate(); err != nil { return nil, ErrorReturn(errMethodName, err) } body, err := ya.post(fmt.Sprintf(ya.config.IotUrl+"/v1.0/groups/"+group.Id+"/actions"), group) if err != nil { return nil, ErrorReturn(errMethodName, err) } var result IotGroupResponse if err = json.Unmarshal(body, &result); err != nil { return nil, ErrorReturn(errMethodName, err) } return &result, nil }
go
14
0.692851
95
22.604167
48
starcoderdata
import random import string from copy import deepcopy from urh import constants from urh.signalprocessing.FieldType import FieldType from urh.signalprocessing.ProtocoLabel import ProtocolLabel from urh.signalprocessing.Ruleset import Ruleset from urh.util.Logger import logger import xml.etree.ElementTree as ET class MessageType(list): """ A message type is a list of protocol fields. """ __slots__ = ["name", "__id", "assigned_by_ruleset", "ruleset", "assigned_by_logic_analyzer"] def __init__(self, name: str, iterable=None, id=None, ruleset=None): iterable = iterable if iterable else [] super().__init__(iterable) self.name = name self.__id = ''.join( random.choice(string.ascii_letters + string.digits) for _ in range(50)) if id is None else id self.assigned_by_logic_analyzer = False self.assigned_by_ruleset = False self.ruleset = Ruleset() if ruleset is None else ruleset def __hash__(self): return hash(super) def __getitem__(self, index) -> ProtocolLabel: return super().__getitem__(index) def __repr__(self): return self.name + " " + super().__repr__() def __eq__(self, other): if isinstance(other, MessageType): return self.id == other.id else: return super().__eq__(other) @property def assign_manually(self): return not self.assigned_by_ruleset @property def id(self) -> str: return self.__id @property def unlabeled_ranges(self): """ :rtype: list[(int,int)] """ return self.__get_unlabeled_ranges_from_labels(self) @staticmethod def __get_unlabeled_ranges_from_labels(labels): """ :type labels: list of ProtocolLabel :rtype: list[(int,int)] """ start = 0 result = [] for lbl in labels: if lbl.start > start: result.append((start, lbl.start)) start = lbl.end result.append((start, None)) return result def unlabeled_ranges_with_other_mt(self, other_message_type): """ :type other_message_type: MessageType :rtype: list[(int,int)] """ labels = self + other_message_type labels.sort() return self.__get_unlabeled_ranges_from_labels(labels) def append(self, lbl: ProtocolLabel): super().append(lbl) self.sort() def add_protocol_label(self, start: int, end: int, name=None, color_ind=None, auto_created=False, type: FieldType = None) -> ProtocolLabel: name = "" if not name else name used_colors = [p.color_index for p in self] avail_colors = [i for i, _ in enumerate(constants.LABEL_COLORS) if i not in used_colors] if color_ind is None: if len(avail_colors) > 0: color_ind = avail_colors[0] else: color_ind = random.randint(0, len(constants.LABEL_COLORS) - 1) proto_label = ProtocolLabel(name=name, start=start, end=end, color_index=color_ind, auto_created=auto_created, type=type) if proto_label not in self: self.append(proto_label) self.sort() return proto_label # Return label to set editor focus after adding def add_label(self, lbl: ProtocolLabel, allow_overlapping=True): if allow_overlapping or not any(lbl.overlaps_with(l) for l in self): self.add_protocol_label(lbl.start, lbl.end, name=lbl.name, color_ind=lbl.color_index) def remove(self, lbl: ProtocolLabel): if lbl in self: super().remove(lbl) else: logger.warning(lbl.name + " is not in set, so cant be removed") def to_xml(self) -> ET.Element: result = ET.Element("message_type", attrib={"name": self.name, "id": self.id, "assigned_by_ruleset": "1" if self.assigned_by_ruleset else "0", "assigned_by_logic_analyzer": "1" if self.assigned_by_logic_analyzer else "0"}) for lbl in self: result.append(lbl.to_xml(-1)) result.append(self.ruleset.to_xml()) return result @staticmethod def from_xml(tag: ET.Element): field_types_by_type_id = {ft.id: ft for ft in FieldType.load_from_xml()} name = tag.get("name", "blank") id = tag.get("id", None) assigned_by_ruleset = bool(int(tag.get("assigned_by_ruleset", 0))) assigned_by_logic_analyzer = bool(int(tag.get("assigned_by_logic_analyzer", 0))) labels = [] for lbl_tag in tag.findall("label"): labels.append(ProtocolLabel.from_xml(lbl_tag, field_types_by_type_id=field_types_by_type_id)) result = MessageType(name=name, iterable=labels, id=id, ruleset=Ruleset.from_xml(tag.find("ruleset"))) result.assigned_by_ruleset = assigned_by_ruleset result.assigned_by_logic_analyzer = assigned_by_logic_analyzer return result def copy_for_fuzzing(self): result = deepcopy(self) for lbl in result: lbl.fuzz_values = [] lbl.fuzz_created = True return result
python
18
0.587165
131
32.515723
159
starcoderdata
package io.sjcdigital.model.dto; import io.sjcdigital.model.builder.CountDTOBuilder; public class CountDTO { private String month; private String year; private String funeral; private long count; private boolean nonZeroAge = false; public static CountDTOBuilder create() { return new CountDTOBuilder(); } public String getMonth() { return month; } public void setMonth(String month) { this.month = month; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getFuneral() { return funeral; } public void setFuneral(String funeral) { this.funeral = funeral; } public long getCount() { return count; } public void setCount(long count) { this.count = count; } public boolean isNonZeroAge() { return nonZeroAge; } public void setNonZeroAge(boolean nonZeroAge) { this.nonZeroAge = nonZeroAge; } }
java
6
0.722966
61
18.816327
49
starcoderdata
def __init__(self, active_states, idle_states, cpu=None, children=None, name=None): super().__init__(cpu, children) logger = self.get_logger() def is_monotonic(l, decreasing=False): op = operator.ge if decreasing else operator.le return all(op(a, b) for a, b in zip(l, l[1:])) if active_states: # Sanity check for active_states's frequencies freqs = list(active_states.keys()) if not is_monotonic(freqs): logger.warning( f'Active states frequencies are expected to be monotonically increasing. Freqs: {freqs}') # Sanity check for active_states's powers power_vals = [s.power for s in list(active_states.values())] if not is_monotonic(power_vals): logger.warning( f'Active states powers are expected to be monotonically increasing. Values: {power_vals}') if idle_states: # This is needed for idle_state_by_idx to work. if not isinstance(idle_states, OrderedDict): f = 'idle_states is {}, must be collections.OrderedDict' raise ValueError(f.format(type(idle_states))) # Sanity check for idle_states powers power_vals = list(idle_states.values()) if not is_monotonic(power_vals, decreasing=True): logger.warning( f'Idle states powers are expected to be monotonically decreasing. Values: {power_vals}') if cpu is not None and not name: name = 'cpu' + str(cpu) self.name = name self.active_states = active_states self.idle_states = idle_states
python
14
0.576349
110
42.575
40
inline
package com.yeepay.yop.showcase.shop.modules.order.biz.impl; import com.yeepay.yop.showcase.shop.modules.order.biz.PayOrderQueryBizService; import com.yeepay.yop.showcase.shop.modules.order.entity.PayOrder; import com.yeepay.yop.showcase.shop.modules.order.service.PayOrderService; import com.yeepay.yop.showcase.notifyhandler.vo.OrderNotifyBean; import com.yeepay.yop.showcase.shop.config.YopOprShowcaseConfig; import com.yeepay.yop.showcase.shop.modules.order.enums.YopPayStatus; import com.yeepay.yop.showcase.shop.modules.order.vo.PayOrderQueryRequestDTO; import com.yeepay.yop.showcase.shop.support.Constant; import com.yeepay.yop.sdk.service.trade.TradeClient; import com.yeepay.yop.sdk.service.trade.TradeClientBuilder; import com.yeepay.yop.sdk.service.trade.model.YopQueryOrderResDTO; import com.yeepay.yop.sdk.service.trade.request.OrderQueryRequest; import com.yeepay.yop.sdk.service.trade.response.OrderQueryResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.text.SimpleDateFormat; import java.util.Date; /** * @author jing.ju * @description * @date 2020/10/13 下午2:14 */ @Slf4j @Service public class PayOrderQueryBizServiceImpl implements PayOrderQueryBizService { @Autowired private PayOrderService payOrderService; @Autowired private YopOprShowcaseConfig yopOprShowcaseConfig; private TradeClient tradeClient = TradeClientBuilder.builder().build(); @Override public OrderNotifyBean payOrderQueryRequest(PayOrderQueryRequestDTO requestDTO) { OrderNotifyBean responseDTO = new OrderNotifyBean(); try { // 对接YOP OrderQueryRequest orderQueryRequest = new OrderQueryRequest(); orderQueryRequest.setParentMerchantNo(yopOprShowcaseConfig.getParentMerchantNo()); orderQueryRequest.setMerchantNo(yopOprShowcaseConfig.getMerchantNo()); orderQueryRequest.setOrderId(requestDTO.getRequestNo()); OrderQueryResponse response = tradeClient.orderQuery(orderQueryRequest); dealOrderAfterResponse(requestDTO, response.getResult()); BeanUtils.copyProperties(response.getResult(), responseDTO); } catch (Exception e) { log.error("refundRequest exception, detail:{}", e.getMessage()); responseDTO.setCode(Constant.PAY_QUERY_ERROR); responseDTO.setMessage(e.getMessage()); } return responseDTO; } private void dealOrderAfterResponse(PayOrderQueryRequestDTO requestDTO, YopQueryOrderResDTO response) { PayOrder dbPayOrder = payOrderService.queryPayOrderByOrderId(requestDTO.getRequestNo()); dbPayOrder.setUniqueOrderNo(response.getUniqueOrderNo()); if (YopPayStatus.SUCCESS.name().equals(response.getStatus())) { Date paySuccessDate = new Date(); try { SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); paySuccessDate = ft.parse(response.getPaySuccessDate()); } catch (Exception e) { log.error("parse Date error."); } dbPayOrder.setPaySuccessDate(paySuccessDate); dbPayOrder.setBankOrderId(response.getBankOrderId()); dbPayOrder.setMerchantFee(response.getMerchantFee()); dbPayOrder.setCustomerFee(response.getCustomerFee()); payOrderService.updataOrderToSuccess(dbPayOrder); } else if (YopPayStatus.TIME_OUT.name().equals(response.getStatus())) { dbPayOrder.setErrorMsg("订单超时"); payOrderService.updataOrderToTimeOut(dbPayOrder); } } }
java
13
0.736201
108
43.872093
86
starcoderdata
package com.jaxsen.xianghacaipu.ui.cook.fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import com.jaxsen.xianghacaipu.R; import com.jaxsen.xianghacaipu.R2; import com.jaxsen.xianghacaipu.ui.cook.adapter.DinnerAdapter; import com.jaxsen.xianghacaipu.ui.cook.bean.DinnerList; import com.jaxsen.xianghacaipu.ui.cook.contract.DinnerContract; import com.jaxsen.xianghacaipu.ui.cook.model.DinnerListModel; import com.jaxsen.xianghacaipu.ui.cook.presenter.DinnerListPresenter; import com.rock.mvplibrary.base.BaseFragment; import butterknife.BindView; /** * Created by Administrator on 2017/4/10. */ public class DinnerFragment extends BaseFragment implements DinnerContract.View { @BindView(R2.id.recycler_dinner) RecyclerView dinner; private DinnerAdapter dinnerAdapter; public static final String TAG = DinnerFragment.class.getSimpleName(); private String tag; private int page = 1; @Override protected int getLayoutId() { return R.layout.fragment_dinner; } public DinnerFragment(String tag) { this.tag = tag; } @Override protected void initPresenter() { mPresenter.setVM(this,mModel); mPresenter.getDinnerList(tag,page+""); } @Override public void initView() { dinnerAdapter = new DinnerAdapter(getActivity(),null); dinner.setAdapter(dinnerAdapter); LinearLayoutManager dinnerManager = new LinearLayoutManager(getActivity()); dinnerManager.setOrientation(LinearLayoutManager.VERTICAL); dinner.setLayoutManager(dinnerManager); } @Override public void onStartLoad() { Log.e(TAG, "onStartLoad: " ); } @Override public void onStopLoad() { Log.e(TAG, "onStopLoad: " ); } @Override public void onError(String errorInfo) { Log.e(TAG, "onError: "+errorInfo ); } @Override public void returnDinnerList(DinnerList dinnerList) { dinnerAdapter.updateDinner(dinnerList.getData()); } }
java
11
0.717564
118
27.092105
76
starcoderdata
/* SPDX-License-Identifier: GPL-2.0 */ /* * Common code for Intel CPUs * * Copyright (c) 2016 Google, Inc */ #ifndef __ASM_CPU_COMMON_H #define __ASM_CPU_COMMON_H /* Standard Intel bus clock is fixed at 100MHz */ enum { INTEL_BCLK_MHZ = 100 }; struct cpu_info; struct udevice; /** * cpu_common_init() - Set up common CPU init * * This reports BIST failure, enables the LAPIC, updates microcode, enables * the upper 128-bytes of CROM RAM, probes the northbridge, PCH, LPC and SATA. * * Return: 0 if OK, -ve on error */ int cpu_common_init(void); /** * cpu_set_flex_ratio_to_tdp_nominal() - Set up the maximum non-turbo rate * * If a change is needed, this function will do a soft reset so it takes * effect. * * Some details are available here: * http://forum.hwbot.org/showthread.php?t=76092 * * Return: 0 if OK, -ve on error */ int cpu_set_flex_ratio_to_tdp_nominal(void); /** * cpu_intel_get_info() - Obtain CPU info for Intel CPUs * * Most Intel CPUs use the same MSR to obtain the clock speed, and use the same * features. This function fills in these values, given the value of the base * clock in MHz (typically this should be set to 100). * * @info: cpu_info struct to fill in * @bclk_mz: the base clock in MHz * * Return: 0 always */ int cpu_intel_get_info(struct cpu_info *info, int bclk_mz); /** * cpu_configure_thermal_target() - Set the thermal target for a CPU * * This looks up the tcc-offset property and uses it to set the * MSR_TEMPERATURE_TARGET value. * * @dev: CPU device * Return: 0 if OK, -ENOENT if no target is given in device tree */ int cpu_configure_thermal_target(struct udevice *dev); /** * cpu_set_perf_control() - Set the nominal CPU clock speed * * This sets the clock speed as a multiplier of BCLK * * @clk_ratio: Ratio to use */ void cpu_set_perf_control(uint clk_ratio); /** * cpu_config_tdp_levels() - Check for configurable TDP option * * Return: true if the CPU has configurable TDP (Thermal-design power) */ bool cpu_config_tdp_levels(void); /** enum burst_mode_t - Burst-mode states */ enum burst_mode_t { BURST_MODE_UNKNOWN, BURST_MODE_UNAVAILABLE, BURST_MODE_DISABLED, BURST_MODE_ENABLED }; /* * cpu_get_burst_mode_state() - Get the Burst/Turbo Mode State * * This reads MSR IA32_MISC_ENABLE 0x1A0 * Bit 38 - TURBO_MODE_DISABLE Bit to get state ENABLED / DISABLED. * Also checks cpuid 0x6 to see whether burst mode is supported. * * Return: current burst mode status */ enum burst_mode_t cpu_get_burst_mode_state(void); /** * cpu_set_burst_mode() - Set CPU burst mode * * @burst_mode: true to enable burst mode, false to disable */ void cpu_set_burst_mode(bool burst_mode); /** * cpu_set_eist() - Enable Enhanced Intel Speed Step Technology * * @eist_status: true to enable EIST, false to disable */ void cpu_set_eist(bool eist_status); /** * cpu_set_p_state_to_turbo_ratio() - Set turbo ratio * * TURBO_RATIO_LIMIT MSR (0x1AD) Bits 31:0 indicates the * factory configured values for of 1-core, 2-core, 3-core * and 4-core turbo ratio limits for all processors. * * 7:0 - MAX_TURBO_1_CORE * 15:8 - MAX_TURBO_2_CORES * 23:16 - MAX_TURBO_3_CORES * 31:24 - MAX_TURBO_4_CORES * * Set PERF_CTL MSR (0x199) P_Req with that value. */ void cpu_set_p_state_to_turbo_ratio(void); /** * cpu_get_coord_type() - Get the type of coordination for P-State transition * * See ACPI spec v6.3 section 8.4.6.5 _PSD (P-State Dependency) * * Return: HW_ALL (always) */ int cpu_get_coord_type(void); /** * cpu_get_min_ratio() - get minimum support frequency ratio for CPU * * Return: minimum ratio */ int cpu_get_min_ratio(void); /** * cpu_get_max_ratio() - get nominal TDP ration or max non-turbo ratio * * If a nominal TDP ratio is available, it is returned. Otherwise this returns * the maximum non-turbo frequency ratio for this processor * * Return: max ratio */ int cpu_get_max_ratio(void); /** * cpu_get_bus_clock_khz() - Get the bus clock frequency in KHz * * This is the value the clock ratio is multiplied with * * Return: bus-block frequency in KHz */ int cpu_get_bus_clock_khz(void); /** * cpu_get_power_max() - Get maximum CPU TDP * * Return: maximum CPU TDP (Thermal-design power) in mW */ int cpu_get_power_max(void); /** * cpu_get_max_turbo_ratio() - Get maximum turbo ratio * * Return: maximum ratio */ int cpu_get_max_turbo_ratio(void); /** * cpu_get_cores_per_package() - Get the number of CPU cores in each package * * Return: number of cores */ int cpu_get_cores_per_package(void); /** * cpu_mca_configure() - Set up machine-check exceptions ready for use * * These allow the SoC to report errors while running. See here for details: * * https://www.intel.com/content/dam/www/public/us/en/documents/white-papers/machine-check-exceptions-debug-paper.pdf */ void cpu_mca_configure(void); #endif
c
7
0.686258
117
23.786802
197
research_code
from corsheaders.signals import check_request_enabled def cors_allow_widget_to_everyone(sender, request, **kwargs): return request.path.startswith('/widget/') check_request_enabled.connect(cors_allow_widget_to_everyone)
python
7
0.783465
61
27.222222
9
starcoderdata
package stannieman.commonservices.resultCodeTranslators; import java.util.Map; import stannieman.commonservices.models.IHasResultCode; /** * A translator to convert a result code to a string. * This is typically used to translate the result code of an operation * to a user friendly message. */ public abstract class ResultCodeTranslatorBase implements IResultCodeTranslator { private Map<Object, String> map = null; private final String defaultString; /** * Constructor accepting a default string. * The default string is used of no string can be found for the * given result code. * @param defaultString default string */ protected ResultCodeTranslatorBase(String defaultString) { this.defaultString = defaultString; } /** * Converts the result code of the given instance to a string. * @param hasResultCode instance to take the result code from * @return the string for the given result code */ @Override public String getErrorMessage(IHasResultCode hasResultCode) { return getErrorMessage((Object)hasResultCode); } String getErrorMessage(Object object) { if (object instanceof IHasResultCode) { Object resultCode = ((IHasResultCode)object).getResultCode(); if (map == null) { map = getMap(); } if (map.containsKey(resultCode)) { return map.get(resultCode); } return defaultString; } return defaultString; } /** * Implementations of translators must implement this method. * It must return a map with result codes as keys and the strings * to translate them to as values. * @return map with result codes and strings */ protected abstract Map<Object, String> getMap(); }
java
13
0.6488
81
29.612903
62
starcoderdata
public String getText(SRepository repo) { if (myText != null) { return myText; } if (myTargetNode == null) { if (myKind != null) { return '<' + String.valueOf(myKind) + '>'; } return "<unknown>"; } SNode n = myTargetNode.resolve(repo); if (n == null) { // GenTrace records additions and deletions as <no node id> at corresponding side, here // we check whether it's the node we simply can't access now, or it's consciously recorded addition/removal if (myTargetNode.getNodeId() == null) { if (myKind == Kind.INPUT) { return "<no input>"; } else if (myKind == Kind.OUTPUT) { return "<no output>"; } // fall-through } return myTargetNode.toString(); } // TODO initialize myText once in the cons String text = String.format("[%s] %s (%s)", n.getConcept().getName(), n.getPresentation(), n.getNodeId()); if (myKind == Kind.APPROXIMATE_OUTPUT || myKind == Kind.APPROXIMATE_INPUT) { return "[approximate location] " + text; } else { return text; } }
java
12
0.576408
113
34
32
inline
@Override public boolean isEqual(Operator other) { if (other != null && other instanceof DNFExpression) { DNFExpression otherexp = (DNFExpression) other; if (type != otherexp.type) return false; try { // this equality check is too strong: it does not allow for permutations; // should be improved in the future List<Operator> thisChildren = plan.getSuccessors(this), thatChildren = plan.getSuccessors(otherexp); if (thisChildren == null && thatChildren == null) return true; else if (thisChildren == null || thatChildren == null) return false; else { if (thisChildren.size() != thatChildren.size()) return false; for (int i = 0; i < thisChildren.size(); i++) { if (!thisChildren.get(i).isEqual( thatChildren.get(i))) return false; } } } catch (FrontendException e) { throw new RuntimeException(e); } return true; } else { return false; } }
java
19
0.476563
116
40.322581
31
inline
#!/usr/bin/python -u # -*- coding:utf-8; tab-width:4; mode:python -*- import sys import Ice Ice.loadSlice('-I %s container.ice' % Ice.getSliceDir()) import Services class ContainerI(Services.Container): def __init__(self): self.proxies = dict() def link(self, key, proxy, current=None): if key in self.proxies: raise Services.AlreadyExists(key) print("link: {0} -> {1}".format(key, proxy)) self.proxies[key] = proxy def unlink(self, key, current=None): if not key in self.proxies: raise Services.NoSuchKey(key) print("unlink: {0}".format(key)) del self.proxies[key] def list(self, current=None): return self.proxies def getProxy(self, key, current=None): return self.proxies[key] class Server(Ice.Application): def run(self, argv): broker = self.communicator() servant = ContainerI() adapter = broker.createObjectAdapter("ContainerAdapter") proxyContainer = adapter.add(servant, broker.stringToIdentity("container1")) print("I'm the container: {} \n".format(proxyContainer)) adapter.activate() self.shutdownOnInterrupt() broker.waitForShutdown() return 0 if __name__ == '__main__': sys.exit(Server().main(sys.argv))
python
12
0.623529
84
25.666667
51
starcoderdata
package litil.ast; import java.util.ArrayList; import java.util.List; public class Program extends AstNode { public final List instructions = new ArrayList @Override public String repr(int indent) { StringBuilder res = new StringBuilder(); for(Instruction instr: instructions) { res.append(instr.repr(indent)).append("\n"); } return res.toString(); } @Override public String toString() { StringBuilder res = new StringBuilder(); for(Instruction instr: instructions) { res.append(instr).append("\n"); } return res.toString(); } }
java
13
0.623377
79
24.666667
27
starcoderdata
package kn.uni.sen.joblibrary.tartar.gui; import kn.uni.sen.joblibrary.tartar.common.SMT2_OPTION; import kn.uni.sen.joblibrary.tartar.job_repaircomputation.Job_RepairComputation; import kn.uni.sen.joblibrary_tartar.job_experiment.Job_SeedExperiment; import kn.uni.sen.jobscheduler.common.impl.JobDataInput; import kn.uni.sen.jobscheduler.common.model.EventHandler; import kn.uni.sen.jobscheduler.common.model.Job; import kn.uni.sen.jobscheduler.common.model.ResourceInterface; import kn.uni.sen.jobscheduler.common.resource.ResourceDescription; import kn.uni.sen.jobscheduler.common.resource.ResourceEnum; import kn.uni.sen.jobscheduler.common.resource.ResourceFile; import kn.uni.sen.jobscheduler.common.resource.ResourceFileXml; import kn.uni.sen.jobscheduler.common.resource.ResourceFolder; import kn.uni.sen.jobscheduler.common.resource.ResourceList; import kn.uni.sen.jobscheduler.core.impl.JobRunAbstract; import kn.uni.sen.jobscheduler.core.model.JobScheduler; public class JobRun_TarTar extends JobRunAbstract implements Runnable { RunParameter Parameter; protected Job job = null; public JobRun_TarTar(Integer id, EventHandler father, ResourceFolder folder) { super(id, father, folder); } @Override public void run() { if (Parameter == null) return; if (Parameter.isExperiment()) job = new Job_SeedExperiment(this); else job = new Job_RepairComputation(this); JobDataInput inData = new JobDataInput(); //job.addLogger(new LogConsole(1)); inData.add("Model", new ResourceFile(Parameter.getModelFile())); inData.add("Trace", new ResourceFile(Parameter.getTraceFile())); ResourceInterface para2 = null; for (SMT2_OPTION opt : Parameter.getOptionList()) para2 = ResourceList.addList(para2, new ResourceEnum(opt)); inData.add("Parameter", para2); inData.add("RepairKind", new ResourceEnum(Parameter.getRepair())); inData.add("SeedKind", new ResourceEnum(Parameter.getRepair())); ResourceDescription.setOwner(job.getInputDescription(), inData); if (job != null) job.start(); } @Override protected JobScheduler createScheduler(ResourceFileXml jobFile, ResourceFolder folder, String schedulerType) { return null; } public void setParameter(RunParameter para) { Parameter = para; } }
java
12
0.781401
109
33.378788
66
starcoderdata
import { Container, Grid, Header, List, Segment } from 'semantic-ui-react' import FooterStyles from './index.styles' const Footer = () => ( <FooterStyles className='site-footer'> <> <Segment inverted vertical> <Grid inverted columns={5}> <Header inverted as='h4' content='About' /> <List link inverted> <List.Item as='a'>Coming Soon <List.Item as='a'>Coming Soon <List.Item as='a'>Coming Soon <List.Item as='a'>Coming Soon <Header inverted as='h4' content='Services' /> <List link inverted> <List.Item as='a'>Coming Soon <List.Item as='a'>Coming Soon <List.Item as='a'>Coming Soon <List.Item as='a'>Coming Soon <Header inverted as='h4' content='Projects' /> <List link inverted> <List.Item as='a'>Coming Soon <List.Item as='a'>Coming Soon <List.Item as='a'>Coming Soon <List.Item as='a'>Coming Soon <Header inverted as='h4' content='Blog' /> <List link inverted> <List.Item as='a'>Coming Soon <List.Item as='a'>Coming Soon <List.Item as='a'>Coming Soon <List.Item as='a'>Coming Soon <Header inverted as='h4' content='Contact' /> <List link inverted> <List.Item as='a'>Coming Soon <List.Item as='a'>Coming Soon <List.Item as='a'>Coming Soon <List.Item as='a'>Coming Soon <Grid inverted> <Grid.Column computer={12}> 2021 Trademarks and brands are the property of their respective owners. <Grid.Column textAlign='right' computer={4}> ) export default Footer
javascript
13
0.474308
104
38.947368
76
starcoderdata
def drawAdditionals(self): self.newPix = self._getNewPixmap(self.width, self.height + self.SPACER) qp = QtGui.QPainter() qp.begin(self.newPix) qp.drawPixmap(0, 0, self.qpix) # self.transformationEngine.decorateText() # highlight selected text self.selector.highlightText() # draw other selections self.selector.drawSelections(qp) # draw our cursor self.drawCursor(qp) # draw dword lines for i in range(self.COLUMNS // 4)[1:]: xw = i * 4 * 3 * self.fontWidth - 4 qp.setPen(QtGui.QColor(0, 255, 0)) qp.drawLine(xw, 0, xw, self.ROWS * self.fontHeight) qp.end()
python
11
0.579466
79
28.666667
24
inline
using System.Collections.Generic; namespace TransactionSamples { public class MenuCard { public int MenuCardId { get; set; } public string Title { get; set; } public List Menus { get; } = new List public override string ToString() => Title; } }
c#
9
0.615635
60
22.615385
13
starcoderdata
using System; using cAlgo.API; using cAlgo.API.Indicators; namespace cAlgo.Indicators { [Indicator(IsOverlay = false, AccessRights = AccessRights.None)] public class AroonHorn : Indicator { [Parameter(DefaultValue = 10)] public int Period { get; set; } [Parameter(DefaultValue = 25)] public int Filter { get; set; } [Output("AroonOSCup", Color = Colors.Blue, IsHistogram = true)] public IndicatorDataSeries aroonoscup { get; set; } [Output("AroonOSCdown", Color = Colors.Red, IsHistogram = true)] public IndicatorDataSeries aroonoscdown { get; set; } [Output("AroonOSCGray", Color = Colors.Gray, IsHistogram = true)] public IndicatorDataSeries aroonoscgray { get; set; } [Output("AroonOSC", Color = Colors.Turquoise)] public IndicatorDataSeries aroonosc { get; set; } private Aroon aroonhorn; protected override void Initialize() { aroonhorn = Indicators.Aroon(Period); } public override void Calculate(int index) { double commander = 10 * (aroonhorn.Up[index] - aroonhorn.Down[index]) / Period; if ((commander >= 0) && (commander > Filter)) { aroonoscup[index] = commander; } if ((commander < 0) && (commander < (-1) * Filter)) { aroonoscdown[index] = commander; } if ((commander >= (-1) * Filter) && (commander <= Filter)) { aroonoscgray[index] = commander; } aroonosc[index] = commander; } } }
c#
18
0.563887
91
30.45283
53
starcoderdata
describe('Test Popular and Recent', function () { beforeEach(function () { var results = [ { "lang_name": "English", "lang_code": "en", "resource_name": "Open Bible Stories", "author": "john_smith", "last_updated": moment().format('YYYY-MM-DD'), "num_views": 123 }, { "lang_name": "French", "lang_code": "fr", "resource_name": "Open Bible Stories", "author": "john_smith", "last_updated": moment().subtract(2, 'days').format('YYYY-MM-DD'), "num_views": 10 }, { "lang_name": "Spanish", "lang_code": "es", "resource_name": "Open Bible Stories", "author": "john_smith", "last_updated": moment().subtract(12, 'days').format('YYYY-MM-DD'), "num_views": 97 }, { "lang_name": "Hindi", "lang_code": "hi", "resource_name": "Open Bible Stories", "author": "john_smith", "last_updated": moment().subtract(21, 'days').format('YYYY-MM-DD'), "num_views": 2 }, { "lang_name": "English", "lang_code": "en", "resource_name": "Unlocked Literal Bible", "author": "john_smith", "last_updated": moment().subtract(40, 'days').format('YYYY-MM-DD'), "num_views": 0 }, { "lang_name": "English", "lang_code": "en", "resource_name": "Open Bible Stories", "author": "john_smith", "last_updated": moment().subtract(41, 'days').format('YYYY-MM-DD'), "num_views": 123 }, { "lang_name": "French", "lang_code": "fr", "resource_name": "Open Bible Stories", "author": "john_smith", "last_updated": moment().subtract(52, 'days').format('YYYY-MM-DD'), "num_views": 10 }, { "lang_name": "Spanish", "lang_code": "es", "resource_name": "Open Bible Stories", "author": "john_smith", "last_updated": moment().subtract(62, 'days').format('YYYY-MM-DD'), "num_views": 97 }, { "lang_name": "Hindi", "lang_code": "hi", "resource_name": "Open Bible Stories", "author": "john_smith", "last_updated": moment().subtract(71, 'days').format('YYYY-MM-DD'), "num_views": 2 }, { "lang_name": "English", "lang_code": "en", "resource_name": "Unlocked Literal Bible", "author": "john_smith", "last_updated": moment().subtract(80, 'days').format('YYYY-MM-DD'), "num_views": 0 }, { "lang_name": "English", "lang_code": "en", "resource_name": "Open Bible Stories", "author": "john_smith", "last_updated": moment().subtract(85, 'days').format('YYYY-MM-DD'), "num_views": 123 }, { "lang_name": "French", "lang_code": "fr", "resource_name": "Open Bible Stories", "author": "john_smith", "last_updated": moment().subtract(92, 'days').format('YYYY-MM-DD'), "num_views": 10 }, { "lang_name": "Spanish", "lang_code": "es", "resource_name": "Open Bible Stories", "author": "john_smith", "last_updated": moment().subtract(95, 'days').format('YYYY-MM-DD'), "num_views": 97 }, { "lang_name": "Hindi", "lang_code": "hi", "resource_name": "Open Bible Stories", "author": "john_smith", "last_updated": moment().subtract(101, 'days').format('YYYY-MM-DD'), "num_views": 2 }, { "lang_name": "English", "lang_code": "en", "resource_name": "Unlocked Literal Bible", "author": "john_smith", "last_updated": moment().subtract(140, 'days').format('YYYY-MM-DD'), "num_views": 0 }, { "lang_name": "English", "lang_code": "en", "resource_name": "Open Bible Stories", "author": "john_smith", "last_updated": moment().subtract(145, 'days').format('YYYY-MM-DD'), "num_views": 123 }, { "lang_name": "French", "lang_code": "fr", "resource_name": "Open Bible Stories", "author": "john_smith", "last_updated": moment().subtract(152, 'days').format('YYYY-MM-DD'), "num_views": 10 }, { "lang_name": "Spanish", "lang_code": "es", "resource_name": "Open Bible Stories", "author": "john_smith", "last_updated": moment().subtract(162, 'days').format('YYYY-MM-DD'), "num_views": 97 }, { "lang_name": "Hindi", "lang_code": "hi", "resource_name": "Open Bible Stories", "author": "john_smith", "last_updated": moment().subtract(171, 'days').format('YYYY-MM-DD'), "num_views": 2 }, { "lang_name": "English", "lang_code": "en", "resource_name": "Unlocked Literal Bible", "author": "john_smith", "last_updated": moment().subtract(180, 'days').format('YYYY-MM-DD'), "num_views": 0 } ]; applySearchResults(results); resetSearch(); jasmine.getFixtures().fixturesPath = 'base/test/fixtures'; loadFixtures('i18n-language-page-fixture.html'); // verify the fixture loaded successfully expect(jQuery('#jasmine-fixtures')).toBeTruthy(); }); it('simpleFormat should work', function () { var found = simpleFormat('one {0} two {1}', ['1', '2']); expect(found).toEqual('one 1 two 2'); found = simpleFormat('one {0} two {1} two {1} one {0}', ['1', '2']); expect(found).toEqual('one 1 two 2 two 2 one 1'); }); it('showSearchResults() should show 5 items in both the popular and recent sections and the more-container', function () { showSearchResults(); // show first 5 var $body = $(document.body); var $popular_listings = $body.find('#popular-div .search-listing .listing-container'); expect($popular_listings.length).toEqual(5); var $more = $body.find('#popular-div .search-listing .more-container'); expect($more.length).toEqual(1); var $recent_listings = $body.find('#recent-div .search-listing .listing-container'); expect($recent_listings.length).toEqual(5); $more = $body.find('#recent-div .search-listing .more-container'); expect($more.length).toEqual(1); }); it('With results sliced to 4, showSearchResults() should not show the more-container', function () { var results = searchResults[SECTION_TYPE_POPULAR].slice(0,4); // make list only 4 items long applySearchResults(results); showSearchResults(); // show all 4 var $body = $(document.body); var $popular_listings = $body.find('#popular-div .search-listing .listing-container'); expect($popular_listings.length).toEqual(4); var $more = $body.find('#popular-div .search-listing .more-container'); expect($more.length).toEqual(0); var $recent_listings = $body.find('#recent-div .search-listing .listing-container'); expect($recent_listings.length).toEqual(4); $more = $body.find('#recent-div .search-listing .more-container'); expect($more.length).toEqual(0); }); it('showSearchResults(SECTION_TYPE_POPULAR) should show 8 more items in the popular section', function () { showSearchResults(); // show first 5 showSearchResults(SECTION_TYPE_POPULAR); // show next 8 var $body = $(document.body); var $popular_listings = $body.find('#popular-div .search-listing .listing-container'); expect($popular_listings.length).toEqual(13); var $more = $body.find('#popular-div .search-listing .more-container'); expect($more.length).toEqual(1); var $recent_listings = $body.find('#recent-div .search-listing .listing-container'); expect($recent_listings.length).toEqual(5); $more = $body.find('#recent-div .search-listing .more-container'); expect($more.length).toEqual(1); }); it('showSearchResults(SECTION_TYPE_RECENT) twice should not show the more-container', function () { showSearchResults(); // show first 5 showSearchResults(SECTION_TYPE_RECENT); // show next 8 showSearchResults(SECTION_TYPE_RECENT); // show next 13, but only 20 exist so shows 7 more var $body = $(document.body); var $popular_listings = $body.find('#popular-div .search-listing .listing-container'); expect($popular_listings.length).toEqual(5); var $more = $body.find('#popular-div .search-listing .more-container'); expect($more.length).toEqual(1); var $recent_listings = $body.find('#recent-div .search-listing .listing-container'); expect($recent_listings.length).toEqual(20); $more = $body.find('#recent-div .search-listing .more-container'); expect($more.length).toEqual(0); }); it('Test fibonacci() function', function () { expect(fibonacci(-1)).toEqual(1); expect(fibonacci(0)).toEqual(1); expect(fibonacci(1)).toEqual(1); expect(fibonacci(2)).toEqual(1); expect(fibonacci(3)).toEqual(2); expect(fibonacci(4)).toEqual(3); expect(fibonacci(5)).toEqual(5); expect(fibonacci(6)).toEqual(8); expect(fibonacci(7)).toEqual(13); expect(fibonacci(8)).toEqual(21); }); }); // // helpers // function applySearchResults(results) { searchResults = {}; searchResults[SECTION_TYPE_POPULAR] = results.slice(); searchResults[SECTION_TYPE_RECENT] = results; }
javascript
24
0.571444
124
32.851064
282
starcoderdata
package dhbw.spotify; public class WrongRequestTypeException extends Exception { public WrongRequestTypeException(String error){ super(error); } }
java
7
0.743902
58
22.428571
7
starcoderdata
func (l *BackgroundLoader) processLoadFileRequests(c context.Context) { log.Infof("Starting file loader...") l.c = c pool := tunny.NewFunc(l.numberOfWorkers, l.worker) fileloadsStore := l.db.FileLoadsStore() // There may have been jobs in process when the server was stopped. Mark those jobs // as not currently being processed, this will cause them to be re-processed. if err := fileloadsStore.MarkAllNotLoading(); err != nil && errors.Cause(err) != mc.ErrNotFound { log.Infof("Unable to mark current jobs as not loading: %s\n", err) } // Loop through all file load requests and look for any that are not currently being processed. for { requests, err := fileloadsStore.GetAllFileLoads() //fmt.Printf("processing file loads %#v: %s\n", requests, err) if err != nil && errors.Cause(err) != mc.ErrNotFound { log.Infof("Error retrieving requests: %s", err) } for _, req := range requests { if req.Loading { // This request is already being processed so ignore it continue } // Check if project is already being processed if _, ok := l.activeProjects.Load(req.ProjectID); ok { // There is already a load active for this project, so skip // processing this load request continue } // If we are here then the current request is not being processed // and it is for a project that is *not* currently being processed. log.Infof("processing request %#v\n", req) // Mark job as loading so we won't attempt to load this request a second time if err := fileloadsStore.UpdateLoading(req.ID, true); err != nil { // If the job cannot be marked as loading then skip processing it log.Infof("Unable to update file load request %s: %s", req.ID, err) continue } // Lock the project so no other uploads for this project will be processed. This is // done to prevent issues such as checks and writes to the database creating two entries. l.activeProjects.Store(req.ProjectID, true) // pool.Process() is synchronous, so run in separate routine and let the pool control // how many jobs are running simultaneously. go func() { // pool.Process will call the worker function (below) for processing the request pool.Process(req) }() } // Sleep for 10 seconds before getting the next set of loading requests. Ten seconds is an // somewhat arbitrary value chosen to balance time to start processing and load on the system. select { case <-time.After(10 * time.Second): case <-c.Done(): log.Infof("Shutting down file loading...") return } } }
go
14
0.697856
98
36.735294
68
inline
package com.example.productexpo.modules.base.fragment; import android.support.v4.app.FragmentManager; import android.view.View; import com.example.productexpo.modules.base.BaseView; /** * Created on 9/17/2017. */ public interface BaseFragmentView extends BaseView { /** * Get resID. * * @return layout resource id for the fragment container */ int getResId(); /** * This is used to check if current activity is null or finishing * * @return true if finishing/null else false; */ boolean isActivityFinishing(); /** * Method to initialize UI components * * @param v root layout from which child views will be initialized */ void initializeUIComponents(View v); /** * get Child Fragment Manager for fragment * * @return FragmentManager object returns Child FragmentManager */ FragmentManager getChildManagerForFragment(); }
java
6
0.679918
70
22.357143
42
starcoderdata
package uk.ac.ebi.atlas.experimentpage.baseline.grouping; import au.com.bytecode.opencsv.CSVReader; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import io.atlassian.util.concurrent.LazyReference; import org.springframework.stereotype.Component; import uk.ac.ebi.atlas.model.OntologyTerm; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.function.Function; @Component public class OrganismPartGroupingService { private final LazyReference<Multimap<String, ColumnGroup>> anatomicalSystemsMap; private final LazyReference<Multimap<String, ColumnGroup>> organsMap; public OrganismPartGroupingService(Path anatomicalSystemsFilePath, Path organsFilePath) { Function<Path, LazyReference<Multimap<String, ColumnGroup>>> makeMap = path -> new LazyReference<>() { @Override protected Multimap<String, ColumnGroup> create() { return getColumnGroups(path); } }; this.anatomicalSystemsMap = makeMap.apply(anatomicalSystemsFilePath); this.organsMap = makeMap.apply(organsFilePath); } public Map<ColumnGroup, Set getAnatomicalSystemsGrouping(Collection ontologyTerms) { return getGrouping(ontologyTerms, term -> anatomicalSystemsMap.get().get(term.accession())); } public Map<ColumnGroup, Set getOrgansGrouping(Collection ontologyTerms) { return getGrouping(ontologyTerms, term -> organsMap.get().get(term.accession())); } private Map<ColumnGroup, Set getGrouping(Collection ontologyTerms, Function<OntologyTerm, Collection columnGroups) { Map<ColumnGroup, Set groupings = new HashMap<>(); for (OntologyTerm ontologyTerm : ontologyTerms) { for (ColumnGroup a : columnGroups.apply(ontologyTerm)) { if (!groupings.containsKey(a)) { groupings.put(a, new HashSet<>()); } groupings.get(a).add(ontologyTerm); } } return groupings; } private Multimap<String, ColumnGroup> getColumnGroups(Path path) { try (CSVReader csvReader = new CSVReader(new InputStreamReader(Files.newInputStream(path)), '\t')) { ImmutableMultimap.Builder<String, ColumnGroup> b = ImmutableMultimap.builder(); csvReader.readAll().stream().filter(row -> !row[0].startsWith("#")).forEach(row -> { b.put(row[2], ColumnGroup.create(row[0], row[1])); }); return b.build(); } catch (IOException e) { throw new RuntimeException(e); } } }
java
18
0.675299
117
37.126582
79
starcoderdata
package com.snowball.location.transport_api.response; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; import java.util.List; public class PublicJourneyRoute { @JsonFormat (shape = JsonFormat.Shape.STRING, pattern = "hh:mm:ss") @Getter @Setter protected String duration; @JsonProperty("departure_time") @Getter @Setter protected String departure; @JsonProperty("arrival_time") @Getter @Setter protected String arrival; @JsonProperty("arrival_date") @Getter @Setter protected String arrivalDate; @JsonProperty("route_parts") @Getter @Setter protected List routeParts = new ArrayList<>(); }
java
10
0.750633
77
26.241379
29
starcoderdata
int storage_erase(){ // FIXME: should erase everything // FIXME: should also zero the whole memory int err = fs.reformat(NULL); return err; // return fs.remove("/internal/gui/calibration"); }
c++
8
0.658768
53
29.285714
7
inline
# -*- coding: utf-8 -*- import json import cv2 import numpy as np import os import shutil import argparse if __name__ == '__main__': save_dir = '/train/trainset/1/Semantic/data/labels' save_img = '/train/trainset/1/Semantic/data/img' json_path = '/train/trainset/1/face_mask_data/mask_test_20200521_135556.json' if not os.path.exists(save_dir): os.makedirs(save_dir) if not os.path.exists(save_img): os.makedirs(save_img) file_dir = '/train/trainset/1/' files = os.listdir(file_dir) with open(json_path) as f: json_s = f.readlines() # draw roi print(len(json_s)) with open(os.path.join(file_dir, 'test_list.txt'), 'w') as f: for i, item_s in enumerate(json_s): item_dict = json.loads(item_s) result = item_dict['result'] url_image = item_dict['url_image'] img_path = os.path.join(file_dir, url_image[8:]) print(img_path) img = cv2.imread(img_path) img_h = img.shape[0] img_w = img.shape[1] img = np.zeros([img.shape[0], img.shape[1]], dtype=np.uint8) save_path = os.path.join(save_dir, url_image[20:]).replace('.jpg', '.png') shutil.copy(img_path, os.path.join(save_img, url_image[20:])) line = os.path.basename(os.path.join(save_img, url_image[20:])) # f.write(line + '\n') # 训练集写这里! # for poly in result: if len(result) == 0: print("0id", i) img = cv2.fillPoly(img, [np.array(points, dtype=int)], 0) target = np.array(img).astype(np.uint8) cv2.imwrite(save_path, img) else: f.write(line + '\n') # 测试集写这里! points = np.array(result[0]['data']).reshape(-1, 2) img = cv2.fillPoly(img, [np.array(points, dtype=int)], 1) target = np.array(img).astype(np.uint8) if np.max(target) != 1: print(np.min(target), np.max(target)) cv2.imwrite(save_path, img) if i % 100==0: print('%d have saved done' % (i)) if i == len(json_s)-1: print('%d have saved done, all have saved done' % (i))
python
18
0.524017
86
33.69697
66
starcoderdata
// create an express app var express = require('express'), app = express(), port = process.env.PORT || 3000; // route handler for GET / app.get('/', function(req, res) { var data = ' world res.send(data); }); app.listen(port); console.log('server started on port %s', port);
javascript
6
0.634731
47
19.875
16
starcoderdata
/* * MIT License * * Copyright(c) 2018 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files(the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions : * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #ifndef FBX_HPP_GUARD #define FBX_HPP_GUARD #include #include #include #include #include namespace Fbx { class Property { public: union Value { bool boolean; int16_t integer16; int32_t integer32; int64_t integer64; float float32; double float64; }; enum class Type { Boolean, Integer16, Integer32, Integer64, Float32, Float64, BooleanArray, Integer32Array, Integer64Array, Float32Array, Float64Array, String, Raw }; Property(const bool primitive); Property(const int16_t primitive); Property(const int32_t primitive); Property(const int64_t primitive); Property(const float primitive); Property(const double primitive); Property(const bool * array, const uint32_t count); Property(const int32_t * array, const uint32_t count); Property(const int64_t * array, const uint32_t count); Property(float * array, const uint32_t count); Property(const double * array, const uint32_t count); Property(const char * string); Property(const std::string & string); Property(const uint8_t * raw, const uint32_t size); Type type() const; uint8_t code() const; Value & primitive(); const Value & primitive() const; std::vector & array(); const std::vector & array() const; std::string string() const; std::vector & raw(); const std::vector & raw() const; uint32_t size() const; bool isPrimitive() const; bool isArray() const; bool isString() const; bool isRaw() const; private: Type m_type; Value m_primitive; std::vector m_array; std::vector m_raw; }; class PropertyList { public: typedef std::list<Property *>::iterator Iterator; typedef std::list<Property *>::const_iterator ConstIterator; PropertyList(); ~PropertyList(); size_t size() const; Iterator insert(Property * property); Iterator insert(Iterator position, Property * property); Iterator begin(); ConstIterator begin() const; Iterator end(); ConstIterator end() const; Property * front(); const Property * front() const; Property * back(); const Property * back() const; Iterator erase(Property * property); Iterator erase(Iterator position); void clear(); private: PropertyList(PropertyList &); std::list<Property *> m_properties; }; class Record { public: typedef std::list<Record *>::iterator Iterator; typedef std::list<Record *>::const_iterator ConstIterator; Record(); Record(const std::string & name); Record(const std::string & name, Record * parent); ~Record(); void read(const std::string & filename); void read(const std::string & filename, std::function<void(std::string, uint32_t)> onHeaderRead); void write(const std::string & filename) const; void write(const std::string & filename, const uint32_t version) const; const std::string & name() const; void name(const std::string & name); Record * parent(); const Record * parent() const; void parent(Record * parent); PropertyList & properties(); const PropertyList & properties() const; size_t size() const; Iterator insert(Record * record); Iterator insert(Iterator position, Record * record); Iterator begin(); ConstIterator begin() const; Iterator end(); ConstIterator end() const; Record * front(); const Record * front() const; Record * back(); const Record * back() const; Iterator find(const std::string & name); ConstIterator find(const std::string & name) const; Iterator erase(Record * record); Iterator erase(Iterator position); void clear(); private: Record(const Record &); std::string m_name; Record * m_pParent; PropertyList m_properties; std::list<Record *> m_nestedList; }; } #endif
c++
18
0.596485
105
27.596059
203
starcoderdata
import gsap from 'gsap'; const animationEnter = container => { // gsap.from(container, { // autoAlpha: 0, // duration: 2, // clearProps: 'all', // ease: 'none', // }); const activeLink = container.querySelector('a.is-active span'); const projects = container.querySelectorAll('.project'); const images = container.querySelectorAll('.image'); const imgs = container.querySelectorAll('img'); const tl = gsap.timeline({ defaults: { duration: 0.9, ease: 'power4.out', }, }); tl.set(projects, { autoAlpha: 1 }) // bice fully visible na pocetku ovog timeline .fromTo( activeLink, { xPercent: -101 }, { xPercent: 0, transformOrigin: 'left' }, 0 ) .from( images, { xPercent: -101, stagger: 0.1, }, 0 ) .from(imgs, { xPercent: 101, stagger: 0.1 }, 0); //! za efekat reveal images, ovo ide uvek u suprotnom pravcu od wrappera (images u ovom slucaju), tzv masking // tl.timeScale(0.2); return tl; }; export default animationEnter;
javascript
14
0.636274
160
21.422222
45
starcoderdata
#include<bits/stdc++.h> using namespace std; int N, M=0; int main () { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); while (cin>>N>>M) { N+=M+1; if (N==1) { cout<<1<<endl; } else cout<<ceil(log(N)/log(10))<<endl; } }
c++
15
0.556485
55
17.461538
13
codenet
#include<bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); int n,g; vector<vector<int>> brojevi(3,vector<int>(3)); vector<vector<bool>> p(3,vector<bool>(3,false)); for (int i=0;i<3;i++) for (int j=0;j<3;j++) cin >> brojevi[i][j]; cin >> n; for (int k=0;k<n;k++) { cin >> g; for (int i=0;i<3;i++) for (int j=0;j<3;j++) if(brojevi[i][j]==g) p[i][j]=true; } if(p[0][0] && p[1][0] && p[2][0] || p[0][1] && p[1][1] && p[2][1] || p[0][2] && p[1][2] && p[2][2] || p[0][0] && p[0][1] && p[0][2] || p[1][0] && p[1][1] && p[1][2] || p[2][0] && p[2][1] && p[2][2] || p[0][0] && p[1][1] && p[2][2] || p[0][2] && p[1][1] && p[2][0]) cout << "Yes"; else cout << "No"; }
c++
17
0.384527
105
29.928571
28
codenet
import React from "react"; import "./quotes.css"; //Components import Button from "../../components/Button"; import Svg from "../../components/Svg"; import Title from "../../components/Title"; import Quote from "../../components/Quote"; const Quotes = () => { const [clickResult, setClickResult] = React.useState([]); const [moving, setMoving] = React.useState(false); const [visible, setVisible] = React.useState(""); const rootUrl = `https://ron-swanson-quotes.herokuapp.com/v2/quotes/`; return ( <div className="quotes-view"> <Title size={"47"}>Find your favorite ron swanson quote <Svg moving={moving} /> <Button handleClick={() => fetch(rootUrl) .then((response) => response.json()) .then((json) => { setClickResult(json); setMoving(!moving); setVisible("visible"); }) } > PRESS HERE <Quote visible={visible}>{clickResult} ); }; export default Quotes;
javascript
21
0.580038
72
26.947368
38
starcoderdata
import re from urllib3.util.url import parse_url def parse_url_from_string(url): parsed_url = None if not url: raise ValueError('Url cannot be empty.') parsed_url = parse_url(url) if not parsed_url.scheme: raise ValueError(f'Could not find a url scheme in {url}. Make sure url has http or https') if parsed_url.scheme != 'http' and parsed_url.scheme != 'https': raise ValueError(f'Could not find http: or https: in "{url}"') return parsed_url STR_PARAM = re.compile(r'\{(?P def partial_format(string, **kwargs): ''' Executes a partial string format - only substitutes the parameters specified in the kwargs, and leaves the other string parameters as-is. ''' kwarg_dict = dict(kwargs) existing_keys = list(kwarg_dict.keys()) new_kwargs = {} for param in STR_PARAM.finditer(string): name = param.group('name') ftype = param.group('ftype') if ftype: msg = f'partial_format does not work with string format types - got "{name + ftype}"' raise ValueError(msg) if name not in existing_keys: new_kwargs[name] = '{'+name+'}' new_kwargs.update(kwarg_dict) return string.format(**new_kwargs)
python
12
0.628235
99
36.5
34
starcoderdata
const mongoose = require('mongoose'); const { Extension } = require('../FHIRDataTypesSchemaExport/allTypeSchemaTopDef'); const uri = require('../FHIRDataTypesSchema/uri'); const string = require('../FHIRDataTypesSchema/string'); const instant = require('../FHIRDataTypesSchema/instant'); const { Bundle_Request } = require("../FHIRDataTypesSchemaExport/allTypeSchemaTopDef"); Bundle_Request.add({ extension: { type: [Extension], default: void 0 }, modifierExtension: { type: [Extension], default: void 0 }, method: { type: String, enum: ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"], default: void 0 }, url: uri, ifNoneMatch: string, ifModifiedSince: instant, ifMatch: string, ifNoneExist: string }); module.exports.Bundle_Request = Bundle_Request;
javascript
10
0.638792
64
25.9375
32
starcoderdata
void GraphicsDisplay::set_font(unsigned char* f, unsigned char firstascii, unsigned char lastascii, bool proportional) { font = f; // read font parameter from start of array //fontoffset = font[0]; // bytes / char fonthor = font[1]; // get hor size of font fontvert = font[2]; // get vert size of font //fontbpl = font[3]; // bytes per line fontbpl = (fontvert+7)>>3; //bytes per line, rounded up to multiple of 8 fontoffset = (fonthor*fontbpl)+1; firstch = firstascii; // first ascii code present in font array (usually 32) lastch = lastascii; // last ascii code present in font array (usually 127) fontprop=proportional; set_font_zoom(1,1); }
c++
8
0.594629
118
51.2
15
inline
public void testUndoDetachComplexAtRoot() { SDODataObject original = (SDODataObject)copyHelper.copy(root); changeSummary.beginLogging();// logging // verify original VS is null and save a copy of current VS for object identity testing after undo ValueStore aCurrentValueStore = root._getCurrentValueStore(); assertNotNull(aCurrentValueStore); ValueStore anOriginalValueStore = (ValueStore)changeSummary.getOriginalValueStores().get(root); assertNull(anOriginalValueStore); // save original child SDODataObject aChild = (SDODataObject)root.get("property-Containment"); assertNotNull(aChild.getChangeSummary()); // operation on complex child of root aChild.detach(); // verify CS is null on removed trees assertChangeSummaryStatusIfClearedIfCSIsAncestor((DataObject)aChild, true); assertNotNull(aCurrentValueStore); ValueStore anOriginalValueStoreAfterOperation = (ValueStore)changeSummary.getOriginalValueStores().get(root); ValueStore aCurrentValueStoreAfterOperation = root._getCurrentValueStore(); assertNotNull(anOriginalValueStoreAfterOperation); assertNotNull(aCurrentValueStoreAfterOperation); assertTrue(anOriginalValueStoreAfterOperation == aCurrentValueStore); assertFalse(root.isSet(rootProperty)); assertNull((SDODataObject)containedDataObject.getContainer());// make sure it is changed // undo and verify equality assertUndoChangesEqualToOriginal(changeSummary, root, original); // verify that property is reset assertTrue(root.isSet(rootProperty)); // we have object identity assertTrue(equalityHelper.equal(original, root)); ValueStore anOriginalValueStoreAfterUndo = (ValueStore)changeSummary.getOriginalValueStores().get(root); ValueStore aCurrentValueStoreAfterUndo = root._getCurrentValueStore(); assertNull(anOriginalValueStoreAfterUndo); assertNotNull(aCurrentValueStoreAfterUndo); // we return the original value store back to the current VS assertTrue(aCurrentValueStoreAfterUndo == aCurrentValueStore); }
java
9
0.694814
117
52.302326
43
inline
def guess_target_mode(self): if not self._hits: return None logging.debug('[guess] target mode') ships = {self._board[pos]: pos for pos in self._hits if self._board[pos] in 'ABSDP'} for ship, ship_pos in ships.items(): length = SHIP_LENGTH[ship] positions = all_ship_positions(length, lambda p: p in self._hits and (self._board[p] == 'H' or self._board[p] == ship)) positions = [points for points in positions if ship_pos in points] assert len(positions) == 1 logging.debug('[target] sunken ship: %r' % positions[0]) for pos in positions[0]: self._hits.remove(pos) if not self._hits: return None # no sunken ship hit = next(iter(self._hits)) nearby_hits = set(adjacent_coordinates(hit)).intersection(self._hits) logging.debug('[target] from hit: %r nearby hits: %r' % (hit, nearby_hits)) for nearby_hit in nearby_hits: # grab all hits on the same line, starting from `hit` cluster = {hit, nearby_hit} guesses = [] direction = point_sub(nearby_hit, hit) current = point_add(nearby_hit, direction) while valid_coordinate(current) and current in self._hits: cluster.add(current) current = point_add(current, direction) if valid_coordinate(current) and current not in self._guesses and self.is_possibly_ship(current): guesses.append(current) current = point_sub(hit, direction) while valid_coordinate(current) and current in self._hits: cluster.add(current) current = point_sub(current, direction) if valid_coordinate(current) and current not in self._guesses and self.is_possibly_ship(current): guesses.append(current) # found a cluster logging.debug('[target] found cluster: %r' % cluster) if guesses: return self.shoot(guesses) # no nearby hits logging.debug('[target] no nearby hits, shooting nearby') positions = set(adjacent_coordinates(hit)).difference(self._guesses) positions = [pos for pos in positions if self.is_possibly_ship(pos)] return self.shoot(positions)
python
16
0.583963
131
39.389831
59
inline
private double[][] readDataFromCSVFile(String fileURL) { // we assume that this file contain array of data // each row has the same amount of columns // read through the file and put data in the list List<Double> tempData = new ArrayList<Double>(); BufferedReader reader = null; try { URL url = new URL(fileURL); InputStream stream = url.openStream(); // This is for file reader locally // reader = new BufferedReader(new FileReader(fileURL)); // This is for any file protocol // for local file system, use [URL url = new // URL("file:/c:/data/test.txt");] log.info("fileURL" + fileURL); reader = new BufferedReader(new InputStreamReader(stream)); String myline = ""; StringTokenizer vals; // Loop for Lat Long blocks int row = 0; int col = 0; while ((myline = reader.readLine()) != null) { if (myline.contains(",")) { vals = new StringTokenizer(myline, ","); // split the value } else { vals = new StringTokenizer(myline, " "); } col = vals.countTokens(); // log.info("loop for lat/long blocks, row: " + row + ", col: " // + col); for (int i = 0; i < col; i++) { String val = vals.nextToken(); // log.info("val:" + val); if (val.contains("e")) { // if the number is presented in // exponential notion int splitPoint = val.indexOf('e'); double num = Double.parseDouble(val.substring(0, splitPoint - 1)); double pw = Double.parseDouble(val .substring(splitPoint + 1)); tempData.add(num * Math.pow(10, pw)); } else { tempData.add(Double.parseDouble(val)); } } row++; } log.info("number of rows: " + row + " number of cols: " + col); // create 2D array of data from the list double[][] data = new double[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { data[i][j] = tempData.get(i * col + j); } } return data; } catch (FileNotFoundException e) { log.error(fileURL + "\n" + e.getMessage()); } catch (IOException e2) { log.error(fileURL + "\n" + e2.getMessage()); } finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }
java
18
0.587868
67
29.726027
73
inline
// 生成AppJSON.js 文件,方便业务方 查看代码里面使用 app.tabs 的值 const path = require('path'); const _ = require('lodash'); _; const Asset = require('../asset'); module.exports = class AppJSON { constructor(options) { this.appEntry = ''; this.options = { output: 'appJson.js', picks: ['tabBar'], ...options, }; } apply(mpb) { mpb.hooks.afterCompile.tapPromise('AppJSON', async () => { // 模拟一个文件出来 const { appEntry } = mpb; const outPutJSON = _.pick(appEntry, this.options.picks); const strAppEntry = `module.exports = ${JSON.stringify(outPutJSON)}`; if (this.appEntry !== strAppEntry) { this.appEntry = strAppEntry; const asset = new Asset( path.join(mpb.src, this.options.output), path.join(mpb.dest, this.options.output), { virtual_file: true } ); asset.contents = strAppEntry; asset.mtime = Date.now(); await mpb.assetManager.addAsset(asset); } return Promise.resolve(); }); } };
javascript
17
0.515974
81
31.102564
39
starcoderdata
using Optsol.Components.Application.DataTransferObjects; using Optsol.Components.Test.Utils.Contracts; using System; namespace Optsol.Components.Test.Utils.ViewModels { public class TestResponseDto : BaseDataTransferObject { public Guid Id { get; set; } public string Nome { get; set; } public string Contato { get; set; } public string Ativo { get; set; } public override void Validate() { //TODO: REVER //AddNotifications(new TestResponseDtoContract(this)); } } public class EnviarWhatsDto { public EnviarWhatsDto() { } public string Mensagem { get; set; } } }
c#
8
0.612447
66
20.424242
33
starcoderdata
package won.bot.framework.eventbot.action.impl; import won.bot.framework.eventbot.EventListenerContext; import won.bot.framework.eventbot.action.EventBotAction; public class DelayedAction extends DelayedDelegatingAction { private final long delay; public DelayedAction(final EventListenerContext eventListenerContext, long delay, final EventBotAction delegate) { super(eventListenerContext, delegate); this.delay = delay; assert 0L <= this.delay : "Delay must be >= 0"; } @Override protected long getDelay() { return delay; } }
java
6
0.73752
118
30.05
20
starcoderdata
export const runSuites = (testSuites, solutions) => { testSuites.forEach((t) => { solutions.forEach((solution) => { it(`${t.title} || solution: ${solution}`, t.suite(solution)); }); }); };
javascript
22
0.574879
67
28.571429
7
starcoderdata
public override void Disconnect() { // Request all server tasks to cancel and wait for their cancellation mCancellationTokenSource.Cancel(); if (mReceiver != null && mReceiver.Status == TaskStatus.Running) Task.WaitAll(mReceiver); if (mSender != null && mSender.Status == TaskStatus.Running) Task.WaitAll(mSender); }
c#
9
0.705539
72
30.272727
11
inline
using System.Windows; using System.Windows.Input; using Microsoft.Win32; using Prism.Commands; namespace JustAssembly.Controls { public partial class SelectorControl : System.Windows.Controls.Control { public SelectorControl() { DefaultStyleKey = typeof(SelectorControl); BrowseCommand = new DelegateCommand(OnBrowseFilePathExecuted); } public static readonly DependencyProperty FilePathProperty = DependencyProperty.Register("FilePath", typeof(string), typeof(SelectorControl)); public static readonly DependencyProperty BrowseCommandProperty = DependencyProperty.Register("BrowseCommand", typeof(ICommand), typeof(SelectorControl)); public static readonly DependencyProperty SelectedItemTypeProperty = DependencyProperty.Register("SelectedItemType", typeof(SelectedItemType), typeof(SelectorControl)); public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register("Header", typeof(string), typeof(SelectorControl)); public static readonly DependencyProperty FilterProperty = DependencyProperty.Register("Filter", typeof(string), typeof(SelectorControl)); public string Header { get => (string)GetValue(HeaderProperty); set => SetValue(HeaderProperty, value); } public string Filter { get => (string)GetValue(FilterProperty); set => SetValue(FilterProperty, value); } public SelectedItemType SelectedItemType { get => (SelectedItemType)GetValue(SelectedItemTypeProperty); set => SetValue(SelectedItemTypeProperty, value); } private void OnBrowseFilePathExecuted() { if (SelectedItemType == SelectedItemType.File) { GetEnteredFilePath(); } else { GetEnteredFolderPath(); } } private void GetEnteredFolderPath() { System.Windows.Forms.FolderBrowserDialog showDialog = new System.Windows.Forms.FolderBrowserDialog() { ShowNewFolderButton = true }; System.Windows.Forms.DialogResult showDialogResult = showDialog.ShowDialog(); if (showDialogResult == System.Windows.Forms.DialogResult.OK) { FilePath = showDialog.SelectedPath; } } private void GetEnteredFilePath() { OpenFileDialog showDialog = new OpenFileDialog { CheckFileExists = true, Multiselect = false, Filter = Filter }; bool? showDialogResult = showDialog.ShowDialog(); if (showDialogResult == true) { FilePath = showDialog.FileName; } } public ICommand BrowseCommand { get => (ICommand)GetValue(BrowseCommandProperty); set => SetValue(BrowseCommandProperty, value); } public string FilePath { get => (string)GetValue(FilePathProperty); set => SetValue(FilePathProperty, value); } } }
c#
15
0.749907
105
29.05618
89
starcoderdata
<?php /** * Created by PhpStorm. * User: Joe * Date: 11/12/2014 * Time: 11:23 PM */ namespace SupahFramework2\Configuration; class Configuration { private static $cached = []; public function __call($name, $args) { return self::__callStatic($name, $args); } public static function __callStatic($name, $args) { if (isset(self::$cached[$name])) { return self::$cached[$name]; } if (file_exists(APPLICATION_PATH."/Configuration/" . ucfirst($name) . ".php") && file_exists(FRAMEWORK_PATH."/Configuration/Defaults/" . ucfirst($name) . ".php")) { // merge two. $name = ucfirst($name); $cfgApp = new StandardConfigurationFile(APPLICATION_PATH."/Configuration/" . $name ); $cfg = new StandardConfigurationFile(FRAMEWORK_PATH."/Configuration/Defaults/" . $name ); $rfc = new \ReflectionObject($cfgApp); foreach ($rfc->getProperties() as $property) { $name = $property->getName(); $value = $property->getValue($cfgApp); $cfg->$name = array_replace_recursive($cfg->$name, $value); } self::$cached[$name] = $cfg; return $cfg; } else if (file_exists(APPLICATION_PATH."/Configuration/" . ucfirst($name) . ".php")) { // load $name = ucfirst($name); $newcfg = new StandardConfigurationFile(APPLICATION_PATH."/Configuration/" . $name ); self::$cached[$name] = $newcfg; return $newcfg; } else if (file_exists(FRAMEWORK_PATH."/Configuration/Defaults/" . ucfirst($name) . ".php")) { // load $name = ucfirst($name); $newcfg = new StandardConfigurationFile(FRAMEWORK_PATH."/Configuration/Defaults/" . $name ); self::$cached[$name] = $newcfg; return $newcfg; }/* // This would be too dangerous, since this is already dangerous in itself! else if (!empty($args) && is_string($args)) { return new Configuration($args); }*/ } }
php
20
0.561044
172
36.666667
57
starcoderdata
<?php /** * Souin Cache powered by * * @author * @copyright 2017 Evolutive Group * @license You are just allowed to modify this copy for your own use. You must not redistribute it. License * is permitted for one Prestashop instance only but you can install it on your test instances. * @link https://addons.prestashop.com/en/contact-us?id_product=26866 */ class BackwardCompatibility { /** * Helper method to compare PS versions. * * @param string $min * @param string $max * @return bool */ public static function versionCheck($min, $max = false) { if ($max) { return _PS_VERSION_ >= $min && _PS_VERSION_ <= $max; } return _PS_VERSION == $min; } /** * Helper method to handle undefined methods for backward compatibility. * * @param string $method * @param mixed $args * @return mixed */ public static function undefinedMethod($method, $args) { switch ($method) { case 'displayWarning': if (self::versionCheck('1.6.0', '1.6.1')) { $warnings = reset($args); $output = ' <div class="bootstrap"> <div class="module_warning alert alert-warning" > <button type="button" class="close" data-dismiss="alert">&times; if (is_array($warnings)) { $output .= ' foreach ($warnings as $msg) { $output .= ' } $output .= ' } else { $output .= $warnings; } // Close div openned previously $output .= ' return $output; } break; } } /** * Redirects on the module configuration page after the form was sent to avoid re-submits. * This is an issue in PS1.6. * * @param string $module * @param string $submit * @return void */ public static function handleSubmit($module, $submit) { if (self::versionCheck('1.6.0', '1.6.9')) { if (Tools::getValue($submit)) { Tools::redirectAdmin('index.php?controller=AdminModules&configure=' . $module .'&tab_module=others&module_name=' . $module .'&token='.Tools::getAdminTokenLite('AdminModules')); } } } /** * Backward compatbility install hooks. * * @param object $module * @return bool */ public static function installHooks($module) { if (self::versionCheck('1.6.0', '1.6.9')) { return ( $module->registerHook("actionDispatcher") ); } return false; } /** * Backward compatbility uninstall hooks. * * @param object $module * @return bool */ public static function uninstallHooks($module) { if (self::versionCheck('1.6.0', '1.6.9')) { return $module->unregisterHook("actionDispatcher"); } return false; } }
php
19
0.492357
113
28.076923
117
starcoderdata
static void _tiffUnmapProc(thandle_t fd, tdata_t base, toff_t size) { char *inadr[2]; int i, j; /* Find the section in the table */ for (i = 0;i < no_mapped; i++) { if (map_table[i].base == (char *) base) { /* Unmap the section */ inadr[0] = (char *) base; inadr[1] = map_table[i].top; sys$deltva(inadr, 0, 0); sys$dassgn(map_table[i].channel); /* Remove this section from the list */ for (j = i+1; j < no_mapped; j++) map_table[j-1] = map_table[j]; no_mapped--; return; } } }
c
12
0.545455
55
22.590909
22
inline
// ============================================================== // RTL generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC // Version: 2017.2 // Copyright (C) 1986-2017 Xilinx, Inc. All Rights Reserved. // // =========================================================== #ifndef _Loop_1_proc_HH_ #define _Loop_1_proc_HH_ #include "systemc.h" #include "AESL_pkg.h" namespace ap_rtl { struct Loop_1_proc : public sc_module { // Port declarations 16 sc_in_clk ap_clk; sc_in< sc_logic > ap_rst; sc_in< sc_logic > ap_start; sc_out< sc_logic > ap_done; sc_in< sc_logic > ap_continue; sc_out< sc_logic > ap_idle; sc_out< sc_logic > ap_ready; sc_in< sc_lv > p_hw_input_stencil_stream_V_value_V_dout; sc_in< sc_logic > p_hw_input_stencil_stream_V_value_V_empty_n; sc_out< sc_logic > p_hw_input_stencil_stream_V_value_V_read; sc_out< sc_lv > hw_output_V_value_V; sc_out< sc_logic > hw_output_V_value_V_ap_vld; sc_in< sc_logic > hw_output_V_value_V_ap_ack; sc_out< sc_lv > hw_output_V_last_V; sc_out< sc_logic > hw_output_V_last_V_ap_vld; sc_in< sc_logic > hw_output_V_last_V_ap_ack; // Module declarations Loop_1_proc(sc_module_name name); SC_HAS_PROCESS(Loop_1_proc); ~Loop_1_proc(); sc_trace_file* mVcdFile; sc_signal< sc_logic > ap_done_reg; sc_signal< sc_lv > ap_CS_fsm; sc_signal< sc_logic > ap_CS_fsm_state1; sc_signal< sc_logic > p_hw_input_stencil_stream_V_value_V_blk_n; sc_signal< sc_logic > ap_CS_fsm_pp0_stage0; sc_signal< sc_logic > ap_enable_reg_pp0_iter1; sc_signal< bool > ap_block_pp0_stage0_flag00000000; sc_signal< sc_lv > exitcond_flatten_reg_405; sc_signal< sc_logic > hw_output_V_value_V_blk_n; sc_signal< sc_logic > ap_enable_reg_pp0_iter4; sc_signal< sc_lv > ap_reg_pp0_iter3_exitcond_flatten_reg_405; sc_signal< sc_logic > hw_output_V_last_V_blk_n; sc_signal< sc_lv > indvar_flatten_reg_126; sc_signal< sc_lv > p_hw_output_y_scan_1_reg_137; sc_signal< sc_lv > p_hw_output_x_scan_2_reg_149; sc_signal< sc_lv > exitcond_flatten_fu_160_p2; sc_signal< bool > ap_block_state2_pp0_stage0_iter0; sc_signal< bool > ap_block_state3_pp0_stage0_iter1; sc_signal< bool > ap_block_state4_pp0_stage0_iter2; sc_signal< bool > ap_block_state5_pp0_stage0_iter3; sc_signal< bool > ap_block_state6_pp0_stage0_iter4; sc_signal< sc_logic > ap_sig_ioackin_hw_output_V_value_V_ap_ack; sc_signal< bool > ap_block_state6_io; sc_signal< bool > ap_block_pp0_stage0_flag00011001; sc_signal< sc_lv > ap_reg_pp0_iter1_exitcond_flatten_reg_405; sc_signal< sc_lv > ap_reg_pp0_iter2_exitcond_flatten_reg_405; sc_signal< sc_lv > indvar_flatten_next_fu_166_p2; sc_signal< sc_logic > ap_enable_reg_pp0_iter0; sc_signal< sc_lv > exitcond_fu_172_p2; sc_signal< sc_lv > exitcond_reg_414; sc_signal< sc_lv > ap_reg_pp0_iter1_exitcond_reg_414; sc_signal< sc_lv > ap_reg_pp0_iter2_exitcond_reg_414; sc_signal< sc_lv > p_hw_output_x_scan_s_fu_178_p3; sc_signal< sc_lv > p_hw_output_x_scan_s_reg_420; sc_signal< sc_lv > p_hw_output_x_scan_1_fu_186_p2; sc_signal< sc_lv > p_hw_output_y_scan_2_fu_192_p2; sc_signal< sc_lv > p_hw_output_y_scan_2_reg_430; sc_signal< sc_lv > tmp8_fu_198_p2; sc_signal< sc_lv > tmp8_reg_435; sc_signal< sc_lv > ap_reg_pp0_iter2_tmp8_reg_435; sc_signal< sc_lv > p_hw_output_y_scan_s_fu_204_p3; sc_signal< sc_lv > p_hw_output_y_scan_s_reg_440; sc_signal< sc_lv > p_345_fu_211_p1; sc_signal< sc_lv > p_345_reg_445; sc_signal< sc_lv > p_357_reg_450; sc_signal< sc_lv > ap_reg_pp0_iter2_p_357_reg_450; sc_signal< sc_lv > p_381_reg_455; sc_signal< sc_lv > p_393_reg_460; sc_signal< sc_lv > tmp_2_reg_465; sc_signal< sc_lv > tmp_4_reg_470; sc_signal< sc_lv > ap_reg_pp0_iter2_tmp_4_reg_470; sc_signal< sc_lv > tmp_5_reg_475; sc_signal< sc_lv > tmp_6_reg_480; sc_signal< sc_lv > tmp_7_reg_485; sc_signal< sc_lv > tmp_s_fu_295_p2; sc_signal< sc_lv > tmp_s_reg_490; sc_signal< sc_lv > ap_reg_pp0_iter2_tmp_s_reg_490; sc_signal< sc_lv > tmp_mid1_fu_300_p2; sc_signal< sc_lv > tmp_mid1_reg_495; sc_signal< sc_lv > tmp2_fu_333_p2; sc_signal< sc_lv > tmp2_reg_500; sc_signal< sc_lv > tmp5_fu_338_p2; sc_signal< sc_lv > tmp5_reg_505; sc_signal< sc_lv > ap_reg_pp0_iter3_tmp5_reg_505; sc_signal< sc_lv > tmp6_fu_349_p2; sc_signal< sc_lv > tmp6_reg_510; sc_signal< sc_lv > ap_reg_pp0_iter3_tmp6_reg_510; sc_signal< sc_lv > tmp1_fu_371_p2; sc_signal< sc_lv > tmp1_reg_515; sc_signal< sc_lv > tmp_last_V_fu_376_p2; sc_signal< sc_lv > tmp_last_V_reg_520; sc_signal< bool > ap_block_state1; sc_signal< bool > ap_block_pp0_stage0_flag00011011; sc_signal< sc_logic > ap_condition_pp0_exit_iter0_state2; sc_signal< sc_logic > ap_enable_reg_pp0_iter2; sc_signal< sc_logic > ap_enable_reg_pp0_iter3; sc_signal< sc_lv > p_hw_output_y_scan_1_phi_fu_141_p4; sc_signal< bool > ap_block_pp0_stage0_flag00001001; sc_signal< sc_logic > ap_reg_ioackin_hw_output_V_value_V_ap_ack; sc_signal< sc_logic > ap_reg_ioackin_hw_output_V_last_V_ap_ack; sc_signal< sc_lv > p_353_fu_305_p3; sc_signal< sc_lv > p_377_fu_319_p3; sc_signal< sc_lv > p_371_fu_312_p3; sc_signal< sc_lv > p_389_fu_326_p3; sc_signal< sc_lv > tmp7_fu_344_p2; sc_signal< sc_lv > p_365_fu_359_p3; sc_signal< sc_lv > tmp3_fu_366_p2; sc_signal< sc_lv > tmp_mid2_fu_354_p3; sc_signal< sc_lv > tmp4_fu_381_p2; sc_signal< sc_lv > p_397_fu_385_p2; sc_signal< sc_lv > tmp_3_fu_390_p4; sc_signal< sc_logic > ap_CS_fsm_state7; sc_signal< sc_lv > ap_NS_fsm; sc_signal< sc_logic > ap_idle_pp0; sc_signal< sc_logic > ap_enable_pp0; static const sc_logic ap_const_logic_1; static const sc_logic ap_const_logic_0; static const sc_lv ap_ST_fsm_state1; static const sc_lv ap_ST_fsm_pp0_stage0; static const sc_lv ap_ST_fsm_state7; static const sc_lv ap_const_lv32_0; static const bool ap_const_boolean_1; static const sc_lv ap_const_lv32_1; static const bool ap_const_boolean_0; static const sc_lv ap_const_lv1_0; static const sc_lv ap_const_lv1_1; static const sc_lv ap_const_lv21_0; static const sc_lv ap_const_lv11_0; static const sc_lv ap_const_lv21_1F8C94; static const sc_lv ap_const_lv21_1; static const sc_lv ap_const_lv11_77E; static const sc_lv ap_const_lv11_1; static const sc_lv ap_const_lv11_435; static const sc_lv ap_const_lv32_40; static const sc_lv ap_const_lv32_5F; static const sc_lv ap_const_lv32_C0; static const sc_lv ap_const_lv32_DF; static const sc_lv ap_const_lv32_100; static const sc_lv ap_const_lv32_11F; static const sc_lv ap_const_lv32_20; static const sc_lv ap_const_lv32_3E; static const sc_lv ap_const_lv32_60; static const sc_lv ap_const_lv32_7E; static const sc_lv ap_const_lv32_80; static const sc_lv ap_const_lv32_9D; static const sc_lv ap_const_lv32_A0; static const sc_lv ap_const_lv32_BE; static const sc_lv ap_const_lv32_E0; static const sc_lv ap_const_lv32_FE; static const sc_lv ap_const_lv11_77D; static const sc_lv ap_const_lv2_0; static const sc_lv ap_const_lv32_4; static const sc_lv ap_const_lv32_1F; static const sc_lv ap_const_lv32_2; // Thread declarations void thread_ap_clk_no_reset_(); void thread_ap_CS_fsm_pp0_stage0(); void thread_ap_CS_fsm_state1(); void thread_ap_CS_fsm_state7(); void thread_ap_block_pp0_stage0_flag00000000(); void thread_ap_block_pp0_stage0_flag00001001(); void thread_ap_block_pp0_stage0_flag00011001(); void thread_ap_block_pp0_stage0_flag00011011(); void thread_ap_block_state1(); void thread_ap_block_state2_pp0_stage0_iter0(); void thread_ap_block_state3_pp0_stage0_iter1(); void thread_ap_block_state4_pp0_stage0_iter2(); void thread_ap_block_state5_pp0_stage0_iter3(); void thread_ap_block_state6_io(); void thread_ap_block_state6_pp0_stage0_iter4(); void thread_ap_condition_pp0_exit_iter0_state2(); void thread_ap_done(); void thread_ap_enable_pp0(); void thread_ap_idle(); void thread_ap_idle_pp0(); void thread_ap_ready(); void thread_ap_sig_ioackin_hw_output_V_value_V_ap_ack(); void thread_exitcond_flatten_fu_160_p2(); void thread_exitcond_fu_172_p2(); void thread_hw_output_V_last_V(); void thread_hw_output_V_last_V_ap_vld(); void thread_hw_output_V_last_V_blk_n(); void thread_hw_output_V_value_V(); void thread_hw_output_V_value_V_ap_vld(); void thread_hw_output_V_value_V_blk_n(); void thread_indvar_flatten_next_fu_166_p2(); void thread_p_345_fu_211_p1(); void thread_p_353_fu_305_p3(); void thread_p_365_fu_359_p3(); void thread_p_371_fu_312_p3(); void thread_p_377_fu_319_p3(); void thread_p_389_fu_326_p3(); void thread_p_397_fu_385_p2(); void thread_p_hw_input_stencil_stream_V_value_V_blk_n(); void thread_p_hw_input_stencil_stream_V_value_V_read(); void thread_p_hw_output_x_scan_1_fu_186_p2(); void thread_p_hw_output_x_scan_s_fu_178_p3(); void thread_p_hw_output_y_scan_1_phi_fu_141_p4(); void thread_p_hw_output_y_scan_2_fu_192_p2(); void thread_p_hw_output_y_scan_s_fu_204_p3(); void thread_tmp1_fu_371_p2(); void thread_tmp2_fu_333_p2(); void thread_tmp3_fu_366_p2(); void thread_tmp4_fu_381_p2(); void thread_tmp5_fu_338_p2(); void thread_tmp6_fu_349_p2(); void thread_tmp7_fu_344_p2(); void thread_tmp8_fu_198_p2(); void thread_tmp_3_fu_390_p4(); void thread_tmp_last_V_fu_376_p2(); void thread_tmp_mid1_fu_300_p2(); void thread_tmp_mid2_fu_354_p3(); void thread_tmp_s_fu_295_p2(); void thread_ap_NS_fsm(); }; } using namespace ap_rtl; #endif
c
10
0.63258
81
41.269388
245
starcoderdata