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
def subgraph_forward(self, x, g): x = super().subgraph_forward(x, g) batch_size, node_num, _ = x.shape # add node-specific representations n_id = g['cent_n_id'] x_id = self.node_emb(n_id)\ .reshape(1, node_num, self.node_dim)\ .expand(batch_size, -1, -1) x = torch.cat([x, x_id], dim=-1) # calculate the edge gate for each node pair edge_index = g['edge_index'].permute(1, 0) # [num_edges, 2] edge_num = edge_index.shape[0] edge_x = x[:, edge_index, :]\ .reshape(batch_size, edge_num, self.edge_dim) edge_gate = self.edge_map(edge_x) return edge_gate
python
11
0.536443
68
35.157895
19
inline
Shopware.Mixin.register('sw-extension-error', { mixins: [Shopware.Mixin.getByName('notification')], methods: { showExtensionErrors(errorResponse) { Shopware.Service('extensionErrorService') .handleErrorResponse(errorResponse, this) .forEach((notification) => { this.createNotificationError(notification); }); }, }, });
javascript
14
0.577273
63
30.428571
14
starcoderdata
<?php namespace GetThingsDone\Shareholder\Models; use Illuminate\Database\Eloquent\Model; class ShareTranferRecord extends Model { public $fillable = [ 'from_record_id','to_record_id', ]; public function from_record() { return $this->hasOne(ShareQuantityRecord::class, 'from_record_id'); } public function to_record() { return $this->hasOne(ShareQuantityRecord::class, 'to_record_id'); } }
php
10
0.655556
75
20.428571
21
starcoderdata
// Licensed to Apache Software Foundation (ASF) under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Apache Software Foundation (ASF) licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package metricservice import ( "errors" "fmt" "math" "sync" "sync/atomic" "unicode/utf8" "unsafe" "github.com/apache/skywalking-satellite/internal/satellite/telemetry" v3 "skywalking.apache.org/repo/goapi/collect/language/agent/v3" ) var errInconsistentCardinality = errors.New("inconsistent label cardinality") // Inspired by Prometheus(prometheus/client_golang), adding labels data is more efficient and saves memory const ( offset64 = 14695981039346656037 prime64 = 1099511628211 SeparatorByte byte = 255 ) type Metric interface { telemetry.Metric WriteMetric(appender *MetricsAppender) } type SubMetric interface { WriteMetric(base *BaseMetric, labels []*v3.Label, appender *MetricsAppender) } type BaseMetric struct { Metric Name string LabelKeys []string NewSubMetric func(labelValues ...string) SubMetric curry []curriedLabelValue mtx sync.RWMutex metrics map[uint64][]metricWithLabelValues } func NewBaseMetric(name string, labels []string, newSubMetric func(labelValues ...string) SubMetric) *BaseMetric { return &BaseMetric{ Name: name, LabelKeys: labels, NewSubMetric: newSubMetric, metrics: map[uint64][]metricWithLabelValues{}, } } func (b *BaseMetric) WriteMetric(appender *MetricsAppender) { for _, m := range b.metrics { for _, metric := range m { labels := make([]*v3.Label, len(b.LabelKeys)) for i := range b.LabelKeys { labels[i] = &v3.Label{ Name: b.LabelKeys[i], Value: metric.values[i], } } metric.metric.WriteMetric(b, labels, appender) } } } func (b *BaseMetric) GetMetricWithLabelValues(lvs ...string) (SubMetric, error) { h, err := b.hashLabelValues(lvs) if err != nil { return nil, err } return b.getOrCreateMetricWithLabelValues(h, lvs, b.curry), nil } type metricWithLabelValues struct { values []string metric SubMetric } // curriedLabelValue sets the curried value for a label at the given index. type curriedLabelValue struct { index int value string } func validateLabelValues(vals []string, expectedNumberOfValues int) error { if len(vals) != expectedNumberOfValues { return fmt.Errorf( "%s: expected %d label values but got %d in %#v", errInconsistentCardinality, expectedNumberOfValues, len(vals), vals, ) } for _, val := range vals { if !utf8.ValidString(val) { return fmt.Errorf("label value %q is not valid UTF-8", val) } } return nil } func (b *BaseMetric) hashLabelValues(vals []string) (uint64, error) { if err := validateLabelValues(vals, len(b.LabelKeys)-len(b.curry)); err != nil { return 0, err } var ( h = hashNew() curry = b.curry iVals, iCurry int ) for i := 0; i < len(b.LabelKeys); i++ { if iCurry < len(curry) && curry[iCurry].index == i { h = hashAdd(h, curry[iCurry].value) iCurry++ } else { h = hashAdd(h, vals[iVals]) iVals++ } h = hashAddByte(h, SeparatorByte) } return h, nil } func (b *BaseMetric) getOrCreateMetricWithLabelValues( hash uint64, lvs []string, curry []curriedLabelValue, ) SubMetric { b.mtx.RLock() metric, ok := b.getMetricWithHashAndLabelValues(hash, lvs, curry) b.mtx.RUnlock() if ok { return metric } b.mtx.Lock() defer b.mtx.Unlock() metric, ok = b.getMetricWithHashAndLabelValues(hash, lvs, curry) if !ok { inlinedLVs := inlineLabelValues(lvs, curry) metric = b.NewSubMetric(inlinedLVs...) b.metrics[hash] = append(b.metrics[hash], metricWithLabelValues{values: inlinedLVs, metric: metric}) } return metric } func (b *BaseMetric) getMetricWithHashAndLabelValues( h uint64, lvs []string, curry []curriedLabelValue, ) (SubMetric, bool) { metrics, ok := b.metrics[h] if ok { if i := findMetricWithLabelValues(metrics, lvs, curry); i < len(metrics) { return metrics[i].metric, true } } return nil, false } func inlineLabelValues(lvs []string, curry []curriedLabelValue) []string { labelValues := make([]string, len(lvs)+len(curry)) var iCurry, iLVs int for i := range labelValues { if iCurry < len(curry) && curry[iCurry].index == i { labelValues[i] = curry[iCurry].value iCurry++ continue } labelValues[i] = lvs[iLVs] iLVs++ } return labelValues } func findMetricWithLabelValues( metrics []metricWithLabelValues, lvs []string, curry []curriedLabelValue, ) int { for i, metric := range metrics { if matchLabelValues(metric.values, lvs, curry) { return i } } return len(metrics) } func matchLabelValues(values, lvs []string, curry []curriedLabelValue) bool { if len(values) != len(lvs)+len(curry) { return false } var iLVs, iCurry int for i, v := range values { if iCurry < len(curry) && curry[iCurry].index == i { if v != curry[iCurry].value { return false } iCurry++ continue } if v != lvs[iLVs] { return false } iLVs++ } return true } // hashNew initializies a new fnv64a hash value. func hashNew() uint64 { return offset64 } // hashAdd adds a string to a fnv64a hash value, returning the updated hash. func hashAdd(h uint64, s string) uint64 { for i := 0; i < len(s); i++ { h ^= uint64(s[i]) h *= prime64 } return h } // hashAddByte adds a byte to a fnv64a hash value, returning the updated hash. func hashAddByte(h uint64, b byte) uint64 { h ^= uint64(b) h *= prime64 return h } func addFloat64(addr *float64, delta float64) { for { old := math.Float64frombits(atomic.LoadUint64((*uint64)(unsafe.Pointer(addr)))) newVal := old + delta if atomic.CompareAndSwapUint64( (*uint64)(unsafe.Pointer(addr)), math.Float64bits(old), math.Float64bits(newVal), ) { break } } }
go
18
0.693703
114
23.610687
262
starcoderdata
#ifndef FILTERING_H #define FILTERING_H ///PCL INCLUDES #include #include #include #include #include #include #include #include #include ///CUSTOM INCLUDES #include "CustomStructures.h" #include "Calculations.h" template <class T> class Filtering{ private: public: Filtering(); ~Filtering(); ///DOWNSAMPLING static void filterArea(class pcl::PointCloud input,class pcl::PointCloud output ,float minDistance, float maxDistance, std::string axis); static void voxelize(class pcl::PointCloud input,class pcl::PointCloud output, Dimension3D leafSize); static void uniformSampling(class pcl::PointCloud input, class pcl::PointCloud output, float radius); ///OUTLIER REMOVAL static void statisticalOutlierFilter(class pcl::PointCloud input, class pcl::PointCloud output,int mean, float stdDev); static void radiusOutlierFilter(class pcl::PointCloud input, class pcl::PointCloud output, float radius, unsigned int minNeighbors); ///PROJECTION static void parametricProjection(class pcl::PointCloud input, class pcl::PointCloud output, pcl::SacModel model, std::vector &coefficientsVect); }; template class Filtering template class Filtering template class Filtering #endif // FILTERING_H
c
8
0.726849
175
37.155556
45
starcoderdata
Mat CutoutFunc(Mat &im, int pad_size, array<uint8_t, 3> replace, bool inplace) { int H{im.rows}, W{im.cols}; int h = static_cast<int>(grandom.rand() * H); int w = static_cast<int>(grandom.rand() * W); int x1 = std::max(0, w - pad_size); int x2 = std::min(W, w + pad_size); int y1 = std::max(0, h - pad_size); int y2 = std::min(H, h + pad_size); Mat convas; if (inplace) {convas = im;} else {convas = im.clone();} auto roi = convas(cv::Rect(x1, y1, x2 - x1, y2 - y1)); // x, y means w, h(c, r) roi.setTo(cv::Scalar(replace[0] , replace[1] , replace[2])); return convas; }
c++
10
0.562701
83
33.611111
18
inline
void DisplayContext::DrawDottedLine(const Vec3& p1, const Vec3& p2, const ColorF& col1, const ColorF& col2, const float numOfSteps) { Vec3 direction = Vec3(p2.x - p1.x, p2.y - p1.y, p2.z - p1.z); //We only draw half of a step and leave the other half empty to make it a dotted line. Vec3 halfstep = (direction / numOfSteps) * 0.5f; Vec3 startPoint = p1; for (int stepCount = 0; stepCount < numOfSteps; stepCount++) { InternalDrawLine(ToWorldSpacePosition(startPoint), m_color4b, ToWorldSpacePosition(startPoint + halfstep), m_color4b); startPoint += 2 * halfstep; //skip a half step to make it dotted } }
c++
11
0.683077
131
49.076923
13
inline
// SPDX-License-Identifier: Apache-2.0 // Licensed to the Ed-Fi Alliance under one or more agreements. // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. #region using System.Linq; using System.Reflection; #endregion namespace MappingEdu.Core.Domain.Enumerations { public interface IDatabaseEnumerationReflector { IDatabaseEnumeration[] GetDatabaseValues(string enumerationName); } public class DatabaseEnumerationReflector : IDatabaseEnumerationReflector { public IDatabaseEnumeration[] GetDatabaseValues(string enumerationName) { var databaseEnumerationInterfaceType = typeof (IDatabaseEnumeration); var enumerationType = typeof (DomainModule).Assembly .GetTypes() .Single(x => x.Name.Equals(enumerationName) && databaseEnumerationInterfaceType.IsAssignableFrom(x)); var genericEnumerationType = typeof (DatabaseEnumeration var getDatabaseValuesMethod = genericEnumerationType.GetMethod("GetDatabaseValues", BindingFlags.Public | BindingFlags.Static); var databaseValues = (dynamic[]) getDatabaseValuesMethod.Invoke(null, null); return databaseValues.Cast } } }
c#
19
0.731691
139
41.942857
35
starcoderdata
def wait_until_signal(signal, timeout=5): """ Blocks the calling thread until the signal emits or the timeout expires. """ init_time = time.time() finished = False def done(*args): nonlocal finished finished = True signal.connect(done) while not finished and time.time() - init_time < timeout: QtTest.QTest.qWait(100) try: signal.disconnect(done) except TypeError: pass finally: return finished
python
9
0.615542
76
22.333333
21
inline
#!/usr/bin/env python import RPi.GPIO as GPIO import time TRIG = 11 ECHO = 12 def setup(): GPIO.setmode(GPIO.BOARD) GPIO.setup(TRIG, GPIO.OUT) GPIO.setup(ECHO, GPIO.IN) def distance(): GPIO.output(TRIG, 0) time.sleep(0.000002) GPIO.output(TRIG, 1) time.sleep(0.00001) GPIO.output(TRIG, 0) while GPIO.input(ECHO) == 0: a = 0 time1 = time.time() while GPIO.input(ECHO) == 1: a = 1 time2 = time.time() during = time2 - time1 return during * 340 / 2 def loop(): while True: dis = distance() print dis, 'm' if dis < 2: print 'Presencia detectada' print '' time.sleep(2) def destroy(): GPIO.cleanup() if __name__ == "__main__": setup() try: loop() except KeyboardInterrupt: destroy()
python
9
0.632226
61
14.941176
51
starcoderdata
package org.archive.wayback.webapp; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import org.archive.wayback.UrlCanonicalizer; import org.archive.wayback.core.WaybackRequest; import org.archive.wayback.resourcestore.locationdb.FlatFileResourceFileLocationDB; public class CustomUserResourceIndex { protected UrlCanonicalizer canonicalizer; protected FlatFileResourceFileLocationDB indexFile = new FlatFileResourceFileLocationDB(); protected String filename; public void setIndexFile(String file) throws IOException { filename = file; indexFile.setPath(file); } public String getIndexFile() { return filename; } public String[] getCustomResources(WaybackRequest request) { String canonKey = null; try { canonKey = canonicalizer.urlStringToKey(request.getRequestUrl()); return indexFile.nameToUrls(canonKey); } catch (Exception e) { e.printStackTrace(); return null; } } // Extracts all fields fieldNum from matching lines and returns as a json array public String getCustomResourcesPathsAsJSON(WaybackRequest request, String replayPrefix, int fieldNum) { String[] matchingLines = getCustomResources(request); if (matchingLines == null || matchingLines.length == 0) { return ""; } StringBuilder builder = new StringBuilder("["); for (int i = 0; i < matchingLines.length; i++) { if (i > 0) { builder.append(",\n"); } String[] fields = matchingLines[i].split(indexFile.getDelimiter()); String url = replayPrefix + fields[fieldNum]; builder.append("\""); try { builder.append(URLEncoder.encode(url, "UTF-8")); } catch (UnsupportedEncodingException e) { } builder.append("\""); } builder.append("]"); return builder.toString(); } public UrlCanonicalizer getCanonicalizer() { return canonicalizer; } public void setCanonicalizer(UrlCanonicalizer canonicalizer) { this.canonicalizer = canonicalizer; } }
java
15
0.730214
103
23.204819
83
starcoderdata
import React from "react" import "./Paragraphe2.css" export default class Paragraphe2 extends React.Component{ render(){ return( <div className="opposition"> <div className="negatif"> <p className="Paragraphe3"> MISSION <br /><br /> Placer l'humain au coeur des enjeux de transformation RH.<br />Nous voulons performer les talents de l'entreprise, les faire grandir pour les fidéliser, contribuer à créer un climat favorable à la motivation professionnelle. <div className="positif"> <p className="Paragraphe4"> VALEURS <br /><br />Conscient de l’ampleur du défi, DEWAN adopte une position résolument optimiste, bienveillante, collaborative, empathique et créative pour inscrire son action dans le respect des droits humains qu’elle défend. AMBITION /><br />Vous permettre de valoriser votre capital humain en rapprochant les ressources humaine de la réalité du terrain. Motiver et engager vos collaborateurs dans leurs formations professionnelles. <br /> Rendre efficace votre Gestion Prévisionnelle de l'Emploi et des Compétences. (GPEC) ); } }
javascript
11
0.587413
133
49.774194
31
starcoderdata
/*! * zero termination */ #include #include #include #include "types.h" #include "array.h" /*! * \ingroup mptArray * \brief enshure zero-termination * * Check/Set array data zero-terminated. * * \param arr data array * * \return start address of string */ extern char *mpt_array_string(MPT_STRUCT(array) *arr) { static const MPT_STRUCT(type_traits) *traits = 0; MPT_STRUCT(buffer) *buf; char *str, *sep; size_t len; if (!(buf = arr->_buf)) { errno = EFAULT; return 0; } /* accept character data only */ if (!traits || (!(traits = mpt_type_traits('c')))) { errno = ENOTSUP; return 0; } if (buf->_content_traits != traits) { errno = EINVAL; return 0; } str = (char *) (buf + 1); len = buf->_used; /* string termination in buffer data */ if ((sep = memchr(str, 0, len))) { return str; } if (!(sep = mpt_array_slice(arr, len, 1))) { return 0; } str = (char *) (buf + 1); *sep = '\0'; return str; }
c
13
0.593117
53
16.333333
57
starcoderdata
func (s *stepCreateSnapshot) Cleanup(state multistep.StateBag) { // if the snapshot isn't there, we probably never created it if s.snapshotId == "" { return } client := state.Get("client").(*ecs.Client) ui := state.Get("ui").(packer.Ui) // Delete the snapshot we just created ui.Say("Delete snapshot...") err := client.DeleteSnapshot(s.snapshotId) if err != nil { ui.Error(fmt.Sprintf( "Error deleting snapshot: %s, please delete it manually", err)) } else { ui.Message("Snapshot has been deleted!") } }
go
11
0.655617
66
26.684211
19
inline
/* * * * ****************************************************************************** * * * Copyright (c) 2015-2018 Skymind, Inc. * * * * * * This program and the accompanying materials are made available under the * * * terms of the Apache License, Version 2.0 which is available at * * * https://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. * * * * * * SPDX-License-Identifier: Apache-2.0 * * ***************************************************************************** * * */ package ai.skymind.pipelines.pipeline.handlers.array.transform; import ai.skymind.pipelines.serving.SchemaType; import org.datavec.api.records.Record; import org.datavec.api.writable.NDArrayWritable; import org.nd4j.autodiff.execution.NativeGraphExecutioner; import org.nd4j.autodiff.samediff.SDVariable; import org.nd4j.autodiff.samediff.SameDiff; import org.nd4j.linalg.api.ndarray.INDArray; import java.io.File; import java.util.*; /** * Base class for running samediff op graphs * * @author */ public abstract class BaseSameDiffTransform implements ArrayTransform { protected SameDiff sameDiff; protected List inputs,outputs; protected NativeGraphExecutioner nativeGraphExecutioner; /** * Load samediff from the given content. * See {@link #getSameDiffFromBytes(byte[])} * for information on how to setup the bytebuffer * @param sameDiffFlatBuffers the content of the flatbuffers * @param inputs the input names * @param outputs the output names */ public BaseSameDiffTransform(byte[] sameDiffFlatBuffers,List inputs,List outputs) { sameDiff = getSameDiffFromBytes(sameDiffFlatBuffers); nativeGraphExecutioner = new NativeGraphExecutioner(); nativeGraphExecutioner.registerGraph(sameDiff); this.inputs = inputs; this.outputs = outputs; } /** * Load samediff from the given file. * @param file the file to load * @param inputs the input names */ public BaseSameDiffTransform(File file,List inputs) { sameDiff = getSameDiffFromFile(file); nativeGraphExecutioner = new NativeGraphExecutioner(); nativeGraphExecutioner.registerGraph(sameDiff); this.inputs = inputs; } /** * Read samediff from a file * @param file the file to read from * @return the loaded samediff instance */ public abstract SameDiff getSameDiffFromFile(File file); /** * Read samediff from an in memory byte array. * Note that if the byte buffer is samediff * and you are trying to samediff.asFlatBuffers() * use: * ByteBuffer byteBuffer = permuteGraph.asFlatBuffers(); byte[] content = new byte[byteBuffer.capacity() - byteBuffer.position()]; byteBuffer.get(content); * The reason for this is due to how flatbuffers positions buffers. * @param content the content to use * @return the loaded samediff instance */ public abstract SameDiff getSameDiffFromBytes(byte[] content); @Override public Record[] transform(Record[] input) { Map mapIndexes = new HashMap<>(); SDVariable[] inputs = new SDVariable[input.length]; for(int i = 0; i < input.length; i++) { inputs[i] = sameDiff.getVariable(this.inputs.get(i)); NDArrayWritable ndArrayWritable = (NDArrayWritable) input[i].getRecord().get(0); mapIndexes.put(this.inputs.get(i),ndArrayWritable.get()); } Map<String, INDArray> stringINDArrayMap = sameDiff.execAll(mapIndexes); Record[] ret = new Record[stringINDArrayMap.size()]; int count = 0; for(String key : stringINDArrayMap.keySet()) { ret[count++] = new org.datavec.api.records.impl.Record(Arrays.asList( new NDArrayWritable(stringINDArrayMap.get(key))), null); } return ret; } @Override public void setInputNames(String... inputNames) { this.inputs = new ArrayList<>(Arrays.asList(inputNames)); } @Override public void setOutputNames(String... outputNames) { this.outputs = new ArrayList<>(Arrays.asList(outputNames)); } @Override public String[] inputNames() { return inputs.toArray(new String[inputs.size()]); } @Override public String[] outputNames() { return outputs.toArray(new String[outputs.size()]); } @Override public Map<String, SchemaType[]> inputTypes() { Map ret = new LinkedHashMap<>(); for(int i = 0; i < inputNames().length; i++) { ret.put(inputNames()[i],new SchemaType[]{SchemaType.NDArray}); } return ret; } @Override public Map<String, SchemaType[]> outputTypes() { Map ret = new LinkedHashMap<>(); for(int i = 0; i < outputNames().length; i++) { ret.put(outputNames()[i],new SchemaType[]{SchemaType.NDArray}); } return ret; } }
java
17
0.636364
103
32.819876
161
starcoderdata
using Controller; using System; using System.Collections.ObjectModel; using System.Linq; using System.Windows; using System.Windows.Controls; using ZdravoKorporacija.DTO; using System.Linq; using System.Collections.ObjectModel; using Controller; using System.Diagnostics; namespace ZdravoKorporacija.Stranice.UpravnikCRUD { /// /// Interaction logic for Renoviranje.xaml /// public partial class Renoviranje : Window { private ObservableCollection prostorije = new ObservableCollection private ProstorijaController prostorijeKontroler = new ProstorijaController(); RenoviranjeController renoviranjeKontroler = new RenoviranjeController(); public ObservableCollection izabraneProstorije; ComboBox satiCombobox; String spajanje; String razdvajanje; public Renoviranje(int index) { InitializeComponent(); izabraneProstorije = new ObservableCollection prostorije = prostorijeKontroler.PregledSvihProstorijaDTO(); cbProstorija.ItemsSource = prostorije; cbProstorija.SelectedIndex = index; satiCombobox = sati; kalendarInit(); } public void kalendarInit() { DateTime danas = DateTime.Today; for (DateTime tm = danas.AddHours(8); tm < danas.AddHours(22); tm = tm.AddMinutes(30)) { satiCombobox.Items.Add(tm.ToShortTimeString()); } } private void cbProstorija_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void potvrdi(object sender, RoutedEventArgs e) { ZahtevRenoviranjeDTO zahtevRenoviranje = new ZahtevRenoviranjeDTO(0, (ProstorijaDTO)cbProstorija.SelectedItem, (DateTime)timePicker.SelectedDate, (String)sati.SelectedItem, textBoxTrajanje.Text, spajanje, razdvajanje); zahtevRenoviranje.prostorije = izabraneProstorije.ToList renoviranjeKontroler.ZakaziRenoviranje(zahtevRenoviranje); } private void odustani(object sender, RoutedEventArgs e) { this.Close(); } private void date_changed(object sender, SelectionChangedEventArgs e) { } private void sati_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void button_Click_1(object sender, RoutedEventArgs e) { BiranjeProstorija biranjeProstorija = new BiranjeProstorija(izabraneProstorije); biranjeProstorija.Show(); } private void radioButton_Checked(object sender, RoutedEventArgs e) { spajanje = "Spajanje"; razdvajanje = ""; Debug.WriteLine(spajanje); Debug.WriteLine(razdvajanje); } private void radioButton1_Checked(object sender, RoutedEventArgs e) { spajanje = ""; razdvajanje = "Razdvajanje"; Debug.WriteLine(spajanje); Debug.WriteLine(razdvajanje); } } }
c#
16
0.649134
230
31
101
starcoderdata
using System.Collections.Generic; using System.IO; namespace Microsoft.Maui.Resizetizer { internal class AndroidAdaptiveIconGenerator { public AndroidAdaptiveIconGenerator(ResizeImageInfo info, string appIconName, string intermediateOutputPath, ILogger logger, bool useVectors) { Info = info; Logger = logger; UseVectors = useVectors; IntermediateOutputPath = intermediateOutputPath; AppIconName = appIconName; } public ResizeImageInfo Info { get; } public string IntermediateOutputPath { get; } public ILogger Logger { get; private set; } public bool UseVectors { get; } public string AppIconName { get; } const string AdaptiveIconDrawableXml = @"<?xml version=""1.0"" encoding=""utf-8""?> <adaptive-icon xmlns:android=""http://schemas.android.com/apk/res/android""> <background android:drawable=""@{backgroundType}/{name}_background""/> <foreground android:drawable=""@{foregroundType}/{name}_foreground""/> const string EmptyVectorDrawable = @"<vector xmlns:android=""http://schemas.android.com/apk/res/android"" xmlns:aapt=""http://schemas.android.com/aapt"" android:viewportWidth=""1024"" android:viewportHeight=""1024"" android:width=""1024dp"" android:height=""1024dp"" /> "; public IEnumerable Generate() { var results = new List var fullIntermediateOutputPath = new DirectoryInfo(IntermediateOutputPath); var backgroundFile = Info.Filename; var backgroundIsVector = UseVectors && Info.IsVector; var backgroundExt = backgroundIsVector ? ".xml" : ".png"; var backgroundDestFilename = AppIconName + "_background" + backgroundExt; var foregroundFile = Info.ForegroundFilename; var foregroundExists = File.Exists(foregroundFile); var foregroundIsVector = !foregroundExists || (UseVectors && Info.ForegroundIsVector); var foregroundExt = foregroundIsVector ? ".xml" : ".png"; var foregroundDestFilename = AppIconName + "_foreground" + foregroundExt; if (backgroundIsVector) { Logger.Log("Converting Background SVG to Android Drawable Vector: " + backgroundFile); var dir = Path.Combine(fullIntermediateOutputPath.FullName, "drawable-v24"); var destination = Path.Combine(dir, backgroundDestFilename); Directory.CreateDirectory(dir); Svg2VectorDrawable.Svg2Vector.Convert(backgroundFile, destination); results.Add(new ResizedImageInfo { Dpi = new DpiPath("drawable-v24", 1, "_background"), Filename = destination }); } else { Logger.Log("Converting Background SVG to PNG: " + backgroundFile); foreach (var dpi in DpiPath.Android.AppIconParts) { var dir = Path.Combine(fullIntermediateOutputPath.FullName, dpi.Path); var destination = Path.Combine(dir, backgroundDestFilename); Directory.CreateDirectory(dir); Logger.Log($"App Icon Background Part: " + destination); var tools = SkiaSharpTools.Create(Info.IsVector, Info.Filename, dpi.Size, null, Logger); tools.Resize(dpi, destination); results.Add(new ResizedImageInfo { Dpi = dpi, Filename = destination }); } } Logger.Log("Looking for Foreground File: " + foregroundFile); var foregroundDestinationDir = Path.Combine(fullIntermediateOutputPath.FullName, "drawable"); var foregroundDestination = Path.Combine(foregroundDestinationDir, foregroundDestFilename); Directory.CreateDirectory(foregroundDestinationDir); if (foregroundExists) { if (foregroundIsVector) { Logger.Log("Converting Foreground SVG to Android Drawable Vector: " + foregroundFile); Svg2VectorDrawable.Svg2Vector.Convert(foregroundFile, foregroundDestination); results.Add(new ResizedImageInfo { Dpi = new DpiPath("drawable", 1, "_foreground"), Filename = foregroundDestination }); } else { Logger.Log("Converting Foreground SVG to PNG: " + foregroundFile); foreach (var dpi in DpiPath.Android.AppIconParts) { var dir = Path.Combine(fullIntermediateOutputPath.FullName, dpi.Path); var destination = Path.Combine(dir, foregroundDestFilename); Directory.CreateDirectory(dir); Logger.Log($"App Icon Foreground Part: " + destination); var tools = SkiaSharpTools.Create(Info.ForegroundIsVector, Info.ForegroundFilename, dpi.Size, null, Logger); tools.Resize(dpi, destination); results.Add(new ResizedImageInfo { Dpi = dpi, Filename = destination }); } } } else { Logger.Log("Foreground was not found: " + foregroundFile); File.WriteAllText(foregroundDestination, EmptyVectorDrawable); } // process adaptive icon xml { var adaptiveIconXmlStr = AdaptiveIconDrawableXml .Replace("{name}", AppIconName) .Replace("{backgroundType}", backgroundIsVector ? "drawable" : "mipmap") .Replace("{foregroundType}", foregroundIsVector ? "drawable" : "mipmap"); var dir = Path.Combine(fullIntermediateOutputPath.FullName, "mipmap-anydpi-v26"); var adaptiveIconDestination = Path.Combine(dir, AppIconName + ".xml"); var adaptiveIconRoundDestination = Path.Combine(dir, AppIconName + "_round.xml"); Directory.CreateDirectory(dir); // Write out the adaptive icon xml drawables File.WriteAllText(adaptiveIconDestination, adaptiveIconXmlStr); File.WriteAllText(adaptiveIconRoundDestination, adaptiveIconXmlStr); results.Add(new ResizedImageInfo { Dpi = new DpiPath("mipmap-anydpi-v26", 1), Filename = adaptiveIconDestination }); results.Add(new ResizedImageInfo { Dpi = new DpiPath("mipmap-anydpi-v26", 1, "_round"), Filename = adaptiveIconRoundDestination }); } return results; } } }
c#
22
0.729352
143
36.927152
151
starcoderdata
package com.impassive.imp; import javax.annotation.Nullable; public interface Serialization { /** * 序列化数据。将数据装换成byte字节数组 * * null,则返回空的直接数组 * * @param obj 需要序列化的对象 * @return 序列化的结果 */ byte[] serialization(Object obj); /** * 反序列化。将给定的字节数组转换成对应的类型。 * * * * @param bytes 需要转换的直接数组 * @param tClass 目标类型 * @param 类型 * @return 反序列化结果 */ @Nullable T deserialization(byte[] bytes, Class tClass); }
java
8
0.620553
55
15.866667
30
starcoderdata
def create_forward(self): """Executes the createForward method Returns: :class:`MessageCreateForwardRequestBuilder<msgraph.request.message_create_forward.MessageCreateForwardRequestBuilder>`: A MessageCreateForwardRequestBuilder for the method """ return MessageCreateForwardRequestBuilder(self.append_to_request_url("createForward"), self._client)
python
9
0.721951
131
44.666667
9
inline
package com.github.copilot.lang.agent.vscodeRpc; import java.nio.charset.StandardCharsets; import com.github.copilot.lang.agent.rpc.JsonRpcMessageHandler; import com.github.copilot.lang.agent.rpc.JsonRpcMessageParser; import me.masecla.copilot.extra.Logger; public class VSCodeJsonRpcParser implements JsonRpcMessageParser { private static final Logger LOG = Logger.getInstance(VSCodeJsonRpcParser.class); private static final byte[] CONTENT_LENGTH = "Content-Length: ".getBytes(StandardCharsets.UTF_8); public static final byte[] SEPARATOR = "\r\n\r\n".getBytes(StandardCharsets.UTF_8); private final JsonRpcMessageHandler messageHandler; private int pendingContentLength = 0; private final ByteArray pendingContent = new ByteArray(); public String getPendingContent() { String string = this.pendingContent.toString(StandardCharsets.UTF_8); if (string == null) { throw new IllegalStateException("string cannot be null!"); } return string; } @Override public void append(String content) { if (content == null) { throw new IllegalStateException("content cannot be null!"); } this.pendingContent.add(content.getBytes(StandardCharsets.UTF_8)); if (this.pendingContent.indexOf(CONTENT_LENGTH) == 0) { this.handleContentLengthMessage(); } if (this.pendingContentLength > 0) { this.processPendingContent(); } } @Override public void close() { } private void handleContentLengthMessage() { assert (this.pendingContentLength == 0); int lineEnd = this.pendingContent.indexOf(SEPARATOR); if (lineEnd > 0) { String line = new String(this.pendingContent.getBytes(CONTENT_LENGTH.length, lineEnd), StandardCharsets.UTF_8); this.pendingContent.deleteFirst(lineEnd + SEPARATOR.length); int length = Integer.parseInt(line, 0, line.length(), 10); LOG.debug("Found content-length: " + line); this.pendingContentLength += length; } } private void processPendingContent() { if (this.pendingContent.size() < this.pendingContentLength) { return; } String message = this.pendingContent.toString(0, this.pendingContentLength, StandardCharsets.UTF_8); this.pendingContent.deleteFirst(this.pendingContentLength); this.pendingContentLength = 0; this.messageHandler.handleJsonMessage(message); } public VSCodeJsonRpcParser(JsonRpcMessageHandler messageHandler) { this.messageHandler = messageHandler; } }
java
12
0.766574
132
33.986111
72
starcoderdata
#include<bits/stdc++.h> #define all(vec) vec.begin(),vec.end() using namespace std; typedef long long ll; typedef pair<int,int> P; const double EPS=1e-10; const ll INF=1000000000; const ll MAX=100010; int main(){ int a0,l; while(cin>>a0>>l,a0+l){ int a[100010]; a[0]=a0; for(int i=0;i<50;i++){ int d[7]={}; int t=a[i]; for(int j=0;j<l;j++){ d[j]=t%10; t/=10; } sort(d,d+l); int ma=0;int mi=0; for(int j=0;j<l;j++){ ma*=10; mi*=10; ma+=d[l-1-j]; mi+=d[j]; } a[i+1]=ma-mi; bool f=false; for(int j=0;j<=i;j++){ if(a[j]==a[i+1]){ f=true; cout<<j<<" "<<a[j]<<" "<<i+1-j<<endl; break; } } if(f){ break; } } } }
c++
18
0.338883
57
22.744186
43
codenet
@Test @Order(1) void testCallerGroupPermission() { init_for_caller(); set_permission_for_caller(); register_script_for_caller(); run_script_with_group_permission();//called by caller. remove_permission_for_caller(); run_script_without_group_permission();//called by caller. uninit_for_caller(); }
java
6
0.622222
65
35.1
10
inline
<?php /* @var $this yii\web\View */ $this->title = 'Rafiki4U'; use yii\bootstrap\Html; ?> <div class="site-index" align="center"> <div class="row"> <div class="col-lg-3 col-md-3 col-sm-6" style="border-bottom: orange 2px solid;margin-left: 100px"> <div class="row"> <div class="col-md-12 text-center" style="background: orange;margin-left: 0px;color: white"> Members <div class="row"> <div class="col-md-12 text-center"><h3 style="color: orange"><i class="fa fa-users"> 455 <div class="col-lg-3 col-md-3 col-sm-6" style="border-bottom: cornflowerblue 2px solid;margin-left: 5px"> <div class="row"> <div class="col-md-12 text-center" style="background: cornflowerblue;margin-left: 0px;color: white"> Donars <div class="row"> <div class="col-md-12 text-center"><h3 style="color: cornflowerblue"><i class="fa fa-users"> 455 <div class="col-lg-3 col-md-3 col-sm-6" style="border-bottom: seagreen 2px solid;margin-left: 5px"> <div class="row"> <div class="col-md-12 text-center" style="background: seagreen;margin-left: 0px;color: white"> Volunteers <div class="row"> <div class="col-md-12 text-center"><h3 style="color: seagreen"><i class="fa fa-unlock"> 455 <div class="row"> <div class="col-lg-3 col-md-3 col-sm-6" style="margin-left: 100px"> <div class="row"> <div class="col-md-12" style="background: white;color: skyblue;border-left: solid 2px skyblue"> <?= Html::a(Yii::t('app', '<i class="fa fa-plus"> New Member'), ['member/create']) ?>
php
9
0.550073
217
42.0625
48
starcoderdata
package ss import ( "github.com/kbinani/screenshot" "testing" ) // 0.04s/op on my system func BenchmarkScreenshot(b *testing.B) { db:=screenshot.GetDisplayBounds(0) for i := 0; i < b.N; i++ { ScreenshotRect(db) } }
go
8
0.672646
40
15
14
starcoderdata
#pragma once #ifndef __cplusplus #error "veda_device_omp.h only supports C++!" #endif #include #include #include #include #include //------------------------------------------------------------------------------ template<typename T> inline void veda_omp_schedule(T& min, T& max, const T cnt, const T vl = 1) { T nthreads = omp_get_num_threads(); T tx = omp_get_thread_num(); T smin = 0; T smax = 0; if(vl == 1) { /** This tries to distribute the work as equal as possible to the cores */ T batch = cnt / nthreads; T remain = cnt % nthreads; min = batch * tx + (tx < remain ? tx : remain); max = min + batch + (tx < remain ? 1 : 0); } else { /** This tries to assign multiples of vl to the threads, even if some of * them then don't have anything to do */ T tcnt = (cnt + nthreads - 1) / nthreads; tcnt = ((tcnt + vl - 1) / vl) * vl; min = tx * tcnt; max = std::min((tx+1) * tcnt, cnt); } } //------------------------------------------------------------------------------ template<typename T, typename F> inline void veda_omp_launch(const T cnt, F func) { #pragma omp parallel { T min, max; veda_omp_schedule(min, max, cnt); if(min < max) func(min, max); } } //------------------------------------------------------------------------------ template<typename T, typename F> inline void veda_omp(const T cnt, F func) { static_assert(std::is_same<T, int32_t>::value || std::is_same<T, int64_t>::value || std::is_same<T, size_t>::value); static_assert(std::is_convertible<F, std::function<void(const T, const T)>>::value); T nthreads = omp_get_max_threads(); if(nthreads == 1 || cnt == 1) { func(T(0), cnt); } else { veda_omp_launch(cnt, func); } } //------------------------------------------------------------------------------ template<typename T, typename F> inline void veda_omp_simd(const T cnt, F func, T vl = 0) { T nthreads = omp_get_max_threads(); if(vl == 0) { if(sizeof(T) == 8) vl = 256; else vl = 512; } if(nthreads > T(1) && cnt > vl) { #pragma omp parallel { T min, max; veda_omp_schedule(min, max, cnt, vl); if(min < max) func(min, max); } } else { func(T(0), cnt); } } //------------------------------------------------------------------------------
c
13
0.50172
117
26.046512
86
starcoderdata
var a04013 = [ [ "base", "a04013.html#a7660b1467ae695875d3d343084b26096", null ], [ "FunctionSignature", "a04013.html#a61a1e321168c8bb8fb52decb2c14d598", null ], [ "_TessFunctionResultCallback_6_5", "a04013.html#a1722bc70e26d796402e45d2ddef5b365", null ], [ "Run", "a04013.html#ae81e6e9f82af9377fbeef003d1e33c6a", null ] ];
javascript
3
0.732194
97
43
8
starcoderdata
private static List<Vm> createVM(int userId, int vms, int idShift) { //Creates a container to store VMs. This list is passed to the broker later LinkedList<Vm> vmList = new LinkedList<Vm>(); //VM Parameters long size = 10000; //image size (MB) int ram = 512; //vm memory (MB) int mips = 250; long bw = 1000; int pesNumber = 1; //number of cpus String vmm = "Xen"; //VMM name //create VMs Vm[] vm = new Vm[vms]; for(int i=0;i < vms;i++) { vm[i] = new Vm(idShift + i, userId, mips, pesNumber, ram, bw, size, vmm, new CloudletSchedulerTimeShared()); vmList.add(vm[i]); } return vmList; }
java
11
0.634769
111
25.166667
24
inline
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. """ An implementation of Orthogonal Random Forests [orf]_ and special case python classes. References ---------- .. [orf] and Orthogonal Random Forest for Causal Inference. *Proceedings of the 36th International Conference on Machine Learning*, 2019. URL http://proceedings.mlr.press/v97/oprescu19a.html. """ from ._ortho_forest import DMLOrthoForest, DROrthoForest __all__ = ["DMLOrthoForest", "DROrthoForest"]
python
5
0.691638
81
29.888889
18
starcoderdata
private void Gravity() { if (Sprite.Velocity.Y < 4) { Sprite.Velocity.Y += gravity; // Make player stay still in air shorter if (Sprite.Velocity.Y < 1 && Sprite.Velocity.Y > 0) { Sprite.Velocity.Y += 0.5f; } } }
c#
12
0.387363
67
27.076923
13
inline
# %% import numpy as np import pandas as pd CONTENT_VECS = "../data/intermediary/bert_vecs.npy" TRAIN_IDS = "../data/intermediary/data_split/train_id_str.txt" VAL_IDS = "../data/intermediary/data_split/val_id_str.txt" TEST_IDS = "../data/intermediary/data_split/test_id_str.txt" DATA = "../data/original/Org-Retweeted-Vectors_preproc.csv" OUT_TRAIN = "../data/prepared/content_train_df.pkl" OUT_VAL = "../data/prepared/content_val_df.pkl" OUT_TEST = "../data/prepared/content_test_df.pkl" # %% with open(CONTENT_VECS, "rb") as f: vecs = np.load(f) data = pd.read_csv(DATA, parse_dates=["created_at"]).iloc[:, 1:] data.info() # %% with open(TRAIN_IDS) as f: train_ids = f.read().splitlines() print("Number of train ids:", len(train_ids)) with open(VAL_IDS) as f: val_ids = f.read().splitlines() print("Number of validation ids:", len(val_ids)) with open(TEST_IDS) as f: test_ids = f.read().splitlines() print("Number of test ids:", len(test_ids)) # %% data = data.astype({"id_str": str}) data_train = data[data.id_str.isin(train_ids)] data_val = data[data.id_str.isin(val_ids)] data_test = data[data.id_str.isin(test_ids)] train_vecs = vecs[data_train.index] val_vecs = vecs[data_val.index]
python
10
0.677686
64
31.702703
37
starcoderdata
/* $Id: stage_unit_formulas.cpp 48153 2011-01-01 15:57:50Z mordante $ */ /* Copyright (C) 2009 - 2011 by Part of the Battle for Wesnoth Project http://www.wesnoth.org/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the COPYING file for more details. */ /** * @file * Defines formula ai unit formulas stage * */ #include "stage_unit_formulas.hpp" #include "ai.hpp" #include "../../formula.hpp" #include "../../formula_function.hpp" #include "../../log.hpp" #include "../../resources.hpp" #include static lg::log_domain log_formula_ai("ai/stage/unit_formulas"); #define LOG_AI LOG_STREAM(info, log_formula_ai) #define WRN_AI LOG_STREAM(warn, log_formula_ai) #define ERR_AI LOG_STREAM(err, log_formula_ai) namespace ai { stage_unit_formulas::stage_unit_formulas(ai_context &context, const config &cfg, formula_ai &fai) : stage(context,cfg), cfg_(cfg), fai_(fai) { } stage_unit_formulas::~stage_unit_formulas() { } bool stage_unit_formulas::do_play_stage() { //execute units formulas first game_logic::unit_formula_set units_with_formulas; unit_map &units_ = *resources::units; for(unit_map::unit_iterator i = units_.begin() ; i != units_.end() ; ++i) { if (i->side() == get_side()) { if (i->has_formula() || i->has_loop_formula()) { int priority = 0; if (i->has_priority_formula()) { try { game_logic::const_formula_ptr priority_formula(fai_.create_optional_formula(i->get_priority_formula())); if (priority_formula) { game_logic::map_formula_callable callable(&fai_); callable.add_ref(); callable.add("me", variant(new unit_callable(*i))); priority = (game_logic::formula::evaluate(priority_formula, callable)).as_int(); } else { WRN_AI << "priority formula skipped, maybe it's empty or incorrect"<< std::endl; } } catch(game_logic::formula_error& e) { if(e.filename == "formula") e.line = 0; fai_.handle_exception( e, "Unit priority formula error for unit: '" + i->type_id() + "' standing at (" + str_cast(i->get_location().x + 1) + "," + str_cast(i->get_location().y + 1) + ")"); priority = 0; } catch(type_error& e) { priority = 0; ERR_AI << "formula type error while evaluating unit priority formula " << e.message << "\n"; } } units_with_formulas.insert( game_logic::unit_formula_pair( i, priority ) ); } } } for(game_logic::unit_formula_set::iterator pair_it = units_with_formulas.begin() ; pair_it != units_with_formulas.end() ; ++pair_it) { unit_map::iterator i = pair_it->first; if( i.valid() ) { if (i->has_formula()) { try { game_logic::const_formula_ptr formula(fai_.create_optional_formula(i->get_formula())); if (formula) { game_logic::map_formula_callable callable(&fai_); callable.add_ref(); callable.add("me", variant(new unit_callable(*i))); fai_.make_action(formula, callable); } else { WRN_AI << "unit formula skipped, maybe it's empty or incorrect" << std::endl; } } catch(game_logic::formula_error& e) { if(e.filename == "formula") { e.line = 0; } fai_.handle_exception( e, "Unit formula error for unit: '" + i->type_id() + "' standing at (" + str_cast(i->get_location().x + 1) + "," + str_cast(i->get_location().y + 1) + ")"); } } } if( i.valid() ) { if (i->has_loop_formula()) { try { game_logic::const_formula_ptr loop_formula(fai_.create_optional_formula(i->get_loop_formula())); if (loop_formula) { game_logic::map_formula_callable callable(&fai_); callable.add_ref(); callable.add("me", variant(new unit_callable(*i))); while ( !fai_.make_action(loop_formula, callable).is_empty() && i.valid() ) { } } else { WRN_AI << "Loop formula skipped, maybe it's empty or incorrect" << std::endl; } } catch(game_logic::formula_error& e) { if (e.filename == "formula") { e.line = 0; } fai_.handle_exception( e, "Unit loop formula error for unit: '" + i->type_id() + "' standing at (" + str_cast(i->get_location().x + 1) + "," + str_cast(i->get_location().y + 1) + ")"); } } } } return false; } void stage_unit_formulas::on_create() { //we have no state on our own } config stage_unit_formulas::to_config() const { config cfg = stage::to_config(); //we have no state on our own return cfg; } } // end of namespace ai
c++
29
0.597081
194
29.658228
158
starcoderdata
#Author- #Description- import adsk.core, adsk.fusion, adsk.cam, traceback from collections import namedtuple Rec = namedtuple('Rec', ['ln_nbr', 'label', 'x', 'y']) fin = '/Users/gskluzacek/fine_grained_striped_very.txt' class PointRec: def __init__(self, line): row = line.strip().split('\t') self.ln_nbr = int(row[0]) self.label = row[1] self.x = float(row[2]) self.y = float(row[3]) def run(context): ui = None try: app = adsk.core.Application.get() ui = app.userInterface # get the design object for the CURRENT document design = app.activeProduct # Get the root component of the active design. root_comp = design.rootComponent # Create a new sketch on the xy plane. sketches = root_comp.sketches xy_plane = root_comp.xYConstructionPlane sketch1 = sketches.add(xy_plane) sketch1.name = f'just some points' circles = sketch1.sketchCurves.sketchCircles circles.addByCenterRadius(adsk.core.Point3D.create(0, 0, 0), 50) with open(fin) as fi: for line in fi: point = PointRec(line) sketch1.sketchPoints.add(adsk.core.Point3D.create(point.x, point.y, 0)) ui.messageBox('Where is the shit') except: if ui: ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
python
16
0.609141
87
26.148148
54
starcoderdata
<?php namespace Rindow\Web\Form; use Rindow\Stdlib\Entity\Hydrator; use Rindow\Stdlib\Entity\EntityHydrator; use Rindow\Stdlib\Entity\PropertyHydrator; use Rindow\Stdlib\Entity\SetterHydrator; use Rindow\Stdlib\Entity\Entity; use Rindow\Stdlib\Entity\PropertyAccessPolicy; use Rindow\Stdlib\ListCollection; use Rindow\Web\Form\Annotation\Select; use Rindow\Web\Form\Annotation\Input; use Rindow\Web\Form\Validator\CsrfValidator; use Traversable; use IteratorAggregate; use Interop\Lenient\Web\Form\FormContext as FormContextInterface; class FormContext implements FormContextInterface { protected $form; protected $bindingEntity; protected $validators = array(); protected $hydrator; protected $data; protected $violation; protected $validated; protected $formatted; public function __construct( ElementCollection $form, $bindingEntity=null, $hydrator=null) { $this->form = $form; $this->bindingEntity = $bindingEntity; $this->hydrator = $hydrator; } public function addValidator($validator) { $this->validators[] = $validator; } public function getForm() { if(!$this->formatted) { $this->formatElements(); $this->formatted = true; } return $this->form; } public function getEntity() { return $this->bindingEntity; } public function bind($bindingEntity) { $this->bindingEntity = $bindingEntity; return $this; } public function setHydrator($hydrator) { $this->hydrator = $hydrator; return $this; } public function getHydrator() { if($this->hydrator) return $this->hydrator; if(is_object($this->bindingEntity)) { if($this->bindingEntity instanceof Entity) $this->hydrator = new EntityHydrator(); else if($this->bindingEntity instanceof PropertyAccessPolicy) $this->hydrator = new PropertyHydrator(); else $this->hydrator = new SetterHydrator(); return $this->hydrator; } throw new Exception\DomainException('Binding Entity or Hydrator type is not spacified.'); } public function setRequestToData(array $data) { $this->data = array(); foreach($this->form as $key => $element) { if(array_key_exists($key, $data)) { $this->data[$element->fieldName] = $data[$key]; } } return $this; } protected function setDataOptions( array $data, $object, $key, Element $element, Hydrator $hydrator=null) { if(is_array($data[$key]) || $data[$key] instanceof Traversable || $data[$key] instanceof IteratorAggregate) { foreach ($data[$key] as $value) { if($hydrator) $this->data[$key][] = $element->value[] = $hydrator->get($value,$element->mappedValue); else $this->data[$key][] = $element->value[] = $value[$element->mappedValue]; } } else { if($hydrator) $this->data[$key] = $element->value = $hydrator->get($data[$key],$element->mappedValue); else $this->data[$key] = $element->value = $data[$key][$element->mappedValue]; } if($element->mappedOptions) { if($hydrator) $mappedOptions = $hydrator->get($object,$element->mappedOptions); else $mappedOptions = $data[$element->mappedOptions]; if($mappedOptions) { foreach ($mappedOptions as $mappedOption) { $option = new Input(); if($hydrator) { $option->value = $hydrator->get($mappedOption,$element->mappedValue); $option->label = $hydrator->get($mappedOption,$element->mappedOptionLabel); } else { $option->value = $mappedOption[$element->mappedValue]; $option->value = $mappedOption[$element->mappedOptionLabel]; } $element[$option->value] = $option; } } } } public function formatElements() { $hydrator = $this->getHydrator(); foreach($this->form as $name => $element) { if($name == CsrfValidator::NAME_CSRFTOKEN) continue; if($element->bindTo) $sourceField = $element->bindTo; else $sourceField = $element->fieldName; if($this->data && array_key_exists($element->fieldName,$this->data)) { $element->value = $this->data[$element->fieldName]; } else { $element->value = $hydrator->get($this->bindingEntity,$sourceField); } if($element instanceof Select && $element->mappedValue) { $this->setupElementOptions($element,$hydrator); } } return $this; } protected function setupElementOptions( Element $element, Hydrator $hydrator) { if(empty($this->data) || !array_key_exists($element->fieldName,$this->data)) { $valueEntity = $element->value; if(is_array($valueEntity) || $valueEntity instanceof Traversable || $valueEntity instanceof IteratorAggregate) { $valueArray = $valueEntity; $element->value = array(); foreach($valueArray as $valueEntity) { if(is_object($valueEntity)) $element->value[] = $hydrator->get($valueEntity,$element->mappedValue); else $element->value[] = $valueEntity; } } else if(is_object($valueEntity)) { $element->value = $hydrator->get($valueEntity,$element->mappedValue); } else { $element->value = $valueEntity; } } if($element->mappedOptions) { $mappedOptions = $hydrator->get($this->bindingEntity,$element->mappedOptions); if($mappedOptions) { if($element->mappedLabel) $labelField = $element->mappedLabel; else $labelField = 'name'; foreach ($mappedOptions as $mappedOption) { $option = new Input(); $option->value = $hydrator->get($mappedOption,$element->mappedValue); $option->label = $hydrator->get($mappedOption,$element->mappedLabel); $element[$option->value] = $option; } } } } public function setAttributes($attributes) { $this->form->attributes = $attributes; return $this; } public function setAttribute($name,$value) { $this->form->attributes[$name] = $value; return $this; } public function setErrors($violation) { foreach($this->form as $key => $element) { if(isset($violation[$key])) $element->errors = $violation[$key];//array($violation[$key][0]->getMessage()); } return $this; } public function isValid() { if($this->validated!==null) return $this->validated; if($this->data===null) { throw new Exception\DomainException('there is no data to validate.'); } $errors = array(); $isValid = true; foreach ($this->validators as $validator) { if(!$validator->isValid( $this->bindingEntity, $this->data, $this->getHydrator(), $errors)) { $isValid = false; } } $this->setErrors($errors); $this->violation = $errors; $this->validated = $isValid; return $this->validated; } public function hasErrors() { return !$this->isValid(); } public function getViolation() { return $this->violation; } }
php
20
0.528502
107
31.592308
260
starcoderdata
#pragma once #include "Agora/IAgoraMediaEngine.h" #include #include "CicleBuffer.hpp" class CExtendAudioFrameObserver : public agora::media::IAudioFrameObserver { public: CicleBuffer* pCircleBuffer; CExtendAudioFrameObserver(); ~CExtendAudioFrameObserver(); LPBYTE pPlayerData; int nPlayerDataLen; bool bDebug; virtual bool onRecordAudioFrame(AudioFrame& audioFrame); virtual bool onPlaybackAudioFrame(AudioFrame& audioFrame); virtual bool onMixedAudioFrame(AudioFrame& audioFrame); virtual bool onPlaybackAudioFrameBeforeMixing(unsigned int uid, AudioFrame& audioFrame); };
c++
8
0.807249
89
27.904762
21
starcoderdata
public async Task TestGetWithFiltersAsync() { // Create items await TestCreateBeaconsAsync(); // Filter by id var page = await _persistence.GetPageByFilterAsync( null, FilterParams.FromTuples( "id", "1" ), new PagingParams() ); Assert.Single(page.Data); // Filter by udi page = await _persistence.GetPageByFilterAsync( null, FilterParams.FromTuples( "udi", "00002" ), new PagingParams() ); Assert.Single(page.Data); // Filter by udis page = await _persistence.GetPageByFilterAsync( null, FilterParams.FromTuples( "udis", "00001,00003" ), new PagingParams() ); Assert.Equal(2, page.Data.Count); // Filter by site_id page = await _persistence.GetPageByFilterAsync( null, FilterParams.FromTuples( "site_id", "1" ), new PagingParams() ); Assert.Equal(2, page.Data.Count); }
c#
16
0.51578
57
21.653061
49
inline
package org.sqlcomposer; public class SqlExpression { protected StringBuilder queryBuilder; public SqlExpression(){ queryBuilder = new StringBuilder(); } public SqlExpression(StringBuilder sb){ queryBuilder = sb; } public String toString(){ String s = queryBuilder.append(";").toString(); queryBuilder.deleteCharAt(queryBuilder.length() - 1); return s; } public SqlExpression where(String condition){ queryBuilder.append(" WHERE ") .append(condition); return this; } public GroupedExpression group(String string) { queryBuilder.append(" GROUP BY ") .append(string); return new GroupedExpression(queryBuilder); } }
java
11
0.620466
61
23.935484
31
starcoderdata
<?php class VerbiController extends BaseController { /** * [$verbo description] * @var [type] */ protected $verbo; /** * [$messages description] * @var [type] */ public static $messages = [ 'required' => 'Il campo :attribute è obbligatorio', 'unique' => 'Questo verbo è già presente', ]; /** * [__construct description] * @param Espressione $verbo [description] */ public function __construct(Verbo $verbo) { $this->beforeFilter('auth.basic'); $this->verbo = $verbo; } /** * Display a listing of the resource. * GET /verbi * * @return Response */ public function index() { $verbi = $this->verbo->orderBy('infinito', 'asc')->paginate(20); return View::make('verbi.index', compact('verbi')); } /** * Show the form for creating a new resource. * GET /verbi/create * * @return Response */ public function create() { return View::make('verbi.edit'); } /** * Store a newly created resource in storage. * POST /verbi * * @return Response */ public function store() { $input = Input::all(); $validation = Validator::make($input, Verbo::rules(), self::$messages); if ($validation->passes()) { $verbo_new = [ 'infinito' => $input['infinito'], 'gerundio' => $input['gerundio'], 'presente1s' => $input['presente1s'], 'presente3s' => $input['presente3s'], 'presente1p' => $input['presente1p'], 'presente3p' => $input['presente3p'], 'passato1s' => $input['passato1s'], 'passato3s' => $input['passato3s'], 'passato1p' => $input['passato1p'], 'passato3p' => $input['passato3p'], 'congiuntivo1s' => $input['congiuntivo1s'], 'congiuntivo3s' => $input['congiuntivo3s'], 'congiuntivo1p' => $input['congiuntivo1p'], 'congiuntivo3p' => $input['congiuntivo3p'], 'riflessivo1s' => $input['riflessivo1s'], 'riflessivo3s' => $input['riflessivo3s'], 'riflessivo1p' => $input['riflessivo1p'], 'riflessivo3p' => $input['riflessivo3p'], 'partpresente' => $input['partpresente'], 'partpassato' => $input['partpassato'] ]; $verbo = $this->verbo->create($verbo_new); if(isset($input['articoli'])) { Event::fire('articoli.save', [$verbo, $input['articoli']]); } if(isset($input['preposizioni'])) { Event::fire('preposizioni.save', [$verbo, $input['preposizioni']]); } if(isset($input['tags'])) { Event::fire('tags.save', [$verbo, $input['tags']]); } return Redirect::route('espressioni.index'); } return Redirect::route('verbi.create') ->withInput() ->withErrors($validation) ->with('message', 'Si è verificato un errore'); } /** * Show the form for editing the specified resource. * GET /verbi/{id}/edit * * @param int $id * @return Response */ public function edit($id) { $verbo = $this->verbo ->with(['articoli', 'preposizioni', 'tags']) ->whereId($id) ->first(); if (is_null($verbo)) { return Redirect::route('verbi.index'); } return View::make('verbi.edit', compact('verbo')); } /** * Update the specified resource in storage. * PUT /verbi/{id} * * @param int $id * @return Response */ public function update($id) { $input = array_except(Input::all(), '_method'); $validation = Validator::make($input, Verbo::rules($id), self::$messages); if ($validation->passes()) { $verbo = $this->verbo->find($id); if(isset($input['articoli'])) { Event::fire('articoli.save', [$verbo, $input['articoli']]); $input = array_except($input, 'articoli'); } if(isset($input['preposizioni'])) { Event::fire('preposizioni.save', [$verbo, $input['preposizioni']]); $input = array_except($input, 'preposizioni'); } if(isset($input['tags'])) { Event::fire('tags.save', [$verbo, $input['tags']]); $input = array_except($input, 'tags'); } $verbo->update($input); return Redirect::route('verbi.index'); } return Redirect::route('verbi.edit', $id) ->withInput() ->withErrors($validation) ->with('message', 'Si è verificato un errore'); } /** * Remove the specified resource from storage. * DELETE /verbi/{id} * * @param int $id * @return Response */ public function destroy($id) { $this->verbo->find($id)->delete(); return Redirect::route('verbi.index'); } }
php
17
0.595715
76
21.040609
197
starcoderdata
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by // #import "NSObject.h" #import "RBSProcessMonitorConfiguring.h" @class NSMutableDictionary, NSSet, RBSProcessMonitorConfiguration, RBSProcessPredicate; @interface RBSProcessMonitor : NSObject { struct os_unfair_lock_s _lock; id _service; BOOL _valid; BOOL _configuring; RBSProcessMonitorConfiguration *_configuration; NSMutableDictionary *_stateByIdentity; } + (id)monitorWithConfiguration:(CDUnknownBlockType)arg1; + (id)monitorWithPredicate:(id)arg1 updateHandler:(CDUnknownBlockType)arg2; + (id)monitor; - (void).cxx_destruct; - (void)_handleProcessStateChange:(id)arg1; - (void)_reconnect; - (void)setUpdateHandler:(CDUnknownBlockType)arg1; - (void)setServiceClass:(unsigned int)arg1; - (void)setStateDescriptor:(id)arg1; - (void)setPredicates:(id)arg1; @property(readonly, nonatomic) unsigned int serviceClass; @property(readonly, nonatomic) RBSProcessMonitorConfiguration *configuration; // @synthesize configuration=_configuration; - (void)invalidate; - (id)description; - (void)updateConfiguration:(CDUnknownBlockType)arg1; @property(readonly, copy, nonatomic) NSSet *states; // @dynamic states; - (id)stateForIdentity:(id)arg1; - (id)predicates; - (BOOL)isValid; - (void)dealloc; - (id)_initWithService:(id)arg1; - (id)init; // Remaining properties @property(readonly, copy, nonatomic) RBSProcessPredicate *predicate; // @dynamic predicate; @end
c
6
0.757306
122
30.48
50
starcoderdata
package de.tum.ei.lkn.eces.routing.algorithms.agnostic.gta; import de.tum.ei.lkn.eces.core.Controller; import de.tum.ei.lkn.eces.graph.Edge; /** * Edge of a new transformed graph. * * @author * @author */ public class TransformedEdge extends Edge { /** * Corresponding original edge. */ private Edge originalEdge; public TransformedEdge(Controller controller, TransformedNode source, TransformedNode destination, Edge originalEdge) { super(source, destination); source.addOutgoingConnection(this); destination.addIncomingConnection(this); this.originalEdge = originalEdge; this.setEntity(controller.createEntity()); } public TransformedEdge(Controller controller,TransformedNode source, TransformedNode destination) { this(controller, source, destination,null); } public Edge getOriginalEdge() { return originalEdge; } }
java
10
0.760992
120
24.342857
35
starcoderdata
<?php declare(strict_types=1); return [ 'APP_ENV' => $_ENV['EVE_SRP_ENV'], 'DB_URL' => $_ENV['EVE_SRP_DB_URL'], // Customizing 'APP_TITLE' => $_ENV['EVE_SRP_APP_TITLE'], 'APP_FAVICON' => $_ENV['EVE_SRP_APP_FAVICON'], 'APP_LOGO' => $_ENV['EVE_SRP_APP_LOGO'], 'APP_LOGO_ALT' => $_ENV['EVE_SRP_APP_LOGO_ALT'], 'LOGIN_HINT' => $_ENV['EVE_SRP_LOGIN_HINT'], 'FOOTER_TEXT' => $_ENV['EVE_SRP_FOOTER_TEXT'], // Admin role, group and character providers 'ROLE_GLOBAL_ADMIN' => $_ENV['EVE_SRP_ROLE_GLOBAL_ADMIN'], 'GROUP_PROVIDER' => $_ENV['EVE_SRP_GROUP_PROVIDER'], 'CHARACTER_PROVIDER' => $_ENV['EVE_SRP_CHARACTER_PROVIDER'], // SSO configuration 'SSO_CLIENT_ID' => $_ENV['EVE_SRP_SSO_CLIENT_ID'], 'SSO_CLIENT_SECRET' => $_ENV['EVE_SRP_SSO_CLIENT_SECRET'], 'SSO_REDIRECT_URI' => $_ENV['EVE_SRP_SSO_REDIRECT_URI'], 'SSO_URL_AUTHORIZE' => 'https://login.eveonline.com/v2/oauth/authorize', 'SSO_URL_ACCESS_TOKEN' => 'https://login.eveonline.com/v2/oauth/token', 'SSO_URL_JWT_KEY_SET' => 'https://login.eveonline.com/oauth/jwks', // Neucore 'NEUCORE_DOMAIN' => $_ENV['EVE_SRP_NEUCORE_DOMAIN'], 'NEUCORE_APP_ID' => $_ENV['EVE_SRP_NEUCORE_APP_ID'], 'NEUCORE_APP_TOKEN' => $_ENV['EVE_SRP_NEUCORE_APP_TOKEN'], // other stuff 'HTTP_USER_AGENT' => $_ENV['EVE_SRP_HTTP_USER_AGENT'], 'ESI_BASE_URL' => 'https://esi.evetech.net/', 'ZKILLBOARD_BASE_URL' => rtrim($_ENV['EVE_SRP_ZKILLBOARD_URL'], '/') . '/', ];
php
10
0.56438
79
40.55
40
starcoderdata
using GVFS.Common; using GVFS.UnitTests.Mock.Common; using NUnit.Framework; namespace GVFS.UnitTests { [SetUpFixture] public class Setup { [OneTimeSetUp] public void SetUp() { GVFSPlatform.Register(new MockPlatform()); } } }
c#
13
0.574257
54
16.9375
16
starcoderdata
func NewRouter(config *config.BrokerConfig) *mux.Router { router := mux.NewRouter().StrictSlash(true) for _, route := range rs { router. Methods(route.method). Path(route.pattern). Name(route.name). Handler(panicHandler(route.handler)) } // static server path router.PathPrefix("/static/"). Handler(http.StripPrefix("/static/", http.FileServer(rice.MustFindBox("./../../web/build").HTTPBox()))) return router }
go
15
0.689655
69
28.066667
15
inline
using AutoMapper; using log4net; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; using Tourism.Eums; using Tourism.IServer; using Tourism.Model; using Tourism.QueryModel; using Tourism.Repository; using Tourism.Util; namespace Tourism.Server { public class CustomerServer : ICustomerServer { private readonly ILog _log; private readonly IMySqlRespostitoryByDapper _mysqlRespository; public CustomerServer() { _log = LogManager.GetLogger(typeof(CustomerServer)); _mysqlRespository = new MySqlRespostitoryByDapper(DbNameEnum.CustomerService.ToString()); } /// /// 添加一条用户信息 /// /// <param name="info">要添加的用户数据 /// public async Task AddCustomerInfoAsync(User info) { try { return await _mysqlRespository.AddAsync(info); } catch (Exception ex) { _log.Error("AddCustomerInfoAsync method error:" + ex); return -1; } } /// /// 批量添加用户信息 /// /// <param name="customers">要添加的用户列表 /// public async Task BatchAddCustomerInfoAsync(List customers) { try { string sql = @"INSERT INTO `User` (`cId`,`cName`, `cSex`, `cAge`, `cAddress`, `cPhone`, `cIdNum`, `cIdentity`, `cNickName`, `cEmail`, `cPasswd`, `cPic`) VALUES(@CId,@cName,@cSex,@cAge,@cAddress,@cPhone,@cIdNum,@cIdentity,@cNickName,@cEmail,@cPasswd,@cPic)"; return await _mysqlRespository.BatchAddAsync(sql, customers); } catch (Exception ex) { _log.Error("BatchAddCustomerInfoAsync method error:" + ex); return -1; } } /// /// 根据ID删除用户信息 /// /// <param name="Id">用户ID /// public async Task DelCustomerInfoByIdAsync(string Id) { try { if (string.IsNullOrWhiteSpace(Id)) { _log.Error("DelCustomerInfoByQueryAsync's error:id is not null"); throw new Exception("DelCustomerInfoByQueryAsync's error:id is not null"); } string sql = "DELETE FROM `User` WHERE cId=@id"; return await _mysqlRespository.DelAsync(sql, Id); } catch (Exception ex) { _log.Error("DelCustomerInfoByQueryAsync method error:" + ex); return -1; } } /// /// 根据参数获取用户信息(可分页) /// /// <param name="query"> /// public async Task GetCustomerInfoByQueryAsync(UserQuery query) { try { if (query == null) { _log.Error("GetCustomerInfoByQueryAsync's error:selQuery is not null"); throw new Exception("GetCustomerInfoByQueryAsync's error:selQuery is not null"); } string sql = "SELECT * FROM `User` WHERE 1=1 "; if (query.CId != null) { sql += " AND cId=@cId"; } if (query.CIdentity != null) { sql += " AND cIdentity=@CIdentity"; } if (!string.IsNullOrWhiteSpace(query.CName)) { sql += " AND cName=@CName"; } if (!string.IsNullOrWhiteSpace(query.CEmail)) { sql += " AND cEmail=@CEmail"; } if (!string.IsNullOrWhiteSpace(query.CPhone)) { sql += " AND cPhone=@CPhone"; } if (query.CIdentity != null) { sql += " AND cIdNum=@CIdentity"; } if (!string.IsNullOrWhiteSpace(query.CNickName)) { sql += " AND cNickName=@CNickName"; } if (!string.IsNullOrWhiteSpace(query.CPasswd)) { sql += " AND cPasswd=@cPasswd"; } if (!string.IsNullOrWhiteSpace(query.Sort)) { query.Sort = SqlHandler.ReplaceSQLChar(query.Sort); sql += $" ORDER BY {query.Sort}"; if (!string.IsNullOrWhiteSpace(query.Order)) { query.Order = SqlHandler.ReplaceSQLChar(query.Order); sql += $" {query.Order}"; } } if (query.PageIndex != 0 && query.PageSize != 0) { query.PageIndex = (query.PageIndex - 1) * query.PageSize; sql += $" LIMIT {query.PageIndex},{query.PageSize}"; } var info = SetMapper(query); var res = await _mysqlRespository.QueryListAsync(sql, info); return res; } catch (Exception ex) { _log.Error("GetCustomerInfoByQueryAsync method error:" + ex); throw; } } /// /// 用户登录 /// /// <param name="query">查询条件,只包括账号密码即可 /// public async Task UserLogin(UserQuery query) { try { if (query == null) { _log.Error("UserLogin's error:selQuery is not null"); throw new Exception("UserLogin's error:selQuery is not null"); } string sql = "SELECT cId,cName,cSex,cAge,cPhone,cNickName,cPic FROM `User` WHERE 1=1 "; if (!string.IsNullOrWhiteSpace(query.CName)) { sql += " AND cName=@CName OR cEmail=@CName OR cPhone=@CName"; } if (!string.IsNullOrWhiteSpace(query.CPasswd)) { sql += " AND cPasswd=@cPasswd"; } var info = SetMapper(query); var res = await _mysqlRespository.QueryInfoAsync(sql, info); return res; } catch (Exception ex) { _log.Error("UserLogin method error:" + ex); throw; } } /// /// 构建ef查询条件 /// /// <param name="query"> /// private Expression<Func<User, bool>> BuildQuery(UserQuery query) { var oLamadaExtention = new LamadaExtention if (query.CId != null) { oLamadaExtention.GetExpression(nameof(User.CId), query.CId, ExpressionTypeEnum.Equal); } if (!string.IsNullOrWhiteSpace(query.CName)) { oLamadaExtention.GetExpression(nameof(User.CName), query.CName, ExpressionTypeEnum.Equal); } if (query.CSex != null) { oLamadaExtention.GetExpression(nameof(User.CSex), query.CSex, ExpressionTypeEnum.Equal); } if (query.CAge != null) { oLamadaExtention.GetExpression(nameof(User.CAge), query.CAge, ExpressionTypeEnum.Equal); } if (!string.IsNullOrWhiteSpace(query.CAddress)) { oLamadaExtention.GetExpression(nameof(User.CAddress), query.CAddress, ExpressionTypeEnum.Equal); } if (!string.IsNullOrWhiteSpace(query.CPhone)) { oLamadaExtention.GetExpression(nameof(User.CPhone), query.CPhone, ExpressionTypeEnum.Equal); } if (!string.IsNullOrWhiteSpace(query.CIdNum)) { oLamadaExtention.GetExpression(nameof(User.CIdNum), query.CIdNum, ExpressionTypeEnum.Equal); } if (query.CIdentity != null) { oLamadaExtention.GetExpression(nameof(User.CIdentity), query.CIdentity, ExpressionTypeEnum.Equal); } if (!string.IsNullOrWhiteSpace(query.CNickName)) { oLamadaExtention.GetExpression(nameof(User.CNickName), query.CNickName, ExpressionTypeEnum.Equal); } if (!string.IsNullOrWhiteSpace(query.CEmail)) { oLamadaExtention.GetExpression(nameof(User.CEmail), query.CEmail, ExpressionTypeEnum.Equal); } if (!string.IsNullOrWhiteSpace(query.CPasswd)) { oLamadaExtention.GetExpression(nameof(User.CPasswd), query.CPasswd, ExpressionTypeEnum.Equal); } if (!string.IsNullOrWhiteSpace(query.CPic)) { oLamadaExtention.GetExpression(nameof(User.CPic), query.CPic, ExpressionTypeEnum.Equal); } return oLamadaExtention.GetLambda(); } private User SetMapper(UserQuery query) { var config = new MapperConfiguration(cfg => cfg.CreateMap<UserQuery, User>()); var mapper = config.CreateMapper(); User info = mapper.Map<UserQuery, User>(query); return info; } } }
c#
19
0.496819
151
33.259516
289
starcoderdata
import './StoryImage.scss' import cx from 'classnames' import { connect } from 'react-redux' import { Tool } from 'components/tool' import { PhotoWidget, StoryImageForm } from '.' import * as photo from 'components/photos/model.js' import { actions, selectors } from './model.js' import { deleteStoryImage } from 'ducks/actions.js' import { toRoute } from 'prodsys/ducks/router' const StoryImageActions = ({ deleteHandler = null, viewPhoto = R.always(null), imagefile, }) => ( <div className="Actions"> <Tool label="fjern" className="warn" icon="Delete" onClick={deleteHandler} /> <Tool label="foto" disabled={!imagefile} className="ok" icon="Eye" onClick={viewPhoto(imagefile)} /> ) export const PlaceHolder = () => ( <div className="StoryImageItem" style={{ opacity: 0.5 }}> <StoryImageActions /> <PhotoWidget /> <StoryImageForm /> ) const StoryImage = ({ pk, imagefile = null, deleteHandler, viewPhoto }) => { return ( imagefile && ( <div className="StoryImageItem"> <StoryImageActions deleteHandler={deleteHandler} viewPhoto={viewPhoto} imagefile={imagefile} /> <PhotoWidget id={pk} pk={imagefile} /> <StoryImageForm pk={pk} /> ) ) } const mapStateToProps = (state, { pk }) => selectors.getItem(pk)(state) const mapDispatchToProps = (dispatch, { pk }) => ({ deleteHandler: () => dispatch(deleteStoryImage(pk)), viewPhoto: pk => () => dispatch(toRoute({ model: 'photos', action: 'change', pk: pk })), }) export default connect( mapStateToProps, mapDispatchToProps, )(StoryImage)
javascript
16
0.62478
76
24.044118
68
starcoderdata
protected static BigInteger getSeed(KNOWN_OP op) { switch (op) { //TODO: Implement MAX and MIN functions case SUM: return BigInteger.ZERO; default: return null; } }
java
8
0.596154
50
28.857143
7
inline
<?php namespace App\Services\Telegram\UpdateHandlers\ShoppingList; use App\Models\ShoppingList\ShoppingListItem; use App\Services\Telegram\UpdateHandlers\MatchHandler; class AddItem extends MatchHandler { protected string $pattern = '/^надо купить (.+)$/iu'; protected function matched(array $matches = []): string { $what = mb_strtolower($matches[1]); $list = collect(explode(',', $what))->map(fn ($item) => trim($item)); foreach ($list as $name) { if (!$item = ShoppingListItem::query()->where('name', $name)->first()) $item = new ShoppingListItem(); $item->name = $name; $item->bought = false; $item->save(); } if (count($list) == 1) return "В список покупок был добавлен элемент \"$what\"!"; else { $list = $list->map(fn ($item) => '- '.$item)->all(); return "В список покупок были добавлены элементы:" . PHP_EOL . implode(PHP_EOL, $list); } } }
php
18
0.563531
99
28.457143
35
starcoderdata
"use strict"; class NError { constructor(_status,_message,_details) { this.status = _status; this.message = _message; this.details = _details; } } exports.NError = NError;
javascript
8
0.598039
44
21.666667
9
starcoderdata
using Microsoft.AspNetCore.Mvc; using Weavy.Core.Controllers; using Weavy.Core.Mvc; namespace Weavy.Dropin.Controllers; /// /// Abstract base class for controllers in the area. /// [Area(Constants.AREA_NAME)] [Route("[area]/[controller]")] [TurboDrive] public abstract class AreaController : WeavyController { }
c#
8
0.75
56
21.4
15
starcoderdata
protected static void ProcessBrackets(IReadOnlyList<IReadOnlyList<MatchTreeNode>> levels, BracketGenerationContext ctx) { foreach (var treeLevel in levels) { var doNextLevel = false; foreach (var matchNode in treeLevel) { if (matchNode == null || ctx.QueuedMatches.ContainsKey(matchNode.MatchIndex)) { // a BYE in this level, we might be able to generate match from the next // level doNextLevel = true; continue; } ProcessNode(matchNode, ctx); } if (!doNextLevel) { // no need to traverse next level, no more matches can be generated break; } } }
c#
14
0.646059
89
23.923077
26
inline
var log = require('fancy-log'); var fs = require('fs'); var globby = require('globby'); var jimp = require('jimp'); var fixYYFile = require('../../utils/').fixYYFile; var args = process.argv.splice(process.execArgv.length + 2); var configPath = args[0] || './gms-tasks-config.json'; var scriptName = 'export-gm-sprites-as-strips'; var config = JSON.parse(fs.readFileSync(configPath))[scriptName]; log("Starting `" + scriptName + "`"); var time = new Date(); start(function(){ log("Finished `" + scriptName + "` after", (((new Date()) - time) / 1000), "seconds"); }); function start(callback) { var pattern = [ //config.spriteDirectory + "spr_Ambush_Dropping*/*.yy", config.spriteDirectory + "spr_Portrait*/*.yy", //config.spriteDirectory + "spr_Wall/*.yy", ]; var name = "Portraits"; log("importing", pattern); //most likely, get all the sprites in the sprites directory return globby(pattern).then(function(paths){ var allExports = []; log("found", paths.length, "yy files updating texture group"); for (var i=0; i<paths.length; i++) { var data = JSON.parse(fixYYFile(fs.readFileSync(paths[i], {encoding:'utf8'}))); log("updating", paths[i]); data.textureGroupId.name = name; data.textureGroupId.path = "texturegroups/" + name; var strData = JSON.stringify(data); fs.writeFileSync(paths[i], strData); } return Promise.all(allExports).then(function(){ return callback(); }); }); }
javascript
21
0.629042
88
26.684211
57
starcoderdata
#include #include #include #include #define maxN 200001 #define DN first #define amount second typedef long maxn; typedef long long maxa; typedef std::pair <maxn, maxa> ad_t; maxn n; std::vector ad[maxN]; ad_t no[maxN]; maxa has[maxN], res; void Prepare() { std::cin >> n; for (maxn v = 0; v < n; v++) { maxn u; maxa a; std::cin >> u >> a; --u, no[v].DN = u, no[v].amount = a; ad[u].push_back(ad_t(v, a)); has[v] = -1; } } void DFS(const maxn u) { has[u] = 0; for (maxn i = 0; i < ad[u].size(); i++) { maxn v = ad[u][i].DN; maxa a = ad[u][i].amount; if (v == no[u].DN) continue; if (has[v] == -1) DFS(v); res += std::max((maxa)0, a - has[v]); has[u] += a; } if (no[no[u].DN].DN == u) { maxn v = no[u].DN; if (has[v] == -1) DFS(v); res += std::max((maxa)0, no[v].amount - has[v]); has[u] += no[v].amount; } } void Process() { for (maxn u = 0; u < n; u++) if (has[u] == -1) DFS(u); std::cout << res; } int main() { Prepare(); Process(); }
c++
13
0.529865
55
16.032787
61
starcoderdata
from odynn import optim, utils import pandas as pd import seaborn as sns import pylab as plt import numpy as np from odynn.models import cfg_model from odynn import neuron as nr from odynn import nsimul as ns from sklearn.decomposition import PCA def corr(df): corr = df.corr() # Set up the matplotlib figure f, ax = plt.subplots(figsize=(11, 9)) # Generate a custom diverging colormap cmap = sns.diverging_palette(220, 10, as_cmap=True) # Draw the heatmap with the mask and correct aspect ratio sns.heatmap(corr, cmap=cmap, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}) plt.show() def scatt(df): f, ax = plt.subplots(figsize=(6.5, 6.5)) sns.despine(f, left=True, bottom=True) sns.scatterplot(x="loss", y="n__tau", hue="rho_ca", palette="autumn", linewidth=0, data=df, ax=ax) plt.show() def violin(df): # Use cubehelix to get a custom sequential palette # pal = sns.cubehelix_palette(p, rot=-.5, dark=.3) # Show each distribution with both violins and points sns.violinplot(data=df, inner="points") plt.show() def get_df(dir): dic = optim.get_vars(dir) return pd.DataFrame.from_dict(dic) def real_std(df): df = df.copy() mdps = [col for col in df.columns if 'mdp' in col or 'E' in col] df = df.drop(columns=mdps) variation = df.std() / df.mean() d = {'Variation': abs(variation.values), 'Parameter': df.columns.values} df2 = pd.DataFrame(d) df2 = df2.sort_values(['Variation']).reset_index(drop=True) mx = np.max(d['Variation']) r = np.array([1., 0., 0.]) g = np.array([0., 1., 0.]) colors = [r * (1. - v / mx) + g * (v / mx) for v in df2['Variation']] df2.plot.bar(x='Parameter', y='Variation', colors=colors, title='Relative standard deviation') # ax = sns.barplot(x='Parameter', y='Variation', data=df2, palette=colors) # plt.yscale('log') plt.show() def sigm(): def plot_sigm(pts, scale, col='k'): plt.plot(pts, 1 / (1 + sp.exp((-30. - pts) / scale)), col, label='scale=%s'%scale) import scipy as sp pts = sp.arange(-12000, 20, 0.5) # plot_sigm(pts, -1, col='#000000') # plot_sigm(pts, -3, col='#440000') # plot_sigm(pts, -10, col='#880000') # plot_sigm(pts, -30, col='#bb0000') # plot_sigm(pts, -100, col='#ff0000') plot_sigm(pts, 1, col='#000000') plot_sigm(pts, 3, col='#004400') plot_sigm(pts, 10, col='#008800') plot_sigm(pts, 30, col='#00bb00') plot_sigm(pts, 1000, col='#00ff00') plt.legend() plt.title('Influence of $V_{scale}$ on the rate dynamics') plt.show() exit(0) def table(): import re neur = cfg_model.NEURON_MODEL from odynn.models import celeg dir = utils.set_dir('Integcomp_volt_mod3dt0.1-YES') best = optim.get_best_result(dir) for k, v in neur.default_params.items(): v = neur._constraints_dic.get(k, ['-inf', 'inf']) u = '' if 'tau' in k: u = 'ms' elif 'scale' in k or 'mdp' in k or 'E' in k: u = 'mV' elif 'g' in k: u = 'mS/cm$^2$' elif k == 'C_m': u = '$\mu$F/cm$^2$' else: u = 'none' tp = '%s &&& %s & %s&%s&%s&%s \\\\\n \\hline' % (k, v[0], v[1], u, cfg_model.NEURON_MODEL.default_params[k], best[k]) tp = re.sub('(.)__(.*) (&.*&.*&.*&.*&)', '\g \g tp) tp = tp.replace('inf', '$\\infty$') tp = re.sub('scale_(.)', '$V_{scale}^\g tp) tp = re.sub('mdp_(.)', '$V_{mdp}^\g tp) tp = re.sub('tau_(.)', '$\\ tau^\g tp) tp = re.sub('E_(..?)', '$E_{\g tp) tp = tp.replace('\\ tau', '\\tau') tp = re.sub('g_([^ ]*) +', '$g_{\g ', tp) tp = tp.replace('rho_ca', '$\\rho_{Ca}$') tp = tp.replace('decay_ca', '$\\tau_{Ca}$') tp = tp.replace('C_m', '$C_m$') tp = tp.replace('alpha_h', '$\\alpha^h$') tp = re.sub('(.*tau.*)&&&', '\g % (celeg.MIN_TAU, celeg.MAX_TAU), tp) tp = re.sub('(.*scale.*)&&&', '\g % (celeg.MIN_SCALE, celeg.MAX_SCALE), tp) print(tp) exit(0) def hhsimp_box(df): utils.box(df, ['b', 'g', 'm', 'g', 'm'], ['C_m', 'g_L', 'g_K', 'E_L', 'E_K']) plt.title('Membrane') utils.save_show(True, True, 'boxmemb', dpi=300) plt.subplot(3, 1, 1) utils.box(df, ['m', '#610395'], ['a__mdp', 'b__mdp']) plt.title('Midpoint') plt.subplot(3, 1, 2) utils.box(df, ['m', '#610395'], ['a__scale', 'b__scale']) plt.title('Scale') plt.subplot(3, 1, 3) utils.box(df, ['m', '#610395'], ['a__tau', 'b__tau']) plt.yscale('log') plt.title('Time constant') plt.tight_layout() utils.save_show(True, True, 'boxrates', dpi=300) def leak_box(df): utils.box(df, ['b', 'g', 'Gold'], ['C_m', 'g_L', 'E_L']) plt.title('Membrane') utils.save_show(True, True, 'box1', dpi=300) if __name__ == '__main__': from odynn.nsimul import simul import scipy as sp t = sp.arange(0., 1200., 0.1) i = 20. * ((t>400) & (t<800)) simul(t=t, i_inj=i, show=True);exit() dir = utils.set_dir('Tapwith_dt0.5') dic = optim.get_vars(dir, loss=False) # df = pd.DataFrame.from_dict(dic) # df = df.dropna() # dfdisp = (df - df.mean()) / df.std() # plt.plot(dfdisp.transpose()) # utils.save_show(True, True, 'dispreal', dpi=300) dd = optim.get_vars_all(dir, losses=True) optim.plot_loss_rate(dd['loss'], dd['rates'], dd['loss_test'], 50, show=True) from odynn import datas dic = optim.get_vars(dir, loss=True) train, test = optim.get_data(dir) print(dic['loss']) df = pd.DataFrame(dic['loss'], columns=['loss']) # df = pd.DataFrame.from_dict(dic)#.head(4) df = df.sort_values('loss').reset_index(drop=True) # df = df.dropna() sns.barplot(x=df.index, y='loss', data=df) # df.plot.bar(y='loss') utils.save_show(True, True, 'lossfin_virt', dpi=300);exit() # df = df[df['loss'] <= np.min(df['loss'])] # hhsimp_box(df) # cfg_model.NEURON_MODEL.boxplot_vars(dic, show=True, save=True) dic = df.to_dict('list') # dic = collections.OrderedDict(sorted(dic.items(), key=lambda t: t[0])) # obj = circuit.CircuitTf.create_random(n_neuron=9, syn_keys={(i,i+1):True for i in range(8)}, gap_keys={}, n_rand=50, dt=0.1) p = optim.get_best_result(dir) print(p) # p = {k: v[0] for k,v in p.items()} for i in range(train[1].shape[-1]): ns.comp_pars_targ(p, cfg_model.NEURON_MODEL.default_params, dt=train[0][1] - train[0][0], i_inj=train[1][:,i], suffix='virtrain%s'%i, show=True, save=True) for i in range(test[1].shape[-1]): ns.comp_pars_targ(p, cfg_model.NEURON_MODEL.default_params, dt=test[0][1] - test[0][0], i_inj=test[1][:,i], suffix='virtest%s'%i, show=True, save=True) n = optim.get_model(dir) n.init_params = dic X = n.calculate(train[1]) Xt = n.calculate(test[1]) for i in range(X.shape[2]): n.plot_output(train[0], train[1][:,i], X[:,:,i], [train[-1][0][:,i], train[-1][-1][:,i]], save=True, suffix='virtend%s'%i) # for i in range(X.shape[3]): # plt.subplot(2, 1, 1) # plt.plot(train[-1][-1], 'r', label='train data') # plt.plot(X[:, -1,:, i]) # plt.legend() # plt.subplot(2, 1, 2) # plt.plot(test[-1][-1], 'r', label='test data') # plt.plot(Xt[:, -1,:, i]) # plt.legend() # utils.save_show(True,True,'best_result%s'%i, dpi=300) # for i in range(9): # dicn = {k: v[:,i] for k,v in dic.items()} # hhmodel.CElegansNeuron.plot_vars(dicn, show=True, save=False) # scatt(df) # pca = PCA() # pca.fit(df) # for c in pca.components_: # for i, name in enumerate(df): # print(name, '%.2f'%c[i]) # plt.plot(pca.explained_variance_ratio_) # plt.show() # sns.FacetGrid(data=df, row='C_m') # plt.show() # violin(df)
python
17
0.541858
163
33.461538
234
starcoderdata
import angular from 'angular'; import uirouter from 'angular-ui-router'; import DocumentoEdicaoController from './edicao.controller'; import documentoService from '../../../servicos/documento.service'; export default angular.module('myApp.edicao', [uirouter, documentoService]) .controller('DocumentoEdicaoController', DocumentoEdicaoController) .name;
javascript
3
0.787383
75
32
13
starcoderdata
private int findLineNumber(Long methodId, int line) { ArrayList<OffsetLine> lines = lineMappings.get(methodId); if (lines == null) { return -1; } OffsetLine bestLine = null; for (OffsetLine offsetLine : lines) { if (offsetLine.pc <= line) { bestLine = offsetLine; } else { if (bestLine == null) { // Better to give a rough line number than fail epicly. // Copied from Python symbolizer. bestLine = offsetLine; } break; } } if (bestLine != null) { return bestLine.mappedLine; } return -1; }
java
11
0.562197
65
25.956522
23
inline
package jsonresult import ( "github.com/incognitochain/incognito-chain/common" ) type ReceivedTransaction struct { TransactionDetail ReceivedAmounts map[common.Hash]ReceivedInfo `json:"ReceivedAmounts"` FromShardID byte `json:"FromShardID"` } type ReceivedInfo struct { CoinDetails ReceivedCoin `json:"CoinDetails"` CoinDetailsEncrypted string `json:"CoinDetailsEncrypted"` } type ReceivedCoin struct { PublicKey string `json:"PublicKey"` Info string `json:"Info"` Value uint64 `json:"Value"` } type ListReceivedTransaction struct { ReceivedTransactions []ReceivedTransaction `json:"ReceivedTransactions"` }
go
8
0.753567
95
27.555556
27
starcoderdata
def unitary(wave, i, l): # different unitary evolution protocol ''' this protocol makes use of the fact that the 2^l by 2^l sparse matrix is in fact block diagonal with each block size being 2^(l-2*i). We can fix position index i and split the wavefunction into chunks given by 2^l/(2^{l-2*i})= 2^{2*i} then performing the mat-vec product for each chunks, with the same sparse matix un. Then we proceed to shift the position index of the wavefuntion and evolve it with another random unitary. After shifting L times the position index assumes its original place and completes a whole evolution (both on even and odd links) To reach optimal efficiency, the position index i must be chosen accordingly with the given system size l. ''' if i >= l//2: raise ValueError("Invalid partition. i must be less than l/2." ) temp = np.zeros((2**(2*i), 2**(l-2*i)),dtype='c16') pss = temp for j in range(l): wave_split = np.split(wave, 2**(2*i)) u = unitary_group.rvs(4) un = sparse.kron(u, sparse.identity(2**(l-2*i-2))) for k in range(2**(2*i)): pss[k] = un.dot(wave_split[k]) wave = np.concatenate(pss) # gathering wavefunction wave = np.reshape(wave,(2, 2**(l-2), 2)) # shift the position and flatten array wave = np.moveaxis(wave, -1, 0).ravel(order='F') pss = temp return wave
python
16
0.634028
95
42.666667
33
inline
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using GraemSheppardOnline.Code; using GraemSheppardOnline.Models; using GraemSheppardOnline.Services.MongoDBContext; using GraemSheppardOnline.ViewModels; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MongoDB.Driver; // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace GraemSheppardOnline.Controllers { [Authorize(Roles = "Owner")] public class FileManagerController : Controller { private readonly FileManager _fileManager; private readonly MongoDBContext _contextMongo; static readonly int resultsPerPage = 8; public FileManagerController () { _fileManager = FileManager.GetInstance(); _contextMongo = ContextManager.GetInstance().MongoContext; } public async Task Index() { return View(); } public async Task Create () { return View(); } [HttpPost] public async Task Create (FileManagerCreateVM vm) { if (_fileManager.GetMetadata(vm.Name) != null) { ModelState.AddModelError("", "A file already exists with that name"); return View(vm); } var fileStream = vm.File.OpenReadStream(); FileData data = new FileData { Name = vm.Name, DisplayName = vm.DisplayName, IsImage = vm.IsImage, IsPublic = vm.IsPublic }; _fileManager.Insert(data, fileStream); return RedirectToAction("Index"); } [HttpGet] [Route("/FileManager/Details/{id}")] public async Task Details (string id) { var data = _contextMongo.Files.Find(x => x.Id == id).FirstOrDefault(); var metaData = _fileManager.GetMetadata(id); var vm = new FileManagerDetailsVM { DisplayName = data.DisplayName, Id = id, Name = data.Name, UploadDate = metaData.UploadDateTime }; return View(vm); } [HttpGet] [Route("/FileManager/Delete/{id}")] public async Task Delete (string id) { _fileManager.Delete(id); return RedirectToAction("Index"); } [HttpGet] [Route("/FileManager/Download/{id}")] public async Task Download(string id) { var metaData = _contextMongo.Files.Find(x => x.Id == id).FirstOrDefault(); var fileStream = _fileManager.Get(id); var file = File(fileStream, "application/octet-stream", metaData.Name); return file; } [AllowAnonymous] [HttpGet] [Route("/Images/{id}")] public async Task Images(string id) { var metaData = _contextMongo.Files.Find(x => x.Id == id).FirstOrDefault(); if (!metaData.IsPublic) { return null; } var fileStream = _fileManager.Get(id); var file = File(fileStream, "application/octet-stream", metaData.Name); return file; } public async Task GetResults(string search, int? page) { var query = _fileManager.Search(search); var results = query.Skip(resultsPerPage * (page ?? 0)) .Take(resultsPerPage) .Select(x => new FileIndexCard { Name = x.Filename, Id = x.Id.ToString(), CardHeader = "File", CardLink = "/FileManager/Details/" + x.Id }) .ToList(); return PartialView("_ResultsPartial", results); } } }
c#
23
0.542205
112
29.535211
142
starcoderdata
package com.runer.toumai.ui.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.chad.library.adapter.base.BaseQuickAdapter; import com.orhanobut.logger.Logger; import com.runer.liabary.recyclerviewUtil.ItemDecorations; import com.runer.liabary.recyclerviewUtil.VerticalItemDecoration; import com.runer.liabary.util.RunerLinearManager; import com.runer.net.RequestCode; import com.runer.toumai.R; import com.runer.toumai.adapter.HomeListAdapter; import com.runer.toumai.base.BaseFragment; import com.runer.toumai.base.BaseLoadMoreFragment; import com.runer.toumai.bean.GetGoodParam; import com.runer.toumai.bean.GoodListBean; import com.runer.toumai.dao.GoodsListDao; import com.runer.toumai.net.NetConfig; import com.runer.toumai.ui.activity.LoginActivity; import com.runer.toumai.ui.activity.ProInfoActivity; import com.runer.toumai.ui.activity.SellGoodsActivity; import com.runer.toumai.util.AppUtil; import com.runer.toumai.widget.LoamoreView; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import butterknife.ButterKnife; import butterknife.InjectView; import cn.iwgang.countdownview.CountdownView; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; /** * Created by szhua on 2017/7/14/014. * github:https://github.com/szhua * TouMaiNetApp * HomeListFragment * 首页列表界面 */ public class HomeListFragment extends BaseLoadMoreFragment { private GoodsListDao goodsListDao; private String lable = ""; private String uid = ""; private List datas=new ArrayList<>(); public static HomeListFragment getInstance(String labe, String uid) { HomeListFragment homeListFragment = new HomeListFragment(); homeListFragment.lable = labe; homeListFragment.uid = uid; return homeListFragment; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); baseQuickAdapter.setCountdownEndListener(new CountdownView.OnCountdownEndListener() { @Override public void onEnd(CountdownView cv) { if (goodsListDao != null) { goodsListDao.refresh(); } } }); swipeRefresh.setEnabled(false); goodsListDao = new GoodsListDao(getContext(), this); GetGoodParam getGoodParam = new GetGoodParam(); getGoodParam.setLabel(lable); getGoodParam.setUser(uid); //明价 getGoodParam.setSell_state2("2"); // //暗价 // getGoodParam.setSell_state1("1"); //降价 getGoodParam.setFall_state("1"); //是否心跳时间 getGoodParam.setHeart_time("1"); //两者不为空的时候==============(标签或者tag进来的时候) if (!TextUtils.isEmpty(lable) || !TextUtils.isEmpty(uid)) { //明价 getGoodParam.setSell_state2(""); //暗价 getGoodParam.setSell_state1(""); //降价 getGoodParam.setFall_state(""); //是否心跳时间 getGoodParam.setHeart_time(""); } goodsListDao.getGoodsList(getGoodParam); baseQuickAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() { @Override public void onItemClick(BaseQuickAdapter adapter, View view, int position) { Bundle bundle = new Bundle(); bundle.putString("id", baseQuickAdapter.getItem(position).getId()); transUi(ProInfoActivity.class, bundle); } }); } @Override public HomeListAdapter getAdater() { return new HomeListAdapter(null); } @Override public void loadMore() { if (goodsListDao.hasMore()) { goodsListDao.loadMore(); } else { recyclerView.postDelayed(new Runnable() { @Override public void run() { baseQuickAdapter.loadMoreEnd(); } }, 1000); } } @Override public void onRequestSuccess(int requestCode) { super.onRequestSuccess(requestCode); if (requestCode == RequestCode.LOADMORE) { showProgress(false); datas = goodsListDao.getDatas(); baseQuickAdapter.setNewData(datas); if(datas==null||datas.isEmpty()){ baseQuickAdapter.setEmptyView(getEmptyViewFixedHeight("该条件下无此商品,请重新设置筛选条件")); } } } @Override public void refresh() { if (goodsListDao != null) { goodsListDao.refresh(); } } public void getNewdata() { if (goodsListDao != null) { datas.clear(); baseQuickAdapter.notifyDataSetChanged(); goodsListDao.refresh(); showProgress(true); } } public void setParam(GetGoodParam getGoodParam) { if (goodsListDao.getDatas() != null) goodsListDao.getDatas().clear(); goodsListDao.getGoodsList(getGoodParam); showProgress(true); } @Override public void onCompeleteRefresh() { super.onCompeleteRefresh(); ((BaseFragment) getParentFragment()).onCompeleteRefresh(); } }
java
18
0.659002
93
34.0625
160
starcoderdata
# -*- coding: utf-8 -*- from model.user import User def test_add_user(app, db, json_users, check_ui ): user = json_users old_users=db.get_user_list() app.user.create(user) assert len(old_users) + 1 == app.user.count() new_users=db.get_user_list() old_users.append(user) assert sorted(old_users,key=User.id_or_max) == sorted(new_users,key=User.id_or_max) if check_ui: new = sorted(new_users, key=User.id_or_max) ui= sorted(app.user.get_user_list(), key=User.id_or_max) assert new == ui
python
12
0.637782
87
29.368421
19
starcoderdata
// ydb_trans.h // Author: // // Ydb_Trans holds state for an open transaction. Transactions are created by // Ydb and , // modified, and deleted by the Ydb_Scheduler. // // Ydb_Trans* trans = db->OpenTransaction(); // db->Put("A", "1", trans); // db->Put("B", "2", trans); // db->Del("C", trans); // trans->Commit(); // deallocates the object // #ifndef _YDB_TRANS_H_ #define _YDB_TRANS_H_ #include #include "ydb_op.h" class Ydb_Trans; typedef vector TransList; class Ydb_Trans { public: ~Ydb_Trans(); // Commits all operations associated with this transaction and deletes the // transaction. The transaction object should not be used after calling // Commit. void Commit(); // Aborts all operations associated with this transaction and deletes the // transaction. The transaction object should not be used after calling // Abort. void Abort(); protected: friend class Ydb_Scheduler; // for AddOp and GetOps enum TransactionState { OPEN = 0, ABORTED, COMMITTED }; // Ydb_Trans cannot be instantiated directly. Ydb_Trans(Ydb_Scheduler* sched) : sched_(sched), state_(OPEN) { }; // Adds the operation to the transaction. The transaction takes ownership // of the operation and will take care of deallocation. void AddOp(Ydb_Op* op); // Returns the list of operations associated with this transaction. Ydb_Ops& GetOps() { return ops_; } Ydb_Scheduler* sched_; TransactionState state_; Ydb_Ops ops_; }; #endif // _YDB_TRANS_H_
c
9
0.685126
78
25.322034
59
starcoderdata
func newListener(a ma.Multiaddr, tlsConf *tls.Config) (*listener, error) { // Only look at the _last_ component. maddr, wscomponent := ma.SplitLast(a) isWSS := wscomponent.Equal(wssma) if isWSS && tlsConf == nil { return nil, fmt.Errorf("cannot listen on wss address %s without a tls.Config", a) } lnet, lnaddr, err := manet.DialArgs(maddr) if err != nil { return nil, err } nl, err := net.Listen(lnet, lnaddr) if err != nil { return nil, err } laddr, err := manet.FromNetAddr(nl.Addr()) if err != nil { return nil, err } first, _ := ma.SplitFirst(a) // Don't resolve dns addresses. // We want to be able to announce domain names, so the peer can validate the TLS certificate. if c := first.Protocol().Code; c == ma.P_DNS || c == ma.P_DNS4 || c == ma.P_DNS6 || c == ma.P_DNSADDR { _, last := ma.SplitFirst(laddr) laddr = first.Encapsulate(last) } ln := &listener{ nl: nl, laddr: laddr.Encapsulate(wscomponent), incoming: make(chan *Conn), closed: make(chan struct{}), } ln.server = http.Server{Handler: ln} if isWSS { ln.server.TLSConfig = tlsConf } return ln, nil }
go
15
0.645648
104
27.175
40
inline
def process_value(self): # expecting a value token_type, token_string, token_line_number = self.consume() if pyradox.token.is_primitive_value_token_type(token_type): maybe_color = self.maybe_subprocess_color(token_string, token_line_number) if maybe_color is not None: value = maybe_color else: # normal value value = pyradox.token.make_primitive(token_string, token_type) self.append_to_result(value) if self.in_group: self.next = self.process_value else: self.next = self.process_key elif token_type == 'begin': # Value is a tree or group. First, determine whether this is a tree or group. lookahead_pos = self.pos level = 0 # Empty brackets are trees by default. is_tree = True while lookahead_pos < len(self.token_data) and level >= 0: token_type, token_string, token_line_number = self.token_data[lookahead_pos] lookahead_pos += 1 if level == 0: if token_type == 'operator': # If an operator is found at this level, it's definitely a tree. is_tree = True break elif token_type not in ['comment', 'end']: # If something else (other than a comment or end) is found at this level, # then it's a group unless an operator is found later. is_tree = False if token_type == 'begin': level += 1 elif token_type == 'end': level -= 1 if is_tree: # Recurse. value, self.pos = parse_tree(self.token_data, self.filename, self.pos) self.append_to_result(value) if self.in_group: self.next = self.process_value else: self.next = self.process_key else: # Process following values as a group. if self.in_group: raise ParseError('%s, line %d: Error: Cannot nest groups inside groups.' % (self.filename, token_line_number + 1)) else: self.in_group = True self.next = self.process_value elif token_type == 'comment': if self.in_group: if token_line_number == self.get_previous_line_number(): self.append_line_comment(token_string[1:]) else: self.pending_comments.append(token_string[1:]) else: self.pending_comments.append(token_string[1:]) self.next = self.process_value elif token_type == 'end' and self.in_group: self.in_group = False self.next = self.process_key else: raise ParseError('%s, line %d: Error: Invalid token type %s after key "%s", expected a value type.' % (self.filename, token_line_number + 1, token_type, self.key_string))
python
17
0.492902
182
44.369863
73
inline
// Copyright 2016 VMware, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package dio adds dynamic behaviour to the standard io package mutliX types package dio import ( "io" "os" "sync" log "github.com/sirupsen/logrus" ) // DynamicMultiWriter adds dynamic add/remove to the base multiwriter behaviour type DynamicMultiWriter interface { io.Writer Add(...io.Writer) Remove(io.Writer) Close() error } type multiWriter struct { mutex sync.Mutex waitGroup sync.WaitGroup writers []io.Writer } func (t *multiWriter) Write(p []byte) (int, error) { var n int var err error var wTmp []io.Writer if verbose { defer func() { log.Debugf("[%p] write %q to %d writers (err: %#+v)", t, string(p[:n]), len(wTmp), err) }() } t.mutex.Lock() t.waitGroup.Add(1) defer t.waitGroup.Done() // stash a local copy of the slice as we never want to write twice to a single writer // if remove is called during this flow wTmp = make([]io.Writer, len(t.writers)) copy(wTmp, t.writers) t.mutex.Unlock() eof := 0 // possibly want to add buffering or parallelize this for _, w := range wTmp { n, err = w.Write(p) if err != nil { // remove the writer log.Debugf("[%p] removing writer %p due to %s", t, w, err.Error()) // Remove grabs the lock t.Remove(w) if err == io.EOF { eof++ } } // FIXME: figure out what semantics we need here - currently we may not write to // everything as we abort if n != len(p) { // remove the writer log.Debugf("[%p] removing writer %p due to short write: %d != %d", t, w, n, len(p)) // Remove grabs the lock t.Remove(w) } } // This means writers closed/removed while we iterate if eof != 0 && n == 0 && err == nil && eof == len(wTmp) { log.Debugf("[%p] All of the writers returned EOF (%d)", t, len(wTmp)) } return len(p), nil } func (t *multiWriter) Add(writer ...io.Writer) { t.mutex.Lock() defer t.mutex.Unlock() t.writers = append(t.writers, writer...) if verbose { log.Debugf("[%p] added writer - now %d writers", t, len(t.writers)) for i, w := range t.writers { log.Debugf("[%p] Writer %d [%p]", t, i, w) } } } // CloseWriter is an interface that implements structs // that close input streams to prevent from writing. type CloseWriter interface { CloseWrite() error } // FIXME: provide a mechanism for selectively closing writers // - currently this closes /dev/stdout and logging as well if present func (t *multiWriter) Close() error { t.mutex.Lock() defer t.mutex.Unlock() // allow any pending writes to complete t.waitGroup.Wait() log.Debugf("[%p] Close on writers", t) for _, w := range t.writers { log.Debugf("[%p] Closing writer %+v", t, w) if c, ok := w.(CloseWriter); ok { log.Debugf("[%p] is a CloseWriter", t, w) c.CloseWrite() } else if c, ok := w.(io.Closer); ok && c != os.Stdout && c != os.Stderr { log.Debugf("[%p] is a Closer", t, w) // squash closing of stdout/err if bound c.Close() } } return nil } // TODO: add a ReadFrom for more efficient copy // Remove doesn't return an error if element isn't found as the end result is // identical func (t *multiWriter) Remove(writer io.Writer) { t.mutex.Lock() defer t.mutex.Unlock() if verbose { log.Debugf("[%p] removing writer %p - currently %d writers", t, writer, len(t.writers)) } for i, w := range t.writers { if w == writer { t.writers = append(t.writers[:i], t.writers[i+1:]...) if verbose { log.Debugf("[%p] removed writer - now %d writers", t, len(t.writers)) for i, w := range t.writers { log.Debugf("[%p] Writer %d [%p]", t, i, w) } } break } } } // MultiWriter extends io.MultiWriter to allow add/remove of writers dynamically // without disrupting existing writing func MultiWriter(writers ...io.Writer) DynamicMultiWriter { w := make([]io.Writer, len(writers)) copy(w, writers) t := &multiWriter{writers: w} if verbose { log.Debugf("[%p] created multiwriter", t) } return t }
go
15
0.655233
90
23.966851
181
starcoderdata
func (self *Request) isHeartbeat() bool { // Check message type if self.MessageType() == "heartbeat" { return true } // Check header if self.getHeader("heartbeat") == "ping" { return true } // fallback to checking body return string(self.delivery.Body) == "PING" }
go
10
0.665468
44
18.928571
14
inline
/* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.3.4-dev at Fri Nov 6 20:10:00 2015. */ #include "MeterReader_pb.h" #if PB_PROTO_HEADER_VERSION != 30 #error Regenerate this file with the current version of nanopb generator. #endif const pb_field_t MeterReader_Message_fields[5] = { PB_ONEOF_FIELD(message, 1, MESSAGE , ONEOF, STATIC , FIRST, MeterReader_Message, update, update, &MeterReader_CounterUpdate_fields), PB_ONEOF_FIELD(message, 2, MESSAGE , ONEOF, STATIC , FIRST, MeterReader_Message, calibrate, calibrate, &MeterReader_StartCalibration_fields), PB_ONEOF_FIELD(message, 3, MESSAGE , ONEOF, STATIC , FIRST, MeterReader_Message, settings, settings, &MeterReader_Settings_fields), PB_ONEOF_FIELD(message, 4, MESSAGE , ONEOF, STATIC , FIRST, MeterReader_Message, log, log, &MeterReader_LogMessage_fields), PB_LAST_FIELD }; const pb_field_t MeterReader_LogMessage_fields[3] = { PB_FIELD( 1, ENUM , REQUIRED, STATIC , FIRST, MeterReader_LogMessage, type, type, 0), PB_FIELD( 2, STRING , REQUIRED, STATIC , OTHER, MeterReader_LogMessage, text, type, 0), PB_LAST_FIELD }; const pb_field_t MeterReader_CounterUpdate_fields[4] = { PB_FIELD( 1, UINT32 , REQUIRED, STATIC , FIRST, MeterReader_CounterUpdate, meterId, meterId, 0), PB_FIELD( 2, UINT32 , REQUIRED, STATIC , OTHER, MeterReader_CounterUpdate, seriesId, meterId, 0), PB_FIELD( 3, UINT64 , REQUIRED, STATIC , OTHER, MeterReader_CounterUpdate, currentCounterValue, seriesId, 0), PB_LAST_FIELD }; const pb_field_t MeterReader_StartCalibration_fields[1] = { PB_LAST_FIELD }; const pb_field_t MeterReader_Settings_fields[6] = { PB_FIELD( 1, UINT32 , REQUIRED, STATIC , FIRST, MeterReader_Settings, meterId, meterId, 0), PB_FIELD( 2, UINT32 , REQUIRED, STATIC , OTHER, MeterReader_Settings, seriesId, meterId, 0), PB_FIELD( 4, ENUM , REQUIRED, STATIC , OTHER, MeterReader_Settings, communicationChannel, seriesId, 0), PB_FIELD( 8, UINT32 , REPEATED, STATIC , OTHER, MeterReader_Settings, risingEdgeAmounts, communicationChannel, 0), PB_FIELD( 9, UINT32 , REPEATED, STATIC , OTHER, MeterReader_Settings, fallingEdgeAmounts, risingEdgeAmounts, 0), PB_LAST_FIELD }; /* Check that field information fits in pb_field_t */ #if !defined(PB_FIELD_32BIT) /* If you get an error here, it means that you need to define PB_FIELD_32BIT * compile-time option. You can do that in pb.h or on compiler command line. * * The reason you need to do this is that some of your messages contain tag * numbers or field sizes that are larger than what can fit in 8 or 16 bit * field descriptors. */ PB_STATIC_ASSERT((pb_membersize(MeterReader_Message, message.update) < 65536), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_MeterReader_Message_MeterReader_LogMessage_MeterReader_CounterUpdate_MeterReader_StartCalibration_MeterReader_Settings) #endif #if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT) /* If you get an error here, it means that you need to define PB_FIELD_16BIT * compile-time option. You can do that in pb.h or on compiler command line. * * The reason you need to do this is that some of your messages contain tag * numbers or field sizes that are larger than what can fit in the default * 8 bit descriptors. */ PB_STATIC_ASSERT((pb_membersize(MeterReader_Message, message.update) < 256), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_MeterReader_Message_MeterReader_LogMessage_MeterReader_CounterUpdate_MeterReader_StartCalibration_MeterReader_Settings) #endif
c
10
0.731924
242
50.371429
70
starcoderdata
/* * Copyright 2019 ConsenSys Software Inc * * 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. * * SPDX-License-Identifier: Apache-2.0 */ package net.consensys.gpact.applications.gpact.erc20bridge; import java.math.BigInteger; import net.consensys.gpact.common.TxManagerCache; import net.consensys.gpact.common.test.AbstractWeb3Test; import net.consensys.gpact.soliditywrappers.applications.gpact.erc20bridge.MockCbcForERC20Test; import net.consensys.gpact.soliditywrappers.applications.gpact.erc20bridge.presets.LockableERC20PresetFixedSupply; import org.web3j.crypto.Credentials; import org.web3j.tx.TransactionManager; import org.web3j.tx.response.PollingTransactionReceiptProcessor; import org.web3j.tx.response.TransactionReceiptProcessor; /** * Check operation, assuming the calls are single blockchain (that is not part of a * cross-blockchain) call. */ public class AbstractERC20Test extends AbstractWeb3Test { public static final int DEFAULT_ACCOUNT_PARALLELIZATION_FACTOR = 5; public static final int DEFAULT_ERC20_PARALLELIZATION_FACTOR = 10; LockableERC20PresetFixedSupply lockableERC20, otherLockableERC20; MockCbcForERC20Test mockCrossBlockchainControlContract; public static final int INITIAL_SUPPLY = 1000000; static final BigInteger INITIAL_SUPPLY_BIG = BigInteger.valueOf(INITIAL_SUPPLY); public String owner; public Credentials otherCredentials; public String otherAccount; protected void deployContracts() throws Exception { this.owner = this.credentials.getAddress(); this.otherCredentials = createNewIdentity(); this.otherAccount = this.otherCredentials.getAddress(); this.mockCrossBlockchainControlContract = MockCbcForERC20Test.deploy(this.web3j, this.tm, this.freeGasProvider).send(); this.lockableERC20 = LockableERC20PresetFixedSupply.deploy( this.web3j, this.tm, this.freeGasProvider, "Wrapped ETH", "wETH", this.mockCrossBlockchainControlContract.getContractAddress(), INITIAL_SUPPLY_BIG, this.owner) .send(); } protected void loadOtherCredentialsContract() { TransactionReceiptProcessor txrProcessor = new PollingTransactionReceiptProcessor(this.web3j, POLLING_INTERVAL, RETRY); TransactionManager otherTm = TxManagerCache.getOrCreate( this.web3j, this.otherCredentials, BLOCKCHAIN_ID.longValue(), txrProcessor); this.otherLockableERC20 = LockableERC20PresetFixedSupply.load( this.lockableERC20.getContractAddress(), this.web3j, otherTm, this.freeGasProvider); } }
java
12
0.758025
137
43.026667
75
starcoderdata
def _transform_line(line, rand_u, sub_sample_rate): line = line.split('\t') # set missing values to zero for j in range(len(line)): if (line[j] == '') or (line[j] == '\n'): line[j] = '0' # sub-sample data by dropping zero targets, if needed target = np.int32(line[0]) if target == 0 and rand_u < sub_sample_rate: return None return (target, np.array(line[1:14], dtype=np.int32), np.array( list(map(lambda x: int(x, 16), line[14:])), dtype=np.int32) )
python
14
0.466142
63
36.411765
17
inline
def __new__(self, targetObject=None, eventName=None): """ __new__(cls: type) __new__(cls: type, targetObject: CodeExpression, eventName: str) """ pass
python
5
0.515306
72
26.428571
7
inline
def get_pubkey_from_transactions(address, raw_transactions): #for each transaction we got back, extract the vin, pubkey, go through, convert it to binary, and see if it reduces down to the given address for tx in raw_transactions: #parse the pubkey out of the first sent transaction for vin in tx['vin']: scriptsig = vin['scriptSig'] asm = scriptsig['asm'].split(' ') pubkey_hex = asm[1] try: if util_bitcoin.pubkey_to_address(pubkey_hex) == address: return pubkey_hex except: pass return None
python
13
0.589258
145
44.285714
14
inline
package dao import ( "context" "testing" pb "go-common/app/service/main/history/api/grpc" "github.com/smartystreets/goconvey/convey" ) func TestDaoListCache(t *testing.T) { var ( c = context.Background() business = "pgc" mid = int64(1) start = int64(0) his = []*pb.AddHistoryReq{{ Mid: 1, Business: "pgc", Kid: 1, Aid: 2, Sid: 3, }, } h = &pb.AddHistoryReq{ Mid: 2, Business: "pgc", Kid: 1, Aid: 2, Sid: 3, } ) convey.Convey("add his", t, func() { convey.So(d.AddHistoriesCache(c, his), convey.ShouldBeNil) convey.So(d.AddHistoryCache(c, h), convey.ShouldBeNil) convey.Convey("ListCacheByTime", func(ctx convey.C) { aids, err := d.ListCacheByTime(c, business, mid, start) ctx.Convey("Then err should be nil.aids should not be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) ctx.So(aids, convey.ShouldNotBeEmpty) }) }) convey.Convey("ListsCacheByTime", func(ctx convey.C) { var ( c = context.Background() businesses = []string{"pgc"} viewAt = int64(100) ps = int64(1) ) res, err := d.ListsCacheByTime(c, businesses, mid, viewAt, ps) ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) ctx.So(res, convey.ShouldNotBeNil) }) }) convey.Convey("HistoriesCache", func(ctx convey.C) { var hs = map[string][]int64{"pgc": {1}} res, err := d.HistoriesCache(c, 2, hs) ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) ctx.So(res, convey.ShouldNotBeNil) }) }) convey.Convey("ClearHistoryCache", func(ctx convey.C) { err := d.ClearHistoryCache(c, mid, []string{business}) ctx.Convey("Then err should be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) }) }) convey.Convey("DelHistoryCache", func(ctx convey.C) { ctx.So(d.DelHistoryCache(c, &pb.DelHistoriesReq{ Mid: 1, Records: []*pb.DelHistoriesReq_Record{{ID: 1, Business: "pgc"}}, }), convey.ShouldBeNil) }) convey.Convey("TrimCache", func(ctx convey.C) { err := d.TrimCache(c, business, mid, 10) ctx.Convey("Then err should be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) }) }) }) } func TestDaoDelCache(t *testing.T) { var ( c = context.Background() business = "pgc" mid = int64(1) aids = []int64{1} ) convey.Convey("DelCache", t, func(ctx convey.C) { err := d.DelCache(c, business, mid, aids) ctx.Convey("Then err should be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) }) }) } func TestDaoSetUserHideCache(t *testing.T) { var ( c = context.Background() mid = int64(1) value = int64(1) ) convey.Convey("SetUserHideCache", t, func(ctx convey.C) { err := d.SetUserHideCache(c, mid, value) ctx.Convey("Then err should be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) }) }) } func TestDaoUserHideCache(t *testing.T) { var ( c = context.Background() mid = int64(1) ) convey.Convey("UserHideCache", t, func(ctx convey.C) { value, err := d.UserHideCache(c, mid) ctx.Convey("Then err should be nil.value should not be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) ctx.So(value, convey.ShouldNotBeNil) // ctx.So(value, convey.ShouldEqual, 1) }) }) }
go
30
0.624749
84
25.648855
131
starcoderdata
"""Part of the flag-loader project. Copyright: (C) 2014 License: MIT License (see LICENSE.txt) Exported classes: TLDResolver """ from .WikidataTitleResolver import WikidataTitleResolver class TLDResolver(WikidataTitleResolver): """Resolves a flag image from a country-code top level domain (e.g. '.de').""" def get_flag(self, tld): # Call base class get_flag method return super(TLDResolver, self).get_flag(tld) def normalize(self, tld): tld = tld.lower() # add dot if missing if tld[0] != '.': tld = '.{0}'.format(tld) return tld
python
12
0.594074
82
24
26
starcoderdata
@Test public void testOpInt2FloatBigIntegerInt() { FloatFormat ff = new FloatFormat(4); BigInteger limit = BigInteger.ONE.shiftLeft(32); BigInteger result = ff.opInt2Float(BigInteger.valueOf(2), 4, true); assertTrue(result.compareTo(limit) < 0);// verify that only 4-bytes are used Assert.assertEquals(BigDecimal.valueOf(2.0d).stripTrailingZeros(), ff.getHostFloat(result)); result = ff.opInt2Float(BigInteger.valueOf(-2), 4, true); assertTrue(result.compareTo(limit) < 0);// verify that only 4-bytes are used Assert.assertEquals(BigDecimal.valueOf(-2.0d).stripTrailingZeros(), ff.getHostFloat(result)); result = ff.opInt2Float(BigInteger.ZERO, 4, true); assertTrue(result.compareTo(limit) < 0);// verify that only 4-bytes are used Assert.assertEquals(BigDecimal.ZERO, ff.getHostFloat(result)); }
java
10
0.748489
94
42.578947
19
inline
Ember.GoogleAnalyticsTrackingMixin = Ember.Mixin.create({ pageHasGa: function() { return window.ga && typeof window.ga === "function"; }, logTrackingEnabled: function() { return !!window.ENV && !!window.ENV.LOG_EVENT_TRACKING; }, logTracking: function() { Ember.Logger.info('Tracking Google Analytics event: ', arguments); }, trackPageView: function(page) { if (this.pageHasGa()) { if (!page) { var loc = window.location; page = loc.hash ? loc.hash.substring(1) : loc.pathname + loc.search; } ga('send', 'pageview', page); } if (this.logTrackingEnabled()) { this.logTracking('pageview', page); } }, trackEvent: function(category, action, label, value) { if (this.pageHasGa()) { ga('send', 'event', category, action, label, value); } if (this.logTrackingEnabled()) { this.logTracking('event', category, action, label, value); } } }); Ember.Application.initializer({ name: "googleAnalytics", initialize: function(container, application) { var router = container.lookup('router:main'); router.on('didTransition', function() { Ember.run.once(this, function() { this.trackPageView(this.get('url')); }); }); } }); Ember.Router.reopen(Ember.GoogleAnalyticsTrackingMixin);
javascript
24
0.625471
76
25.019608
51
starcoderdata
const { gql } = require("apollo-server-koa"); const paginationTypes = gql` input PagerInput { afterId: ID sortBy: String direction: Int pageSize: Int } type Page { afterId: ID sortBy: String direction: Int pageSize: Int } type Pagination { totalCount: Int prevPage: Page nextPage: Page } `; module.exports = paginationTypes;
javascript
6
0.632813
45
14.4
25
starcoderdata
module.exports = { nrwa: { brandName: 'National Rural Water Association', headerSrc: '/files/base/roguemonkeymedia/all/image/static/nrwa/RuralWaterWire-1200x454.png', logoSrc: '/files/base/roguemonkeymedia/all/image/static/nrwa/rural-water-wire-logo-white.png', advertiseLink: 'https://content.nrwa.org/page/advertise', contactUsLink: 'https://content.nrwa.org/page/contact-us', bgColor: '#3856a6', socialMedia: { imagePath: '/files/base/roguemonkeymedia/all/image/static/nrwa/newsletter/', links: [ { provider: 'facebook', href: 'https://www.facebook.com/NationalRuralWaterAssociation/', target: '_blank' }, { provider: 'twitter', href: 'https://twitter.com/NRWA', target: '_blank' }, { provider: 'linkedin', href: 'https://www.linkedin.com/company/national-rural-water-associaiton/', target: '_blank' }, ], }, }, };
javascript
13
0.672991
127
48.777778
18
starcoderdata
/* Object elements retrieval */ var polyfill = require('./lib/polyfill'), check = require('./lib/check'), properties = require('./lib/properties'), general = require('./lib/general'), trigonometry = require('./lib/trigonometry'), mean = require('./lib/mean'), distance = require('./lib/distance'), conversion = require('./lib/conversion'), extra = require('./lib/extra'); /* Object elements retrieval end */ /* Object composition */ var Mathp = {}; var importFunctions = function (obj, properties) { "use strict"; var key, i; properties = properties || Object.keys(obj); for (i = 0; i < properties.length; i++) { key = properties[i]; if (obj.hasOwnProperty(key) && !Mathp.hasOwnProperty(key)) { if (typeof obj[key] === 'function') { Mathp[key] = obj[key].bind(Mathp); } else { Object.defineProperty(Mathp, key, { enumerable: true, writable: false, value: obj[key] }); } } } }; var mathProperties = [ 'E', 'PI', 'LN2', 'LN10', 'LOG2E', 'LOG10E', 'SQRT1_2', 'SQRT2', 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'atan2', 'cbrt', 'ceil', 'clz32', 'cos', 'cosh', 'exp', 'floor', 'fround', 'hypot', 'imul', 'log', 'log1p', 'log10', 'log2', 'max', 'min', 'pow', 'random', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc' ]; importFunctions(Math, mathProperties); importFunctions(polyfill); importFunctions(check); importFunctions(properties); importFunctions(general); importFunctions(trigonometry); importFunctions(mean); importFunctions(distance); importFunctions(conversion); importFunctions(extra); /* Object composition end */ module.exports = Mathp;
javascript
12
0.57709
76
27.338462
65
starcoderdata
package ca.ulaval.glo2003.locations.exceptions; public abstract class LocationException extends RuntimeException { public LocationException(String message) { super(message); } }
java
7
0.78
66
21.222222
9
starcoderdata
<?php /* * This file is part of the Symfony package. * * (c) * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Messenger\Asynchronous\Routing; use Symfony\Component\Messenger\Exception\RuntimeException; use Symfony\Component\Messenger\Transport\SenderInterface; /** * @author */ class SenderLocator extends AbstractSenderLocator { private $messageToSenderMapping; public function __construct(array $messageToSenderMapping) { $this->messageToSenderMapping = $messageToSenderMapping; } /** * {@inheritdoc} */ public function getSenderForMessage($message): ?SenderInterface { $sender = self::getValueFromMessageRouting($this->messageToSenderMapping, $message); if (null === $sender) { return null; } if (!$sender instanceof SenderInterface) { throw new RuntimeException(sprintf('The sender instance provided for message "%s" should be of type "%s" but got "%s".', \get_class($message), SenderInterface::class, \is_object($sender) ? \get_class($sender) : \gettype($sender))); } return $sender; } }
php
20
0.685103
243
28.478261
46
starcoderdata
""" a context to get codes' executing time""" import datetime from contextlib import contextmanager @contextmanager def code_timer(msg: str="code execute time: ", show_start=False) -> datetime.time: """"a context function to count code executing time""" start = datetime.datetime.now() if show_start: print(msg + ' start running') try: yield datetime.datetime.now finally: end = datetime.datetime.now() print(msg + str(end-start)) # test # import time # with code_timer("sleeping time:"): # time.sleep(65)
python
14
0.656085
82
24.818182
22
starcoderdata
func Source(ctx context.Context, pkgs []*vulncheck.Package, c client.Client) (*vulncheck.Result, error) { r, err := vulncheck.Source(ctx, pkgs, &vulncheck.Config{Client: c}) if err != nil { return nil, err } // Keep only the vulns that are called. var vulns []*vulncheck.Vuln for _, v := range r.Vulns { if v.CallSink != 0 { vulns = append(vulns, v) } } r.Vulns = vulns return r, nil }
go
12
0.652605
105
25.933333
15
inline
func (i *ldbOpCacheIterator) GraphOp() (ValueSlice, NomsKind, sequenceItem) { ldbKey := i.iter.Key() ldbVal := i.iter.Value() // skip over 4 bytes of colId and get opKind, and numKeys from bytes 4 & 5 opKind := NomsKind(ldbKey[4]) numKeys := uint8(ldbKey[5]) ldbKey = ldbKey[6:] // Call decodeValue for each encoded graphKey. nil will be appended to // graphKeys for any keys that were encoded as hash digests. graphKeys := ValueSlice{} for pos := uint8(0); pos < numKeys; pos++ { var gk Value ldbKey, gk = decodeValue(ldbKey, false, i.vrw) graphKeys = append(graphKeys, gk) } // Get the number of values whose value was encoded in ldbVal numEncodedValues := uint8(ldbVal[0]) ldbVal = ldbVal[1:] // Call decodeValue for each non-primitive key stored in ldbVal. Replace // the nil value in graphKeys with the new decodedValue. values := ValueSlice{} for pos := uint8(0); pos < numEncodedValues; pos++ { var gk Value ldbVal, gk = decodeValue(ldbVal, true, i.vrw) values = append(values, gk) } // Fold in any non-primitive key values that were stored in ldbVal pos := 0 for idx, k1 := range graphKeys { if k1 == nil { graphKeys[idx] = values[pos] pos++ } } // Remove the last key in graphKeys. The last key in graphKeys is the // mapkey for Maps, the item for Sets, and the index for Lists. key := graphKeys[len(graphKeys)-1] graphKeys = graphKeys[:len(graphKeys)-1] var item sequenceItem switch opKind { case MapKind: val := values[len(values)-1] item = mapEntry{key, val} case SetKind: item = key case ListKind: item = values[len(values)-1] } return graphKeys, opKind, item }
go
11
0.690158
77
27.396552
58
inline
#include "FontFace.h" namespace es { const i16vec2 &FontFace::getSize() { return size; } void FontFace::setThreadSafe(bool set) { threadSafe = set; } }
c++
9
0.727273
88
17.142857
14
starcoderdata
from django.test import TestCase from frontend.models import MeasureValue class MeasureValueManagerTests(TestCase): fixtures = ['one_month_of_measures'] def test_by_ccg_with_no_org(self): mvs = MeasureValue.objects.by_ccg([]) self.assertEqual(len(mvs), 2) def test_by_ccg_with_org(self): mvs = MeasureValue.objects.by_ccg(['04D']) self.assertEqual(len(mvs), 1) def test_by_ccg_with_orgs(self): mvs = MeasureValue.objects.by_ccg(['04D', '02Q']) self.assertEqual(len(mvs), 2) def test_by_ccg_with_measure(self): mvs = MeasureValue.objects.by_ccg([], measure_id='cerazette') self.assertEqual(len(mvs), 2) mvs = MeasureValue.objects.by_ccg([], measure_id='bananas') self.assertEqual(len(mvs), 0) def test_by_ccg_with_tag(self): mvs = MeasureValue.objects.by_ccg([], tags=['core']) self.assertEqual(len(mvs), 2) mvs = MeasureValue.objects.by_ccg([], tags=['lowpriority']) self.assertEqual(len(mvs), 0) def test_by_ccg_with_tags(self): mvs = MeasureValue.objects.by_ccg([], tags=['core', 'lowpriority']) self.assertEqual(len(mvs), 0) def test_by_practice_with_no_org(self): mvs = MeasureValue.objects.by_practice([]) self.assertEqual(len(mvs), 9) def test_by_practice_with_pct_org(self): mvs = MeasureValue.objects.by_practice(['04D']) self.assertEqual(len(mvs), 1) def test_by_practice_with_practice_org(self): mvs = MeasureValue.objects.by_practice(['C83051']) self.assertEqual(len(mvs), 1) def test_by_practice_with_orgs(self): mvs = MeasureValue.objects.by_practice(['C83051', '02Q']) self.assertEqual(len(mvs), 8) def test_by_practice_with_measure(self): mvs = MeasureValue.objects.by_practice( ['C83051'], measure_id='cerazette') self.assertEqual(len(mvs), 1) mvs = MeasureValue.objects.by_practice( ['C83051'], measure_id='bananas') self.assertEqual(len(mvs), 0) def test_by_practice_with_tag(self): mvs = MeasureValue.objects.by_practice(['C83051'], tags=['core']) self.assertEqual(len(mvs), 1) mvs = MeasureValue.objects.by_practice( ['C83051'], tags=['lowpriority']) self.assertEqual(len(mvs), 0) def test_by_practice_with_tags(self): mvs = MeasureValue.objects.by_practice( ['C83051'], tags=['core', 'lowpriority']) self.assertEqual(len(mvs), 0)
python
12
0.618375
75
32.96
75
starcoderdata
from __future__ import absolute_import, division, print_function import tensorflow as tf import numpy as np import os import zipfile def _parse_flat(filename, label): image_string = tf.read_file(filename) image_decoded = tf.image.decode_jpeg(image_string, channels=1) # the image gets decoded in the shape of height,width,channels image_reshaped = tf.reshape(image_decoded, (-1,)) # flatten the tensor image_casted = tf.cast(image_reshaped, tf.float32) # Convert the array to float32 as opposed to uint8 image_casted /= 255 # Convert the pixel values from integers between 0 and 255 to floats between 0 and 1 return image_casted, label def _parse(filename, label): image_string = tf.read_file(filename) image_decoded = tf.image.decode_jpeg(image_string, channels=1) # the image gets decoded in the shape of height,width,channels image_casted = tf.cast(image_decoded, tf.float32) # Convert the array to float32 as opposed to uint8 image_casted /= 255 # Convert the pixel values from integers between 0 and 255 to floats between 0 and 1 return image_casted, label def load_data(image_dir, number_of_outputs=None, flatten=None, batch_size=None, shuffle_size=None, percent_of_test_examples=None): subdirs = [x[1] for x in os.walk(image_dir)][0] label_enums = [] trainFileList = [] trainLabelList = [] testFileList = [] testLabelList = [] if(percent_of_test_examples is None): percent_of_test_examples = 0.1 for subdir in subdirs: files = os.listdir(image_dir+"/"+subdir) files = [image_dir+"/"+subdir+'/'+f for f in files] if(subdir not in label_enums): label_enums.append(subdir) number_of_test_examples = int(percent_of_test_examples * len(files)) trainFiles = files[number_of_test_examples:] trainFileList.extend(trainFiles) trainLabelList.extend([label_enums.index(subdir)]*len(trainFiles)) testFiles = files[:number_of_test_examples] testFileList.extend(testFiles) testLabelList.extend([label_enums.index(subdir)]*len(testFiles)) trainFileList = tf.constant(trainFileList) trainLabelList = tf.keras.utils.to_categorical(trainLabelList, number_of_outputs) # The format of the labels trainLabelList = trainLabelList.astype(np.float32) # Cast the labels to floats train_dataset = tf.data.Dataset.from_tensor_slices((trainFileList, trainLabelList)) testFileList = tf.constant(testFileList) testLabelList = tf.keras.utils.to_categorical(testLabelList, number_of_outputs) # The format of the labels testLabelList = testLabelList.astype(np.float32) # Cast the labels to floats test_dataset = tf.data.Dataset.from_tensor_slices((testFileList, testLabelList)) if(flatten is None): train_dataset = train_dataset.map(_parse) test_dataset = test_dataset.map(_parse) elif(flatten): train_dataset = train_dataset.map(_parse_flat) test_dataset = test_dataset.map(_parse_flat) else: train_dataset = train_dataset.map(_parse) test_dataset = test_dataset.map(_parse) # shuffle if(shuffle_size is not None): train_dataset = train_dataset.shuffle(shuffle_size) # create batch if(batch_size is not None): train_dataset = train_dataset.batch(batch_size) else: train_dataset = train_dataset.batch() test_dataset = test_dataset.batch(len(testLabelList)) return train_dataset, test_dataset def load_one_data(image_dir, number_of_outputs=None, flatten=None): image_set_dir = image_dir[:image_dir.rindex('/')] image_set_dir = image_set_dir[:image_set_dir.rindex('/')] subdirs = [x[1] for x in os.walk(image_set_dir)][0] label_enums = [] testFileList = [] testLabelList = [] for subdir in subdirs: if(subdir not in label_enums): label_enums.append(subdir) label = os.path.split(os.path.dirname(image_dir))[-1] testFileList = tf.constant([image_dir]) testLabelList = tf.keras.utils.to_categorical([label_enums.index(label)], number_of_outputs) # The format of the labels testLabelList = testLabelList.astype(np.float32) # Cast the labels to floats test_dataset = tf.data.Dataset.from_tensor_slices((testFileList, testLabelList)) test_dataset = test_dataset.map(_parse) test_dataset = test_dataset.batch(1) return test_dataset def prepare_data(image_dir): # look for .zip files and unzip them # returns number labels (folders) in the image_dir subdirs = [x[1] for x in os.walk(image_dir)][0] files = [x[2] for x in os.walk(image_dir)][0] zip_files = list(filter(lambda file: file.endswith('.zip'), files)) dirs = set(subdirs) for zip_file in zip_files: if not zip_file[:-4] in dirs: _unzip(zip_file,image_dir) else: print('found ' + zip_file + ' already unzipped') labels = [x[1] for x in os.walk(image_dir)][0] print('labels:', labels) return labels def _unzip(source,image_dir): print('unzipping ' + source) with zipfile.ZipFile(image_dir+"/"+source,"r") as zip_ref: zip_ref.extractall(image_dir+"/"+source[:-4]) return True
python
14
0.69725
130
39.721311
122
starcoderdata
package com.sw.haruka.model.dialog; import android.app.Dialog; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.Nullable; public class LoadingDialog extends Dialog { public LoadingDialog(@NonNull Context context) { super(context); init(context); } public LoadingDialog(@NonNull Context context, int themeResId) { super(context, themeResId); init(context); } protected LoadingDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) { super(context, cancelable, cancelListener); init(context); } private void init(Context context) { setTitle("正在加载..."); } }
java
9
0.69891
118
27.230769
26
starcoderdata
import path from 'path' import fs from 'fs' import glob from 'glob' import yaml from 'js-yaml' import consola from 'consola' import { validate, getValidationError } from './validation' import { websiteScore } from './score' const logger = consola.withTag('password-police:data') function loadYamlFile(filepath) { const data = yaml.safeLoad(fs.readFileSync(filepath, 'utf-8')) const valid = validate(data) if (!valid) { throw new Error( `Invalid YAML file ${filepath}: ${getValidationError(validate)}` ) } data.score = websiteScore(data.policies) return data } function findContent(basepath) { const extension = '.yml' const searchPattern = `{${basepath}/*/,${basepath}/*${extension}}` return glob .sync(searchPattern) .map(filepath => { const isdir = fs.lstatSync(filepath).isDirectory() const name = isdir ? path.basename(filepath) : path.basename(filepath, extension) const content = isdir ? findContent(filepath) : loadYamlFile(path.resolve(__dirname, filepath)) return { name: name, content: content } }) .reduce((obj, item) => { obj[item.name] = item.content return obj }, {}) } function findCategories() { const categoriesPath = path.resolve(__dirname, '.') logger.info(`Finding categories in ${categoriesPath}`) const categories = findContent(categoriesPath) const numCategories = Object.entries(categories).length const numWebsites = Object.entries(categories).reduce( (sum, [k, c]) => sum + Object.entries(c).length, 0 ) logger.success(`${numWebsites} websites found in ${numCategories} categories`) return categories } export default { categories: findCategories() }
javascript
17
0.666477
80
24.463768
69
starcoderdata
#ifndef STATISTICSITEM_H #define STATISTICSITEM_H #include "CoreObject.h" namespace Biz { extern const QString StatisticsKey_LoginSucceed; extern const QString StatisticsKey_LoginFailure; extern const QString StatisticsKey_MessageSent; extern const QString StatisticsKey_OpenDialog; class StatisticsItem : public QObject { Q_OBJECT public: StatisticsItem(const QString& key); ~StatisticsItem(); QString Key() const { return mKey; } int Count() const { return mCount; } void Count(int val) { mCount = val; } void IncCount(); private: QString mKey; int mCount; }; } #endif // STATISTICSITEM_H
c
11
0.664439
52
22.375
32
starcoderdata
/* * Copyright (c) 1991 * * Disclaimer: No guarantees of performance accompany this software, * nor is any responsibility assumed on the part of the authors. All the * software has been tested extensively and every effort has been made to * insure its reliability. */ /* * h_wgauss.c - Window an image with a 2-dimensional Gaussian * * multiplies an input image by a 2-dimensional Gaussian with mean * (rowmu,colmu) and standard deviation (rowsigma,colsigma). The resulting * window has a peak value of factor (allowing one to factor in a temporal * Gaussian). Negative values of either sigma are taken to indicate an * infinite Gaussian (identically 1). * * pixel formats: FLOAT * * - 8/10/91 */ #include #include static double *rowmult,*colmult,saverowsigma,savecolsigma,savecolmu,saverowmu; static int wralloc = FALSE; static int wcalloc = FALSE; static int savenr = -1; static int savenc = -1; int h_wgauss(hdi,hdo,rowmu,colmu,rowsigma,colsigma,factor) struct header *hdi,*hdo; double rowmu,colmu,rowsigma,colsigma,factor; { switch(hdi->pixel_format) { case PFFLOAT: return(h_wgauss_f(hdi,hdo,rowmu,colmu,rowsigma, colsigma,factor)); default: return(perr(HE_FMTSUBR,"h_wgauss", hformatname(hdi->pixel_format))); } } int h_wgauss_f(hdi,hdo,rowmu,colmu,rowsigma,colsigma,factor) struct header *hdi,*hdo; double rowmu,colmu,rowsigma,colsigma,factor; { return(h_wgauss_F((float *) hdi->firstpix,(float *) hdo->firstpix, hdi->rows,hdi->cols,hdi->ocols,hdo->ocols,rowmu,colmu,rowsigma, colsigma,factor)); } int h_wgauss_F(imagei,imageo,nr,nc,nlpi,nlpo,rowmu,colmu,rowsigma,colsigma,factor) float *imagei,*imageo; int nr,nc,nlpi,nlpo; double rowmu,colmu,rowsigma,colsigma,factor; { int i,j,nexi,nexo; double *p,diff,twosigmasq,mult; float *pi,*po; if (wralloc && savenr != nr) { free(rowmult); wralloc = FALSE; } if (!wralloc) { if ((rowmult = (double *) memalloc(nr,sizeof(double))) == (double *) HIPS_ERROR) return(HIPS_ERROR); wralloc = TRUE; savenr = nr; saverowsigma = rowsigma + 1.; /* force computation */ } if (saverowsigma != rowsigma || saverowmu != rowmu) { p = rowmult; if (rowsigma < 0) { for (i=0;i<nr;i++) *p++ = 1.; } else { twosigmasq = 2.*rowsigma*rowsigma; for (i=0;i<nr;i++) { diff = rowmu - i; *p++ = exp(-diff*diff/twosigmasq); } } saverowsigma = rowsigma; saverowmu = rowmu; } if (wcalloc && savenc != nc) { free(colmult); wcalloc = FALSE; } if (!wcalloc) { if ((colmult = (double *) memalloc(nc,sizeof(double))) == (double *) HIPS_ERROR) return(HIPS_ERROR); wcalloc = TRUE; savenc = nc; savecolsigma = colsigma + 1.; /* force computation */ } if (savecolsigma != colsigma || savecolmu != colmu) { p = colmult; if (colsigma < 0) { for (i=0;i<nc;i++) *p++ = 1.; } else { twosigmasq = 2.*colsigma*colsigma; for (i=0;i<nc;i++) { diff = colmu - i; *p++ = exp(-diff*diff/twosigmasq); } } saverowsigma = rowsigma; saverowmu = rowmu; } nexi = nlpi - nc; nexo = nlpo - nc; pi = imagei; po = imageo; for (i=0;i<nr;i++) { mult = factor * rowmult[i]; p = colmult; for (j=0;j<nc;j++) *po++ = *pi++ * *p++ * mult; pi += nexi; po += nexo; } return(HIPS_OK); }
c
17
0.64864
82
22.81295
139
starcoderdata
@Post("json") public Representation store(String jsonIntent) { IPathCalcRuntimeService pathRuntime = (IPathCalcRuntimeService) getContext().getAttributes() .get(IPathCalcRuntimeService.class.getCanonicalName()); // // Extract the Application Intents // ObjectMapper mapper = new ObjectMapper(); ApplicationIntent[] addOperations = null; try { if (jsonIntent != null) { addOperations = mapper.readValue(jsonIntent, ApplicationIntent[].class); } } catch (IOException ex) { log.error("Exception occurred parsing inbound JSON", ex); } if (addOperations == null) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST); final RestError error = RestError.createRestError(RestErrorCode.INTENT_INVALID); return toRepresentation(error, null); } // // Add the intents // if (pathRuntime.addApplicationIntents(APPLICATION_ID, Arrays.asList(addOperations))) { setStatus(Status.SUCCESS_CREATED); } else { setStatus(Status.SERVER_ERROR_INTERNAL); } return toRepresentation(addOperations, null); }
java
14
0.56982
88
35.027027
37
inline
func (c *Client) do(req *http.Request) ([]byte, error) { start := time.Now() res, err := c.client.Do(req) if err != nil { return nil, err } defer res.Body.Close() if c.AfterRequest != nil { c.AfterRequest(c, req, res, time.Since(start)) } if res.StatusCode >= http.StatusOK && res.StatusCode < http.StatusBadRequest { // clear headers so that they will not infect the next request. c.headers = getHeadersMap(c.Options.OrgID) // return the response return ioutil.ReadAll(res.Body) } apiError := parseError(req, res) // return apiError if it is not rate limit error if _, ok := apiError.(RateLimitExceededError); !ok { return nil, apiError } resetHeader := res.Header.Get("x-contentful-ratelimit-reset") // return apiError if Ratelimit-Reset header is not presented if resetHeader == "" { return nil, apiError } // wait X-Contentful-Ratelimit-Reset amount of seconds waitSeconds, err := strconv.Atoi(resetHeader) if err != nil { return nil, apiError } // retry on rate limit time.Sleep(time.Second * time.Duration(waitSeconds)) return c.do(req) }
go
11
0.69287
79
24.465116
43
inline
private IEnumerator LoadAppScene(byte[] bytes) { SetState(State.LoadingAssetBundle); var request = AssetBundle.LoadFromMemoryAsync(bytes); yield return request; var assetBundle = request.assetBundle; ExperienceAppReflectionCache.AssetBundleField.SetValue(null, assetBundle); SetState(State.LoadingScene); // Fetch scene name from the bundle and begin loading it var scenePath = assetBundle.GetAllScenePaths()[0]; SceneManager.LoadSceneAsync(scenePath, LoadSceneMode.Additive); SceneManager.sceneLoaded += OnSceneLoadCompleted; SetState(State.Loaded); IsLoaded = true; }
c#
11
0.641689
86
35.75
20
inline
using System; using System.Collections.Generic; using System.Text; namespace MyPdfGeneratorLambda.Dto { public class PageSetting { public string Size { get; set; } = "A4"; public string Orientation { get; set; } = "縦向き"; public Margin Margin { get; set; } = new Margin() { Top = 0F, Left = 0F, Right = 0F, Bottom = 0F }; } }
c#
10
0.566586
59
23.875
16
starcoderdata
package netflix.karyon.jersey.blocking; import io.netty.buffer.ByteBuf; import netflix.karyon.transport.http.KaryonHttpModule; /** * @author */ public abstract class KaryonJerseyModule extends KaryonHttpModule<ByteBuf, ByteBuf> { public KaryonJerseyModule() { super("karyonJerseyModule", ByteBuf.class, ByteBuf.class); } protected KaryonJerseyModule(String moduleName) { super(moduleName, ByteBuf.class, ByteBuf.class); } @Override protected void configure() { bindRouter().to(JerseyBasedRouter.class); super.configure(); } }
java
9
0.705977
85
23.76
25
starcoderdata
void foo(int numNodes,int numNodes2,int *x,int *nodelist) { int j; for (j = numNodes - 1; j >= 0; j += -1) { if (x[j] <= 0.) { numNodes2--; nodelist[j] = nodelist[numNodes2]; nodelist[numNodes2] = j; } } }
c
10
0.518828
57
18.916667
12
starcoderdata
/* Pour les constantes EXIT_SUCCESS et EXIT_FAILURE */ #include /* Pour fprintf() */ #include /* Pour fork() */ #include /* Pour perror() et errno */ #include /* Pour le type pid_t */ #include /* Pour wait() */ #include /* Pour faire simple, on déclare status en globale à la barbare */ int status; /* La fonction create_process duplique le processus appelant et retourne le PID du processus fils ainsi créé */ pid_t create_process(void) { /* On crée une nouvelle valeur de type pid_t */ pid_t pid; /* On fork() tant que l'erreur est EAGAIN */ do { pid = fork(); } while ((pid == -1) && (errno == EAGAIN)); /* On retourne le PID du processus ainsi créé */ return pid; } /* La fonction child_process effectue les actions du processus fils */ void child_process(void) { printf(" Nous sommes dans le fils !\n" " Le PID du fils est %d.\n" " Le PPID du fils est %d.\n", (int) getpid(), (int) getppid()); } /* La fonction father_process effectue les actions du processus père */ void father_process(int child_pid) { printf(" Nous sommes dans le père !\n" " Le PID du fils est %d.\n" " Le PID du père est %d.\n", (int) child_pid, (int) getpid()); if (wait(&status) == -1) { perror("wait :"); exit(EXIT_FAILURE); } if (WIFEXITED(status)) { printf(" Terminaison normale du processus fils.\n" " Code de retour : %d.\n", WEXITSTATUS(status)); } if (WIFSIGNALED(status)) { printf(" Terminaison anormale du processus fils.\n" " Tué par le signal : %d.\n", WTERMSIG(status)); } } int main(void) { pid_t pid = create_process(); switch (pid) { /* Si on a une erreur irrémédiable (ENOMEM dans notre cas) */ case -1: perror("fork"); return EXIT_FAILURE; break; /* Si on est dans le fils */ case 0: child_process(); break; /* Si on est dans le père */ default: father_process(pid); break; } return EXIT_SUCCESS; }
c
10
0.621622
72
22.816092
87
starcoderdata
void CML::velocityComponentLaplacianFvMotionSolver::solve() { // The points have moved so before interpolation update // the fvMotionSolver accordingly movePoints(fvMesh_.points()); diffusivityPtr_->correct(); pointMotionU_.boundaryField().updateCoeffs(); CML::solve ( fvm::laplacian ( diffusivityPtr_->operator()(), cellMotionU_, "laplacian(diffusivity,cellMotionU)" ) ); }
c++
11
0.617521
59
23.684211
19
inline
package com.fcgl.madrid.stock.repository; import com.fcgl.madrid.stock.model.IArticleBody; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Repository; @Repository public class ArticlesRepository { private HashOperations hashOperations; private RedisTemplate redisTemplate; private final static String LAST_ARTICLE = "LAST"; public ArticlesRepository(RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; this.hashOperations = this.redisTemplate.opsForHash(); } public void put(IArticleBody articleBody) { hashOperations.put(articleBody.getName(), LAST_ARTICLE, articleBody.getArticleUrl()); } public String getLastArticle(String name) { return (String) hashOperations.get(name, LAST_ARTICLE); } }
java
10
0.760943
93
32
27
starcoderdata
<?php namespace AppBundle\Controller; use AppBundle\Datatables\AnalisisServicioDatatable; use AppBundle\Entity\AnalisisServicio; use AppBundle\Entity\AnalisisServicioDetalle; use AppBundle\Entity\AnalisisServicioPeriodo; use AppBundle\Entity\Mes; use AppBundle\Form\PeriodoActualType; use AppBundle\Form\PeriodoType; use DateInterval; use DateTime; use Exception; use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\ResponseHeaderBag; use Symfony\Component\HttpFoundation\Session\Session; use Doctrine\DBAL\Exception\UniqueConstraintViolationException; use Doctrine\DBAL\DBALException; /** * Class AnalisisServicioController * * @package AppBundle\Controller */ class AnalisisServicioController extends Controller { /** * @var Session */ private $sesion; /** * AnalisisServicioController constructor. */ public function __construct() { $this->sesion = new Session(); } /** * @param Request $request * @return JsonResponse|Response * @throws Exception */ public function queryAction(Request $request) { $EntityManager = $this->getDoctrine()->getManager(); $AnalisisServicioAll = $EntityManager->getRepository("AppBundle:AnalisisServicio")->findAll(); return $this->render('analisisServicio/queryAnalisisServicio.html.twig', [ 'AnalisisServicioALL' => $AnalisisServicioAll, ]); } /** * @param $id * @return JsonResponse|Response */ public function queryAnalisisServicioPeriodoAction($id) { $EntityManager = $this->getDoctrine()->getManager(); $AnalisisServicio = $EntityManager->getRepository("AppBundle:AnalisisServicio")->find($id); $AnalisisServicioPeriodoAll = $EntityManager->getRepository("AppBundle:AnalisisServicioPeriodo")->findBy(["analisisServicio" => $AnalisisServicio]); return $this->render('analisisServicio/queryAnalisisServicioPeriodo.html.twig', [ 'AnalisisServicio' => $AnalisisServicio, 'AnalisisServicioAPeriodoAll' => $AnalisisServicioPeriodoAll, ]); } /** * @param $id * @return JsonResponse|Response */ public function queryAnalisisServicioDetalleAction($id) { $EntityManager = $this->getDoctrine()->getManager(); $AnalisisServicioPeriodo = $EntityManager->getRepository("AppBundle:AnalisisServicioPeriodo")->find($id); $AnalisisServicioDetalleAll = $EntityManager->getRepository("AppBundle:AnalisisServicioDetalle")->findBy(["analisisServicioPeriodo" => $AnalisisServicioPeriodo]); return $this->render('analisisServicio/queryAnalisisServicioDetalle.html.twig', [ 'AnalisisServicioPeriodo' => $AnalisisServicioPeriodo, 'AnalisisServicioDetalleAll' => $AnalisisServicioDetalleAll, ]); } /** * @param Request $request * @return Response */ public function addAction(Request $request) { $EntityManager = $this->getDoctrine()->getManager(); $PeriodoActual = $EntityManager->getRepository("AppBundle:PeriodoActual")->find(1); $form = $this->createForm(PeriodoType::class); $form->handleRequest($request); if ($form->isSubmitted()) { return $this->redirectToRoute("queryAnalisisServicio"); } $params = ["periodoActual" => $PeriodoActual, "form" => $form->createView()]; return $this->render("analisisServicio/genera.html.twig", $params); } /** * @param $periodo_id * @return bool */ public function generaAnalisisServicioAction($periodo_id) { $EntityManager = $this->getDoctrine()->getManager(); $TipoObjetoNPL = $EntityManager->getRepository("AppBundle:TipoObjeto")->find(1); /** @var Mes $Periodo */ $Periodo = $EntityManager->getRepository("AppBundle:Mes")->findOneBy(["id" => $periodo_id]); $AnalisisServicio = $EntityManager->getRepository("AppBundle:AnalisisServicio")->findOneBy(["mes" => $Periodo]); if ($AnalisisServicio) { $EntityManager->remove($AnalisisServicio); } $AplicacionAll = $EntityManager->getRepository("AppBundle:Aplicacion")->findAll(); $ObjetosEncargoAll = $EntityManager->getRepository("AppBundle:ObjetoEncargo") ->findBy(["tipoObjeto" => $TipoObjetoNPL]); // $CriticidadAll = $EntityManager->getRepository("AppBundle:Criticidad")->findAll(); $CriticidadNormal = $EntityManager->getRepository("AppBundle:Criticidad")->find(1); $fechaInicial = $Periodo->getFechaInicio(); $fechaFinal = $Periodo->getFechaFin(); $conection = $this->getDoctrine()->getConnection(); $sentenciaEntradas = " select ifnull(count(*),0) as entradas " . " from view_encargos_npl_total " . " where date_format(fechaRegistro,'%Y-%m-%d') = :fecha " . " and aplicacionId = :aplicacionId " . " and criticidadId = :criticidadId " . " and objetoEncargoId = :objetoEncargoId "; $sentenciaCancelados = " select ifnull(count(*),0) as cancelados " . " from view_encargos_npl_total " . " where date_format(fechaEstadoActual,'%Y-%m-%d') = :fecha " . " and aplicacionId = :aplicacionId " . " and criticidadId = :criticidadId " . " and objetoEncargoId = :objetoEncargoId " . " and estadoEncargoCd = 'CAN' "; $sentenciaCerrados = " select ifnull(count(*),0) as cerrados ," . " ifnull(avg(horasRealizadas),0) as esfuerzoMedio," . " ifnull(sum(horasRealizadas),0) as esfuerzoTotal," . " ifnull(avg(tiempoResolucion/3600000,0) as tiempoMedioResolucion," . " ifnull(sum(tiempoResolucion/3600000),0) as tiempoTotalResolucion" . " from view_encargos_npl_total " . " where date_format(fechaEntrega,'%Y-%m-%d') = :fecha " . " and aplicacionId = :aplicacionId " . " and criticidadId = :criticidadId " . " and objetoEncargoId = :objetoEncargoId " . " and estadoEncargoCd = 'CRR'"; // Se recorre desde la fecha de inicio a la fecha fin, incrementando en 1 dia /** @var DateTime $midia */ $fechaInicio = clone $Periodo->getFechaInicio(); $fechaFin = clone $Periodo->getFechaFin(); $AnalisisServicio = new AnalisisServicio(); $AnalisisServicio->setMes($Periodo); $EntityManager->persist($AnalisisServicio); $EntityManager->flush(); $Contador2 = []; $Contador2["entradas"] = 0; $Contador2["cancelados"] = 0; $Contador2["cerrados"] = 0; $Contador2["esfuerzoTotal"] = 0; $Contador2["tiempoTotalResolucion"] = 0; foreach ($AplicacionAll as $Aplicacion) { foreach ($ObjetosEncargoAll as $ObjetoEncargo) { $AnalisisServicioPeridodo = new AnalisisServicioPeriodo(); $AnalisisServicioPeridodo->setAnalisisServicio($AnalisisServicio); $AnalisisServicioPeridodo->setAplicacion($Aplicacion); $AnalisisServicioPeridodo->setObjetoEncargo($ObjetoEncargo); $AnalisisServicioPeridodo->setCriticidad($CriticidadNormal); $EntityManager->persist($AnalisisServicioPeridodo); $EntityManager->flush(); $Contador = []; $Contador["entradas"] = 0; $Contador["cancelados"] = 0; $Contador["cerrados"] = 0; $Contador["esfuerzoTotal"] = 0; $Contador["tiempoTotalResolucion"] = 0; $fechaInicio = clone $Periodo->getFechaInicio(); $fechaFin = clone $Periodo->getFechaFin(); for ($midia = $fechaInicio; $midia <= $fechaFin; $midia->add(new DateInterval('P1D'))) { $AnalisisServicioDetalle = new AnalisisServicioDetalle(); $AnalisisServicioDetalle->setAnalisisServicioPeriodo($AnalisisServicioPeridodo); $AnalisisServicioDetalle->setFecha($midia); $EntityManager->persist($AnalisisServicioDetalle); $EntityManager->flush(); /** * ENTRADAS */ $params = [":fecha" => $midia->format('Y-m-d'), ":aplicacionId" => $Aplicacion->getId(), ":objetoEncargoId" => $ObjetoEncargo->getId(), ":criticidadId" => $CriticidadNormal->getId()]; $stmt = $conection->prepare($sentenciaEntradas); $stmt->execute($params); $EntradasDia = $stmt->fetch(); /** * CANCELADOS */ $stmt = $conection->prepare($sentenciaCancelados); $stmt->execute($params); $Cancelados = $stmt->fetch(); /** * CERRADOS */ $stmt = $conection->prepare($sentenciaCerrados); $stmt->execute($params); $Cerrados = $stmt->fetch(); $AnalisisServicioDetalle->setTotalEntradas($EntradasDia["entradas"]); $AnalisisServicioDetalle->setTotalCancelados($Cancelados["cancelados"]); $AnalisisServicioDetalle->setTotalCerrados($Cerrados["cerrados"]); $saldo = $EntradasDia["entradas"] - ($Cancelados["cancelados"] + $Cerrados["cerrados"]); $AnalisisServicioDetalle->setSaldo($saldo); $AnalisisServicioDetalle->setEsfuerzoTotal($Cerrados["esfuerzoTotal"]); $AnalisisServicioDetalle->setEsfuerzoMedio($Cerrados["esfuerzoMedio"]); $AnalisisServicioDetalle->setTiempoTotalResolucion($Cerrados["tiempoTotalResolucion"]); $AnalisisServicioDetalle->setTiempoMedioResolucion($Cerrados["tiempoMedioResolucion"]); $EntityManager->persist($AnalisisServicioDetalle); $EntityManager->flush(); $Contador["entradas"] = $Contador["entradas"] + $AnalisisServicioDetalle->getTotalEntradas(); $Contador["cancelados"] = $Contador["cancelados"] + $AnalisisServicioDetalle->getTotalCancelados(); $Contador["cerrados"] = $Contador["cerrados"] + $AnalisisServicioDetalle->getTotalCerrados(); $Contador["esfuerzoTotal"] = $Contador["esfuerzoTotal"] + $AnalisisServicioDetalle->getEsfuerzoTotal(); $Contador["tiempoTotalResolucion"] = $Contador["tiempoTotalResolucion"] + $AnalisisServicioDetalle->getTiempoTotalResolucion(); } $AnalisisServicioPeridodo->setTotalEntradas($Contador["entradas"]); $AnalisisServicioPeridodo->setTotalCerrados($Contador["cerrados"]); $AnalisisServicioPeridodo->setTotalCancelados($Contador["cancelados"]); $saldo = $Contador["entradas"] - ($Contador["cancelados"] + $Contador["cerrados"]); $AnalisisServicioPeridodo->setSaldo($saldo); $Contador["cerrados"] > 0 ? $esfuerzoMedio = $Contador["esfuerzoTotal"] / $Contador["cerrados"] : $esfuerzoMedio = 0; $AnalisisServicioPeridodo->setEsfuerzoMedio($esfuerzoMedio); $AnalisisServicioPeridodo->setEsfuerzoTotal($Contador["esfuerzoTotal"]); $Contador["cerrados"] > 0 ? $tiempoMedioResolucion = $Contador["tiempoTotalResolucion"] / $Contador["cerrados"] : $tiempoMedioResolucion = 0; $AnalisisServicioPeridodo->setTiempoTotalResolucion($Contador["tiempoTotalResolucion"]); $AnalisisServicioPeridodo->setTiempoMedioResolucion($tiempoMedioResolucion); $EntityManager->persist($AnalisisServicioPeridodo); $EntityManager->flush(); $Contador2["entradas"] = $Contador2["entradas"] + $AnalisisServicioPeridodo->getTotalEntradas(); $Contador2["cancelados"] = $Contador2["cancelados"] + $AnalisisServicioPeridodo->getTotalCancelados(); $Contador2["cerrados"] = $Contador2["cerrados"] + $AnalisisServicioPeridodo->getTotalCerrados(); $Contador2["esfuerzoTotal"] = $Contador2["esfuerzoTotal"] + $AnalisisServicioPeridodo->getEsfuerzoTotal(); $Contador2["tiempoTotalResolucion"] = $Contador2["tiempoTotalResolucion"] + $AnalisisServicioPeridodo->getTiempoTotalResolucion(); } } $AnalisisServicio->setTotalEntradas($Contador2["entradas"]); $AnalisisServicio->setTotalCerrados($Contador2["cerrados"]); $AnalisisServicio->setTotalCancelados($Contador2["cancelados"]); $saldo = $Contador2["entradas"] - ($Contador2["cancelados"] + $Contador2["cerrados"]); $AnalisisServicio->setSaldo($saldo); $Contador2["cerrados"] > 0 ? $esfuerzoMedio = $Contador2["esfuerzoTotal"] / $Contador2["cerrados"] : $esfuerzoMedio = 0; $AnalisisServicio->setEsfuerzoMedio($esfuerzoMedio); $AnalisisServicio->setEsfuerzoTotal($Contador2["esfuerzoTotal"]); $Contador2["cerrados"] > 0 ? $tiempoMedioResolucion = $Contador2["tiempoTotalResolucion"] / $Contador2["cerrados"] : $tiempoMedioResolucion = 0; $AnalisisServicio->setTiempoTotalResolucion($Contador2["tiempoTotalResolucion"]); $AnalisisServicio->setTiempoMedioResolucion($tiempoMedioResolucion); $EntityManager->persist($AnalisisServicio); $EntityManager->flush(); return new Response(); } }
php
19
0.726536
164
41.546075
293
starcoderdata
/** * extract-selectors * https://github.com/cedaro/extract-selectors * * @copyright Copyright (c) 2017 Cedaro, LLC * @license MIT */ 'use strict'; var postcss = require('postcss'); module.exports = postcss.plugin('extract-selectors', function(opts) { opts = opts || {}; var propFilter = opts.prop || ''; var valueFilter = opts.value || ''; return function (css, result) { var selectorMapping = {}; css.walkDecls(propFilter, function (decl) { var value = decl.value; if ('' === valueFilter || value === valueFilter) { selectorMapping[value] = selectorMapping[value] || []; selectorMapping[value].push(decl.parent.selector); } }); result.root = postcss.root(); Object.keys(selectorMapping).forEach(function(value) { var selectors = selectorMapping[value]; var decl = postcss.decl({ prop: propFilter, value: value, raws: { before: '\n\t' } }); var rule = postcss.rule({ selector: selectors.join(',\n'), raws: { before: '\n\n', semicolon: true } }).append(decl); result.root.append(rule); }); }; });
javascript
26
0.565397
69
21.37037
54
starcoderdata
#include <iostream> #include <string> using namespace std; int const NMAX = 6; char v[1 + NMAX][1 + NMAX]; int k, n, m; bool kExact(int l, int c){ int ans = 0; for(int i = 1;i <= n;i++){ int cl = c; for(int j = 1;j <= m;j++){ if(v[i][j] == '#' && !(l % 2 == 1 || cl % 2 == 1)){ ans++; } cl /= 2; } l /= 2; } return (ans == k); } int main() { int ans = 0, tCol, tLin; cin >> n >> m >> k; for(int i = 1;i <= n;i++){ for(int j = 1;j <= m;j++){ cin >> v[i][j]; } } tLin = 1 << n; tCol = 1 << m; for(int i = 0;i < tLin;i++){ for(int j = 0;j < tCol;j++){ if(kExact(i, j) == true){ ans++; } } } cout << ans; return 0; }
c++
15
0.395349
57
14.891304
46
codenet