max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
4,772 | package example.service;
import example.repo.Customer1707Repository;
import org.springframework.stereotype.Service;
@Service
public class Customer1707Service {
public Customer1707Service(Customer1707Repository repo) {}
}
| 64 |
3,066 | <reponame>0mp/musikcube<gh_stars>1000+
// MSX computer KSS music file emulator
// Game_Music_Emu $vers
#ifndef KSS_EMU_H
#define KSS_EMU_H
#include "Classic_Emu.h"
#include "Kss_Core.h"
#include "Kss_Scc_Apu.h"
#include "Sms_Apu.h"
#include "Ay_Apu.h"
#include "Opl_Apu.h"
class Kss_Emu : public Classic_Emu {
public:
// KSS file header (see Kss_Core.h)
typedef Kss_Core::header_t header_t;
// Header for currently loaded file
header_t const& header() const { return core.header(); }
blargg_err_t hash_( Hash_Function& ) const;
static gme_type_t static_type() { return gme_kss_type; }
// Implementation
public:
Kss_Emu();
~Kss_Emu();
protected:
virtual blargg_err_t track_info_( track_info_t*, int track ) const;
virtual blargg_err_t load_( Data_Reader& );
virtual blargg_err_t start_track_( int );
virtual blargg_err_t run_clocks( blip_time_t&, int );
virtual void set_tempo_( double );
virtual void set_voice( int, Blip_Buffer*, Blip_Buffer*, Blip_Buffer* );
virtual void update_eq( blip_eq_t const& );
virtual void unload();
private:
struct Core;
friend struct Core;
struct Core : Kss_Core {
Kss_Emu& emu;
// detection of tunes that use SCC so they can be made louder
bool scc_accessed;
enum { scc_enabled_true = 0xC000 };
unsigned scc_enabled; // 0 or 0xC000
int ay_latch;
struct {
Sms_Apu* psg;
Opl_Apu* fm;
} sms;
struct {
Ay_Apu* psg;
Scc_Apu* scc;
Opl_Apu* music;
Opl_Apu* audio;
} msx;
Core( Kss_Emu* e ) : emu( *e ) { }
virtual void cpu_write( addr_t, int );
virtual int cpu_in( time_t, addr_t );
virtual void cpu_out( time_t, addr_t, int );
virtual void update_gain();
void cpu_write_( addr_t addr, int data );
void update_gain_();
void unload();
} core;
};
#endif
| 781 |
3,172 | # Copyright (c) 2021 PaddlePaddle Authors. 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.
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import parl
class MujocoModel(parl.Model):
def __init__(self, obs_dim, act_dim):
super(MujocoModel, self).__init__()
hid1_size = 256
hid2_size = 256
value1 = np.sqrt(1.0 / obs_dim)
value2 = np.sqrt(1.0 / hid1_size)
value3 = np.sqrt(1.0 / hid2_size)
param_attr1 = paddle.framework.ParamAttr(
initializer=paddle.nn.initializer.Uniform(
low=-value1, high=value1))
param_attr2 = paddle.framework.ParamAttr(
initializer=paddle.nn.initializer.Uniform(
low=-value2, high=value2))
param_attr3 = paddle.framework.ParamAttr(
initializer=paddle.nn.initializer.Uniform(
low=-value3, high=value3))
self.fc1 = nn.Linear(
obs_dim, hid1_size, weight_attr=param_attr1, bias_attr=param_attr1)
self.fc2 = nn.Linear(
hid1_size,
hid2_size,
weight_attr=param_attr2,
bias_attr=param_attr2)
self.fc3 = nn.Linear(
hid2_size, act_dim, weight_attr=param_attr3, bias_attr=param_attr3)
def forward(self, obs):
hid1 = F.tanh(self.fc1(obs))
hid2 = F.tanh(self.fc2(hid1))
means = self.fc3(hid2)
return means
| 863 |
866 | <reponame>pablo0722/Commitizen-<gh_stars>100-1000
__version__ = "2.20.0"
| 34 |
1,615 | <filename>MLN-Android/mmui/src/main/java/com/immomo/mmui/ui/LuaScrollViewContainer.java<gh_stars>1000+
/**
* Created by MomoLuaNative.
* Copyright (c) 2020, Momo Group. All rights reserved.
*
* This source code is licensed under the MIT.
* For the full copyright and license information,please view the LICENSE file in the root directory of this source tree.
*/
package com.immomo.mmui.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewGroup;
import com.immomo.mls.fun.other.Point;
import com.immomo.mls.fun.other.Size;
import com.immomo.mls.fun.weight.BorderRadiusFrameLayout;
import com.immomo.mls.util.LuaViewUtil;
import com.immomo.mmui.gesture.ArgoTouchLink;
import com.immomo.mmui.gesture.ICompose;
import com.immomo.mmui.ud.UDScrollView;
import com.immomo.mmui.weight.layout.NodeLayout;
/**
* Created by zhang.ke
* 圆角切割,引起ScrollView屏幕外部分,不显示。
* 用FrameLayout包裹解决
* on 2019/9/29
*/
public class LuaScrollViewContainer extends BorderRadiusFrameLayout implements IScrollView<UDScrollView>, ICompose {
private final UDScrollView userdata;
private ViewLifeCycleCallback cycleCallback;
private IScrollView iScrollView;
private ArgoTouchLink touchLink = new ArgoTouchLink();
public LuaScrollViewContainer(Context context, UDScrollView userdata) {
super(context);
this.userdata = userdata;
setViewLifeCycleCallback(userdata);
}
public void init(boolean vertical, boolean same, AttributeSet attributeSet) {
if (vertical) {
iScrollView = new LuaVerticalScrollView(getContext(), userdata, same, attributeSet);
} else {
iScrollView = new LuaHorizontalScrollView(getContext(), userdata, same);
}
addView(iScrollView.getScrollView(), LuaViewUtil.createRelativeLayoutParamsMM());
// 处理组合控件
touchLink.setHead(this);
touchLink.addChild(iScrollView.getScrollView());
}
@Override
public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
super.setHorizontalScrollBarEnabled(horizontalScrollBarEnabled);
iScrollView.setHorizontalScrollBarEnabled(horizontalScrollBarEnabled);
}
@Override
public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
super.setVerticalScrollBarEnabled(verticalScrollBarEnabled);
iScrollView.setVerticalScrollBarEnabled(verticalScrollBarEnabled);
}
@Override
public UDScrollView getUserdata() {
return userdata;
}
@Override
public void setViewLifeCycleCallback(ViewLifeCycleCallback cycleCallback) {
this.cycleCallback = cycleCallback;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (cycleCallback != null) {
cycleCallback.onAttached();
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (cycleCallback != null) {
cycleCallback.onDetached();
}
}
@Override
public void setContentSize(Size size) {
iScrollView.setContentSize(size);
}
@Override
public NodeLayout getContentView() {
return iScrollView.getContentView();
}
@Override
public Size getContentSize() {
return iScrollView.getContentSize();
}
@Override
public ViewGroup getScrollView() {
return iScrollView.getScrollView();
}
@Override
public void setContentOffset(Point p) {
iScrollView.setContentOffset(p);
}
@Override
public void setScrollEnable(boolean scrollEnable) {
iScrollView.setScrollEnable(scrollEnable);
}
@Override
public void setOffsetWithAnim(Point p) {
iScrollView.setOffsetWithAnim(p);
}
@Override
public Point getContentOffset() {
return iScrollView.getContentOffset();
}
@Override
public void setOnScrollListener(OnScrollListener l) {
iScrollView.setOnScrollListener(l);
}
@Override
public void setTouchActionListener(touchActionListener l) {
iScrollView.setTouchActionListener(l);
}
@Override
public void setFlingListener(FlingListener flingListener) {
iScrollView.setFlingListener(flingListener);
}
@Override
public void setFlingSpeed(float speed) {
iScrollView.setFlingSpeed(speed);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return isEnabled() && super.dispatchTouchEvent(ev);
}
@Override
public ArgoTouchLink getTouchLink() {
return touchLink;
}
} | 1,777 |
60,067 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <immintrin.h>
#include <qnnpack/q8dwconv.h>
void pytorch_q8dwconv_ukernel_mp8x25__sse2(
size_t channels,
size_t output_width,
const uint8_t** input,
const void* weights,
int32_t* outacc32,
uint8_t* output,
size_t input_stride,
size_t output_increment,
const union pytorch_qnnp_conv_quantization_params
quantization_params[RESTRICT_STATIC 1]) {
const __m128i vinput_zero_point = _mm_load_si128(
(const __m128i*)quantization_params->sse2.input_zero_point);
const __m128i vkernel_zero_point = _mm_set1_epi16(
quantization_params->sse2.kernel_zero_points[0]);
const __m128i vzero = _mm_setzero_si128();
do {
int32_t* outacc = outacc32;
const void* w = weights;
{
const uint8_t* i00 = input[0];
const uint8_t* i01 = input[1];
const uint8_t* i02 = input[2];
const uint8_t* i10 = input[3];
const uint8_t* i11 = input[4];
const uint8_t* i12 = input[5];
const uint8_t* i20 = input[6];
const uint8_t* i21 = input[7];
const uint8_t* i22 = input[8];
const uint8_t* i23 = input[9];
size_t c = channels;
for (; c >= 8; c -= 8) {
__m128i vacc_lo = _mm_loadu_si128((const __m128i*)w);
__m128i vacc_hi = _mm_loadu_si128((const __m128i*)((uintptr_t)w + 16));
const __m128i vi00 = _mm_loadl_epi64((const __m128i*)i00);
i00 += 8;
const __m128i vxi00 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi00, vzero), vinput_zero_point);
const __m128i vk00 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 32));
const __m128i vxk00 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk00, vzero), vkernel_zero_point);
const __m128i vprod00_odd = _mm_mullo_epi16(vxi00, vxk00);
const __m128i vprod00_even = _mm_mulhi_epi16(vxi00, vxk00);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod00_odd, vprod00_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod00_odd, vprod00_even));
const __m128i vi01 = _mm_loadl_epi64((const __m128i*)i01);
i01 += 8;
const __m128i vxi01 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi01, vzero), vinput_zero_point);
const __m128i vk01 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 40));
const __m128i vxk01 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk01, vzero), vkernel_zero_point);
const __m128i vprod01_odd = _mm_mullo_epi16(vxi01, vxk01);
const __m128i vprod01_even = _mm_mulhi_epi16(vxi01, vxk01);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod01_odd, vprod01_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod01_odd, vprod01_even));
const __m128i vi02 = _mm_loadl_epi64((const __m128i*)i02);
i02 += 8;
const __m128i vxi02 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi02, vzero), vinput_zero_point);
const __m128i vk02 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 48));
const __m128i vxk02 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk02, vzero), vkernel_zero_point);
const __m128i vprod02_odd = _mm_mullo_epi16(vxi02, vxk02);
const __m128i vprod02_even = _mm_mulhi_epi16(vxi02, vxk02);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod02_odd, vprod02_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod02_odd, vprod02_even));
const __m128i vi10 = _mm_loadl_epi64((const __m128i*)i10);
i10 += 8;
const __m128i vxi10 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi10, vzero), vinput_zero_point);
const __m128i vk10 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 56));
const __m128i vxk10 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk10, vzero), vkernel_zero_point);
const __m128i vprod10_odd = _mm_mullo_epi16(vxi10, vxk10);
const __m128i vprod10_even = _mm_mulhi_epi16(vxi10, vxk10);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod10_odd, vprod10_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod10_odd, vprod10_even));
const __m128i vi11 = _mm_loadl_epi64((const __m128i*)i11);
i11 += 8;
const __m128i vxi11 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi11, vzero), vinput_zero_point);
const __m128i vk11 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 64));
const __m128i vxk11 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk11, vzero), vkernel_zero_point);
const __m128i vprod11_odd = _mm_mullo_epi16(vxi11, vxk11);
const __m128i vprod11_even = _mm_mulhi_epi16(vxi11, vxk11);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod11_odd, vprod11_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod11_odd, vprod11_even));
const __m128i vi12 = _mm_loadl_epi64((const __m128i*)i12);
i12 += 8;
const __m128i vxi12 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi12, vzero), vinput_zero_point);
const __m128i vk12 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 72));
const __m128i vxk12 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk12, vzero), vkernel_zero_point);
const __m128i vprod12_odd = _mm_mullo_epi16(vxi12, vxk12);
const __m128i vprod12_even = _mm_mulhi_epi16(vxi12, vxk12);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod12_odd, vprod12_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod12_odd, vprod12_even));
const __m128i vi20 = _mm_loadl_epi64((const __m128i*)i20);
i20 += 8;
const __m128i vxi20 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi20, vzero), vinput_zero_point);
const __m128i vk20 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 80));
const __m128i vxk20 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk20, vzero), vkernel_zero_point);
const __m128i vprod20_odd = _mm_mullo_epi16(vxi20, vxk20);
const __m128i vprod20_even = _mm_mulhi_epi16(vxi20, vxk20);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod20_odd, vprod20_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod20_odd, vprod20_even));
const __m128i vi21 = _mm_loadl_epi64((const __m128i*)i21);
i21 += 8;
const __m128i vxi21 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi21, vzero), vinput_zero_point);
const __m128i vk21 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 88));
const __m128i vxk21 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk21, vzero), vkernel_zero_point);
const __m128i vprod21_odd = _mm_mullo_epi16(vxi21, vxk21);
const __m128i vprod21_even = _mm_mulhi_epi16(vxi21, vxk21);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod21_odd, vprod21_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod21_odd, vprod21_even));
const __m128i vi22 = _mm_loadl_epi64((const __m128i*)i22);
i22 += 8;
const __m128i vxi22 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi22, vzero), vinput_zero_point);
const __m128i vk22 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 96));
const __m128i vxk22 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk22, vzero), vkernel_zero_point);
const __m128i vprod22_odd = _mm_mullo_epi16(vxi22, vxk22);
const __m128i vprod22_even = _mm_mulhi_epi16(vxi22, vxk22);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod22_odd, vprod22_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod22_odd, vprod22_even));
const __m128i vi23 = _mm_loadl_epi64((const __m128i*)i23);
i23 += 8;
const __m128i vxi23 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi23, vzero), vinput_zero_point);
const __m128i vk23 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 104));
const __m128i vxk23 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk23, vzero), vkernel_zero_point);
const __m128i vprod23_odd = _mm_mullo_epi16(vxi23, vxk23);
const __m128i vprod23_even = _mm_mulhi_epi16(vxi23, vxk23);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod23_odd, vprod23_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod23_odd, vprod23_even));
w = (const void*)((uintptr_t)w + 112);
_mm_storeu_si128((__m128i*)outacc, vacc_lo);
outacc += 4;
_mm_storeu_si128((__m128i*)outacc, vacc_hi);
outacc += 4;
}
if (c != 0) {
const size_t i_predecrement = 8 - c;
const __m128i vi_shift = _mm_cvtsi32_si128(8 * i_predecrement);
i00 -= i_predecrement;
i01 -= i_predecrement;
i02 -= i_predecrement;
i10 -= i_predecrement;
i11 -= i_predecrement;
i12 -= i_predecrement;
i20 -= i_predecrement;
i21 -= i_predecrement;
i22 -= i_predecrement;
i23 -= i_predecrement;
__m128i vacc_lo = _mm_loadu_si128((const __m128i*)w);
__m128i vacc_hi = _mm_loadu_si128((const __m128i*)((uintptr_t)w + 16));
const __m128i vi00 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i00), vi_shift);
const __m128i vxi00 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi00, vzero), vinput_zero_point);
const __m128i vk00 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 32));
const __m128i vxk00 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk00, vzero), vkernel_zero_point);
const __m128i vprod00_odd = _mm_mullo_epi16(vxi00, vxk00);
const __m128i vprod00_even = _mm_mulhi_epi16(vxi00, vxk00);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod00_odd, vprod00_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod00_odd, vprod00_even));
const __m128i vi01 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i01), vi_shift);
const __m128i vxi01 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi01, vzero), vinput_zero_point);
const __m128i vk01 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 40));
const __m128i vxk01 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk01, vzero), vkernel_zero_point);
const __m128i vprod01_odd = _mm_mullo_epi16(vxi01, vxk01);
const __m128i vprod01_even = _mm_mulhi_epi16(vxi01, vxk01);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod01_odd, vprod01_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod01_odd, vprod01_even));
const __m128i vi02 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i02), vi_shift);
const __m128i vxi02 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi02, vzero), vinput_zero_point);
const __m128i vk02 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 48));
const __m128i vxk02 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk02, vzero), vkernel_zero_point);
const __m128i vprod02_odd = _mm_mullo_epi16(vxi02, vxk02);
const __m128i vprod02_even = _mm_mulhi_epi16(vxi02, vxk02);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod02_odd, vprod02_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod02_odd, vprod02_even));
const __m128i vi10 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i10), vi_shift);
const __m128i vxi10 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi10, vzero), vinput_zero_point);
const __m128i vk10 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 56));
const __m128i vxk10 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk10, vzero), vkernel_zero_point);
const __m128i vprod10_odd = _mm_mullo_epi16(vxi10, vxk10);
const __m128i vprod10_even = _mm_mulhi_epi16(vxi10, vxk10);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod10_odd, vprod10_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod10_odd, vprod10_even));
const __m128i vi11 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i11), vi_shift);
const __m128i vxi11 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi11, vzero), vinput_zero_point);
const __m128i vk11 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 64));
const __m128i vxk11 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk11, vzero), vkernel_zero_point);
const __m128i vprod11_odd = _mm_mullo_epi16(vxi11, vxk11);
const __m128i vprod11_even = _mm_mulhi_epi16(vxi11, vxk11);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod11_odd, vprod11_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod11_odd, vprod11_even));
const __m128i vi12 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i12), vi_shift);
const __m128i vxi12 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi12, vzero), vinput_zero_point);
const __m128i vk12 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 72));
const __m128i vxk12 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk12, vzero), vkernel_zero_point);
const __m128i vprod12_odd = _mm_mullo_epi16(vxi12, vxk12);
const __m128i vprod12_even = _mm_mulhi_epi16(vxi12, vxk12);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod12_odd, vprod12_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod12_odd, vprod12_even));
const __m128i vi20 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i20), vi_shift);
const __m128i vxi20 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi20, vzero), vinput_zero_point);
const __m128i vk20 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 80));
const __m128i vxk20 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk20, vzero), vkernel_zero_point);
const __m128i vprod20_odd = _mm_mullo_epi16(vxi20, vxk20);
const __m128i vprod20_even = _mm_mulhi_epi16(vxi20, vxk20);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod20_odd, vprod20_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod20_odd, vprod20_even));
const __m128i vi21 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i21), vi_shift);
const __m128i vxi21 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi21, vzero), vinput_zero_point);
const __m128i vk21 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 88));
const __m128i vxk21 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk21, vzero), vkernel_zero_point);
const __m128i vprod21_odd = _mm_mullo_epi16(vxi21, vxk21);
const __m128i vprod21_even = _mm_mulhi_epi16(vxi21, vxk21);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod21_odd, vprod21_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod21_odd, vprod21_even));
const __m128i vi22 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i22), vi_shift);
const __m128i vxi22 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi22, vzero), vinput_zero_point);
const __m128i vk22 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 96));
const __m128i vxk22 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk22, vzero), vkernel_zero_point);
const __m128i vprod22_odd = _mm_mullo_epi16(vxi22, vxk22);
const __m128i vprod22_even = _mm_mulhi_epi16(vxi22, vxk22);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod22_odd, vprod22_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod22_odd, vprod22_even));
const __m128i vi23 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i23), vi_shift);
const __m128i vxi23 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi23, vzero), vinput_zero_point);
const __m128i vk23 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 104));
const __m128i vxk23 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk23, vzero), vkernel_zero_point);
const __m128i vprod23_odd = _mm_mullo_epi16(vxi23, vxk23);
const __m128i vprod23_even = _mm_mulhi_epi16(vxi23, vxk23);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod23_odd, vprod23_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod23_odd, vprod23_even));
w = (const void*)((uintptr_t)w + 112);
_mm_storeu_si128((__m128i*)outacc, vacc_lo);
outacc += 4;
_mm_storeu_si128((__m128i*)outacc, vacc_hi);
outacc += 4;
}
}
{
const uint8_t* i00 = input[10];
const uint8_t* i01 = input[11];
const uint8_t* i02 = input[12];
const uint8_t* i10 = input[13];
const uint8_t* i11 = input[14];
const uint8_t* i12 = input[15];
const uint8_t* i20 = input[16];
const uint8_t* i21 = input[17];
const uint8_t* i22 = input[18];
const uint8_t* i23 = input[19];
outacc = outacc32;
size_t c = channels;
for (; c >= 8; c -= 8) {
const __m128i vi00 = _mm_loadl_epi64((const __m128i*)i00);
i00 += 8;
const __m128i vxi00 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi00, vzero), vinput_zero_point);
const __m128i vk00 = _mm_loadl_epi64((const __m128i*)((uintptr_t)w));
const __m128i vxk00 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk00, vzero), vkernel_zero_point);
const __m128i vprod00_odd = _mm_mullo_epi16(vxi00, vxk00);
const __m128i vprod00_even = _mm_mulhi_epi16(vxi00, vxk00);
__m128i vacc_lo = _mm_unpacklo_epi16(vprod00_odd, vprod00_even);
__m128i vacc_hi = _mm_unpackhi_epi16(vprod00_odd, vprod00_even);
const __m128i vi01 = _mm_loadl_epi64((const __m128i*)i01);
i01 += 8;
const __m128i vxi01 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi01, vzero), vinput_zero_point);
const __m128i vk01 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 8));
const __m128i vxk01 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk01, vzero), vkernel_zero_point);
const __m128i vprod01_odd = _mm_mullo_epi16(vxi01, vxk01);
const __m128i vprod01_even = _mm_mulhi_epi16(vxi01, vxk01);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod01_odd, vprod01_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod01_odd, vprod01_even));
const __m128i vi02 = _mm_loadl_epi64((const __m128i*)i02);
i02 += 8;
const __m128i vxi02 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi02, vzero), vinput_zero_point);
const __m128i vk02 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 16));
const __m128i vxk02 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk02, vzero), vkernel_zero_point);
const __m128i vprod02_odd = _mm_mullo_epi16(vxi02, vxk02);
const __m128i vprod02_even = _mm_mulhi_epi16(vxi02, vxk02);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod02_odd, vprod02_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod02_odd, vprod02_even));
const __m128i vi10 = _mm_loadl_epi64((const __m128i*)i10);
i10 += 8;
const __m128i vxi10 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi10, vzero), vinput_zero_point);
const __m128i vk10 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 24));
const __m128i vxk10 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk10, vzero), vkernel_zero_point);
const __m128i vprod10_odd = _mm_mullo_epi16(vxi10, vxk10);
const __m128i vprod10_even = _mm_mulhi_epi16(vxi10, vxk10);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod10_odd, vprod10_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod10_odd, vprod10_even));
const __m128i vi11 = _mm_loadl_epi64((const __m128i*)i11);
i11 += 8;
const __m128i vxi11 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi11, vzero), vinput_zero_point);
const __m128i vk11 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 32));
const __m128i vxk11 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk11, vzero), vkernel_zero_point);
const __m128i vprod11_odd = _mm_mullo_epi16(vxi11, vxk11);
const __m128i vprod11_even = _mm_mulhi_epi16(vxi11, vxk11);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod11_odd, vprod11_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod11_odd, vprod11_even));
const __m128i vi12 = _mm_loadl_epi64((const __m128i*)i12);
i12 += 8;
const __m128i vxi12 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi12, vzero), vinput_zero_point);
const __m128i vk12 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 40));
const __m128i vxk12 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk12, vzero), vkernel_zero_point);
const __m128i vprod12_odd = _mm_mullo_epi16(vxi12, vxk12);
const __m128i vprod12_even = _mm_mulhi_epi16(vxi12, vxk12);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod12_odd, vprod12_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod12_odd, vprod12_even));
const __m128i vi20 = _mm_loadl_epi64((const __m128i*)i20);
i20 += 8;
const __m128i vxi20 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi20, vzero), vinput_zero_point);
const __m128i vk20 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 48));
const __m128i vxk20 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk20, vzero), vkernel_zero_point);
const __m128i vprod20_odd = _mm_mullo_epi16(vxi20, vxk20);
const __m128i vprod20_even = _mm_mulhi_epi16(vxi20, vxk20);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod20_odd, vprod20_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod20_odd, vprod20_even));
const __m128i vi21 = _mm_loadl_epi64((const __m128i*)i21);
i21 += 8;
const __m128i vxi21 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi21, vzero), vinput_zero_point);
const __m128i vk21 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 56));
const __m128i vxk21 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk21, vzero), vkernel_zero_point);
const __m128i vprod21_odd = _mm_mullo_epi16(vxi21, vxk21);
const __m128i vprod21_even = _mm_mulhi_epi16(vxi21, vxk21);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod21_odd, vprod21_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod21_odd, vprod21_even));
const __m128i vi22 = _mm_loadl_epi64((const __m128i*)i22);
i22 += 8;
const __m128i vxi22 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi22, vzero), vinput_zero_point);
const __m128i vk22 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 64));
const __m128i vxk22 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk22, vzero), vkernel_zero_point);
const __m128i vprod22_odd = _mm_mullo_epi16(vxi22, vxk22);
const __m128i vprod22_even = _mm_mulhi_epi16(vxi22, vxk22);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod22_odd, vprod22_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod22_odd, vprod22_even));
const __m128i vi23 = _mm_loadl_epi64((const __m128i*)i23);
i23 += 8;
const __m128i vxi23 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi23, vzero), vinput_zero_point);
const __m128i vk23 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 72));
const __m128i vxk23 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk23, vzero), vkernel_zero_point);
const __m128i vprod23_odd = _mm_mullo_epi16(vxi23, vxk23);
const __m128i vprod23_even = _mm_mulhi_epi16(vxi23, vxk23);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod23_odd, vprod23_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod23_odd, vprod23_even));
w = (const void*)((uintptr_t)w + 80);
vacc_lo = _mm_add_epi32(vacc_lo, _mm_loadu_si128((__m128i*)outacc));
vacc_hi =
_mm_add_epi32(vacc_hi, _mm_loadu_si128((__m128i*)(outacc + 4)));
_mm_storeu_si128((__m128i*)outacc, vacc_lo);
outacc += 4;
_mm_storeu_si128((__m128i*)outacc, vacc_hi);
outacc += 4;
}
if (c != 0) {
const size_t i_predecrement = 8 - c;
const __m128i vi_shift = _mm_cvtsi32_si128(8 * i_predecrement);
i00 -= i_predecrement;
i01 -= i_predecrement;
i02 -= i_predecrement;
i10 -= i_predecrement;
i11 -= i_predecrement;
i12 -= i_predecrement;
i20 -= i_predecrement;
i21 -= i_predecrement;
i22 -= i_predecrement;
i23 -= i_predecrement;
const __m128i vi00 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i00), vi_shift);
const __m128i vxi00 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi00, vzero), vinput_zero_point);
const __m128i vk00 = _mm_loadl_epi64((const __m128i*)((uintptr_t)w));
const __m128i vxk00 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk00, vzero), vkernel_zero_point);
const __m128i vprod00_odd = _mm_mullo_epi16(vxi00, vxk00);
const __m128i vprod00_even = _mm_mulhi_epi16(vxi00, vxk00);
__m128i vacc_lo = _mm_unpacklo_epi16(vprod00_odd, vprod00_even);
__m128i vacc_hi = _mm_unpackhi_epi16(vprod00_odd, vprod00_even);
const __m128i vi01 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i01), vi_shift);
const __m128i vxi01 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi01, vzero), vinput_zero_point);
const __m128i vk01 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 8));
const __m128i vxk01 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk01, vzero), vkernel_zero_point);
const __m128i vprod01_odd = _mm_mullo_epi16(vxi01, vxk01);
const __m128i vprod01_even = _mm_mulhi_epi16(vxi01, vxk01);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod01_odd, vprod01_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod01_odd, vprod01_even));
const __m128i vi02 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i02), vi_shift);
const __m128i vxi02 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi02, vzero), vinput_zero_point);
const __m128i vk02 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 16));
const __m128i vxk02 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk02, vzero), vkernel_zero_point);
const __m128i vprod02_odd = _mm_mullo_epi16(vxi02, vxk02);
const __m128i vprod02_even = _mm_mulhi_epi16(vxi02, vxk02);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod02_odd, vprod02_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod02_odd, vprod02_even));
const __m128i vi10 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i10), vi_shift);
const __m128i vxi10 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi10, vzero), vinput_zero_point);
const __m128i vk10 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 24));
const __m128i vxk10 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk10, vzero), vkernel_zero_point);
const __m128i vprod10_odd = _mm_mullo_epi16(vxi10, vxk10);
const __m128i vprod10_even = _mm_mulhi_epi16(vxi10, vxk10);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod10_odd, vprod10_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod10_odd, vprod10_even));
const __m128i vi11 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i11), vi_shift);
const __m128i vxi11 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi11, vzero), vinput_zero_point);
const __m128i vk11 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 32));
const __m128i vxk11 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk11, vzero), vkernel_zero_point);
const __m128i vprod11_odd = _mm_mullo_epi16(vxi11, vxk11);
const __m128i vprod11_even = _mm_mulhi_epi16(vxi11, vxk11);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod11_odd, vprod11_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod11_odd, vprod11_even));
const __m128i vi12 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i12), vi_shift);
const __m128i vxi12 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi12, vzero), vinput_zero_point);
const __m128i vk12 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 40));
const __m128i vxk12 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk12, vzero), vkernel_zero_point);
const __m128i vprod12_odd = _mm_mullo_epi16(vxi12, vxk12);
const __m128i vprod12_even = _mm_mulhi_epi16(vxi12, vxk12);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod12_odd, vprod12_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod12_odd, vprod12_even));
const __m128i vi20 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i20), vi_shift);
const __m128i vxi20 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi20, vzero), vinput_zero_point);
const __m128i vk20 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 48));
const __m128i vxk20 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk20, vzero), vkernel_zero_point);
const __m128i vprod20_odd = _mm_mullo_epi16(vxi20, vxk20);
const __m128i vprod20_even = _mm_mulhi_epi16(vxi20, vxk20);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod20_odd, vprod20_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod20_odd, vprod20_even));
const __m128i vi21 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i21), vi_shift);
const __m128i vxi21 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi21, vzero), vinput_zero_point);
const __m128i vk21 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 56));
const __m128i vxk21 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk21, vzero), vkernel_zero_point);
const __m128i vprod21_odd = _mm_mullo_epi16(vxi21, vxk21);
const __m128i vprod21_even = _mm_mulhi_epi16(vxi21, vxk21);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod21_odd, vprod21_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod21_odd, vprod21_even));
const __m128i vi22 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i22), vi_shift);
const __m128i vxi22 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi22, vzero), vinput_zero_point);
const __m128i vk22 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 64));
const __m128i vxk22 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk22, vzero), vkernel_zero_point);
const __m128i vprod22_odd = _mm_mullo_epi16(vxi22, vxk22);
const __m128i vprod22_even = _mm_mulhi_epi16(vxi22, vxk22);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod22_odd, vprod22_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod22_odd, vprod22_even));
const __m128i vi23 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i23), vi_shift);
const __m128i vxi23 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi23, vzero), vinput_zero_point);
const __m128i vk23 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 72));
const __m128i vxk23 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk23, vzero), vkernel_zero_point);
const __m128i vprod23_odd = _mm_mullo_epi16(vxi23, vxk23);
const __m128i vprod23_even = _mm_mulhi_epi16(vxi23, vxk23);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod23_odd, vprod23_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod23_odd, vprod23_even));
w = (const void*)((uintptr_t)w + 80);
vacc_lo = _mm_add_epi32(vacc_lo, _mm_loadu_si128((__m128i*)outacc));
vacc_hi =
_mm_add_epi32(vacc_hi, _mm_loadu_si128((__m128i*)(outacc + 4)));
_mm_storeu_si128((__m128i*)outacc, vacc_lo);
outacc += 4;
_mm_storeu_si128((__m128i*)outacc, vacc_hi);
outacc += 4;
}
}
{
const uint8_t* i00 = input[20];
const uint8_t* i01 = input[21];
const uint8_t* i02 = input[22];
const uint8_t* i10 = input[23];
const uint8_t* i11 = input[24];
input = (const uint8_t**)((uintptr_t)input + input_stride);
outacc = outacc32;
size_t c = channels;
for (; c >= 8; c -= 8) {
const __m128i vi00 = _mm_loadl_epi64((const __m128i*)i00);
i00 += 8;
const __m128i vxi00 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi00, vzero), vinput_zero_point);
const __m128i vk00 = _mm_loadl_epi64((const __m128i*)((uintptr_t)w));
const __m128i vxk00 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk00, vzero), vkernel_zero_point);
const __m128i vprod00_odd = _mm_mullo_epi16(vxi00, vxk00);
const __m128i vprod00_even = _mm_mulhi_epi16(vxi00, vxk00);
__m128i vacc_lo = _mm_unpacklo_epi16(vprod00_odd, vprod00_even);
__m128i vacc_hi = _mm_unpackhi_epi16(vprod00_odd, vprod00_even);
const __m128i vi01 = _mm_loadl_epi64((const __m128i*)i01);
i01 += 8;
const __m128i vxi01 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi01, vzero), vinput_zero_point);
const __m128i vk01 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 8));
const __m128i vxk01 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk01, vzero), vkernel_zero_point);
const __m128i vprod01_odd = _mm_mullo_epi16(vxi01, vxk01);
const __m128i vprod01_even = _mm_mulhi_epi16(vxi01, vxk01);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod01_odd, vprod01_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod01_odd, vprod01_even));
const __m128i vi02 = _mm_loadl_epi64((const __m128i*)i02);
i02 += 8;
const __m128i vxi02 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi02, vzero), vinput_zero_point);
const __m128i vk02 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 16));
const __m128i vxk02 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk02, vzero), vkernel_zero_point);
const __m128i vprod02_odd = _mm_mullo_epi16(vxi02, vxk02);
const __m128i vprod02_even = _mm_mulhi_epi16(vxi02, vxk02);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod02_odd, vprod02_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod02_odd, vprod02_even));
const __m128i vi10 = _mm_loadl_epi64((const __m128i*)i10);
i10 += 8;
const __m128i vxi10 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi10, vzero), vinput_zero_point);
const __m128i vk10 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 24));
const __m128i vxk10 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk10, vzero), vkernel_zero_point);
const __m128i vprod10_odd = _mm_mullo_epi16(vxi10, vxk10);
const __m128i vprod10_even = _mm_mulhi_epi16(vxi10, vxk10);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod10_odd, vprod10_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod10_odd, vprod10_even));
const __m128i vi11 = _mm_loadl_epi64((const __m128i*)i11);
i11 += 8;
const __m128i vxi11 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi11, vzero), vinput_zero_point);
const __m128i vk11 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 32));
const __m128i vxk11 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk11, vzero), vkernel_zero_point);
const __m128i vprod11_odd = _mm_mullo_epi16(vxi11, vxk11);
const __m128i vprod11_even = _mm_mulhi_epi16(vxi11, vxk11);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod11_odd, vprod11_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod11_odd, vprod11_even));
w = (const void*)((uintptr_t)w + 40);
vacc_lo = _mm_add_epi32(vacc_lo, _mm_loadu_si128((__m128i*)outacc));
vacc_hi =
_mm_add_epi32(vacc_hi, _mm_loadu_si128((__m128i*)(outacc + 4)));
outacc += 8;
const __m128 vmultiplier =
_mm_set1_ps(quantization_params->sse2.requantization_scales[0]);
vacc_lo = _mm_cvtps_epi32(
_mm_mul_ps(
_mm_cvtepi32_ps(vacc_lo),
vmultiplier
)
);
vacc_hi = _mm_cvtps_epi32(
_mm_mul_ps(
_mm_cvtepi32_ps(vacc_hi),
vmultiplier
)
);
const __m128i voutput_zero_point = _mm_load_si128(
(const __m128i*)quantization_params->sse2.output_zero_point);
__m128i vout = _mm_adds_epi16(
_mm_packs_epi32(vacc_lo, vacc_hi), voutput_zero_point);
vout = _mm_packus_epi16(vout, vout);
vout = _mm_max_epu8(
vout,
_mm_load_si128(
(const __m128i*)quantization_params->sse2.output_min));
vout = _mm_min_epu8(
vout,
_mm_load_si128(
(const __m128i*)quantization_params->sse2.output_max));
_mm_storel_epi64((__m128i*)output, vout);
output += 8;
}
if (c != 0) {
const size_t i_predecrement = 8 - c;
const __m128i vi_shift = _mm_cvtsi32_si128(8 * i_predecrement);
i00 -= i_predecrement;
i01 -= i_predecrement;
i02 -= i_predecrement;
i10 -= i_predecrement;
i11 -= i_predecrement;
const __m128i vi00 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i00), vi_shift);
const __m128i vxi00 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi00, vzero), vinput_zero_point);
const __m128i vk00 = _mm_loadl_epi64((const __m128i*)((uintptr_t)w));
const __m128i vxk00 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk00, vzero), vkernel_zero_point);
const __m128i vprod00_odd = _mm_mullo_epi16(vxi00, vxk00);
const __m128i vprod00_even = _mm_mulhi_epi16(vxi00, vxk00);
__m128i vacc_lo = _mm_unpacklo_epi16(vprod00_odd, vprod00_even);
__m128i vacc_hi = _mm_unpackhi_epi16(vprod00_odd, vprod00_even);
const __m128i vi01 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i01), vi_shift);
const __m128i vxi01 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi01, vzero), vinput_zero_point);
const __m128i vk01 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 8));
const __m128i vxk01 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk01, vzero), vkernel_zero_point);
const __m128i vprod01_odd = _mm_mullo_epi16(vxi01, vxk01);
const __m128i vprod01_even = _mm_mulhi_epi16(vxi01, vxk01);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod01_odd, vprod01_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod01_odd, vprod01_even));
const __m128i vi02 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i02), vi_shift);
const __m128i vxi02 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi02, vzero), vinput_zero_point);
const __m128i vk02 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 16));
const __m128i vxk02 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk02, vzero), vkernel_zero_point);
const __m128i vprod02_odd = _mm_mullo_epi16(vxi02, vxk02);
const __m128i vprod02_even = _mm_mulhi_epi16(vxi02, vxk02);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod02_odd, vprod02_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod02_odd, vprod02_even));
const __m128i vi10 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i10), vi_shift);
const __m128i vxi10 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi10, vzero), vinput_zero_point);
const __m128i vk10 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 24));
const __m128i vxk10 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk10, vzero), vkernel_zero_point);
const __m128i vprod10_odd = _mm_mullo_epi16(vxi10, vxk10);
const __m128i vprod10_even = _mm_mulhi_epi16(vxi10, vxk10);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod10_odd, vprod10_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod10_odd, vprod10_even));
const __m128i vi11 =
_mm_srl_epi64(_mm_loadl_epi64((const __m128i*)i11), vi_shift);
const __m128i vxi11 =
_mm_sub_epi16(_mm_unpacklo_epi8(vi11, vzero), vinput_zero_point);
const __m128i vk11 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 32));
const __m128i vxk11 =
_mm_sub_epi16(_mm_unpacklo_epi8(vk11, vzero), vkernel_zero_point);
const __m128i vprod11_odd = _mm_mullo_epi16(vxi11, vxk11);
const __m128i vprod11_even = _mm_mulhi_epi16(vxi11, vxk11);
vacc_lo = _mm_add_epi32(
vacc_lo, _mm_unpacklo_epi16(vprod11_odd, vprod11_even));
vacc_hi = _mm_add_epi32(
vacc_hi, _mm_unpackhi_epi16(vprod11_odd, vprod11_even));
vacc_lo = _mm_add_epi32(vacc_lo, _mm_loadu_si128((__m128i*)outacc));
vacc_hi =
_mm_add_epi32(vacc_hi, _mm_loadu_si128((__m128i*)(outacc + 4)));
outacc += 8;
const __m128 vmultiplier =
_mm_set1_ps(quantization_params->sse2.requantization_scales[0]);
vacc_lo = _mm_cvtps_epi32(
_mm_mul_ps(
_mm_cvtepi32_ps(vacc_lo),
vmultiplier
)
);
vacc_hi = _mm_cvtps_epi32(
_mm_mul_ps(
_mm_cvtepi32_ps(vacc_hi),
vmultiplier
)
);
const __m128i voutput_zero_point = _mm_load_si128(
(const __m128i*)quantization_params->sse2.output_zero_point);
__m128i vout = _mm_adds_epi16(
_mm_packs_epi32(vacc_lo, vacc_hi), voutput_zero_point);
vout = _mm_packus_epi16(vout, vout);
vout = _mm_max_epu8(
vout,
_mm_load_si128(
(const __m128i*)quantization_params->sse2.output_min));
vout = _mm_min_epu8(
vout,
_mm_load_si128(
(const __m128i*)quantization_params->sse2.output_max));
if (c & 4) {
*((uint32_t*)output) = (uint32_t)_mm_cvtsi128_si32(vout);
output += 4;
vout = _mm_srli_epi64(vout, 32);
}
if (c & 2) {
*((uint16_t*)output) = (uint16_t)_mm_extract_epi16(vout, 0);
output += 2;
vout = _mm_srli_epi32(vout, 16);
}
if (c & 1) {
*((uint8_t*)output) = (uint8_t)_mm_cvtsi128_si32(vout);
output += 1;
}
}
}
output = (uint8_t*)((uintptr_t)output + output_increment);
} while (--output_width != 0);
}
| 26,276 |
5,169 | <gh_stars>1000+
{
"name": "International-iOS",
"version": "0.1.2",
"summary": "iOS国际化",
"description": "iOS国际化,支持的控件有:UILabel",
"homepage": "https://github.com/wangjufan/International-iOS",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"wangjufan": "<EMAIL>"
},
"platforms": {
"ios": "9.0"
},
"source": {
"git": "https://github.com/wangjufan/International-iOS.git",
"tag": "0.1.2"
},
"source_files": "International/Classes/*.{h,m}",
"public_header_files": "International/Classes/{YDLocalizationCenter,YDLocalBlock}.{h}",
"requires_arc": true,
"resources": "International/Resources/*.{lproj}"
}
| 305 |
852 | <reponame>malbouis/cmssw
#include "CondFormats/BeamSpotObjects/interface/BeamSpotOnlineObjects.h"
#include "CondFormats/DataRecord/interface/BeamSpotObjectsRcd.h"
#include "CondFormats/DataRecord/interface/BeamSpotOnlineHLTObjectsRcd.h"
#include "CondFormats/DataRecord/interface/BeamSpotOnlineLegacyObjectsRcd.h"
#include "CondFormats/DataRecord/interface/BeamSpotTransientObjectsRcd.h"
#include "DataFormats/BeamSpot/interface/BeamSpot.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/ESProducer.h"
#include "FWCore/Framework/interface/ESProducer.h"
#include "FWCore/Framework/interface/ESProductHost.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/ModuleFactory.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/Utilities/interface/ReusableObjectHolder.h"
#include "FWCore/Utilities/interface/do_nothing_deleter.h"
#include <memory>
#include <string>
using namespace edm;
class OnlineBeamSpotESProducer : public edm::ESProducer {
public:
OnlineBeamSpotESProducer(const edm::ParameterSet& p);
std::shared_ptr<const BeamSpotObjects> produce(const BeamSpotTransientObjectsRcd&);
static void fillDescriptions(edm::ConfigurationDescriptions& desc);
private:
const BeamSpotOnlineObjects* compareBS(const BeamSpotOnlineObjects* bs1, const BeamSpotOnlineObjects* bs2);
const BeamSpotOnlineObjects* checkSingleBS(const BeamSpotOnlineObjects* bs1);
edm::ESGetToken<BeamSpotObjects, BeamSpotTransientObjectsRcd> const bsToken_;
edm::ESGetToken<BeamSpotOnlineObjects, BeamSpotOnlineHLTObjectsRcd> bsHLTToken_;
edm::ESGetToken<BeamSpotOnlineObjects, BeamSpotOnlineLegacyObjectsRcd> bsLegacyToken_;
BeamSpotObjects fakeBS_;
const int timeThreshold_;
const double sigmaZThreshold_;
};
OnlineBeamSpotESProducer::OnlineBeamSpotESProducer(const edm::ParameterSet& p)
// get parameters
: timeThreshold_(p.getParameter<int>("timeThreshold")),
sigmaZThreshold_(p.getParameter<double>("sigmaZThreshold")) {
auto cc = setWhatProduced(this);
fakeBS_.SetBeamWidthX(0.1);
fakeBS_.SetBeamWidthY(0.1);
fakeBS_.SetSigmaZ(15.);
fakeBS_.SetPosition(0.0001, 0.0001, 0.0001);
fakeBS_.SetType(-1);
bsHLTToken_ = cc.consumesFrom<BeamSpotOnlineObjects, BeamSpotOnlineHLTObjectsRcd>();
bsLegacyToken_ = cc.consumesFrom<BeamSpotOnlineObjects, BeamSpotOnlineLegacyObjectsRcd>();
}
void OnlineBeamSpotESProducer::fillDescriptions(edm::ConfigurationDescriptions& desc) {
edm::ParameterSetDescription dsc;
dsc.add<int>("timeThreshold", 48)->setComment("hours");
dsc.add<double>("sigmaZThreshold", 2.)->setComment("cm");
desc.addWithDefaultLabel(dsc);
}
const BeamSpotOnlineObjects* OnlineBeamSpotESProducer::compareBS(const BeamSpotOnlineObjects* bs1,
const BeamSpotOnlineObjects* bs2) {
// Current time to be compared with the one read from the payload
auto currentTime =
std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch());
// Get two beamspot creation times and compute the time difference wrt currentTime
auto bs1time = std::chrono::microseconds(bs1->GetCreationTime());
auto diffBStime1 = (currentTime - bs1time).count();
auto bs2time = std::chrono::microseconds(bs2->GetCreationTime());
auto diffBStime2 = (currentTime - bs2time).count();
// Convert timeThreshold_ from hours to microseconds for comparison
auto limitTime = std::chrono::microseconds((std::chrono::hours)timeThreshold_).count();
// Logic to choose between the two BeamSpots:
// 1. If both BS are older than limitTime retun fake BS
// 2. If only one BS is newer than limitTime return it only if it has
// sigmaZ larger than sigmaZthreshold_ and the fit converged (BeamType 2)
// 3. If both are newer than the limit threshold return
// the BS that converged and has larger sigmaZ
if (diffBStime1 > limitTime && diffBStime2 > limitTime) {
edm::LogInfo("OnlineBeamSpotESProducer") << "Defaulting to fake becuase both payloads are too old.";
return nullptr;
} else if (diffBStime2 > limitTime) {
if (bs1->GetSigmaZ() > sigmaZThreshold_ && bs1->GetBeamType() == 2) {
return bs1;
} else {
edm::LogInfo("OnlineBeamSpotESProducer")
<< "Defaulting to fake because the legacy Beam Spot is not suitable and HLT one is too old.";
return nullptr;
}
} else if (diffBStime1 > limitTime) {
if (bs2->GetSigmaZ() > sigmaZThreshold_ && bs2->GetBeamType() == 2) {
return bs2;
} else {
edm::LogInfo("OnlineBeamSpotESProducer")
<< "Defaulting to fake because the HLT Beam Spot is not suitable and the legacy one too old.";
return nullptr;
}
} else {
if (bs1->GetSigmaZ() > bs2->GetSigmaZ() && bs1->GetBeamType() == 2) {
return bs1;
} else if (bs2->GetSigmaZ() >= bs1->GetSigmaZ() && bs2->GetBeamType() == 2) {
return bs2;
} else {
edm::LogInfo("OnlineBeamSpotESProducer")
<< "Defaulting to fake because despite both payloads are young enough, none has the right BeamType.";
return nullptr;
}
}
}
const BeamSpotOnlineObjects* OnlineBeamSpotESProducer::checkSingleBS(const BeamSpotOnlineObjects* bs1) {
// Current time to be compared with the one read from the payload
auto currentTime =
std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch());
// Get the beamspot creation time and compute the time difference wrt currentTime
auto bs1time = std::chrono::microseconds(bs1->GetCreationTime());
auto diffBStime1 = (currentTime - bs1time).count();
// Convert timeThreshold_ from hours to microseconds for comparison
auto limitTime = std::chrono::microseconds((std::chrono::hours)timeThreshold_).count();
// Check that the BS is within the timeThreshold, converges and passes the sigmaZthreshold
if (diffBStime1 < limitTime && bs1->GetSigmaZ() > sigmaZThreshold_ && bs1->GetBeamType() == 2) {
return bs1;
} else {
return nullptr;
}
}
std::shared_ptr<const BeamSpotObjects> OnlineBeamSpotESProducer::produce(const BeamSpotTransientObjectsRcd& iRecord) {
auto legacyRec = iRecord.tryToGetRecord<BeamSpotOnlineLegacyObjectsRcd>();
auto hltRec = iRecord.tryToGetRecord<BeamSpotOnlineHLTObjectsRcd>();
if (not legacyRec and not hltRec) {
edm::LogInfo("OnlineBeamSpotESProducer") << "None of the Beam Spots in ES are available! \n returning a fake one.";
return std::shared_ptr<const BeamSpotObjects>(&fakeBS_, edm::do_nothing_deleter());
}
const BeamSpotOnlineObjects* best;
if (legacyRec and hltRec) {
best = compareBS(&legacyRec->get(bsLegacyToken_), &hltRec->get(bsHLTToken_));
} else if (legacyRec) {
best = checkSingleBS(&legacyRec->get(bsLegacyToken_));
} else {
best = checkSingleBS(&hltRec->get(bsHLTToken_));
}
if (best) {
return std::shared_ptr<const BeamSpotObjects>(best, edm::do_nothing_deleter());
} else {
return std::shared_ptr<const BeamSpotObjects>(&fakeBS_, edm::do_nothing_deleter());
edm::LogInfo("OnlineBeamSpotESProducer")
<< "None of the Online BeamSpots in the ES is suitable, \n returning a fake one. ";
}
};
DEFINE_FWK_EVENTSETUP_MODULE(OnlineBeamSpotESProducer);
| 2,713 |
868 | package com.sedmelluq.lava.extensions.youtuberotator.planner;
import com.sedmelluq.lava.extensions.youtuberotator.tools.Tuple;
import com.sedmelluq.lava.extensions.youtuberotator.tools.ip.IpBlock;
import com.sedmelluq.lava.extensions.youtuberotator.tools.ip.Ipv6Block;
import org.apache.http.HttpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
public final class RotatingNanoIpRoutePlanner extends AbstractRoutePlanner {
private static final Logger log = LoggerFactory.getLogger(RotatingNanoIpRoutePlanner.class);
private final Predicate<InetAddress> ipFilter;
private final AtomicReference<BigInteger> currentBlock;
private final AtomicReference<BigInteger> blockNanoStart;
private final AtomicBoolean next;
public RotatingNanoIpRoutePlanner(final List<IpBlock> ipBlocks) {
this(ipBlocks, ip -> true);
}
public RotatingNanoIpRoutePlanner(final List<IpBlock> ipBlocks, final Predicate<InetAddress> ipFilter) {
this(ipBlocks, ipFilter, true);
}
public RotatingNanoIpRoutePlanner(final List<IpBlock> ipBlocks, final Predicate<InetAddress> ipFilter, final boolean handleSearchFailure) {
super(ipBlocks, handleSearchFailure);
this.ipFilter = ipFilter;
this.currentBlock = new AtomicReference<>(BigInteger.ZERO);
this.blockNanoStart = new AtomicReference<>(BigInteger.valueOf(System.nanoTime()));
this.next = new AtomicBoolean(false);
if (ipBlock.getType() != Inet6Address.class || ipBlock.getSize().compareTo(Ipv6Block.BLOCK64_IPS) < 0)
throw new IllegalArgumentException("Please use a bigger IPv6 Block!");
}
/**
* Returns the current block index
* @return block index which is currently used
*/
public BigInteger getCurrentBlock() {
return currentBlock.get();
}
/**
* Returns the address offset for the current nano time
* @return address offset as long
*/
public long getAddressIndexInBlock() {
return System.nanoTime() - blockNanoStart.get().longValue();
}
@Override
protected Tuple<InetAddress, InetAddress> determineAddressPair(final Tuple<Inet4Address, Inet6Address> remoteAddresses) throws HttpException {
InetAddress currentAddress = null;
InetAddress remoteAddress;
if (ipBlock.getType() == Inet6Address.class) {
if (remoteAddresses.r != null) {
currentAddress = extractLocalAddress();
log.debug("Selected " + currentAddress.toString() + " as new outgoing ip");
remoteAddress = remoteAddresses.r;
} else if (remoteAddresses.l != null) {
remoteAddress = remoteAddresses.l;
log.warn("Could not look up AAAA record for host. Falling back to unbalanced IPv4.");
} else {
throw new HttpException("Could not resolve host");
}
} else {
throw new HttpException("Unknown IpBlock type: " + ipBlock.getType().getCanonicalName());
}
next.set(false);
return new Tuple<>(currentAddress, remoteAddress);
}
@Override
protected void onAddressFailure(final InetAddress address) {
currentBlock.accumulateAndGet(BigInteger.ONE, BigInteger::add);
blockNanoStart.set(BigInteger.valueOf(System.nanoTime()));
}
private InetAddress extractLocalAddress() {
InetAddress localAddress;
long triesSinceBlockSkip = 0;
BigInteger it = BigInteger.valueOf(0);
do {
try {
if (ipBlock.getSize().multiply(BigInteger.valueOf(2)).compareTo(it) < 0) {
throw new RuntimeException("Can't find a free ip");
}
it = it.add(BigInteger.ONE);
triesSinceBlockSkip++;
if (triesSinceBlockSkip > 128) {
this.currentBlock.accumulateAndGet(BigInteger.ONE, BigInteger::add);
}
final BigInteger nanoTime = BigInteger.valueOf(System.nanoTime());
final BigInteger timeOffset = nanoTime.subtract(blockNanoStart.get());
final BigInteger blockOffset = currentBlock.get().multiply(Ipv6Block.BLOCK64_IPS);
localAddress = ipBlock.getAddressAtIndex(blockOffset.add(timeOffset));
} catch (final IllegalArgumentException ex) {
this.currentBlock.set(BigInteger.ZERO);
localAddress = null;
}
} while (localAddress == null || !ipFilter.test(localAddress) || !isValidAddress(localAddress));
return localAddress;
}
}
| 1,599 |
339 | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2017.02.06 um 01:12:59 PM CET
//
package com.innoq.mploed.ddd.customer.ws;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the com.innoq.mploed.ddd.customer.ws package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.innoq.mploed.ddd.customer.ws
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link SaveCustomerResponse }
*
*/
public SaveCustomerResponse createSaveCustomerResponse() {
return new SaveCustomerResponse();
}
/**
* Create an instance of {@link Customer }
*
*/
public Customer createCustomer() {
return new Customer();
}
/**
* Create an instance of {@link SaveCustomerRequest }
*
*/
public SaveCustomerRequest createSaveCustomerRequest() {
return new SaveCustomerRequest();
}
}
| 603 |
1,007 | <reponame>mzule/btrace
{
"android.gui.IGraphicBufferProducer": [
"REQUEST_BUFFER",
"DEQUEUE_BUFFER",
"DETACH_BUFFER",
"DETACH_NEXT_BUFFER",
"ATTACH_BUFFER",
"QUEUE_BUFFER",
"CANCEL_BUFFER",
"QUERY",
"CONNECT",
"DISCONNECT",
"SET_SIDEBAND_STREAM",
"ALLOCATE_BUFFERS",
"ALLOW_ALLOCATION",
"SET_GENERATION_NUMBER",
"GET_CONSUMER_NAME",
"SET_MAX_DEQUEUED_BUFFER_COUNT",
"SET_ASYNC_MODE",
"SET_SHARED_BUFFER_MODE",
"SET_AUTO_REFRESH",
"SET_DEQUEUE_TIMEOUT",
"GET_LAST_QUEUED_BUFFER",
"GET_FRAME_TIMESTAMPS",
"GET_UNIQUE_ID",
"GET_CONSUMER_USAGE",
"SET_LEGACY_BUFFER_DROP",
"SET_AUTO_PREROTATION",
"REQUEST_BUFFERS",
"DEQUEUE_BUFFERS",
"DETACH_BUFFERS",
"ATTACH_BUFFERS",
"QUEUE_BUFFERS",
"CANCEL_BUFFERS",
"QUERY_MULTIPLE",
"GET_LAST_QUEUED_BUFFER2"
],
"android.gui.DisplayEventConnection": [
"STEAL_RECEIVE_CHANNEL",
"SET_VSYNC_RATE",
"REQUEST_NEXT_VSYNC",
"LAST"
],
"android.ui.ISurfaceComposer": [
"BOOT_FINISHED",
"CREATE_CONNECTION",
"GET_STATIC_DISPLAY_INFO",
"CREATE_DISPLAY_EVENT_CONNECTION",
"CREATE_DISPLAY",
"DESTROY_DISPLAY",
"GET_PHYSICAL_DISPLAY_TOKEN",
"SET_TRANSACTION_STATE",
"AUTHENTICATE_SURFACE",
"GET_SUPPORTED_FRAME_TIMESTAMPS",
"GET_DISPLAY_MODES",
"GET_ACTIVE_DISPLAY_MODE",
"GET_DISPLAY_STATE",
"CAPTURE_DISPLAY",
"CAPTURE_LAYERS",
"CLEAR_ANIMATION_FRAME_STATS",
"GET_ANIMATION_FRAME_STATS",
"SET_POWER_MODE",
"GET_DISPLAY_STATS",
"GET_HDR_CAPABILITIES",
"GET_DISPLAY_COLOR_MODES",
"GET_ACTIVE_COLOR_MODE",
"SET_ACTIVE_COLOR_MODE",
"ENABLE_VSYNC_INJECTIONS",
"INJECT_VSYNC",
"GET_LAYER_DEBUG_INFO",
"GET_COMPOSITION_PREFERENCE",
"GET_COLOR_MANAGEMENT",
"GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES",
"SET_DISPLAY_CONTENT_SAMPLING_ENABLED",
"GET_DISPLAYED_CONTENT_SAMPLE",
"GET_PROTECTED_CONTENT_SUPPORT",
"IS_WIDE_COLOR_DISPLAY",
"GET_DISPLAY_NATIVE_PRIMARIES",
"GET_PHYSICAL_DISPLAY_IDS",
"ADD_REGION_SAMPLING_LISTENER",
"REMOVE_REGION_SAMPLING_LISTENER",
"SET_DESIRED_DISPLAY_MODE_SPECS",
"GET_DESIRED_DISPLAY_MODE_SPECS",
"GET_DISPLAY_BRIGHTNESS_SUPPORT",
"SET_DISPLAY_BRIGHTNESS",
"CAPTURE_DISPLAY_BY_ID",
"NOTIFY_POWER_BOOST",
"SET_GLOBAL_SHADOW_SETTINGS",
"GET_AUTO_LOW_LATENCY_MODE_SUPPORT",
"SET_AUTO_LOW_LATENCY_MODE",
"GET_GAME_CONTENT_TYPE_SUPPORT",
"SET_GAME_CONTENT_TYPE",
"SET_FRAME_RATE",
"ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN",
"SET_FRAME_TIMELINE_INFO",
"ADD_TRANSACTION_TRACE_LISTENER",
"GET_GPU_CONTEXT_PRIORITY",
"GET_MAX_ACQUIRED_BUFFER_COUNT",
"GET_DYNAMIC_DISPLAY_INFO",
"ADD_FPS_LISTENER",
"REMOVE_FPS_LISTENER",
"OVERRIDE_HDR_TYPES",
"ADD_HDR_LAYER_INFO_LISTENER",
"REMOVE_HDR_LAYER_INFO_LISTENER",
"ON_PULL_ATOM",
"ADD_TUNNEL_MODE_ENABLED_LISTENER",
"REMOVE_TUNNEL_MODE_ENABLED_LISTENER",
"GET_PRIMARY_PHYSICAL_DISPLAY_ID"
],
"android.graphicsenv.IGpuService": [
"SET_GPU_STATS",
"SET_TARGET_STATS",
"SET_UPDATABLE_DRIVER_PATH",
"GET_UPDATABLE_DRIVER_PATH"
]
} | 1,699 |
2,542 | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Management
{
namespace FileStoreService
{
class ReplicationManager :
public Common::ComponentRoot,
private Common::TextTraceComponent<Common::TraceTaskCodes::FileStoreService>
{
DENY_COPY(ReplicationManager)
public:
ReplicationManager(
ImageStoreServiceReplicaHolder const & serviceReplicaHolder);
~ReplicationManager();
bool ProcessCopyNotification(Api::IStoreItemEnumeratorPtr const & storeItemEnumerator);
bool ProcessReplicationNotification(Api::IStoreNotificationEnumeratorPtr const & storeNotificationEnumerator);
private:
class ProcessCopyJobQueue;
class ProcessCopyJobItem;
friend class ProcessCopyJobItem;
bool ReplicateFileAndDeleteOlderVersion(FileMetadata const & metadata);
bool ReplicateFile(FileMetadata const & metadata);
Common::ErrorCode EnsurePrimaryStoreShareLocation();
void TryRefreshShareLocations(std::wstring const & relativeStorePath);
Common::ErrorCode IsFilePresentInPrimary(
std::wstring const & relativeStorePath,
__out bool & isPresent,
__out FileState::Enum & fileState,
__out StoreFileVersion & currentFileVersion,
__out std::wstring & primaryStoreShare) const;
void GetReplicationFileAction(FileState::Enum, std::wstring const & key, __out bool & shouldCopy, __out bool & shouldDelete);
__declspec(property(get=get_ReplicaObj)) FileStoreServiceReplica const & ReplicaObj;
inline FileStoreServiceReplica const & get_ReplicaObj() const { return serviceReplicaHolder_.RootedObject; }
private:
Common::RwLock lock_;
std::wstring currentPrimaryStoreLocation_;
std::vector<std::wstring> secondaryStoreLocations_;
ImageStoreServiceReplicaHolder serviceReplicaHolder_;
};
}
}
| 985 |
1,980 | package InvertedIndex.plugin.Function;
import java.util.Set;
/**
* Created by liwei on 6/8/16.
*/
public interface Function {
public Set<String> Process(String input);
public Set<String> Process(Set<String> input);
}
| 77 |
575 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package com.android.webview.chromium;
import android.annotation.TargetApi;
import android.os.Build;
import android.webkit.PacProcessor;
import org.chromium.base.annotations.VerifiesOnR;
/**
* Utility class to use new APIs that were added in R (API level 30). These need to exist in a
* separate class so that Android framework can successfully verify glue layer classes without
* encountering the new APIs. Note that GlueApiHelper is only for APIs that cannot go to ApiHelper
* in base/, for reasons such as using system APIs or instantiating an adapter class that is
* specific to glue layer.
*/
@VerifiesOnR
@TargetApi(Build.VERSION_CODES.R)
public final class GlueApiHelperForR {
private GlueApiHelperForR() {}
public static PacProcessor getPacProcessor() {
return PacProcessorImpl.getInstance();
}
}
| 285 |
357 | class _DagreD3Mixin(object):
def _greendd3g(self):
if self._dd3g:
self._dd3g.setNode(
self._name, tooltip=str(self.value()), style="fill: #0f0"
)
def _yellowdd3g(self):
if self._dd3g:
self._dd3g.setNode(
self._name, tooltip=str(self.value()), style="fill: #ff0"
)
def _reddd3g(self):
if self._dd3g:
self._dd3g.setNode(
self._name, tooltip=str(self.value()), style="fill: #f00"
)
def _whited3g(self):
if self._dd3g:
self._dd3g.setNode(
self._name, tooltip=str(self.value()), style="fill: #fff"
)
| 410 |
903 | <reponame>hesslink111/node-qt
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (<EMAIL>)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QTCONCURRENT_RUNBASE_H
#define QTCONCURRENT_RUNBASE_H
#include <QtCore/qglobal.h>
#ifndef QT_NO_CONCURRENT
#include <QtCore/qfuture.h>
#include <QtCore/qrunnable.h>
#include <QtCore/qthreadpool.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Core)
#ifndef qdoc
namespace QtConcurrent {
template <typename T>
struct SelectSpecialization
{
template <class Normal, class Void>
struct Type { typedef Normal type; };
};
template <>
struct SelectSpecialization<void>
{
template <class Normal, class Void>
struct Type { typedef Void type; };
};
template <typename T>
class RunFunctionTaskBase : public QFutureInterface<T> , public QRunnable
{
public:
QFuture<T> start()
{
this->setRunnable(this);
this->reportStarted();
QFuture<T> future = this->future();
QThreadPool::globalInstance()->start(this, /*m_priority*/ 0);
return future;
}
void run() {}
virtual void runFunctor() = 0;
};
template <typename T>
class RunFunctionTask : public RunFunctionTaskBase<T>
{
public:
void run()
{
if (this->isCanceled()) {
this->reportFinished();
return;
}
#ifndef QT_NO_EXCEPTIONS
try {
#endif
this->runFunctor();
#ifndef QT_NO_EXCEPTIONS
} catch (QtConcurrent::Exception &e) {
QFutureInterface<T>::reportException(e);
} catch (...) {
QFutureInterface<T>::reportException(QtConcurrent::UnhandledException());
}
#endif
this->reportResult(result);
this->reportFinished();
}
T result;
};
template <>
class RunFunctionTask<void> : public RunFunctionTaskBase<void>
{
public:
void run()
{
if (this->isCanceled()) {
this->reportFinished();
return;
}
#ifndef QT_NO_EXCEPTIONS
try {
#endif
this->runFunctor();
#ifndef QT_NO_EXCEPTIONS
} catch (QtConcurrent::Exception &e) {
QFutureInterface<void>::reportException(e);
} catch (...) {
QFutureInterface<void>::reportException(QtConcurrent::UnhandledException());
}
#endif
this->reportFinished();
}
};
} //namespace QtConcurrent
#endif //qdoc
QT_END_NAMESPACE
QT_END_HEADER
#endif // QT_NO_CONCURRENT
#endif
| 1,616 |
14,425 | <gh_stars>1000+
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager.reservation;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException;
import org.apache.hadoop.yarn.util.resource.ResourceCalculator;
import org.apache.hadoop.yarn.util.resource.Resources;
/**
* This is a run length encoded sparse data structure that maintains resource
* allocations over time.
*/
public class RLESparseResourceAllocation {
private static final int THRESHOLD = 100;
private static final Resource ZERO_RESOURCE = Resources.none();
@SuppressWarnings("checkstyle:visibilitymodifier")
protected NavigableMap<Long, Resource> cumulativeCapacity =
new TreeMap<Long, Resource>();
private final ReentrantReadWriteLock readWriteLock =
new ReentrantReadWriteLock();
@SuppressWarnings("checkstyle:visibilitymodifier")
protected final Lock readLock = readWriteLock.readLock();
private final Lock writeLock = readWriteLock.writeLock();
private final ResourceCalculator resourceCalculator;
public RLESparseResourceAllocation(ResourceCalculator resourceCalculator) {
this.resourceCalculator = resourceCalculator;
}
public RLESparseResourceAllocation(NavigableMap<Long, Resource> out,
ResourceCalculator resourceCalculator) {
// miss check for repeated entries
this.cumulativeCapacity = out;
this.resourceCalculator = resourceCalculator;
}
/**
* Add a resource for the specified interval.
*
* @param reservationInterval the interval for which the resource is to be
* added
* @param totCap the resource to be added
* @return true if addition is successful, false otherwise
*/
public boolean addInterval(ReservationInterval reservationInterval,
Resource totCap) {
if (totCap.equals(ZERO_RESOURCE)) {
return true;
}
writeLock.lock();
try {
NavigableMap<Long, Resource> addInt = new TreeMap<Long, Resource>();
addInt.put(reservationInterval.getStartTime(), totCap);
addInt.put(reservationInterval.getEndTime(), ZERO_RESOURCE);
try {
cumulativeCapacity =
merge(resourceCalculator, totCap, cumulativeCapacity, addInt,
Long.MIN_VALUE, Long.MAX_VALUE, RLEOperator.add);
} catch (PlanningException e) {
// never happens for add
}
return true;
} finally {
writeLock.unlock();
}
}
/**
* Removes a resource for the specified interval.
*
* @param reservationInterval the interval for which the resource is to be
* removed
* @param totCap the resource to be removed
* @return true if removal is successful, false otherwise
*/
public boolean removeInterval(ReservationInterval reservationInterval,
Resource totCap) {
if (totCap.equals(ZERO_RESOURCE)) {
return true;
}
writeLock.lock();
try {
NavigableMap<Long, Resource> removeInt = new TreeMap<Long, Resource>();
removeInt.put(reservationInterval.getStartTime(), totCap);
removeInt.put(reservationInterval.getEndTime(), ZERO_RESOURCE);
try {
cumulativeCapacity =
merge(resourceCalculator, totCap, cumulativeCapacity, removeInt,
Long.MIN_VALUE, Long.MAX_VALUE, RLEOperator.subtract);
} catch (PlanningException e) {
// never happens for subtract
}
return true;
} finally {
writeLock.unlock();
}
}
/**
* Returns the capacity, i.e. total resources allocated at the specified point
* of time.
*
* @param tick timeStap at which resource needs to be known
* @return the resources allocated at the specified time
*/
public Resource getCapacityAtTime(long tick) {
readLock.lock();
try {
Entry<Long, Resource> closestStep = cumulativeCapacity.floorEntry(tick);
if (closestStep != null) {
return Resources.clone(closestStep.getValue());
}
return Resources.clone(ZERO_RESOURCE);
} finally {
readLock.unlock();
}
}
/**
* Get the timestamp of the earliest resource allocation.
*
* @return the timestamp of the first resource allocation
*/
public long getEarliestStartTime() {
readLock.lock();
try {
if (cumulativeCapacity.isEmpty()) {
return -1;
} else {
return cumulativeCapacity.firstKey();
}
} finally {
readLock.unlock();
}
}
/**
* Get the timestamp of the latest non-null resource allocation.
*
* @return the timestamp of the last resource allocation
*/
public long getLatestNonNullTime() {
readLock.lock();
try {
if (cumulativeCapacity.isEmpty()) {
return -1;
} else {
// the last entry might contain null (to terminate
// the sequence)... return previous one.
Entry<Long, Resource> last = cumulativeCapacity.lastEntry();
if (last.getValue() == null) {
return cumulativeCapacity.floorKey(last.getKey() - 1);
} else {
return last.getKey();
}
}
} finally {
readLock.unlock();
}
}
/**
* Returns true if there are no non-zero entries.
*
* @return true if there are no allocations or false otherwise
*/
public boolean isEmpty() {
readLock.lock();
try {
if (cumulativeCapacity.isEmpty()) {
return true;
}
// Deletion leaves a single zero entry with a null at the end so check for
// that
if (cumulativeCapacity.size() == 2) {
return cumulativeCapacity.firstEntry().getValue().equals(ZERO_RESOURCE)
&& cumulativeCapacity.lastEntry().getValue() == null;
}
return false;
} finally {
readLock.unlock();
}
}
@Override
public String toString() {
StringBuilder ret = new StringBuilder();
readLock.lock();
try {
if (cumulativeCapacity.size() > THRESHOLD) {
ret.append("Number of steps: ").append(cumulativeCapacity.size())
.append(" earliest entry: ").append(cumulativeCapacity.firstKey())
.append(" latest entry: ").append(cumulativeCapacity.lastKey());
} else {
for (Map.Entry<Long, Resource> r : cumulativeCapacity.entrySet()) {
ret.append(r.getKey()).append(": ").append(r.getValue())
.append("\n ");
}
}
return ret.toString();
} finally {
readLock.unlock();
}
}
/**
* Returns the representation of the current resources allocated over time as
* an interval map (in the defined non-null range).
*
* @return the representation of the current resources allocated over time as
* an interval map.
*/
public Map<ReservationInterval, Resource> toIntervalMap() {
readLock.lock();
try {
Map<ReservationInterval, Resource> allocations =
new TreeMap<ReservationInterval, Resource>();
// Empty
if (isEmpty()) {
return allocations;
}
Map.Entry<Long, Resource> lastEntry = null;
for (Map.Entry<Long, Resource> entry : cumulativeCapacity.entrySet()) {
if (lastEntry != null && entry.getValue() != null) {
ReservationInterval interval =
new ReservationInterval(lastEntry.getKey(), entry.getKey());
Resource resource = lastEntry.getValue();
allocations.put(interval, resource);
}
lastEntry = entry;
}
return allocations;
} finally {
readLock.unlock();
}
}
public NavigableMap<Long, Resource> getCumulative() {
readLock.lock();
try {
return cumulativeCapacity;
} finally {
readLock.unlock();
}
}
public ResourceCalculator getResourceCalculator() {
return resourceCalculator;
}
/**
* Merges the range start to end of two {@code RLESparseResourceAllocation}
* using a given {@code RLEOperator}.
*
* @param resCalc the resource calculator
* @param clusterResource the total cluster resources (for DRF)
* @param a the left operand
* @param b the right operand
* @param operator the operator to be applied during merge
* @param start the start-time of the range to be considered
* @param end the end-time of the range to be considered
* @return the a merged RLESparseResourceAllocation, produced by applying
* "operator" to "a" and "b"
* @throws PlanningException in case the operator is subtractTestPositive and
* the result would contain a negative value
*/
public static RLESparseResourceAllocation merge(ResourceCalculator resCalc,
Resource clusterResource, RLESparseResourceAllocation a,
RLESparseResourceAllocation b, RLEOperator operator, long start, long end)
throws PlanningException {
NavigableMap<Long, Resource> cumA =
a.getRangeOverlapping(start, end).getCumulative();
NavigableMap<Long, Resource> cumB =
b.getRangeOverlapping(start, end).getCumulative();
NavigableMap<Long, Resource> out =
merge(resCalc, clusterResource, cumA, cumB, start, end, operator);
return new RLESparseResourceAllocation(out, resCalc);
}
private static NavigableMap<Long, Resource> merge(ResourceCalculator resCalc,
Resource clusterResource, NavigableMap<Long, Resource> a,
NavigableMap<Long, Resource> b, long start, long end,
RLEOperator operator) throws PlanningException {
// handle special cases of empty input
if (a == null || a.isEmpty()) {
if (operator == RLEOperator.subtract
|| operator == RLEOperator.subtractTestNonNegative) {
return negate(operator, b);
} else {
return b;
}
}
if (b == null || b.isEmpty()) {
return a;
}
// define iterators and support variables
Iterator<Entry<Long, Resource>> aIt = a.entrySet().iterator();
Iterator<Entry<Long, Resource>> bIt = b.entrySet().iterator();
Entry<Long, Resource> curA = aIt.next();
Entry<Long, Resource> curB = bIt.next();
Entry<Long, Resource> lastA = null;
Entry<Long, Resource> lastB = null;
boolean aIsDone = false;
boolean bIsDone = false;
TreeMap<Long, Resource> out = new TreeMap<Long, Resource>();
while (!(curA.equals(lastA) && curB.equals(lastB))) {
Resource outRes;
long time = -1;
// curA is smaller than curB
if (bIsDone || (curA.getKey() < curB.getKey() && !aIsDone)) {
outRes = combineValue(operator, resCalc, clusterResource, curA, lastB);
time = (curA.getKey() < start) ? start : curA.getKey();
lastA = curA;
if (aIt.hasNext()) {
curA = aIt.next();
} else {
aIsDone = true;
}
} else {
// curB is smaller than curA
if (aIsDone || (curA.getKey() > curB.getKey() && !bIsDone)) {
outRes =
combineValue(operator, resCalc, clusterResource, lastA, curB);
time = (curB.getKey() < start) ? start : curB.getKey();
lastB = curB;
if (bIt.hasNext()) {
curB = bIt.next();
} else {
bIsDone = true;
}
} else {
// curA is equal to curB
outRes = combineValue(operator, resCalc, clusterResource, curA, curB);
time = (curA.getKey() < start) ? start : curA.getKey();
lastA = curA;
if (aIt.hasNext()) {
curA = aIt.next();
} else {
aIsDone = true;
}
lastB = curB;
if (bIt.hasNext()) {
curB = bIt.next();
} else {
bIsDone = true;
}
}
}
// add to out if not redundant
addIfNeeded(out, time, outRes);
}
addIfNeeded(out, end, null);
return out;
}
private static NavigableMap<Long, Resource> negate(RLEOperator operator,
NavigableMap<Long, Resource> a) throws PlanningException {
TreeMap<Long, Resource> out = new TreeMap<Long, Resource>();
for (Entry<Long, Resource> e : a.entrySet()) {
Resource val = Resources.negate(e.getValue());
// test for negative value and throws
if (operator == RLEOperator.subtractTestNonNegative
&& (Resources.fitsIn(val, ZERO_RESOURCE)
&& !Resources.equals(val, ZERO_RESOURCE))) {
throw new PlanningException(
"RLESparseResourceAllocation: merge failed as the "
+ "resulting RLESparseResourceAllocation would be negative");
}
out.put(e.getKey(), val);
}
return out;
}
private static void addIfNeeded(TreeMap<Long, Resource> out, long time,
Resource outRes) {
if (out.isEmpty() || (out.lastEntry() != null && outRes == null)
|| (out.lastEntry().getValue() != null
&& !Resources.equals(out.lastEntry().getValue(), outRes))) {
out.put(time, outRes);
}
}
private static Resource combineValue(RLEOperator op,
ResourceCalculator resCalc, Resource clusterResource,
Entry<Long, Resource> eA, Entry<Long, Resource> eB)
throws PlanningException {
// deal with nulls
if (eA == null || eA.getValue() == null) {
if (eB == null || eB.getValue() == null) {
return null;
}
if (op == RLEOperator.subtract) {
return Resources.negate(eB.getValue());
} else {
return eB.getValue();
}
}
if (eB == null || eB.getValue() == null) {
return eA.getValue();
}
Resource a = eA.getValue();
Resource b = eB.getValue();
switch (op) {
case add:
return Resources.add(a, b);
case subtract:
return Resources.subtract(a, b);
case subtractTestNonNegative:
if (!Resources.fitsIn(b, a)) {
throw new PlanningException(
"RLESparseResourceAllocation: merge failed as the "
+ "resulting RLESparseResourceAllocation would "
+ "be negative, when testing: (" + eB + ") > (" + eA + ")");
} else {
return Resources.subtract(a, b);
}
case min:
return Resources.min(resCalc, clusterResource, a, b);
case max:
return Resources.max(resCalc, clusterResource, a, b);
default:
return null;
}
}
/**
* Get a {@link RLESparseResourceAllocation} view of the {@link Resource}
* allocations between the specified start and end times.
*
* @param start the time from which the {@link Resource} allocations are
* required
* @param end the time upto which the {@link Resource} allocations are
* required
* @return the overlapping allocations
*/
public RLESparseResourceAllocation getRangeOverlapping(long start, long end) {
readLock.lock();
try {
NavigableMap<Long, Resource> a = this.getCumulative();
if (a != null && !a.isEmpty()) {
// include the portion of previous entry that overlaps start
if (start > a.firstKey()) {
long previous = a.floorKey(start);
a = a.tailMap(previous, true);
}
if (end < a.lastKey()) {
a = a.headMap(end, true);
}
}
RLESparseResourceAllocation ret =
new RLESparseResourceAllocation(a, resourceCalculator);
return ret;
} finally {
readLock.unlock();
}
}
/**
* This method shifts all the timestamp of the {@link Resource} entries by the
* specified "delta".
*
* @param delta the time by which to shift the {@link Resource} allocations
*/
public void shift(long delta) {
writeLock.lock();
try {
TreeMap<Long, Resource> newCum = new TreeMap<>();
long start;
for (Map.Entry<Long, Resource> entry : cumulativeCapacity.entrySet()) {
if (delta > 0) {
start = (entry.getKey() == Long.MAX_VALUE) ? Long.MAX_VALUE
: entry.getKey() + delta;
} else {
start = (entry.getKey() == Long.MIN_VALUE) ? Long.MIN_VALUE
: entry.getKey() + delta;
}
newCum.put(start, entry.getValue());
}
cumulativeCapacity = newCum;
} finally {
writeLock.unlock();
}
}
/**
* The set of operators that can be applied to two
* {@code RLESparseResourceAllocation} during a merge operation.
*/
public enum RLEOperator {
add, subtract, min, max, subtractTestNonNegative
}
/**
* Get the maximum capacity across specified time instances. The search-space
* is specified using the starting value, tick, and the periodic interval for
* search. Maximum resource allocation across tick, tick + period, tick + 2 *
* period,..., tick + n * period .. is returned.
*
* @param tick the starting time instance
* @param period interval at which capacity is evaluated
* @return maximum resource allocation
*/
public Resource getMaximumPeriodicCapacity(long tick, long period) {
Resource maxCapacity = ZERO_RESOURCE;
readLock.lock();
try {
if (!cumulativeCapacity.isEmpty()) {
Long lastKey = cumulativeCapacity.lastKey();
for (long t = tick; t <= lastKey; t = t + period) {
maxCapacity = Resources.componentwiseMax(maxCapacity,
cumulativeCapacity.floorEntry(t).getValue());
}
}
return maxCapacity;
} finally {
readLock.unlock();
}
}
/**
* Get the minimum capacity in the specified time range.
*
* @param interval the {@link ReservationInterval} to be searched
* @return minimum resource allocation
*/
public Resource getMinimumCapacityInInterval(ReservationInterval interval) {
Resource minCapacity =
Resource.newInstance(Integer.MAX_VALUE, Integer.MAX_VALUE);
long start = interval.getStartTime();
long end = interval.getEndTime();
NavigableMap<Long, Resource> capacityRange =
getRangeOverlapping(start, end).getCumulative();
if (!capacityRange.isEmpty()) {
for (Map.Entry<Long, Resource> entry : capacityRange.entrySet()) {
if (entry.getValue() != null) {
minCapacity =
Resources.componentwiseMin(minCapacity, entry.getValue());
}
}
}
return minCapacity;
}
}
| 7,355 |
3,984 | {
"name": "element-slot",
"main": "./element-slot",
"description": "Slot in element tree",
"displayName": "Element Slot",
"flag": "alpha",
"version": "1.0.0",
"tags": []
}
| 76 |
341 | {
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Site Column Formatting JSON Definition Deployment",
"type": "shell",
"command": "powershell .\\PowerShell\\ListFormatting.Deployment.SiteColumn.ps1"
},
{
"label": "List Column Formatting JSON Definition Deployment",
"type": "shell",
"command": "powershell .\\PowerShell\\ListFormatting.Deployment.ListColumn.ps1"
},
{
"label": "List View Formatting JSON Definition Deployment",
"type": "shell",
"command": "powershell .\\PowerShell\\ListFormatting.Deployment.ListView.ps1"
}
]
} | 358 |
307 | //
//
#if defined(_MSC_VER) && _MSC_VER <= 1920
// work around MSVC 2015 and 2017 compiler bug
// https://bugreports.qt.io/browse/QTBUG-72073
#define QT_NO_FLOAT16_OPERATORS
#endif
#include "QtGraphicsOperations.h"
#include "widgets/renderwidget.h"
#include <QtWidgets/QtWidgets>
#include "FredApplication.h"
namespace {
QSurfaceFormat getSurfaceFormat(const os::ViewPortProperties& viewProps, const os::OpenGLContextAttributes& glAttrs) {
QSurfaceFormat format;
format.setRedBufferSize(viewProps.pixel_format.red_size);
format.setGreenBufferSize(viewProps.pixel_format.green_size);
format.setBlueBufferSize(viewProps.pixel_format.blue_size);
format.setAlphaBufferSize(viewProps.pixel_format.alpha_size);
format.setDepthBufferSize(viewProps.pixel_format.depth_size);
format.setStencilBufferSize(viewProps.pixel_format.stencil_size);
format.setSamples(viewProps.pixel_format.multi_samples);
format.setRenderableType(QSurfaceFormat::OpenGL);
switch(glAttrs.profile) {
case os::OpenGLProfile::Core:
format.setProfile(QSurfaceFormat::CoreProfile);
break;
case os::OpenGLProfile::Compatibility:
format.setProfile(QSurfaceFormat::CompatibilityProfile);
break;
}
if (glAttrs.flags[os::OpenGLContextFlags::Debug]) {
format.setOption(QSurfaceFormat::DebugContext);
}
if (!glAttrs.flags[os::OpenGLContextFlags::ForwardCompatible]) {
format.setOption(QSurfaceFormat::DeprecatedFunctions);
}
format.setMajorVersion(glAttrs.major_version);
format.setMinorVersion(glAttrs.minor_version);
return format;
}
}
namespace fso {
namespace fred {
QtGraphicsOperations::QtGraphicsOperations(Editor* editor) : _editor(editor) {
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) {
Error(LOCATION, "Couldn't init SDL video: %s", SDL_GetError());
return;
}
}
QtGraphicsOperations::~QtGraphicsOperations() {
SDL_QuitSubSystem(SDL_INIT_VIDEO);
}
std::unique_ptr<os::OpenGLContext>
QtGraphicsOperations::createOpenGLContext(os::Viewport* viewport, const os::OpenGLContextAttributes& gl_attrs) {
auto qtPort = static_cast<QtViewport*>(viewport);
std::unique_ptr<QOpenGLContext> context(new QOpenGLContext());
context->setFormat(getSurfaceFormat(qtPort->getViewProperties(), gl_attrs));
if (!context->create()) {
return nullptr;
}
return std::unique_ptr<os::OpenGLContext>(new QtOpenGLContext(std::move(context)));
}
void QtGraphicsOperations::makeOpenGLContextCurrent(os::Viewport* view, os::OpenGLContext* ctx) {
auto qtPort = static_cast<QtViewport*>(view);
auto qtContext = static_cast<QtOpenGLContext*>(ctx);
if (qtPort == nullptr && qtContext == nullptr) {
if (_lastContext != nullptr) {
_lastContext->makeCurrent(nullptr);
}
} else {
qtContext->makeCurrent(qtPort->getWindow()->getRenderSurface());
}
// We keep track of our last context since the qt information may return contexts managed by the GUI framework
_lastContext = qtContext;
}
QtViewport::QtViewport(std::unique_ptr<FredView>&& window, const os::ViewPortProperties& viewProps) :
_viewProps(viewProps) {
_viewportWindow = std::move(window);
}
QtViewport::~QtViewport() {
}
std::unique_ptr<os::Viewport> QtGraphicsOperations::createViewport(const os::ViewPortProperties& props) {
std::unique_ptr<FredView> mw(new FredView());
mw->getRenderWidget()->setSurfaceFormat(getSurfaceFormat(props, props.gl_attributes));
auto viewPtr = mw.get();
auto view = std::unique_ptr<os::Viewport>(new QtViewport(std::move(mw), props));
auto renderer = _editor->createEditorViewport(view.get());
viewPtr->setEditor(_editor, renderer);
if (fredApp->isInitializeComplete()) {
// Only show new viewports if the initialization has already been completed
// The windows created at program start will only be shown once initialization is completed
viewPtr->show();
}
return view;
}
SDL_Window* QtViewport::toSDLWindow() {
return nullptr;
}
std::pair<uint32_t, uint32_t> QtViewport::getSize() {
auto size = _viewportWindow->getRenderSurface()->size();
return std::make_pair((uint32_t) size.width(), (uint32_t) size.height());
}
void QtViewport::swapBuffers() {
auto qSurf = dynamic_cast<QWindow*>(_viewportWindow->getRenderSurface());
if (qSurf && qSurf->isExposed()) {
QOpenGLContext::currentContext()->swapBuffers(qSurf);
}
}
void QtViewport::setState(os::ViewportState /*state*/) {
// Not used in FRED
}
void QtViewport::minimize() {
_viewportWindow->showMinimized();
}
void QtViewport::restore() {
_viewportWindow->show();
}
const os::ViewPortProperties& QtViewport::getViewProperties() const {
return _viewProps;
}
FredView* QtViewport::getWindow() {
return _viewportWindow.get();
}
static void* openglFunctionLoader(const char* name) {
auto currentCtx = QOpenGLContext::currentContext();
if (currentCtx == nullptr) {
return nullptr;
}
return reinterpret_cast<void*>(currentCtx->getProcAddress(name));
}
QtOpenGLContext::QtOpenGLContext(std::unique_ptr<QOpenGLContext>&& context) : _context(std::move(context)) {
}
QtOpenGLContext::~QtOpenGLContext() {
}
os::OpenGLLoadProc QtOpenGLContext::getLoaderFunction() {
return openglFunctionLoader;
}
bool QtOpenGLContext::setSwapInterval(int) {
// Not used at the moment, should default to vsync enabled
return true;
}
void QtOpenGLContext::makeCurrent(QSurface* surface) {
_context->makeCurrent(surface);
}
}
}
| 1,862 |
323 | package io.codearte.jfairy;
import io.codearte.jfairy.data.DataMaster;
import io.codearte.jfairy.producer.RandomGenerator;
import io.codearte.jfairy.producer.VATIdentificationNumberProvider;
import io.codearte.jfairy.producer.company.locale.es.EsVATIdentificationNumberProvider;
import io.codearte.jfairy.producer.person.AddressProvider;
import io.codearte.jfairy.producer.person.NationalIdentificationNumberFactory;
import io.codearte.jfairy.producer.person.NationalIdentityCardNumberProvider;
import io.codearte.jfairy.producer.person.PassportNumberProvider;
import io.codearte.jfairy.producer.person.locale.NoNationalIdentificationNumberFactory;
import io.codearte.jfairy.producer.person.locale.es.EsAddressProvider;
import io.codearte.jfairy.producer.person.locale.es.EsNationalIdentityCardNumberProvider;
import io.codearte.jfairy.producer.person.locale.es.EsPassportNumberProvider;
/**
* @author graux
* @since 26.04.15
*/
public class EsFairyModule extends FairyModule {
public EsFairyModule(DataMaster dataMaster, RandomGenerator randomGenerator) {
super(dataMaster, randomGenerator);
}
@Override
protected void configure() {
super.configure();
bind(NationalIdentificationNumberFactory.class).to(NoNationalIdentificationNumberFactory.class);
bind(NationalIdentityCardNumberProvider.class).to(EsNationalIdentityCardNumberProvider.class);
bind(VATIdentificationNumberProvider.class).to(EsVATIdentificationNumberProvider.class);
bind(AddressProvider.class).to(EsAddressProvider.class);
bind(PassportNumberProvider.class).to(EsPassportNumberProvider.class);
}
}
| 495 |
390 | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.tinylog.format;
/**
* Formatter for text messages with placeholders for arguments.
*/
public interface MessageFormatter {
/**
* Formats a text message. All placeholders will be replaced with the given arguments.
*
* @param message
* Text message with placeholders
* @param arguments
* Replacements for placeholders
* @return Formatted text message
*/
String format(String message, Object[] arguments);
}
| 282 |
9,182 | <filename>Ref/Top/FppConstantsAc.cpp<gh_stars>1000+
// ======================================================================
// \title FppConstantsAc.cpp
// \author Generated by fpp-to-cpp
// \brief cpp file for FPP constants
//
// \copyright
// Copyright (c) 2021 California Institute of Technology.
// U.S. Government sponsorship acknowledged.
// All rights reserved.
// ======================================================================
#include "Ref/Top/FppConstantsAc.hpp"
namespace Ref {
namespace Default {
}
}
| 140 |
2,151 | <reponame>zipated/src
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef IOS_CHROME_BROWSER_INFOBARS_CONFIRM_INFOBAR_CONTROLLER_H_
#define IOS_CHROME_BROWSER_INFOBARS_CONFIRM_INFOBAR_CONTROLLER_H_
#import "ios/chrome/browser/infobars/infobar_controller.h"
class ConfirmInfoBarDelegate;
@interface ConfirmInfoBarController : InfoBarController
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithInfoBarDelegate:(ConfirmInfoBarDelegate*)delegate;
@end
#endif // IOS_CHROME_BROWSER_INFOBARS_CONFIRM_INFOBAR_CONTROLLER_H_
| 249 |
772 | <reponame>malliina/scrimage
package com.sksamuel.scrimage.filter;
public enum RippleType {
Sine,
Sawtooth,
Triangle,
Noise
}
| 63 |
4,262 | <reponame>rikvb/camel
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.google.bigquery.unit.sql;
import java.util.HashMap;
import java.util.Map;
import com.google.cloud.bigquery.JobId;
import com.google.cloud.bigquery.QueryJobConfiguration;
import com.google.cloud.bigquery.QueryParameterValue;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.RuntimeExchangeException;
import org.apache.camel.component.google.bigquery.GoogleBigQueryConstants;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static org.apache.camel.component.google.bigquery.integration.BigQueryITSupport.PROJECT_ID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
public class GoogleBigQuerySQLProducerWithParamersTest extends GoogleBigQuerySQLProducerBaseTest {
@BeforeEach
public void init() throws Exception {
sql = "insert into testDatasetId.testTableId(id, data) values(@id, @data)";
setupBigqueryMock();
producer = createAndStartProducer();
}
@Test
public void sendMessageWithParametersInBody() throws Exception {
Map<String, String> body = new HashMap<>();
body.put("id", "100");
body.put("data", "some data");
producer.process(createExchangeWithBody(body));
ArgumentCaptor<QueryJobConfiguration> dataCaptor = ArgumentCaptor.forClass(QueryJobConfiguration.class);
verify(bigquery).query(dataCaptor.capture(), any(JobId.class));
QueryJobConfiguration request = dataCaptor.getValue();
assertEquals(sql, request.getQuery());
Map<String, QueryParameterValue> namedParameters = request.getNamedParameters();
assertEquals(2, namedParameters.size());
assertTrue(namedParameters.containsKey("id"));
assertEquals("100", namedParameters.get("id").getValue());
assertTrue(namedParameters.containsKey("data"));
assertEquals("some data", namedParameters.get("data").getValue());
}
@Test
public void sendMessageWithParametersInBodyAndHeaders() throws Exception {
Map<String, String> body = new HashMap<>();
body.put("id", "100");
Exchange exchange = createExchangeWithBody(body);
Message message = exchange.getMessage();
message.setHeader("id", "200");
message.setHeader("data", "some data");
producer.process(exchange);
ArgumentCaptor<QueryJobConfiguration> dataCaptor = ArgumentCaptor.forClass(QueryJobConfiguration.class);
verify(bigquery).query(dataCaptor.capture(), any(JobId.class));
QueryJobConfiguration request = dataCaptor.getValue();
assertEquals(sql, request.getQuery());
Map<String, QueryParameterValue> namedParameters = request.getNamedParameters();
assertEquals(2, namedParameters.size());
assertTrue(namedParameters.containsKey("id"));
assertEquals("100", namedParameters.get("id").getValue(), "Body data must have higher priority");
assertTrue(namedParameters.containsKey("data"));
assertEquals("some data", namedParameters.get("data").getValue());
}
@Test
public void sendMessageWithJobIdHeader() throws Exception {
Map<String, String> body = new HashMap<>();
body.put("id", "100");
Exchange exchange = createExchangeWithBody(body);
Message message = exchange.getMessage();
message.setHeader("id", "200");
message.setHeader("data", "some data");
JobId jobId = JobId.of(PROJECT_ID, "a-test-job");
message.setHeader(GoogleBigQueryConstants.JOB_ID, jobId);
producer.process(exchange);
ArgumentCaptor<QueryJobConfiguration> dataCaptor = ArgumentCaptor.forClass(QueryJobConfiguration.class);
verify(bigquery).query(dataCaptor.capture(), eq(jobId));
QueryJobConfiguration request = dataCaptor.getValue();
assertEquals(sql, request.getQuery());
Map<String, QueryParameterValue> namedParameters = request.getNamedParameters();
assertEquals(2, namedParameters.size());
assertTrue(namedParameters.containsKey("id"));
assertEquals("100", namedParameters.get("id").getValue(), "Body data must have higher priority");
assertTrue(namedParameters.containsKey("data"));
assertEquals("some data", namedParameters.get("data").getValue());
}
@Test
public void sendMessageWithoutParameters() throws Exception {
final Exchange exchangeWithBody = createExchangeWithBody(new HashMap<>());
assertThrows(RuntimeExchangeException.class, () -> producer.process(exchangeWithBody));
}
}
| 1,921 |
1,647 | <gh_stars>1000+
#ifndef PYTHONIC_INCLUDE_NUMPY__HPP
#define PYTHONIC_INCLUDE_NUMPY__HPP
#endif
| 54 |
407 | <filename>core/src/main/java/com/alibaba/smart/framework/engine/exception/LockException.java
package com.alibaba.smart.framework.engine.exception;
/**
* @author 高海军 帝奇 2016.11.11
*/
public class LockException extends EngineException {
private static final long serialVersionUID = -5576514678329147766L;
public LockException(String message) {
super(message);
}
public LockException(String message, Exception e) {
super(message, e);
}
}
| 171 |
12,278 | <reponame>rajeev02101987/arangodb<gh_stars>1000+
/*=============================================================================
Copyright (c) 2000-2003 <NAME> and <NAME>
Copyright (c) 2001-2007 <NAME>
Copyright (c) 2011 <NAME>
Copyright (c) 2015 <NAME>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#include <boost/phoenix/function/lazy_prelude.hpp>
int main() {}
| 170 |
336 | package me.saket.dank.ui.submission;
import android.content.Context;
import android.widget.Toast;
import net.dean.jraw.models.Comment;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import dagger.Lazy;
import me.saket.dank.R;
import me.saket.dank.di.Dank;
import me.saket.dank.reddit.Reddit;
import me.saket.dank.utils.Clipboards;
import me.saket.dank.utils.Intents;
import me.saket.dank.utils.NestedOptionsPopupMenu;
import me.saket.dank.utils.markdown.Markdown;
import okhttp3.HttpUrl;
public class CommentOptionsPopup extends NestedOptionsPopupMenu {
private static final int ID_SHOW_USER_PROFILE = 0;
private static final int ID_SAVE = 1_1;
private static final int ID_UNSAVE = 1_2;
private static final int ID_SHARE_PERMALINK = 2;
private static final int ID_COPY_PERMALINK = 3;
@Inject Lazy<Markdown> markdown;
@Inject Lazy<BookmarksRepository> bookmarksRepository;
private final Comment comment;
public CommentOptionsPopup(Context c, Comment comment) {
super(c);
this.comment = comment;
Dank.dependencyInjector().inject(this);
createMenuLayout(c, menuStructure(c));
}
private MenuStructure menuStructure(Context c) {
//noinspection AccessStaticViaInstance
String commentBody = markdown.get().stripMarkdown(comment);
List<MenuStructure.SingleLineItem> primaryItems = new ArrayList<>(3);
primaryItems.add(MenuStructure.SingleLineItem.create(
ID_SHOW_USER_PROFILE,
c.getString(R.string.user_name_u_prefix, comment.getAuthor()),
R.drawable.ic_user_profile_20dp
));
if (bookmarksRepository.get().isSaved(comment)) {
primaryItems.add(MenuStructure.SingleLineItem.create(
ID_UNSAVE,
c.getString(R.string.submission_comment_option_unsave),
R.drawable.ic_unsave_24dp
));
} else {
primaryItems.add(MenuStructure.SingleLineItem.create(
ID_SAVE,
c.getString(R.string.submission_comment_option_save),
R.drawable.ic_save_20dp
));
}
primaryItems.add(MenuStructure.SingleLineItem.create(
ID_SHARE_PERMALINK,
c.getString(R.string.submission_comment_option_share_link),
R.drawable.ic_share_20dp
));
primaryItems.add(MenuStructure.SingleLineItem.create(
ID_COPY_PERMALINK,
c.getString(R.string.submission_comment_option_copy_link),
R.drawable.ic_copy_20dp
));
return MenuStructure.create(commentBody, primaryItems);
}
@Override
protected void handleAction(Context c, int actionId) {
//noinspection ConstantConditions
String permalinkWithContext = HttpUrl.parse("https://reddit.com" + comment.getPermalink())
.newBuilder()
.addQueryParameter(Reddit.CONTEXT_QUERY_PARAM, String.valueOf(Reddit.COMMENT_DEFAULT_CONTEXT_COUNT))
.build()
.toString();
switch (actionId) {
case ID_SHOW_USER_PROFILE:
Toast.makeText(c, R.string.work_in_progress, Toast.LENGTH_SHORT).show();
break;
case ID_UNSAVE:
bookmarksRepository.get().markAsUnsaved(comment);
break;
case ID_SAVE:
bookmarksRepository.get().markAsSaved(comment);
break;
case ID_SHARE_PERMALINK:
c.startActivity(Intents.createForSharingUrl(c, permalinkWithContext));
break;
case ID_COPY_PERMALINK:
Clipboards.save(c, permalinkWithContext);
Toast.makeText(c, R.string.copy_to_clipboard_confirmation, Toast.LENGTH_SHORT).show();
break;
default:
throw new UnsupportedOperationException("actionId: " + actionId);
}
dismiss();
}
}
| 1,485 |
6,989 | <reponame>HeyLey/catboost<filename>contrib/libs/clapack/clascl.c
/* clascl.f -- translated by f2c (version 20061008).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#include "f2c.h"
#include "blaswrap.h"
/* Subroutine */ int clascl_(char *type__, integer *kl, integer *ku, real *
cfrom, real *cto, integer *m, integer *n, complex *a, integer *lda,
integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5;
complex q__1;
/* Local variables */
integer i__, j, k1, k2, k3, k4;
real mul, cto1;
logical done;
real ctoc;
extern logical lsame_(char *, char *);
integer itype;
real cfrom1;
extern doublereal slamch_(char *);
real cfromc;
extern /* Subroutine */ int xerbla_(char *, integer *);
real bignum;
extern logical sisnan_(real *);
real smlnum;
/* -- LAPACK auxiliary routine (version 3.2) -- */
/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */
/* November 2006 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* CLASCL multiplies the M by N complex matrix A by the real scalar */
/* CTO/CFROM. This is done without over/underflow as long as the final */
/* result CTO*A(I,J)/CFROM does not over/underflow. TYPE specifies that */
/* A may be full, upper triangular, lower triangular, upper Hessenberg, */
/* or banded. */
/* Arguments */
/* ========= */
/* TYPE (input) CHARACTER*1 */
/* TYPE indices the storage type of the input matrix. */
/* = 'G': A is a full matrix. */
/* = 'L': A is a lower triangular matrix. */
/* = 'U': A is an upper triangular matrix. */
/* = 'H': A is an upper Hessenberg matrix. */
/* = 'B': A is a symmetric band matrix with lower bandwidth KL */
/* and upper bandwidth KU and with the only the lower */
/* half stored. */
/* = 'Q': A is a symmetric band matrix with lower bandwidth KL */
/* and upper bandwidth KU and with the only the upper */
/* half stored. */
/* = 'Z': A is a band matrix with lower bandwidth KL and upper */
/* bandwidth KU. */
/* KL (input) INTEGER */
/* The lower bandwidth of A. Referenced only if TYPE = 'B', */
/* 'Q' or 'Z'. */
/* KU (input) INTEGER */
/* The upper bandwidth of A. Referenced only if TYPE = 'B', */
/* 'Q' or 'Z'. */
/* CFROM (input) REAL */
/* CTO (input) REAL */
/* The matrix A is multiplied by CTO/CFROM. A(I,J) is computed */
/* without over/underflow if the final result CTO*A(I,J)/CFROM */
/* can be represented without over/underflow. CFROM must be */
/* nonzero. */
/* M (input) INTEGER */
/* The number of rows of the matrix A. M >= 0. */
/* N (input) INTEGER */
/* The number of columns of the matrix A. N >= 0. */
/* A (input/output) COMPLEX array, dimension (LDA,N) */
/* The matrix to be multiplied by CTO/CFROM. See TYPE for the */
/* storage type. */
/* LDA (input) INTEGER */
/* The leading dimension of the array A. LDA >= max(1,M). */
/* INFO (output) INTEGER */
/* 0 - successful exit */
/* <0 - if INFO = -i, the i-th argument had an illegal value. */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. External Functions .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. Executable Statements .. */
/* Test the input arguments */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1;
a -= a_offset;
/* Function Body */
*info = 0;
if (lsame_(type__, "G")) {
itype = 0;
} else if (lsame_(type__, "L")) {
itype = 1;
} else if (lsame_(type__, "U")) {
itype = 2;
} else if (lsame_(type__, "H")) {
itype = 3;
} else if (lsame_(type__, "B")) {
itype = 4;
} else if (lsame_(type__, "Q")) {
itype = 5;
} else if (lsame_(type__, "Z")) {
itype = 6;
} else {
itype = -1;
}
if (itype == -1) {
*info = -1;
} else if (*cfrom == 0.f || sisnan_(cfrom)) {
*info = -4;
} else if (sisnan_(cto)) {
*info = -5;
} else if (*m < 0) {
*info = -6;
} else if (*n < 0 || itype == 4 && *n != *m || itype == 5 && *n != *m) {
*info = -7;
} else if (itype <= 3 && *lda < max(1,*m)) {
*info = -9;
} else if (itype >= 4) {
/* Computing MAX */
i__1 = *m - 1;
if (*kl < 0 || *kl > max(i__1,0)) {
*info = -2;
} else /* if(complicated condition) */ {
/* Computing MAX */
i__1 = *n - 1;
if (*ku < 0 || *ku > max(i__1,0) || (itype == 4 || itype == 5) &&
*kl != *ku) {
*info = -3;
} else if (itype == 4 && *lda < *kl + 1 || itype == 5 && *lda < *
ku + 1 || itype == 6 && *lda < (*kl << 1) + *ku + 1) {
*info = -9;
}
}
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("CLASCL", &i__1);
return 0;
}
/* Quick return if possible */
if (*n == 0 || *m == 0) {
return 0;
}
/* Get machine parameters */
smlnum = slamch_("S");
bignum = 1.f / smlnum;
cfromc = *cfrom;
ctoc = *cto;
L10:
cfrom1 = cfromc * smlnum;
if (cfrom1 == cfromc) {
/* CFROMC is an inf. Multiply by a correctly signed zero for */
/* finite CTOC, or a NaN if CTOC is infinite. */
mul = ctoc / cfromc;
done = TRUE_;
cto1 = ctoc;
} else {
cto1 = ctoc / bignum;
if (cto1 == ctoc) {
/* CTOC is either 0 or an inf. In both cases, CTOC itself */
/* serves as the correct multiplication factor. */
mul = ctoc;
done = TRUE_;
cfromc = 1.f;
} else if (dabs(cfrom1) > dabs(ctoc) && ctoc != 0.f) {
mul = smlnum;
done = FALSE_;
cfromc = cfrom1;
} else if (dabs(cto1) > dabs(cfromc)) {
mul = bignum;
done = FALSE_;
ctoc = cto1;
} else {
mul = ctoc / cfromc;
done = TRUE_;
}
}
if (itype == 0) {
/* Full matrix */
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
i__2 = *m;
for (i__ = 1; i__ <= i__2; ++i__) {
i__3 = i__ + j * a_dim1;
i__4 = i__ + j * a_dim1;
q__1.r = mul * a[i__4].r, q__1.i = mul * a[i__4].i;
a[i__3].r = q__1.r, a[i__3].i = q__1.i;
/* L20: */
}
/* L30: */
}
} else if (itype == 1) {
/* Lower triangular matrix */
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
i__2 = *m;
for (i__ = j; i__ <= i__2; ++i__) {
i__3 = i__ + j * a_dim1;
i__4 = i__ + j * a_dim1;
q__1.r = mul * a[i__4].r, q__1.i = mul * a[i__4].i;
a[i__3].r = q__1.r, a[i__3].i = q__1.i;
/* L40: */
}
/* L50: */
}
} else if (itype == 2) {
/* Upper triangular matrix */
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
i__2 = min(j,*m);
for (i__ = 1; i__ <= i__2; ++i__) {
i__3 = i__ + j * a_dim1;
i__4 = i__ + j * a_dim1;
q__1.r = mul * a[i__4].r, q__1.i = mul * a[i__4].i;
a[i__3].r = q__1.r, a[i__3].i = q__1.i;
/* L60: */
}
/* L70: */
}
} else if (itype == 3) {
/* Upper Hessenberg matrix */
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/* Computing MIN */
i__3 = j + 1;
i__2 = min(i__3,*m);
for (i__ = 1; i__ <= i__2; ++i__) {
i__3 = i__ + j * a_dim1;
i__4 = i__ + j * a_dim1;
q__1.r = mul * a[i__4].r, q__1.i = mul * a[i__4].i;
a[i__3].r = q__1.r, a[i__3].i = q__1.i;
/* L80: */
}
/* L90: */
}
} else if (itype == 4) {
/* Lower half of a symmetric band matrix */
k3 = *kl + 1;
k4 = *n + 1;
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/* Computing MIN */
i__3 = k3, i__4 = k4 - j;
i__2 = min(i__3,i__4);
for (i__ = 1; i__ <= i__2; ++i__) {
i__3 = i__ + j * a_dim1;
i__4 = i__ + j * a_dim1;
q__1.r = mul * a[i__4].r, q__1.i = mul * a[i__4].i;
a[i__3].r = q__1.r, a[i__3].i = q__1.i;
/* L100: */
}
/* L110: */
}
} else if (itype == 5) {
/* Upper half of a symmetric band matrix */
k1 = *ku + 2;
k3 = *ku + 1;
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/* Computing MAX */
i__2 = k1 - j;
i__3 = k3;
for (i__ = max(i__2,1); i__ <= i__3; ++i__) {
i__2 = i__ + j * a_dim1;
i__4 = i__ + j * a_dim1;
q__1.r = mul * a[i__4].r, q__1.i = mul * a[i__4].i;
a[i__2].r = q__1.r, a[i__2].i = q__1.i;
/* L120: */
}
/* L130: */
}
} else if (itype == 6) {
/* Band matrix */
k1 = *kl + *ku + 2;
k2 = *kl + 1;
k3 = (*kl << 1) + *ku + 1;
k4 = *kl + *ku + 1 + *m;
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/* Computing MAX */
i__3 = k1 - j;
/* Computing MIN */
i__4 = k3, i__5 = k4 - j;
i__2 = min(i__4,i__5);
for (i__ = max(i__3,k2); i__ <= i__2; ++i__) {
i__3 = i__ + j * a_dim1;
i__4 = i__ + j * a_dim1;
q__1.r = mul * a[i__4].r, q__1.i = mul * a[i__4].i;
a[i__3].r = q__1.r, a[i__3].i = q__1.i;
/* L140: */
}
/* L150: */
}
}
if (! done) {
goto L10;
}
return 0;
/* End of CLASCL */
} /* clascl_ */
| 4,738 |
721 | <reponame>asmuth-archive/travistest
/**
* This file is part of the "clip" project
* Copyright (c) 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.
*/
#include "draw.h"
#include "context.h"
#include <graphics/text.h>
#include <graphics/text_shaper.h>
#include "graphics/text_layout.h"
#include "graphics/text_support.h"
#include "draw/text.h"
namespace clip {
void draw_shape(Context* ctx, DrawCommand shape) {
auto layer = layer_get(ctx);
if (shape.fill_style.color) {
if (shape.fill_style.hatch) {
shape.style.fill_hatch.push_back({
.color = *shape.fill_style.color,
.angle_deg = shape.fill_style.hatch_angle_deg,
.offset = Number(shape.fill_style.hatch_offset),
.stride = Number(shape.fill_style.hatch_stride),
.width = Number(shape.fill_style.hatch_width),
});
} else {
shape.style.fill_solid.emplace_back(*shape.fill_style.color);
}
shape.fill_style = {};
}
if (shape.stroke_style.line_width.value) {
switch (shape.stroke_style.dash_type) {
case StrokeStyle::SOLID:
shape.style.stroke_solid.push_back({
.color = shape.stroke_style.color,
.width = shape.stroke_style.line_width
});
break;
case StrokeStyle::DASH:
std::vector<Number> pattern(shape.stroke_style.dash_pattern.size());
std::transform(
shape.stroke_style.dash_pattern.begin(),
shape.stroke_style.dash_pattern.end(),
pattern.begin(),
[] (auto v) { return Number(v); });
shape.style.stroke_dash.push_back({
.color = shape.stroke_style.color,
.width = shape.stroke_style.line_width,
.pattern = pattern,
.offset = Number(shape.stroke_style.dash_offset),
});
break;
}
shape.stroke_style = {};
}
layer_get(ctx)->drawlist.emplace_back(std::move(shape));
}
void draw_path(
Context* ctx,
const Path& path,
StrokeStyle stroke_style,
FillStyle fill_style) {
DrawCommand shape;
shape.path = path;
shape.stroke_style = stroke_style;
shape.fill_style = fill_style;
draw_shape(ctx, shape);
}
void draw_polygon(
Context* ctx,
const Poly2& poly,
StrokeStyle stroke_style,
FillStyle fill_style) {
DrawCommand shape;
shape.path = path_from_poly2(poly);
shape.stroke_style = stroke_style;
shape.fill_style = fill_style;
draw_shape(ctx, shape);
}
void draw_line(
Context* ctx,
vec2 from,
vec2 to,
StrokeStyle stroke_style) {
DrawCommand shape;
shape.path.moveTo(from.x, from.y);
shape.path.lineTo(to.x, to.y);
shape.stroke_style = stroke_style;
draw_shape(ctx, shape);
}
ReturnCode draw_text(
Context* ctx,
const std::string& text,
const Point& position,
HAlign align_x,
VAlign align_y,
double rotate,
TextStyle text_style) {
draw::text_op op;
op.text = text;
op.placement.position = position;
op.placement.align_x = align_x;
op.placement.align_y = align_y;
op.text_style = text_style;
op.draw_style.fill_solid.push_back(draw_style::fill_solid(text_style.color));
if (rotate) {
op.transform = mul(
translate2({position.x, position.y}),
mul(
rotate2(rotate),
translate2({-position.x, -position.y})));
}
return draw::text(ctx, op);
}
ReturnCode draw_text(
Context* ctx,
const std::string& text,
const Point& position,
HAlign align_x,
VAlign align_y,
TextStyle text_style) {
return draw_text(
ctx,
text,
position,
align_x,
align_y,
0,
text_style);
}
} // namespace clip
| 1,674 |
938 | <reponame>LaudateCorpus1/swift-llvm<filename>lib/ProfileData/InstrProfReader.cpp<gh_stars>100-1000
//===- InstrProfReader.cpp - Instrumented profiling reader ----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains support for reading profiling data for clang's
// instrumentation based PGO and coverage.
//
//===----------------------------------------------------------------------===//
#include "llvm/ProfileData/InstrProfReader.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/ProfileSummary.h"
#include "llvm/ProfileData/InstrProf.h"
#include "llvm/ProfileData/ProfileCommon.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SymbolRemappingReader.h"
#include "llvm/Support/SwapByteOrder.h"
#include <algorithm>
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <memory>
#include <system_error>
#include <utility>
#include <vector>
using namespace llvm;
static Expected<std::unique_ptr<MemoryBuffer>>
setupMemoryBuffer(const Twine &Path) {
ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
MemoryBuffer::getFileOrSTDIN(Path);
if (std::error_code EC = BufferOrErr.getError())
return errorCodeToError(EC);
return std::move(BufferOrErr.get());
}
static Error initializeReader(InstrProfReader &Reader) {
return Reader.readHeader();
}
Expected<std::unique_ptr<InstrProfReader>>
InstrProfReader::create(const Twine &Path) {
// Set up the buffer to read.
auto BufferOrError = setupMemoryBuffer(Path);
if (Error E = BufferOrError.takeError())
return std::move(E);
return InstrProfReader::create(std::move(BufferOrError.get()));
}
Expected<std::unique_ptr<InstrProfReader>>
InstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer) {
// Sanity check the buffer.
if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<unsigned>::max())
return make_error<InstrProfError>(instrprof_error::too_large);
if (Buffer->getBufferSize() == 0)
return make_error<InstrProfError>(instrprof_error::empty_raw_profile);
std::unique_ptr<InstrProfReader> Result;
// Create the reader.
if (IndexedInstrProfReader::hasFormat(*Buffer))
Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
else if (RawInstrProfReader64::hasFormat(*Buffer))
Result.reset(new RawInstrProfReader64(std::move(Buffer)));
else if (RawInstrProfReader32::hasFormat(*Buffer))
Result.reset(new RawInstrProfReader32(std::move(Buffer)));
else if (TextInstrProfReader::hasFormat(*Buffer))
Result.reset(new TextInstrProfReader(std::move(Buffer)));
else
return make_error<InstrProfError>(instrprof_error::unrecognized_format);
// Initialize the reader and return the result.
if (Error E = initializeReader(*Result))
return std::move(E);
return std::move(Result);
}
Expected<std::unique_ptr<IndexedInstrProfReader>>
IndexedInstrProfReader::create(const Twine &Path, const Twine &RemappingPath) {
// Set up the buffer to read.
auto BufferOrError = setupMemoryBuffer(Path);
if (Error E = BufferOrError.takeError())
return std::move(E);
// Set up the remapping buffer if requested.
std::unique_ptr<MemoryBuffer> RemappingBuffer;
std::string RemappingPathStr = RemappingPath.str();
if (!RemappingPathStr.empty()) {
auto RemappingBufferOrError = setupMemoryBuffer(RemappingPathStr);
if (Error E = RemappingBufferOrError.takeError())
return std::move(E);
RemappingBuffer = std::move(RemappingBufferOrError.get());
}
return IndexedInstrProfReader::create(std::move(BufferOrError.get()),
std::move(RemappingBuffer));
}
Expected<std::unique_ptr<IndexedInstrProfReader>>
IndexedInstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer,
std::unique_ptr<MemoryBuffer> RemappingBuffer) {
// Sanity check the buffer.
if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<unsigned>::max())
return make_error<InstrProfError>(instrprof_error::too_large);
// Create the reader.
if (!IndexedInstrProfReader::hasFormat(*Buffer))
return make_error<InstrProfError>(instrprof_error::bad_magic);
auto Result = llvm::make_unique<IndexedInstrProfReader>(
std::move(Buffer), std::move(RemappingBuffer));
// Initialize the reader and return the result.
if (Error E = initializeReader(*Result))
return std::move(E);
return std::move(Result);
}
void InstrProfIterator::Increment() {
if (auto E = Reader->readNextRecord(Record)) {
// Handle errors in the reader.
InstrProfError::take(std::move(E));
*this = InstrProfIterator();
}
}
bool TextInstrProfReader::hasFormat(const MemoryBuffer &Buffer) {
// Verify that this really looks like plain ASCII text by checking a
// 'reasonable' number of characters (up to profile magic size).
size_t count = std::min(Buffer.getBufferSize(), sizeof(uint64_t));
StringRef buffer = Buffer.getBufferStart();
return count == 0 ||
std::all_of(buffer.begin(), buffer.begin() + count,
[](char c) { return isPrint(c) || ::isspace(c); });
}
// Read the profile variant flag from the header: ":FE" means this is a FE
// generated profile. ":IR" means this is an IR level profile. Other strings
// with a leading ':' will be reported an error format.
Error TextInstrProfReader::readHeader() {
Symtab.reset(new InstrProfSymtab());
bool IsIRInstr = false;
if (!Line->startswith(":")) {
IsIRLevelProfile = false;
return success();
}
StringRef Str = (Line)->substr(1);
if (Str.equals_lower("ir"))
IsIRInstr = true;
else if (Str.equals_lower("fe"))
IsIRInstr = false;
else if (Str.equals_lower("csir")) {
IsIRInstr = true;
HasCSIRLevelProfile = true;
} else
return error(instrprof_error::bad_header);
++Line;
IsIRLevelProfile = IsIRInstr;
return success();
}
Error
TextInstrProfReader::readValueProfileData(InstrProfRecord &Record) {
#define CHECK_LINE_END(Line) \
if (Line.is_at_end()) \
return error(instrprof_error::truncated);
#define READ_NUM(Str, Dst) \
if ((Str).getAsInteger(10, (Dst))) \
return error(instrprof_error::malformed);
#define VP_READ_ADVANCE(Val) \
CHECK_LINE_END(Line); \
uint32_t Val; \
READ_NUM((*Line), (Val)); \
Line++;
if (Line.is_at_end())
return success();
uint32_t NumValueKinds;
if (Line->getAsInteger(10, NumValueKinds)) {
// No value profile data
return success();
}
if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1)
return error(instrprof_error::malformed);
Line++;
for (uint32_t VK = 0; VK < NumValueKinds; VK++) {
VP_READ_ADVANCE(ValueKind);
if (ValueKind > IPVK_Last)
return error(instrprof_error::malformed);
VP_READ_ADVANCE(NumValueSites);
if (!NumValueSites)
continue;
Record.reserveSites(VK, NumValueSites);
for (uint32_t S = 0; S < NumValueSites; S++) {
VP_READ_ADVANCE(NumValueData);
std::vector<InstrProfValueData> CurrentValues;
for (uint32_t V = 0; V < NumValueData; V++) {
CHECK_LINE_END(Line);
std::pair<StringRef, StringRef> VD = Line->rsplit(':');
uint64_t TakenCount, Value;
if (ValueKind == IPVK_IndirectCallTarget) {
if (InstrProfSymtab::isExternalSymbol(VD.first)) {
Value = 0;
} else {
if (Error E = Symtab->addFuncName(VD.first))
return E;
Value = IndexedInstrProf::ComputeHash(VD.first);
}
} else {
READ_NUM(VD.first, Value);
}
READ_NUM(VD.second, TakenCount);
CurrentValues.push_back({Value, TakenCount});
Line++;
}
Record.addValueData(ValueKind, S, CurrentValues.data(), NumValueData,
nullptr);
}
}
return success();
#undef CHECK_LINE_END
#undef READ_NUM
#undef VP_READ_ADVANCE
}
Error TextInstrProfReader::readNextRecord(NamedInstrProfRecord &Record) {
// Skip empty lines and comments.
while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
++Line;
// If we hit EOF while looking for a name, we're done.
if (Line.is_at_end()) {
return error(instrprof_error::eof);
}
// Read the function name.
Record.Name = *Line++;
if (Error E = Symtab->addFuncName(Record.Name))
return error(std::move(E));
// Read the function hash.
if (Line.is_at_end())
return error(instrprof_error::truncated);
if ((Line++)->getAsInteger(0, Record.Hash))
return error(instrprof_error::malformed);
// Read the number of counters.
uint64_t NumCounters;
if (Line.is_at_end())
return error(instrprof_error::truncated);
if ((Line++)->getAsInteger(10, NumCounters))
return error(instrprof_error::malformed);
if (NumCounters == 0)
return error(instrprof_error::malformed);
// Read each counter and fill our internal storage with the values.
Record.Clear();
Record.Counts.reserve(NumCounters);
for (uint64_t I = 0; I < NumCounters; ++I) {
if (Line.is_at_end())
return error(instrprof_error::truncated);
uint64_t Count;
if ((Line++)->getAsInteger(10, Count))
return error(instrprof_error::malformed);
Record.Counts.push_back(Count);
}
// Check if value profile data exists and read it if so.
if (Error E = readValueProfileData(Record))
return error(std::move(E));
return success();
}
template <class IntPtrT>
bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
if (DataBuffer.getBufferSize() < sizeof(uint64_t))
return false;
uint64_t Magic =
*reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
return RawInstrProf::getMagic<IntPtrT>() == Magic ||
sys::getSwappedBytes(RawInstrProf::getMagic<IntPtrT>()) == Magic;
}
template <class IntPtrT>
Error RawInstrProfReader<IntPtrT>::readHeader() {
if (!hasFormat(*DataBuffer))
return error(instrprof_error::bad_magic);
if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header))
return error(instrprof_error::bad_header);
auto *Header = reinterpret_cast<const RawInstrProf::Header *>(
DataBuffer->getBufferStart());
ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
return readHeader(*Header);
}
template <class IntPtrT>
Error RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
const char *End = DataBuffer->getBufferEnd();
// Skip zero padding between profiles.
while (CurrentPos != End && *CurrentPos == 0)
++CurrentPos;
// If there's nothing left, we're done.
if (CurrentPos == End)
return make_error<InstrProfError>(instrprof_error::eof);
// If there isn't enough space for another header, this is probably just
// garbage at the end of the file.
if (CurrentPos + sizeof(RawInstrProf::Header) > End)
return make_error<InstrProfError>(instrprof_error::malformed);
// The writer ensures each profile is padded to start at an aligned address.
if (reinterpret_cast<size_t>(CurrentPos) % alignof(uint64_t))
return make_error<InstrProfError>(instrprof_error::malformed);
// The magic should have the same byte order as in the previous header.
uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
if (Magic != swap(RawInstrProf::getMagic<IntPtrT>()))
return make_error<InstrProfError>(instrprof_error::bad_magic);
// There's another profile to read, so we need to process the header.
auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos);
return readHeader(*Header);
}
template <class IntPtrT>
Error RawInstrProfReader<IntPtrT>::createSymtab(InstrProfSymtab &Symtab) {
if (Error E = Symtab.create(StringRef(NamesStart, NamesSize)))
return error(std::move(E));
for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) {
const IntPtrT FPtr = swap(I->FunctionPointer);
if (!FPtr)
continue;
Symtab.mapAddress(FPtr, I->NameRef);
}
return success();
}
template <class IntPtrT>
Error RawInstrProfReader<IntPtrT>::readHeader(
const RawInstrProf::Header &Header) {
Version = swap(Header.Version);
if (GET_VERSION(Version) != RawInstrProf::Version)
return error(instrprof_error::unsupported_version);
CountersDelta = swap(Header.CountersDelta);
NamesDelta = swap(Header.NamesDelta);
auto DataSize = swap(Header.DataSize);
auto CountersSize = swap(Header.CountersSize);
NamesSize = swap(Header.NamesSize);
ValueKindLast = swap(Header.ValueKindLast);
auto DataSizeInBytes = DataSize * sizeof(RawInstrProf::ProfileData<IntPtrT>);
auto PaddingSize = getNumPaddingBytes(NamesSize);
ptrdiff_t DataOffset = sizeof(RawInstrProf::Header);
ptrdiff_t CountersOffset = DataOffset + DataSizeInBytes;
ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize;
auto *Start = reinterpret_cast<const char *>(&Header);
if (Start + ValueDataOffset > DataBuffer->getBufferEnd())
return error(instrprof_error::bad_header);
Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
Start + DataOffset);
DataEnd = Data + DataSize;
CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
NamesStart = Start + NamesOffset;
ValueDataStart = reinterpret_cast<const uint8_t *>(Start + ValueDataOffset);
std::unique_ptr<InstrProfSymtab> NewSymtab = make_unique<InstrProfSymtab>();
if (Error E = createSymtab(*NewSymtab.get()))
return E;
Symtab = std::move(NewSymtab);
return success();
}
template <class IntPtrT>
Error RawInstrProfReader<IntPtrT>::readName(NamedInstrProfRecord &Record) {
Record.Name = getName(Data->NameRef);
return success();
}
template <class IntPtrT>
Error RawInstrProfReader<IntPtrT>::readFuncHash(NamedInstrProfRecord &Record) {
Record.Hash = swap(Data->FuncHash);
return success();
}
template <class IntPtrT>
Error RawInstrProfReader<IntPtrT>::readRawCounts(
InstrProfRecord &Record) {
uint32_t NumCounters = swap(Data->NumCounters);
IntPtrT CounterPtr = Data->CounterPtr;
if (NumCounters == 0)
return error(instrprof_error::malformed);
auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
ptrdiff_t MaxNumCounters = NamesStartAsCounter - CountersStart;
// Check bounds. Note that the counter pointer embedded in the data record
// may itself be corrupt.
if (NumCounters > MaxNumCounters)
return error(instrprof_error::malformed);
ptrdiff_t CounterOffset = getCounterOffset(CounterPtr);
if (CounterOffset < 0 || CounterOffset > MaxNumCounters ||
(CounterOffset + NumCounters) > MaxNumCounters)
return error(instrprof_error::malformed);
auto RawCounts = makeArrayRef(getCounter(CounterOffset), NumCounters);
if (ShouldSwapBytes) {
Record.Counts.clear();
Record.Counts.reserve(RawCounts.size());
for (uint64_t Count : RawCounts)
Record.Counts.push_back(swap(Count));
} else
Record.Counts = RawCounts;
return success();
}
template <class IntPtrT>
Error RawInstrProfReader<IntPtrT>::readValueProfilingData(
InstrProfRecord &Record) {
Record.clearValueData();
CurValueDataSize = 0;
// Need to match the logic in value profile dumper code in compiler-rt:
uint32_t NumValueKinds = 0;
for (uint32_t I = 0; I < IPVK_Last + 1; I++)
NumValueKinds += (Data->NumValueSites[I] != 0);
if (!NumValueKinds)
return success();
Expected<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
ValueProfData::getValueProfData(
ValueDataStart, (const unsigned char *)DataBuffer->getBufferEnd(),
getDataEndianness());
if (Error E = VDataPtrOrErr.takeError())
return E;
// Note that besides deserialization, this also performs the conversion for
// indirect call targets. The function pointers from the raw profile are
// remapped into function name hashes.
VDataPtrOrErr.get()->deserializeTo(Record, Symtab.get());
CurValueDataSize = VDataPtrOrErr.get()->getSize();
return success();
}
template <class IntPtrT>
Error RawInstrProfReader<IntPtrT>::readNextRecord(NamedInstrProfRecord &Record) {
if (atEnd())
// At this point, ValueDataStart field points to the next header.
if (Error E = readNextHeader(getNextHeaderPos()))
return error(std::move(E));
// Read name ad set it in Record.
if (Error E = readName(Record))
return error(std::move(E));
// Read FuncHash and set it in Record.
if (Error E = readFuncHash(Record))
return error(std::move(E));
// Read raw counts and set Record.
if (Error E = readRawCounts(Record))
return error(std::move(E));
// Read value data and set Record.
if (Error E = readValueProfilingData(Record))
return error(std::move(E));
// Iterate.
advanceData();
return success();
}
namespace llvm {
template class RawInstrProfReader<uint32_t>;
template class RawInstrProfReader<uint64_t>;
} // end namespace llvm
InstrProfLookupTrait::hash_value_type
InstrProfLookupTrait::ComputeHash(StringRef K) {
return IndexedInstrProf::ComputeHash(HashType, K);
}
using data_type = InstrProfLookupTrait::data_type;
using offset_type = InstrProfLookupTrait::offset_type;
bool InstrProfLookupTrait::readValueProfilingData(
const unsigned char *&D, const unsigned char *const End) {
Expected<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
if (VDataPtrOrErr.takeError())
return false;
VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), nullptr);
D += VDataPtrOrErr.get()->TotalSize;
return true;
}
data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D,
offset_type N) {
using namespace support;
// Check if the data is corrupt. If so, don't try to read it.
if (N % sizeof(uint64_t))
return data_type();
DataBuffer.clear();
std::vector<uint64_t> CounterBuffer;
const unsigned char *End = D + N;
while (D < End) {
// Read hash.
if (D + sizeof(uint64_t) >= End)
return data_type();
uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D);
// Initialize number of counters for GET_VERSION(FormatVersion) == 1.
uint64_t CountsSize = N / sizeof(uint64_t) - 1;
// If format version is different then read the number of counters.
if (GET_VERSION(FormatVersion) != IndexedInstrProf::ProfVersion::Version1) {
if (D + sizeof(uint64_t) > End)
return data_type();
CountsSize = endian::readNext<uint64_t, little, unaligned>(D);
}
// Read counter values.
if (D + CountsSize * sizeof(uint64_t) > End)
return data_type();
CounterBuffer.clear();
CounterBuffer.reserve(CountsSize);
for (uint64_t J = 0; J < CountsSize; ++J)
CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
// Read value profiling data.
if (GET_VERSION(FormatVersion) > IndexedInstrProf::ProfVersion::Version2 &&
!readValueProfilingData(D, End)) {
DataBuffer.clear();
return data_type();
}
}
return DataBuffer;
}
template <typename HashTableImpl>
Error InstrProfReaderIndex<HashTableImpl>::getRecords(
StringRef FuncName, ArrayRef<NamedInstrProfRecord> &Data) {
auto Iter = HashTable->find(FuncName);
if (Iter == HashTable->end())
return make_error<InstrProfError>(instrprof_error::unknown_function);
Data = (*Iter);
if (Data.empty())
return make_error<InstrProfError>(instrprof_error::malformed);
return Error::success();
}
template <typename HashTableImpl>
Error InstrProfReaderIndex<HashTableImpl>::getRecords(
ArrayRef<NamedInstrProfRecord> &Data) {
if (atEnd())
return make_error<InstrProfError>(instrprof_error::eof);
Data = *RecordIterator;
if (Data.empty())
return make_error<InstrProfError>(instrprof_error::malformed);
return Error::success();
}
template <typename HashTableImpl>
InstrProfReaderIndex<HashTableImpl>::InstrProfReaderIndex(
const unsigned char *Buckets, const unsigned char *const Payload,
const unsigned char *const Base, IndexedInstrProf::HashT HashType,
uint64_t Version) {
FormatVersion = Version;
HashTable.reset(HashTableImpl::Create(
Buckets, Payload, Base,
typename HashTableImpl::InfoType(HashType, Version)));
RecordIterator = HashTable->data_begin();
}
namespace {
/// A remapper that does not apply any remappings.
class InstrProfReaderNullRemapper : public InstrProfReaderRemapper {
InstrProfReaderIndexBase &Underlying;
public:
InstrProfReaderNullRemapper(InstrProfReaderIndexBase &Underlying)
: Underlying(Underlying) {}
Error getRecords(StringRef FuncName,
ArrayRef<NamedInstrProfRecord> &Data) override {
return Underlying.getRecords(FuncName, Data);
}
};
}
/// A remapper that applies remappings based on a symbol remapping file.
template <typename HashTableImpl>
class llvm::InstrProfReaderItaniumRemapper
: public InstrProfReaderRemapper {
public:
InstrProfReaderItaniumRemapper(
std::unique_ptr<MemoryBuffer> RemapBuffer,
InstrProfReaderIndex<HashTableImpl> &Underlying)
: RemapBuffer(std::move(RemapBuffer)), Underlying(Underlying) {
}
/// Extract the original function name from a PGO function name.
static StringRef extractName(StringRef Name) {
// We can have multiple :-separated pieces; there can be pieces both
// before and after the mangled name. Find the first part that starts
// with '_Z'; we'll assume that's the mangled name we want.
std::pair<StringRef, StringRef> Parts = {StringRef(), Name};
while (true) {
Parts = Parts.second.split(':');
if (Parts.first.startswith("_Z"))
return Parts.first;
if (Parts.second.empty())
return Name;
}
}
/// Given a mangled name extracted from a PGO function name, and a new
/// form for that mangled name, reconstitute the name.
static void reconstituteName(StringRef OrigName, StringRef ExtractedName,
StringRef Replacement,
SmallVectorImpl<char> &Out) {
Out.reserve(OrigName.size() + Replacement.size() - ExtractedName.size());
Out.insert(Out.end(), OrigName.begin(), ExtractedName.begin());
Out.insert(Out.end(), Replacement.begin(), Replacement.end());
Out.insert(Out.end(), ExtractedName.end(), OrigName.end());
}
Error populateRemappings() override {
if (Error E = Remappings.read(*RemapBuffer))
return E;
for (StringRef Name : Underlying.HashTable->keys()) {
StringRef RealName = extractName(Name);
if (auto Key = Remappings.insert(RealName)) {
// FIXME: We could theoretically map the same equivalence class to
// multiple names in the profile data. If that happens, we should
// return NamedInstrProfRecords from all of them.
MappedNames.insert({Key, RealName});
}
}
return Error::success();
}
Error getRecords(StringRef FuncName,
ArrayRef<NamedInstrProfRecord> &Data) override {
StringRef RealName = extractName(FuncName);
if (auto Key = Remappings.lookup(RealName)) {
StringRef Remapped = MappedNames.lookup(Key);
if (!Remapped.empty()) {
if (RealName.begin() == FuncName.begin() &&
RealName.end() == FuncName.end())
FuncName = Remapped;
else {
// Try rebuilding the name from the given remapping.
SmallString<256> Reconstituted;
reconstituteName(FuncName, RealName, Remapped, Reconstituted);
Error E = Underlying.getRecords(Reconstituted, Data);
if (!E)
return E;
// If we failed because the name doesn't exist, fall back to asking
// about the original name.
if (Error Unhandled = handleErrors(
std::move(E), [](std::unique_ptr<InstrProfError> Err) {
return Err->get() == instrprof_error::unknown_function
? Error::success()
: Error(std::move(Err));
}))
return Unhandled;
}
}
}
return Underlying.getRecords(FuncName, Data);
}
private:
/// The memory buffer containing the remapping configuration. Remappings
/// holds pointers into this buffer.
std::unique_ptr<MemoryBuffer> RemapBuffer;
/// The mangling remapper.
SymbolRemappingReader Remappings;
/// Mapping from mangled name keys to the name used for the key in the
/// profile data.
/// FIXME: Can we store a location within the on-disk hash table instead of
/// redoing lookup?
DenseMap<SymbolRemappingReader::Key, StringRef> MappedNames;
/// The real profile data reader.
InstrProfReaderIndex<HashTableImpl> &Underlying;
};
bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
using namespace support;
if (DataBuffer.getBufferSize() < 8)
return false;
uint64_t Magic =
endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
// Verify that it's magical.
return Magic == IndexedInstrProf::Magic;
}
const unsigned char *
IndexedInstrProfReader::readSummary(IndexedInstrProf::ProfVersion Version,
const unsigned char *Cur, bool UseCS) {
using namespace IndexedInstrProf;
using namespace support;
if (Version >= IndexedInstrProf::Version4) {
const IndexedInstrProf::Summary *SummaryInLE =
reinterpret_cast<const IndexedInstrProf::Summary *>(Cur);
uint64_t NFields =
endian::byte_swap<uint64_t, little>(SummaryInLE->NumSummaryFields);
uint64_t NEntries =
endian::byte_swap<uint64_t, little>(SummaryInLE->NumCutoffEntries);
uint32_t SummarySize =
IndexedInstrProf::Summary::getSize(NFields, NEntries);
std::unique_ptr<IndexedInstrProf::Summary> SummaryData =
IndexedInstrProf::allocSummary(SummarySize);
const uint64_t *Src = reinterpret_cast<const uint64_t *>(SummaryInLE);
uint64_t *Dst = reinterpret_cast<uint64_t *>(SummaryData.get());
for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
Dst[I] = endian::byte_swap<uint64_t, little>(Src[I]);
SummaryEntryVector DetailedSummary;
for (unsigned I = 0; I < SummaryData->NumCutoffEntries; I++) {
const IndexedInstrProf::Summary::Entry &Ent = SummaryData->getEntry(I);
DetailedSummary.emplace_back((uint32_t)Ent.Cutoff, Ent.MinBlockCount,
Ent.NumBlocks);
}
std::unique_ptr<llvm::ProfileSummary> &Summary =
UseCS ? this->CS_Summary : this->Summary;
// initialize InstrProfSummary using the SummaryData from disk.
Summary = llvm::make_unique<ProfileSummary>(
UseCS ? ProfileSummary::PSK_CSInstr : ProfileSummary::PSK_Instr,
DetailedSummary, SummaryData->get(Summary::TotalBlockCount),
SummaryData->get(Summary::MaxBlockCount),
SummaryData->get(Summary::MaxInternalBlockCount),
SummaryData->get(Summary::MaxFunctionCount),
SummaryData->get(Summary::TotalNumBlocks),
SummaryData->get(Summary::TotalNumFunctions));
return Cur + SummarySize;
} else {
// For older version of profile data, we need to compute on the fly:
using namespace IndexedInstrProf;
InstrProfSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
// FIXME: This only computes an empty summary. Need to call addRecord for
// all NamedInstrProfRecords to get the correct summary.
this->Summary = Builder.getSummary();
return Cur;
}
}
Error IndexedInstrProfReader::readHeader() {
using namespace support;
const unsigned char *Start =
(const unsigned char *)DataBuffer->getBufferStart();
const unsigned char *Cur = Start;
if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
return error(instrprof_error::truncated);
auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur);
Cur += sizeof(IndexedInstrProf::Header);
// Check the magic number.
uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
if (Magic != IndexedInstrProf::Magic)
return error(instrprof_error::bad_magic);
// Read the version.
uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
if (GET_VERSION(FormatVersion) >
IndexedInstrProf::ProfVersion::CurrentVersion)
return error(instrprof_error::unsupported_version);
Cur = readSummary((IndexedInstrProf::ProfVersion)FormatVersion, Cur,
/* UseCS */ false);
if (FormatVersion & VARIANT_MASK_CSIR_PROF)
Cur = readSummary((IndexedInstrProf::ProfVersion)FormatVersion, Cur,
/* UseCS */ true);
// Read the hash type and start offset.
IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
endian::byte_swap<uint64_t, little>(Header->HashType));
if (HashType > IndexedInstrProf::HashT::Last)
return error(instrprof_error::unsupported_hash_type);
uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
// The rest of the file is an on disk hash table.
auto IndexPtr =
llvm::make_unique<InstrProfReaderIndex<OnDiskHashTableImplV3>>(
Start + HashOffset, Cur, Start, HashType, FormatVersion);
// Load the remapping table now if requested.
if (RemappingBuffer) {
Remapper = llvm::make_unique<
InstrProfReaderItaniumRemapper<OnDiskHashTableImplV3>>(
std::move(RemappingBuffer), *IndexPtr);
if (Error E = Remapper->populateRemappings())
return E;
} else {
Remapper = llvm::make_unique<InstrProfReaderNullRemapper>(*IndexPtr);
}
Index = std::move(IndexPtr);
return success();
}
InstrProfSymtab &IndexedInstrProfReader::getSymtab() {
if (Symtab.get())
return *Symtab.get();
std::unique_ptr<InstrProfSymtab> NewSymtab = make_unique<InstrProfSymtab>();
if (Error E = Index->populateSymtab(*NewSymtab.get())) {
consumeError(error(InstrProfError::take(std::move(E))));
}
Symtab = std::move(NewSymtab);
return *Symtab.get();
}
Expected<InstrProfRecord>
IndexedInstrProfReader::getInstrProfRecord(StringRef FuncName,
uint64_t FuncHash) {
ArrayRef<NamedInstrProfRecord> Data;
Error Err = Remapper->getRecords(FuncName, Data);
if (Err)
return std::move(Err);
// Found it. Look for counters with the right hash.
for (unsigned I = 0, E = Data.size(); I < E; ++I) {
// Check for a match and fill the vector if there is one.
if (Data[I].Hash == FuncHash) {
return std::move(Data[I]);
}
}
return error(instrprof_error::hash_mismatch);
}
Error IndexedInstrProfReader::getFunctionCounts(StringRef FuncName,
uint64_t FuncHash,
std::vector<uint64_t> &Counts) {
Expected<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash);
if (Error E = Record.takeError())
return error(std::move(E));
Counts = Record.get().Counts;
return success();
}
Error IndexedInstrProfReader::readNextRecord(NamedInstrProfRecord &Record) {
ArrayRef<NamedInstrProfRecord> Data;
Error E = Index->getRecords(Data);
if (E)
return error(std::move(E));
Record = Data[RecordIndex++];
if (RecordIndex >= Data.size()) {
Index->advanceToNextKey();
RecordIndex = 0;
}
return success();
}
void InstrProfReader::accumuateCounts(CountSumOrPercent &Sum, bool IsCS) {
uint64_t NumFuncs = 0;
for (const auto &Func : *this) {
if (isIRLevelProfile()) {
bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
if (FuncIsCS != IsCS)
continue;
}
Func.accumuateCounts(Sum);
++NumFuncs;
}
Sum.NumEntries = NumFuncs;
}
| 12,143 |
562 | #include <iostream>
#include <cor3ntin/rangesnext/enumerate.hpp>
namespace rangesnext = cor3ntin::rangesnext;
template <class RangeT>
bool test_enumerate_with(RangeT &&range) {
auto enumerated_range = rangesnext::enumerate(range);
std::size_t idx_ref = 0;
auto it_ref = std::ranges::begin(range);
bool success = true;
for (auto &&[i, v] : enumerated_range) {
std::cout << i << " - " << v << "\n";
success = (i == idx_ref++) && (v == *it_ref++);
if (success == false) {
return false;
}
}
return true;
}
int main() {
int const test_array[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
test_enumerate_with(test_array);
}
| 307 |
427 | <filename>SymbolExtractorAndRenamer/swift-integration-tests/example-package-dealer.py
# Test the open source example packages.
#
# REQUIRES: have-network
#
# Make a sandbox dir. If you want to experiment with this test without waiting
# for the clone, disable the first three lines here.
#
# RUN: rm -rf %t.dir
# RUN: mkdir -p %t.dir/
# RUN: git clone https://github.com/apple/example-package-dealer %t.dir/dealer
# RUN: rm -rf %t.dir/dealer/.build
# RUN: %{swift} build --package-path %t.dir/dealer 2>&1 | tee %t.build-log
# Check the build log.
#
# RUN: %{FileCheck} --check-prefix CHECK-BUILD-LOG --input-file %t.build-log %s
#
# CHECK-BUILD-LOG: Compile Swift Module 'FisherYates'
# CHECK-BUILD-LOG: Compile Swift Module 'Dealer'
# Verify that the build worked.
#
# RUN: test -x %t.dir/dealer/.build/debug/Dealer
# RUN: %t.dir/dealer/.build/debug/Dealer > %t.out
# RUN: %{FileCheck} --check-prefix CHECK-TOOL-OUTPUT --input-file %t.out %s
#
# We should get an example that is easier to test.
#
# CHECK-TOOL-OUTPUT: {{♡|♠|♢|♣}}{{[0-9JQKA]|10}}
# Verify that the 'git status' is clean after a build.
#
# RUN: cd %t.dir/dealer && git status > %t.out
# RUN: %{FileCheck} --check-prefix CHECK-GIT-STATUS --input-file %t.out %s
#
# CHECK-GIT-STATUS: nothing to commit, working directory clean
# Verify that another 'swift build' does nothing.
#
# RUN: %{swift} build --package-path %t.dir/dealer 2>&1 | tee %t.rebuild-log
# RUN: echo END-OF-INPUT >> %t.rebuild-log
# RUN: %{FileCheck} --check-prefix CHECK-BUILD-LOG --input-file %t.build-log %s
#
# CHECK-REBUILD-LOG-NOT: Compile
| 615 |
2,577 | <reponame>mlehotsky13/camunda-bpm-platform
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.rest.util;
import org.camunda.bpm.engine.authorization.Resource;
public class ResourceUtil implements Resource {
protected String resourceName;
protected int resourceType;
public ResourceUtil(String resourceName, int resourceType) {
this.resourceName = resourceName;
this.resourceType = resourceType;
}
public String resourceName() {
return resourceName;
}
public int resourceType() {
return resourceType;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((resourceName == null) ? 0 : resourceName.hashCode());
result = prime * result + resourceType;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ResourceUtil other = (ResourceUtil) obj;
if (resourceName == null) {
if (other.resourceName != null)
return false;
} else if (!resourceName.equals(other.resourceName))
return false;
if (resourceType != other.resourceType)
return false;
return true;
}
}
| 623 |
342 | <gh_stars>100-1000
package com.edlplan.osu.support.slider;
import com.edlplan.andengine.Triangle3DPack;
import com.edlplan.framework.math.line.LinePath;
import org.anddev.andengine.entity.scene.Scene;
import ru.nsu.ccfit.zuev.osu.RGBColor;
public class SliderBody3D extends AbstractSliderBody {
private static float zOff = 0.001f;
private static float zStart = -1 + zOff;
private static float zEnd = 1;
private Triangle3DPack body = null, border = null, bodyMask = null, borderMask = null;
private RGBColor bodyColor = new RGBColor(), borderColor = new RGBColor();
private float bodyWidth, borderWidth;
private float startLength = 0, endLength = 0;
public SliderBody3D(LinePath path) {
super(path);
}
@Override
public void onUpdate() {
LinePath sub = path.cutPath(startLength, endLength).fitToLinePath();
float zBody = -bodyWidth / borderWidth + zOff;
float alpha = endLength / path.getMeasurer().maxLength();
/*bodyMask.setVertices(
(new Draw3DLinePath(sub, bodyWidth, zEnd - zOff, zBody - zOff))
.getTriangles()
.getVertex());*/
body.setVertices(
(new Draw3DLinePath(sub, bodyWidth, 1, 1))
.getTriangles()
.getVertex());
body.setAlpha(0.7f * alpha);
/*borderMask.setVertices(
(new Draw3DLinePath(sub, borderWidth, zEnd - zOff, zStart - zOff))
.getTriangles()
.getVertex());*/
border.setVertices(
(new Draw3DLinePath(sub, borderWidth, -1, -1))
.getTriangles()
.getVertex());
border.setAlpha(alpha);
}
@Override
public void setBodyWidth(float width) {
bodyWidth = width;
}
@Override
public void setBorderWidth(float width) {
borderWidth = width;
}
@Override
public void setBodyColor(float r, float g, float b) {
bodyColor.set(r, g, b);
if (body != null) {
body.setColor(r, g, b);
}
}
@Override
public void setBorderColor(float r, float g, float b) {
borderColor.set(r, g, b);
if (border != null) {
border.setColor(r, g, b);
}
}
@Override
public void setStartLength(float length) {
startLength = length;
}
@Override
public void setEndLength(float length) {
endLength = length;
}
@Override
public void applyToScene(Scene scene, boolean emptyOnStart) {
if (!emptyOnStart) {
startLength = 0;
endLength = path.getMeasurer().maxLength();
}
float zBody = -bodyWidth / borderWidth + zOff;
/*bodyMask = new Triangle3DPack(0, 0,
emptyOnStart ?
new float[0] :
(new Draw3DLinePath(path, bodyWidth, zEnd - zOff, zBody - zOff))
.getTriangles()
.getVertex());
bodyMask.setClearDepthOnStart(true);*/
body = new Triangle3DPack(0, 0,
emptyOnStart ?
new float[0] :
(new Draw3DLinePath(path, bodyWidth, zEnd, zBody))
.getTriangles()
.getVertex()
);
body.setClearDepthOnStart(true);
/*borderMask = new Triangle3DPack(0, 0,
emptyOnStart ?
new float[0] :
(new Draw3DLinePath(path, borderWidth, zEnd - zOff, zStart - zOff))
.getTriangles()
.getVertex()
);*/
border = new Triangle3DPack(0, 0,
emptyOnStart ?
new float[0] :
(new Draw3DLinePath(path, borderWidth, zEnd, zStart))
.getTriangles()
.getVertex()
);
//bodyMask.setAlpha(0);
//borderMask.setAlpha(0);
body.setColor(bodyColor.r(), bodyColor.g(), bodyColor.b());
border.setColor(borderColor.r(), borderColor.g(), borderColor.b());
scene.attachChild(border, 0);
//scene.attachChild(borderMask, 0);
scene.attachChild(body, 0);
//scene.attachChild(bodyMask, 0);
}
@Override
public void removeFromScene(Scene scene) {
if (body != null) {
body.detachSelf();
}
if (border != null) {
border.detachSelf();
}
if (bodyMask != null) {
bodyMask.detachSelf();
}
if (borderMask != null) {
borderMask.detachSelf();
}
}
}
| 2,497 |
852 | #include "FWCore/PluginManager/interface/ModuleDef.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h"
#include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h"
#include "CommonTools/UtilAlgos/interface/ObjectSelector.h"
#include "CommonTools/ParticleFlow/interface/PtMinPFCandidateSelectorDefinition.h"
typedef ObjectSelector<pf2pat::PtMinPFCandidateSelectorDefinition> PtMinPFCandidateSelector;
DEFINE_FWK_MODULE(PtMinPFCandidateSelector);
| 187 |
1,602 | <reponame>kroggen/aergo
/* Generic x86 gmp-mparam.h -- Compiler/machine parameter header file.
Copyright 1991, 1993, 1994, 2000-2002, 2011 Free Software Foundation, Inc.
This file is part of the GNU MP Library.
The GNU MP Library is free software; you can redistribute it and/or modify
it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* 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.
or both in parallel, as here.
The GNU MP Library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received copies of the GNU General Public License and the
GNU Lesser General Public License along with the GNU MP Library. If not,
see https://www.gnu.org/licenses/. */
#define GMP_LIMB_BITS 32
#define GMP_LIMB_BYTES 4
/* Generated by tuneup.c, 2011-01-30, gcc 3.4 */
#define MOD_1_NORM_THRESHOLD 6
#define MOD_1_UNNORM_THRESHOLD MP_SIZE_T_MAX /* never */
#define MOD_1N_TO_MOD_1_1_THRESHOLD 17
#define MOD_1U_TO_MOD_1_1_THRESHOLD 9
#define MOD_1_1_TO_MOD_1_2_THRESHOLD 0 /* never mpn_mod_1_1p */
#define MOD_1_2_TO_MOD_1_4_THRESHOLD 14
#define PREINV_MOD_1_TO_MOD_1_THRESHOLD MP_SIZE_T_MAX /* never */
#define USE_PREINV_DIVREM_1 0
#define DIVEXACT_1_THRESHOLD 0 /* always (native) */
#define BMOD_1_TO_MOD_1_THRESHOLD 42
#define MUL_TOOM22_THRESHOLD 18
#define MUL_TOOM33_THRESHOLD 66
#define MUL_TOOM44_THRESHOLD 105
#define MUL_TOOM6H_THRESHOLD 141
#define MUL_TOOM8H_THRESHOLD 212
#define MUL_TOOM32_TO_TOOM43_THRESHOLD 62
#define MUL_TOOM32_TO_TOOM53_THRESHOLD 69
#define MUL_TOOM42_TO_TOOM53_THRESHOLD 65
#define MUL_TOOM42_TO_TOOM63_THRESHOLD 67
#define SQR_BASECASE_THRESHOLD 0 /* always (native) */
#define SQR_TOOM2_THRESHOLD 33
#define SQR_TOOM3_THRESHOLD 60
#define SQR_TOOM4_THRESHOLD 136
#define SQR_TOOM6_THRESHOLD 196
#define SQR_TOOM8_THRESHOLD 292
#define MULMOD_BNM1_THRESHOLD 14
#define SQRMOD_BNM1_THRESHOLD 16
#define MUL_FFT_MODF_THRESHOLD 468 /* k = 5 */
#define MUL_FFT_TABLE3 \
{ { 468, 5}, { 17, 6}, { 9, 5}, { 19, 6}, \
{ 11, 5}, { 23, 6}, { 21, 7}, { 11, 6}, \
{ 25, 7}, { 13, 6}, { 27, 7}, { 15, 6}, \
{ 31, 7}, { 21, 8}, { 11, 7}, { 27, 8}, \
{ 15, 7}, { 33, 8}, { 19, 7}, { 39, 8}, \
{ 23, 7}, { 47, 8}, { 27, 9}, { 15, 8}, \
{ 39, 9}, { 23, 8}, { 47,10}, { 15, 9}, \
{ 31, 8}, { 67, 9}, { 39, 8}, { 79, 9}, \
{ 47, 8}, { 95, 9}, { 55,10}, { 31, 9}, \
{ 63, 8}, { 127, 9}, { 79,10}, { 47, 9}, \
{ 95,11}, { 31,10}, { 63, 9}, { 135,10}, \
{ 79, 9}, { 159,10}, { 95, 9}, { 191,11}, \
{ 63,10}, { 127, 9}, { 255,10}, { 143, 9}, \
{ 287,10}, { 159,11}, { 95,10}, { 191, 9}, \
{ 383,12}, { 4096,13}, { 8192,14}, { 16384,15}, \
{ 32768,16} }
#define MUL_FFT_TABLE3_SIZE 61
#define MUL_FFT_THRESHOLD 5504
#define SQR_FFT_MODF_THRESHOLD 396 /* k = 5 */
#define SQR_FFT_TABLE3 \
{ { 396, 5}, { 21, 6}, { 11, 5}, { 23, 6}, \
{ 21, 7}, { 11, 6}, { 24, 7}, { 13, 6}, \
{ 27, 7}, { 15, 6}, { 31, 7}, { 21, 8}, \
{ 11, 7}, { 27, 8}, { 15, 7}, { 33, 8}, \
{ 19, 7}, { 39, 8}, { 23, 7}, { 47, 8}, \
{ 27, 9}, { 15, 8}, { 39, 9}, { 23, 8}, \
{ 51,10}, { 15, 9}, { 31, 8}, { 67, 9}, \
{ 39, 8}, { 79, 9}, { 47, 8}, { 95, 9}, \
{ 55,10}, { 31, 9}, { 79,10}, { 47, 9}, \
{ 95,11}, { 31,10}, { 63, 9}, { 127, 8}, \
{ 255, 9}, { 135,10}, { 79, 9}, { 159, 8}, \
{ 319,10}, { 95, 9}, { 191,11}, { 63,10}, \
{ 127, 9}, { 255, 8}, { 511,10}, { 143, 9}, \
{ 287, 8}, { 575,10}, { 159,11}, { 95,10}, \
{ 191,12}, { 4096,13}, { 8192,14}, { 16384,15}, \
{ 32768,16} }
#define SQR_FFT_TABLE3_SIZE 61
#define SQR_FFT_THRESHOLD 3712
#define MULLO_BASECASE_THRESHOLD 3
#define MULLO_DC_THRESHOLD 37
#define MULLO_MUL_N_THRESHOLD 10950
#define DC_DIV_QR_THRESHOLD 59
#define DC_DIVAPPR_Q_THRESHOLD 189
#define DC_BDIV_QR_THRESHOLD 55
#define DC_BDIV_Q_THRESHOLD 136
#define INV_MULMOD_BNM1_THRESHOLD 50
#define INV_NEWTON_THRESHOLD 183
#define INV_APPR_THRESHOLD 181
#define BINV_NEWTON_THRESHOLD 204
#define REDC_1_TO_REDC_N_THRESHOLD 54
#define MU_DIV_QR_THRESHOLD 1142
#define MU_DIVAPPR_Q_THRESHOLD 1142
#define MUPI_DIV_QR_THRESHOLD 81
#define MU_BDIV_QR_THRESHOLD 889
#define MU_BDIV_Q_THRESHOLD 998
#define MATRIX22_STRASSEN_THRESHOLD 13
#define HGCD_THRESHOLD 133
#define GCD_DC_THRESHOLD 451
#define GCDEXT_DC_THRESHOLD 318
#define JACOBI_BASE_METHOD 1
#define GET_STR_DC_THRESHOLD 15
#define GET_STR_PRECOMPUTE_THRESHOLD 30
#define SET_STR_DC_THRESHOLD 547
#define SET_STR_PRECOMPUTE_THRESHOLD 1049
| 3,426 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.test.permanentUI.utils;
import java.util.ArrayList;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JRadioButtonMenuItem;
/**
*
* @author <NAME>
*/
public class NbMenuItem implements Comparable {
private String name = "NONE";
private char mnemo = 0;
private String accelerator = null;
private boolean enabled = false;
private boolean radiobutton = false;
private boolean checkbox = false;
private boolean separator = false;
private boolean checked = false;
ArrayList<NbMenuItem> submenu = null;
public NbMenuItem() {
}
public NbMenuItem(String name) {
this.name = name;
}
/**
* @param it
* @return instance of NbMenuItem constructed from parameter it */
public NbMenuItem(JMenuItem it) {
setName(it.getText());//getLabel();
this.accelerator = (it.getAccelerator() == null) ? null : it.getAccelerator().toString();
this.mnemo = (char) it.getMnemonic();
// System.out.println("NbMenuItem ["+name+"] - mnemo: ["+it.getMnemonic()+"]"); why are the mnemonic always in capital?
this.enabled = it.isEnabled();
this.checkbox = it instanceof JCheckBoxMenuItem;
this.radiobutton = it instanceof JRadioButtonMenuItem;
this.checked = it.isSelected();
}
/** needed for comparing in TreeSet
* @param obj
* @return */
public int compareTo(Object obj) {
NbMenuItem n = (NbMenuItem) obj;
return (getName() != null) ? getName().compareTo(n.getName()) : n.getName().compareTo(getName());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getMnemo() {
return mnemo;
}
public void setMnemo(char mnemo) {
this.mnemo = Character.toUpperCase(mnemo); //all the mnemonic returned by JMenuItem.getMnemonic() are upper case
}
public String getAccelerator() {
return accelerator;
}
public void setAccelerator(String accelerator) {
this.accelerator = accelerator;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isRadiobutton() {
return radiobutton;
}
public void setRadiobutton(boolean radiobutton) {
this.radiobutton = radiobutton;
}
public boolean isCheckbox() {
return checkbox;
}
public void setCheckbox(boolean checkbox) {
this.checkbox = checkbox;
}
public boolean isSeparator() {
return separator;
}
public void setSeparator(boolean separator) {
this.separator = separator;
setName("==========");
}
public ArrayList<NbMenuItem> getSubmenu () {
return submenu;
}
public void setSubmenu(ArrayList<NbMenuItem> submenu) {
this.submenu = submenu;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public boolean equals(NbMenuItem obj) {
if (this.isSeparator()) {
return obj.isSeparator();
} else {
return (this.getName().equals(obj.getName())) &&
(Character.toUpperCase(this.getMnemo()) == Character.toUpperCase(obj.getMnemo()) ) && //TODO: for unknown reason the AbstractButton.getMnemonic() returns always capital letter
// (this.getMnemo() == obj.getMnemo()) &&
((this.getSubmenu () != null) && (obj.getSubmenu () != null)) &&
//((this.getAccelerator()!= null)?this.getAccelerator().equals(obj.getAccelerator()):false) &&
(this.isCheckbox() && obj.isCheckbox()) &&
(this.isRadiobutton() && obj.isRadiobutton())
//&& (this.isEnabled() && obj.isEnabled())
;
}
}
public String findDifference(NbMenuItem obj) {
String text = "";
String compar = "diff[" + this.getName() + "], [" + obj.getName() + "] ";
if ((this.isSeparator() && !obj.isSeparator()) || (!this.isSeparator() && obj.isSeparator())) {
text = this.isSeparator() ? obj.getName() : this.getName() + " is on the same position as separator";
} else {
if (!(this.getName().equals(obj.getName()))) {
text = ", NAMES differs [" + this.getName() + "], [" + obj.getName() + "]";
} else {
if (Character.toUpperCase(this.getMnemo()) != Character.toUpperCase(obj.getMnemo()) ) {//TODO: for unknown reason the AbstarctButton.getMnemonic() returns always capital letter
// if (this.getMnemo() != obj.getMnemo()) {//TODO: for unknown reason the AbstarctButton.getMnemonic() returns always capital letter
text += ", MNEMONICS are NOT same [" + this.getMnemo() + "] != [" + obj.getMnemo() + "]";
}
if ((this.getSubmenu () != null) != (obj.getSubmenu () != null)) { //do they both have submenus?
text += ", " + (this.getSubmenu () != null ? obj.getName() : this.getName()) + " has NO SUBMENU";
}
// if (this.getAccelerator() != null) {
// if (!this.getAccelerator() .equals(obj.getAccelerator())) {
// text += "ACCELERATORS differ [" + this.getAccelerator() + " != " + obj.getAccelerator() + "]";
// }
// }
if (!this.isCheckbox() && obj.isCheckbox()) {
text += ", " + (this.isCheckbox() ? obj.getName() : this.getName()) + " is NOT CHECKBOX";
}
if (!this.isRadiobutton() && obj.isRadiobutton()) {
text += ", " + (this.isRadiobutton() ? obj.getName() : this.getName()) + " is NOT RADIOBUTTON";
}
// if (!this.isEnabled() && obj.isEnabled()) {
// text += ", " + (this.isEnabled() ? obj.getName() : this.getName()) + " is NOT ENABLED";
// }
}
}
return text.length()==0?text:compar+text+"\n";
}
@Override
public String toString() {
return this.getName() + " [acc:" + this.getAccelerator() + "] ["
+this.getMnemo()+"] [e:" + this.isEnabled()+", ch:" + this.isCheckbox() +
", r:"+ this.isRadiobutton()+", checked:"+this.isChecked()+", sep:" + this.isSeparator() +"]"
+ ((this.getSubmenu() != null)?" SUBMENU":"");
}
}
| 3,232 |
12,700 | <reponame>brenden7158/v86
/*
* Header for stack related functions
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU Library General Public License version 2.
*/
#ifndef _STACK_H_
#define _STACK_H_
#include <libcflat.h>
#include <asm/stack.h>
#ifdef HAVE_ARCH_BACKTRACE_FRAME
extern int backtrace_frame(const void *frame, const void **return_addrs,
int max_depth);
#else
static inline int
backtrace_frame(const void *frame __unused, const void **return_addrs __unused,
int max_depth __unused)
{
return 0;
}
#endif
extern int backtrace(const void **return_addrs, int max_depth);
#endif
| 229 |
4,095 | /*
* Copyright 2011-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
package io.lettuce.core;
import java.net.SocketAddress;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Close Events Facility. Can register/unregister CloseListener and fire a closed event to all registered listeners. This class
* is part of the internal API and may change without further notice.
*
* @author <NAME>
* @since 3.0
*/
public class ConnectionEvents {
private final Set<RedisConnectionStateListener> listeners = ConcurrentHashMap.newKeySet();
void fireEventRedisConnected(RedisChannelHandler<?, ?> connection, SocketAddress socketAddress) {
for (RedisConnectionStateListener listener : listeners) {
listener.onRedisConnected(connection, socketAddress);
}
}
void fireEventRedisDisconnected(RedisChannelHandler<?, ?> connection) {
for (RedisConnectionStateListener listener : listeners) {
listener.onRedisDisconnected(connection);
}
}
void fireEventRedisExceptionCaught(RedisChannelHandler<?, ?> connection, Throwable cause) {
for (RedisConnectionStateListener listener : listeners) {
listener.onRedisExceptionCaught(connection, cause);
}
}
public void addListener(RedisConnectionStateListener listener) {
listeners.add(listener);
}
public void removeListener(RedisConnectionStateListener listener) {
listeners.remove(listener);
}
/**
* Internal event when a channel is closed.
*/
public static class Reset {
}
/**
* Internal event when a reconnect is initiated.
*/
public static class Reconnect {
private final int attempt;
public Reconnect(int attempt) {
this.attempt = attempt;
}
public int getAttempt() {
return attempt;
}
}
static ConnectionEvents of(ConnectionEvents... delegates) {
return delegates.length == 1 ? delegates[0] : new MergedConnectionEvents(delegates);
}
static class MergedConnectionEvents extends ConnectionEvents {
private final ConnectionEvents[] delegates;
MergedConnectionEvents(ConnectionEvents[] delegates) {
this.delegates = delegates;
}
@Override
void fireEventRedisConnected(RedisChannelHandler<?, ?> connection, SocketAddress socketAddress) {
for (ConnectionEvents delegate : delegates) {
delegate.fireEventRedisConnected(connection, socketAddress);
}
}
@Override
void fireEventRedisDisconnected(RedisChannelHandler<?, ?> connection) {
for (ConnectionEvents delegate : delegates) {
delegate.fireEventRedisDisconnected(connection);
}
}
@Override
void fireEventRedisExceptionCaught(RedisChannelHandler<?, ?> connection, Throwable cause) {
for (ConnectionEvents delegate : delegates) {
delegate.fireEventRedisExceptionCaught(connection, cause);
}
}
@Override
public void addListener(RedisConnectionStateListener listener) {
throw new UnsupportedOperationException();
}
@Override
public void removeListener(RedisConnectionStateListener listener) {
throw new UnsupportedOperationException();
}
}
}
| 1,382 |
460 | #include "../../src/qt3support/tools/q3strlist.h"
| 22 |
1,501 | <reponame>sarvex/tensorflow-quantum
# Copyright 2020 The TensorFlow Quantum Authors. 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.
# ==============================================================================
"""Test for ParameterShift specific C++ ops."""
import numpy as np
import tensorflow as tf
import sympy
import cirq
from tensorflow_quantum.core.ops import tfq_ps_util_ops
from tensorflow_quantum.python import util
def _complex_test_circuit():
t = sympy.Symbol('t')
r = sympy.Symbol('r')
qubits = cirq.GridQubit.rect(1, 6)
circuit_batch = [
cirq.Circuit(
cirq.Moment([cirq.H(q) for q in qubits]),
cirq.Moment([
cirq.X(qubits[4]),
cirq.PhasedXPowGate(phase_exponent=np.random.random() * t).on(
qubits[5]),
cirq.ISwapPowGate(exponent=np.random.random() * t).on(
qubits[0], qubits[1]),
cirq.FSimGate(theta=np.random.random() * t,
phi=np.random.random() * r).on(
qubits[2], qubits[3])
]), cirq.Moment([cirq.H(q) for q in qubits])),
cirq.Circuit(
cirq.FSimGate(theta=np.random.random() * t,
phi=np.random.random() * r).on(*qubits[:2]),
cirq.FSimGate(theta=np.random.random() * r,
phi=np.random.random() * t).on(qubits[1], qubits[0])),
cirq.Circuit(
cirq.Moment([
cirq.ISwapPowGate(exponent=np.random.random() *
t).on(*qubits[:2]),
cirq.PhasedXPowGate(phase_exponent=np.random.random() * r).on(
qubits[2]),
cirq.ISwapPowGate(exponent=np.random.random() *
r).on(*qubits[3:5])
]))
]
return circuit_batch
class PSDecomposeTest(tf.test.TestCase):
"""Tests on tfq_ps_decompose"""
def test_iswap_gate_test(self):
"""Test 1 ISwapPowGate decomposition."""
t = sympy.Symbol('t')
qubits = cirq.GridQubit.rect(1, 2)
circuit = cirq.Circuit(
cirq.ISwapPowGate(exponent=np.random.random() * t).on(*qubits))
inputs = util.convert_to_tensor([circuit])
outputs = tfq_ps_util_ops.tfq_ps_decompose(inputs)
decomposed_programs = util.from_tensor(outputs)
rand_resolver = {'t': np.random.random()}
self.assertAllClose(cirq.unitary(
cirq.resolve_parameters(circuit, rand_resolver)),
cirq.unitary(
cirq.resolve_parameters(decomposed_programs[0],
rand_resolver)),
atol=1e-5)
def test_phased_x_pow_gate_test(self):
"""Test 1 PhasedXPowGate decomposition."""
t = sympy.Symbol('t')
r = sympy.Symbol('r')
q = cirq.GridQubit(0, 0)
circuit = cirq.Circuit(
cirq.PhasedXPowGate(phase_exponent=np.random.random() * r,
exponent=np.random.random() * t).on(q))
inputs = util.convert_to_tensor([circuit])
outputs = tfq_ps_util_ops.tfq_ps_decompose(inputs)
decomposed_programs = util.from_tensor(outputs)
rand_resolver = {'t': np.random.random(), 'r': np.random.random()}
self.assertAllClose(cirq.unitary(
cirq.resolve_parameters(circuit, rand_resolver)),
cirq.unitary(
cirq.resolve_parameters(decomposed_programs[0],
rand_resolver)),
atol=1e-5)
def test_fsim_gate_test(self):
"""Test 1 FSimPowGate decomposition."""
t = sympy.Symbol('t')
r = sympy.Symbol('r')
qubits = cirq.GridQubit.rect(1, 2)
circuit = cirq.Circuit(
cirq.FSimGate(theta=np.random.random() * r,
phi=np.random.random() * t).on(*qubits))
inputs = util.convert_to_tensor([circuit])
outputs = tfq_ps_util_ops.tfq_ps_decompose(inputs)
decomposed_programs = util.from_tensor(outputs)
rand_resolver = {'t': np.random.random(), 'r': np.random.random()}
self.assertAllClose(cirq.unitary(
cirq.resolve_parameters(circuit, rand_resolver)),
cirq.unitary(
cirq.resolve_parameters(decomposed_programs[0],
rand_resolver)),
atol=1e-5)
def test_decompose_with_complex_circuit(self):
"""Test decompose with complex circuit."""
names = ['CLAE', 'HRYV', 'IRKB', 'LKRV', 'PJOU', 'CJKX', 'NASW']
# Test circuit has a Moment with 1) FSimGate & PhasedXPowGate,
# 2) PhasedXPowGate & ISwapPowGate and 3) FSimGate & ISwapPowGate.
# Be careful, they are not decomposed if not parameterized.
circuit_batch = [
cirq.Circuit([
cirq.Moment([
cirq.FSimGate(
theta=0.10338130973488413 * sympy.Symbol('CLAE'),
phi=0.10338130973488413 * sympy.Symbol('IRKB')).on(
cirq.GridQubit(0, 2), cirq.GridQubit(0, 3)),
cirq.PhasedXPowGate(phase_exponent=1.0,
exponent=0.86426029696045281 *
sympy.Symbol('HRYV')).on(
cirq.GridQubit(0, 1)),
]),
cirq.Moment([
cirq.Y.on(cirq.GridQubit(0, 3)),
cirq.Z.on(cirq.GridQubit(0, 0)),
cirq.FSimGate(theta=1, phi=1).on(cirq.GridQubit(0, 1),
cirq.GridQubit(0, 2)),
]),
cirq.Moment([
(cirq.CNOT**(0.92874230274398684 *
sympy.Symbol('IRKB'))).on(
cirq.GridQubit(0, 1), cirq.GridQubit(0,
2)),
]),
cirq.Moment([
cirq.PhasedXPowGate(phase_exponent=sympy.Symbol('PJOU'),
exponent=0.2081415255258906 *
sympy.Symbol('LKRV')).on(
cirq.GridQubit(0, 2)),
(cirq.ISWAP**(0.32860954996781722 *
sympy.Symbol('PJOU'))).on(
cirq.GridQubit(0, 1),
cirq.GridQubit(0, 3)),
]),
cirq.Moment([
cirq.PhasedXPowGate(phase_exponent=sympy.Symbol('CJKX')).on(
cirq.GridQubit(0, 1)),
cirq.ZZ.on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 3)),
(cirq.X**(0.6826594585474709 * sympy.Symbol('HRYV'))).on(
cirq.GridQubit(0, 2)),
]),
cirq.Moment([
(cirq.ZZ**(0.18781276022427218 * sympy.Symbol('PJOU'))).on(
cirq.GridQubit(0, 0), cirq.GridQubit(0, 3)),
]),
cirq.Moment([
cirq.Y.on(cirq.GridQubit(0, 0)),
]),
cirq.Moment([
cirq.FSimGate(
theta=0.13793763138552417 * sympy.Symbol('CJKX'),
phi=0.13793763138552417 * sympy.Symbol('PJOU')).on(
cirq.GridQubit(0, 2), cirq.GridQubit(0, 3)),
(cirq.ISWAP**(0.028165738453673095 *
sympy.Symbol('NASW'))).on(
cirq.GridQubit(0, 0),
cirq.GridQubit(0, 1)),
]),
cirq.Moment([
cirq.FSimGate(
theta=0.74356520426349459 * sympy.Symbol('CJKX'),
phi=0.74356520426349459 * sympy.Symbol('NASW')).on(
cirq.GridQubit(0, 3), cirq.GridQubit(0, 0)),
]),
cirq.Moment([
cirq.CNOT.on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 2)),
cirq.SWAP.on(cirq.GridQubit(0, 3), cirq.GridQubit(0, 1)),
]),
cirq.Moment([
cirq.H.on(cirq.GridQubit(0, 3)),
cirq.H.on(cirq.GridQubit(0, 2)),
cirq.CNOT.on(cirq.GridQubit(0, 1), cirq.GridQubit(0, 0)),
]),
cirq.Moment([
cirq.CNOT.on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)),
cirq.YY.on(cirq.GridQubit(0, 2), cirq.GridQubit(0, 3)),
]),
cirq.Moment([
cirq.CZ.on(cirq.GridQubit(0, 1), cirq.GridQubit(0, 0)),
cirq.CNOT.on(cirq.GridQubit(0, 2), cirq.GridQubit(0, 3)),
]),
cirq.Moment([
cirq.FSimGate(theta=1, phi=1).on(cirq.GridQubit(0, 0),
cirq.GridQubit(0, 2)),
cirq.CNOT.on(cirq.GridQubit(0, 3), cirq.GridQubit(0, 1)),
]),
cirq.Moment([
cirq.FSimGate(theta=1, phi=1).on(cirq.GridQubit(0, 0),
cirq.GridQubit(0, 3)),
cirq.SWAP.on(cirq.GridQubit(0, 2), cirq.GridQubit(0, 1)),
]),
cirq.Moment([
cirq.Y.on(cirq.GridQubit(0, 0)),
cirq.PhasedXPowGate(phase_exponent=1.0).on(
cirq.GridQubit(0, 2)),
cirq.FSimGate(theta=1, phi=1).on(cirq.GridQubit(0, 1),
cirq.GridQubit(0, 3)),
]),
])
]
# Decompose programs.
inputs = util.convert_to_tensor(circuit_batch)
outputs = tfq_ps_util_ops.tfq_ps_decompose(inputs)
decomposed_programs = util.from_tensor(outputs)
self.assertEqual(len(decomposed_programs), len(circuit_batch))
# Original programs has parameterized ISP, PXP, FSIM, but this result
# has no such gates at all. All parameterized gates have at most two
# eigenvalues. There are still ISwap and PhasedX(1.0) because they are
# not parameterized, which doesn't affect ParameterShift differentiation
# at all.
for program in decomposed_programs:
for moment in program:
for gate_op in moment:
# Consider parameterized gates only
if cirq.is_parameterized(gate_op.gate):
# Check I. The gate should have _eigen_components.
self.assertTrue(
hasattr(gate_op.gate, '_eigen_components'))
# Check II. The gate should have two eigen values.
self.assertEqual(len(gate_op.gate._eigen_components()),
2, gate_op.gate)
# Now all programs don't have ISWAP & PhasedXPowGate because ISWAP has
# 3 eigenvalues and PhasedXPowGate doesn't have _eigen_components.
# Check if two programs are identical.
rand_resolver = {name: np.random.random() for name in names}
self.assertAllClose(cirq.unitary(
cirq.resolve_parameters(circuit_batch[0], rand_resolver)),
cirq.unitary(
cirq.resolve_parameters(decomposed_programs[0],
rand_resolver)),
atol=1e-5)
def test_moment_preservation(self):
"""Test Moment-structure preservation."""
t = sympy.Symbol('t')
r = sympy.Symbol('r')
qubits = cirq.LineQubit.range(6)
circuit_batch = [
cirq.Circuit(
cirq.Moment([cirq.H(q) for q in qubits]),
cirq.Moment([
cirq.X(qubits[4]),
cirq.PhasedXPowGate(phase_exponent=np.random.random() *
t).on(qubits[5]),
cirq.ISwapPowGate(exponent=np.random.random() * t).on(
qubits[0], qubits[1]),
cirq.FSimGate(theta=np.random.random() * t,
phi=np.random.random() * r).on(
qubits[2], qubits[3])
]), cirq.Moment([cirq.H(q) for q in qubits]))
]
inputs = util.convert_to_tensor(circuit_batch)
outputs = tfq_ps_util_ops.tfq_ps_decompose(inputs)
decomposed_programs = util.from_tensor(outputs)
# Now all programs don't have ISWAP & PhasedXPowGate because ISWAP has
# 3 eigenvalues and PhasedXPowGate doesn't have _eigen_components.
# Check if two programs are identical.
rand_resolver = {'t': np.random.random(), 'r': np.random.random()}
self.assertAllClose(cirq.unitary(
cirq.resolve_parameters(circuit_batch[0], rand_resolver)),
cirq.unitary(
cirq.resolve_parameters(decomposed_programs[0],
rand_resolver)),
atol=1e-5)
# Check if the Moments are conserved.
max_decomposed_length = 3
n_non_decomposed_moments = 2
self.assertEqual(len(decomposed_programs[0]),
n_non_decomposed_moments + max_decomposed_length)
# Total length of Moments = 5
# The non-decomposed moments should be the same.
self.assertEqual(decomposed_programs[0][0], circuit_batch[0][0])
self.assertEqual(decomposed_programs[0][-1], circuit_batch[0][-1])
# Check paralellized decompose gates in Moment[1]~[3].
# The target ops are replaced by the first decomposition gates. It means
# the first Moment has exactly the same number of gate ops.
self.assertEqual(len(decomposed_programs[0][1]),
len(circuit_batch[0][1]))
# From the second Moments, the Moments only have decomposition gates.
# In this example, two ISwapPowGate & one PhasedXPowGate are located.
# Since PhasedXPowGate, ISwapPowGate, FSimGate has 3, 2, 3 result gates
# Moment[2] have 3 gate ops and Moment[3] have 2 gate ops.
self.assertEqual(len(decomposed_programs[0][2]), 3)
self.assertEqual(len(decomposed_programs[0][3]), 2)
def test_more_complex_moment_preservation(self):
"""Test Moment-structure preservation."""
circuit_batch = _complex_test_circuit()
inputs = util.convert_to_tensor(circuit_batch)
outputs = tfq_ps_util_ops.tfq_ps_decompose(inputs)
decomposed_programs = util.from_tensor(outputs)
# Now all programs don't have ISWAP & PhasedXPowGate because ISWAP has
# 3 eigenvalues and PhasedXPowGate doesn't have _eigen_components.
# Check if two programs are identical.
rand_resolver = {'t': np.random.random(), 'r': np.random.random()}
for i in range(3):
self.assertAllClose(cirq.unitary(
cirq.resolve_parameters(circuit_batch[i], rand_resolver)),
cirq.unitary(
cirq.resolve_parameters(
decomposed_programs[i], rand_resolver)),
atol=1e-5)
# Check if the Moments are conserved.
# Circuit 1.
max_decomposed_length = 3
n_non_decomposed_moments = 2
self.assertEqual(len(decomposed_programs[0]),
n_non_decomposed_moments + max_decomposed_length)
# Total length of Moments = 5
# The non-decomposed moments should be the same.
self.assertEqual(decomposed_programs[0][0], circuit_batch[0][0])
self.assertEqual(decomposed_programs[0][-1], circuit_batch[0][-1])
# Check paralellized decompose gates in Moment[1]~[3].
# The target ops are replaced by the first decomposition gates. It means
# the first Moment has exactly the same number of gate ops.
self.assertEqual(len(decomposed_programs[0][1]),
len(circuit_batch[0][1]))
# From the second Moments, the Moments only have decomposition gates.
# In this example, two ISwapPowGate & one PhasedXPowGate are located.
# Since PhasedXPowGate, ISwapPowGate, FSimGate has 3, 2, 3 result gates
# Moment[2] have 3 gate ops and Moment[3] have 2 gate ops.
self.assertEqual(len(decomposed_programs[0][2]), 3)
self.assertEqual(len(decomposed_programs[0][3]), 2)
# Circuit 2. two FSimGates.
self.assertEqual(len(decomposed_programs[1]), 2 * max_decomposed_length)
# Circuit 3. one PXP between two ISwapPowGates.
self.assertEqual(len(decomposed_programs[2]), max_decomposed_length)
class PSSymbolReplaceTest(tf.test.TestCase):
"""Tests tfq_ps_symbol_replace."""
def test_simple_case(self):
"""Test trivial case."""
bit = cirq.GridQubit(0, 0)
circuit = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('alpha'),
cirq.Y(bit)**sympy.Symbol('alpha'),
cirq.Z(bit)**sympy.Symbol('alpha'),
)
inputs = util.convert_to_tensor([circuit])
symbols = tf.convert_to_tensor(['alpha'])
new = tf.convert_to_tensor(['new'])
res = tfq_ps_util_ops.tfq_ps_symbol_replace(inputs, symbols, new)
output = util.from_tensor(res)
correct_00 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('new'),
cirq.Y(bit)**sympy.Symbol('alpha'),
cirq.Z(bit)**sympy.Symbol('alpha'),
)
correct_01 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('alpha'),
cirq.Y(bit)**sympy.Symbol('new'),
cirq.Z(bit)**sympy.Symbol('alpha'),
)
correct_02 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('alpha'),
cirq.Y(bit)**sympy.Symbol('alpha'),
cirq.Z(bit)**sympy.Symbol('new'),
)
self.assertEqual(correct_00, output[0][0][0])
self.assertEqual(correct_01, output[0][0][1])
self.assertEqual(correct_02, output[0][0][2])
def test_error(self):
"""Ensure that errors happen with bad inputs."""
bit = cirq.GridQubit(0, 0)
circuit = cirq.Circuit(cirq.X(bit)**(sympy.Symbol('alpha') * 2))
inputs = util.convert_to_tensor([[circuit]])
symbols = tf.convert_to_tensor(['test'])
replacements = tf.convert_to_tensor(['nothing'])
with self.assertRaisesRegex(Exception,
expected_regex='rank 1. Got rank 2.'):
tfq_ps_util_ops.tfq_ps_symbol_replace(inputs, symbols, replacements)
inputs = tf.convert_to_tensor(['junk'])
with self.assertRaisesRegex(Exception,
expected_regex='Unparseable proto:'):
tfq_ps_util_ops.tfq_ps_symbol_replace(inputs, symbols, replacements)
inputs = util.convert_to_tensor([circuit])
symbols = tf.convert_to_tensor([['test']])
replacements = tf.convert_to_tensor(['nothing'])
with self.assertRaisesRegex(Exception,
expected_regex='rank 1. Got rank 2.'):
tfq_ps_util_ops.tfq_ps_symbol_replace(inputs, symbols, replacements)
symbols = tf.convert_to_tensor(['test'])
replacements = tf.convert_to_tensor([['nothing']])
with self.assertRaisesRegex(Exception,
expected_regex='rank 1. Got rank 2.'):
tfq_ps_util_ops.tfq_ps_symbol_replace(inputs, symbols, replacements)
symbols = tf.convert_to_tensor(['test'])
replacements = tf.convert_to_tensor(['nothing', 'too long'])
with self.assertRaisesRegex(
Exception,
expected_regex=
'symbols.shape is not equal to replacement_symbols.shape'):
tfq_ps_util_ops.tfq_ps_symbol_replace(inputs, symbols, replacements)
def test_weight_coefficient(self):
"""Test that scalar multiples of trivial case work."""
bit = cirq.GridQubit(0, 0)
circuit = cirq.Circuit(
cirq.X(bit)**(sympy.Symbol('alpha') * 2.4),
cirq.Y(bit)**(sympy.Symbol('alpha') * 3.4),
cirq.Z(bit)**(sympy.Symbol('alpha') * 4.4),
)
inputs = util.convert_to_tensor([circuit])
symbols = tf.convert_to_tensor(['alpha'])
new = tf.convert_to_tensor(['new'])
res = tfq_ps_util_ops.tfq_ps_symbol_replace(inputs, symbols, new)
output = util.from_tensor(res)
correct_00 = cirq.Circuit(
cirq.X(bit)**(sympy.Symbol('new') * 2.4),
cirq.Y(bit)**(sympy.Symbol('alpha') * 3.4),
cirq.Z(bit)**(sympy.Symbol('alpha') * 4.4),
)
correct_01 = cirq.Circuit(
cirq.X(bit)**(sympy.Symbol('alpha') * 2.4),
cirq.Y(bit)**(sympy.Symbol('new') * 3.4),
cirq.Z(bit)**(sympy.Symbol('alpha') * 4.4),
)
correct_02 = cirq.Circuit(
cirq.X(bit)**(sympy.Symbol('alpha') * 2.4),
cirq.Y(bit)**(sympy.Symbol('alpha') * 3.4),
cirq.Z(bit)**(sympy.Symbol('new') * 4.4),
)
for i, c in enumerate([correct_00, correct_01, correct_02]):
u1 = cirq.unitary(
cirq.resolve_parameters(c,
param_resolver={
'alpha': 1.23,
'new': 4.56
}))
u2 = cirq.unitary(
cirq.resolve_parameters(output[0][0][i],
param_resolver={
'alpha': 1.23,
'new': 4.56
}))
self.assertTrue(cirq.approx_eq(u1, u2, atol=1e-5))
def test_simple_pad(self):
"""Test simple padding."""
bit = cirq.LineQubit(1)
circuit = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('alpha'),
cirq.Y(bit)**sympy.Symbol('alpha'),
cirq.Z(bit)**sympy.Symbol('alpha'),
)
circuit2 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('beta'),
cirq.Y(bit)**sympy.Symbol('beta'),
cirq.Z(bit)**sympy.Symbol('beta'),
)
circuit3 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('alpha'),
cirq.Y(bit)**sympy.Symbol('alpha'),
cirq.Z(bit)**sympy.Symbol('alpha'),
)
inputs = util.convert_to_tensor([circuit, circuit2, circuit3])
symbols = tf.convert_to_tensor(['alpha', 'beta', 'gamma'])
new = tf.convert_to_tensor(['new', 'old', 'nothing'])
res = tfq_ps_util_ops.tfq_ps_symbol_replace(inputs, symbols, new)
output = util.from_tensor(res)
correct_00 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('new'),
cirq.Y(bit)**sympy.Symbol('alpha'),
cirq.Z(bit)**sympy.Symbol('alpha'),
)
correct_01 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('alpha'),
cirq.Y(bit)**sympy.Symbol('new'),
cirq.Z(bit)**sympy.Symbol('alpha'),
)
correct_02 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('alpha'),
cirq.Y(bit)**sympy.Symbol('alpha'),
cirq.Z(bit)**sympy.Symbol('new'),
)
self.assertEqual(correct_00, output[0][0][0])
self.assertEqual(correct_01, output[0][0][1])
self.assertEqual(correct_02, output[0][0][2])
self.assertEqual(correct_00, output[2][0][0])
self.assertEqual(correct_01, output[2][0][1])
self.assertEqual(correct_02, output[2][0][2])
correct_10 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('old'),
cirq.Y(bit)**sympy.Symbol('beta'),
cirq.Z(bit)**sympy.Symbol('beta'),
)
correct_11 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('beta'),
cirq.Y(bit)**sympy.Symbol('old'),
cirq.Z(bit)**sympy.Symbol('beta'),
)
correct_12 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('beta'),
cirq.Y(bit)**sympy.Symbol('beta'),
cirq.Z(bit)**sympy.Symbol('old'),
)
self.assertEqual(correct_10, output[1][1][0])
self.assertEqual(correct_11, output[1][1][1])
self.assertEqual(correct_12, output[1][1][2])
correct_20 = cirq.Circuit()
correct_21 = cirq.Circuit()
correct_22 = cirq.Circuit()
self.assertEqual(correct_20, output[2][2][0])
self.assertEqual(correct_21, output[2][2][1])
self.assertEqual(correct_22, output[2][2][2])
correct = cirq.Circuit()
for i in range(3):
for j in range(3):
for k in range(3):
if i != j and (not (i == 2 and j == 0)):
self.assertEqual(correct, output[i][j][k])
def test_complex_pad(self):
"""Test trickier padding."""
bit = cirq.GridQubit(0, 0)
bit2 = cirq.GridQubit(0, 1)
circuit = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('alpha'),
cirq.Y(bit)**sympy.Symbol('alpha'),
cirq.Z(bit)**sympy.Symbol('alpha'),
cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
circuit2 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('beta'),
cirq.Y(bit)**sympy.Symbol('beta'),
cirq.Z(bit)**sympy.Symbol('beta'),
cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
circuit3 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('alpha'),
cirq.Y(bit)**sympy.Symbol('alpha'),
cirq.Z(bit)**sympy.Symbol('alpha'),
cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
inputs = util.convert_to_tensor([circuit, circuit2, circuit3])
symbols = tf.convert_to_tensor(['alpha', 'beta', 'gamma'])
new = tf.convert_to_tensor(['new', 'old', 'nothing'])
res = tfq_ps_util_ops.tfq_ps_symbol_replace(inputs, symbols, new)
output = util.from_tensor(res)
correct_000 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('new'),
cirq.Y(bit)**sympy.Symbol('alpha'),
cirq.Z(bit)**sympy.Symbol('alpha'),
cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
correct_001 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('alpha'),
cirq.Y(bit)**sympy.Symbol('new'),
cirq.Z(bit)**sympy.Symbol('alpha'),
cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
correct_002 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('alpha'),
cirq.Y(bit)**sympy.Symbol('alpha'),
cirq.Z(bit)**sympy.Symbol('new'),
cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
correct_003 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('alpha'),
cirq.Y(bit)**sympy.Symbol('alpha'),
cirq.Z(bit)**sympy.Symbol('alpha'),
cirq.XX(bit, bit2)**sympy.Symbol('new'))
self.assertEqual(correct_000, output[0][0][0])
self.assertEqual(correct_001, output[0][0][1])
self.assertEqual(correct_002, output[0][0][2])
self.assertEqual(correct_003, output[0][0][3])
self.assertEqual(correct_000, output[2][0][0])
self.assertEqual(correct_001, output[2][0][1])
self.assertEqual(correct_002, output[2][0][2])
self.assertEqual(correct_003, output[2][0][3])
correct_110 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('old'),
cirq.Y(bit)**sympy.Symbol('beta'),
cirq.Z(bit)**sympy.Symbol('beta'),
cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
correct_111 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('beta'),
cirq.Y(bit)**sympy.Symbol('old'),
cirq.Z(bit)**sympy.Symbol('beta'),
cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
correct_112 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('beta'),
cirq.Y(bit)**sympy.Symbol('beta'),
cirq.Z(bit)**sympy.Symbol('old'),
cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
correct_113 = cirq.Circuit()
self.assertEqual(correct_110, output[1][1][0])
self.assertEqual(correct_111, output[1][1][1])
self.assertEqual(correct_112, output[1][1][2])
self.assertEqual(correct_113, output[1][1][3])
correct_100 = cirq.Circuit(
cirq.X(bit)**sympy.Symbol('beta'),
cirq.Y(bit)**sympy.Symbol('beta'),
cirq.Z(bit)**sympy.Symbol('beta'),
cirq.XX(bit, bit2)**sympy.Symbol('new'))
correct_101 = cirq.Circuit()
correct_102 = cirq.Circuit()
correct_103 = cirq.Circuit()
self.assertEqual(correct_100, output[1][0][0])
self.assertEqual(correct_101, output[1][0][1])
self.assertEqual(correct_102, output[1][0][2])
self.assertEqual(correct_103, output[1][0][3])
correct_220 = cirq.Circuit()
correct_221 = cirq.Circuit()
correct_222 = cirq.Circuit()
correct_223 = cirq.Circuit()
self.assertEqual(correct_220, output[2][2][0])
self.assertEqual(correct_221, output[2][2][1])
self.assertEqual(correct_222, output[2][2][2])
self.assertEqual(correct_223, output[2][2][3])
correct = cirq.Circuit()
for i in range(3):
for j in range(3):
for k in range(3):
if i != j and (not (i == 2 and j == 0)) \
and (not (i == 1 and j == 0)):
self.assertEqual(correct, output[i][j][k])
class PSWeightsFromSymbolTest(tf.test.TestCase):
"""Tests tfq_ps_weights_from_symbols."""
def test_simple(self):
"""Ensure that weight extraction works."""
bit = cirq.GridQubit(0, 0)
circuit = cirq.Circuit(cirq.X(bit)**(sympy.Symbol('alpha') * 2))
inputs = util.convert_to_tensor([circuit])
symbols = tf.convert_to_tensor(['alpha'])
res = tfq_ps_util_ops.tfq_ps_weights_from_symbols(inputs, symbols)
self.assertAllClose(res, np.array([[[2.0]]]))
def test_empty(self):
"""Test empty circuit. and symbol free circuit. does nothing."""
bit = cirq.GridQubit(0, 0)
circuit = cirq.Circuit(cirq.X(bit))
circuit2 = cirq.Circuit()
inputs = util.convert_to_tensor([circuit, circuit2])
symbols = tf.convert_to_tensor(['alpha'])
res = tfq_ps_util_ops.tfq_ps_weights_from_symbols(inputs, symbols)
self.assertAllClose(res, np.array([[[]], [[]]]))
def test_rotation_gates(self):
"""Test that rotation gates work."""
bit = cirq.GridQubit(0, 0)
circuit = cirq.Circuit(cirq.rx(sympy.Symbol('alpha') * 5.0)(bit))
inputs = util.convert_to_tensor([circuit])
symbols = tf.convert_to_tensor(['alpha'])
res = tfq_ps_util_ops.tfq_ps_weights_from_symbols(inputs, symbols)
self.assertAllClose(res, np.array([[[5.0 / np.pi]]]))
def test_error(self):
"""Ensure if a symbol can't be found the op errors."""
bit = cirq.GridQubit(0, 0)
circuit = cirq.Circuit(cirq.X(bit)**(sympy.Symbol('delta') * 2))
inputs = util.convert_to_tensor([circuit])
symbols = tf.convert_to_tensor(['alpha', 'delta'])
tfq_ps_util_ops.tfq_ps_weights_from_symbols(inputs, symbols)
symbols = tf.convert_to_tensor(['alpha'])
with self.assertRaisesRegex(Exception, expected_regex='sympy.Symbol'):
tfq_ps_util_ops.tfq_ps_weights_from_symbols(inputs, symbols)
symbols = tf.convert_to_tensor([['delta']])
with self.assertRaisesRegex(Exception,
expected_regex='rank 1. Got rank 2.'):
tfq_ps_util_ops.tfq_ps_weights_from_symbols(inputs, symbols)
inputs = tf.convert_to_tensor(['junk'])
symbols = tf.convert_to_tensor(['delta'])
with self.assertRaisesRegex(Exception,
expected_regex='Unparseable proto:'):
tfq_ps_util_ops.tfq_ps_weights_from_symbols(inputs, symbols)
inputs = util.convert_to_tensor([[circuit]])
with self.assertRaisesRegex(Exception,
expected_regex='rank 1. Got rank 2.'):
tfq_ps_util_ops.tfq_ps_weights_from_symbols(inputs, symbols)
def test_many_values(self):
"""Ensure that padding with few symbols and many values works."""
bit = cirq.LineQubit(1)
circuits = [
cirq.Circuit(
cirq.X(bit)**(sympy.Symbol('alpha') * 2.0),
cirq.Y(bit)**(sympy.Symbol('alpha') * 3.0),
cirq.Z(bit)**(sympy.Symbol('alpha')),
cirq.X(bit)**(sympy.Symbol('alpha') * 4.0)),
cirq.Circuit(cirq.X(bit)**(sympy.Symbol('alpha') * 9.0)),
cirq.Circuit(cirq.X(bit)**sympy.Symbol('beta'))
]
inputs = util.convert_to_tensor(circuits)
symbols = tf.convert_to_tensor(['alpha', 'beta'])
res = tfq_ps_util_ops.tfq_ps_weights_from_symbols(inputs, symbols)
self.assertAllClose(
res,
np.array([[[2.0, 3.0, 1.0, 4.0], [0.0, 0.0, 0.0, 0.0]],
[[9.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]],
[[0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0]]]))
def test_many_symbols(self):
"""Ensure that padding with few values and many symbols works."""
bit = cirq.GridQubit(0, 0)
circuits = [
cirq.Circuit(cirq.X(bit)**(sympy.Symbol('alpha') * 2.0)),
cirq.Circuit(cirq.X(bit)**(sympy.Symbol('beta') * 6)),
cirq.Circuit(cirq.X(bit)**(sympy.Symbol('alpha') * 5.0)),
cirq.Circuit(cirq.X(bit)**(sympy.Symbol('gamma') * 8)),
cirq.Circuit(cirq.X(bit)**(sympy.Symbol('delta') * 9))
]
inputs = util.convert_to_tensor(circuits)
symbols = tf.convert_to_tensor(['alpha', 'beta', 'gamma', 'delta'])
res = tfq_ps_util_ops.tfq_ps_weights_from_symbols(inputs, symbols)
self.assertAllClose(
res,
np.array([[[2.0], [0.0], [0.0], [0.0]], [[0.0], [6.0], [0.0],
[0.0]],
[[5.0], [0.0], [0.0], [0.0]], [[0.0], [0.0], [8.0],
[0.0]],
[[0.0], [0.0], [0.0], [9.0]]]))
def test_out_of_order(self):
"""Test that discovery order of symbols in circuits doesn't matter."""
bit = cirq.GridQubit(0, 0)
circuit = cirq.Circuit(
cirq.X(bit)**(sympy.Symbol('alpha') * 2),
cirq.Y(bit)**(sympy.Symbol('beta') * 3))
inputs = util.convert_to_tensor([circuit])
symbols = tf.convert_to_tensor(['alpha', 'beta'])
res = tfq_ps_util_ops.tfq_ps_weights_from_symbols(inputs, symbols)
self.assertAllClose(res, np.array([[[2.0], [3.0]]]))
symbols = tf.convert_to_tensor(['beta', 'alpha'])
res = tfq_ps_util_ops.tfq_ps_weights_from_symbols(inputs, symbols)
self.assertAllClose(res, np.array([[[3.0], [2.0]]]))
def test_padding(self):
"""Ensure that the padding is correct in a complex example."""
bit = cirq.GridQubit(0, 0)
circuits = [
cirq.Circuit(
cirq.X(bit)**(sympy.Symbol('alpha') * 2.0),
cirq.Y(bit)**(sympy.Symbol('alpha') * 3.0),
cirq.Z(bit)**(sympy.Symbol('beta') * 4.0),
),
cirq.Circuit(
cirq.X(bit)**(sympy.Symbol('alpha') * 2.0),
cirq.Y(bit)**(sympy.Symbol('beta') * 3.0),
cirq.Z(bit)**(sympy.Symbol('beta') * 4.0),
),
cirq.Circuit(
cirq.X(bit)**(sympy.Symbol('alpha') * 2.0),
cirq.Y(bit)**(sympy.Symbol('beta') * 3.0),
cirq.Z(bit)**(sympy.Symbol('gamma') * 4.0),
)
]
inputs = util.convert_to_tensor(circuits)
symbols = tf.convert_to_tensor(['alpha', 'beta', 'gamma'])
res = tfq_ps_util_ops.tfq_ps_weights_from_symbols(inputs, symbols)
self.assertAllClose(
res,
np.array([[[2.0, 3.0], [4.0, 0.0], [0.0, 0.0]],
[[2.0, 0.0], [3.0, 4.0], [0.0, 0.0]],
[[2.0, 0.0], [3.0, 0.0], [4.0, 0.0]]]))
def test_padding_with_non_parameterized_gates(self):
"""Ensure that the padding is correct in a complex example."""
bit = cirq.GridQubit(0, 0)
circuits = [
cirq.Circuit(
cirq.X(bit)**(sympy.Symbol('alpha') * 2.0),
cirq.Y(bit)**3.0,
cirq.Z(bit)**(sympy.Symbol('beta') * 4.0),
),
cirq.Circuit(
cirq.X(bit)**(sympy.Symbol('alpha') * 2.0),
cirq.Y(bit)**(sympy.Symbol('beta') * 3.0),
cirq.Z(bit)**4.0,
),
cirq.Circuit(
cirq.X(bit)**2.0,
cirq.Y(bit)**(sympy.Symbol('beta') * 3.0),
cirq.Z(bit)**(sympy.Symbol('gamma') * 4.0),
)
]
inputs = util.convert_to_tensor(circuits)
symbols = tf.convert_to_tensor(['alpha', 'beta', 'gamma'])
res = tfq_ps_util_ops.tfq_ps_weights_from_symbols(inputs, symbols)
self.assertAllClose(
res,
np.array([[[2.0], [4.0], [0.0]], [[2.0], [3.0], [0.0]],
[[0.0], [3.0], [4.0]]]))
def test_ignorance(self):
"""Test ignorance of ISP, PXP, FSIM gates."""
circuit_batch = _complex_test_circuit()
inputs = util.convert_to_tensor(circuit_batch)
symbols = tf.convert_to_tensor(['r', 't'])
res = tfq_ps_util_ops.tfq_ps_weights_from_symbols(inputs, symbols)
# Because there are no weights to be gathered, the last dimension = 0
self.assertAllClose(tf.shape(res), [len(circuit_batch), 2, 0])
if __name__ == "__main__":
tf.test.main()
| 22,233 |
2,085 | def test():
assert Doc.has_extension("has_number"), "Você registrou a extensão no doc?"
ext = Doc.get_extension("has_number")
assert ext[2] is not None, "Você definiu o getter corretamente?"
assert (
"getter=get_has_number" in __solution__
), "Você atribuiu a função get_has_number como a função getter?"
assert "doc._.has_number" in __solution__, "Você está acessando o atributo personalizado?"
assert doc._.has_number, "Parece que a função getter está retornando o valor errado."
__msg__.good("Bom trabalho!")
| 224 |
677 | /*
* Copyright (C) 2012, 2014-2016 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "JSScope.h"
#include "PropertyDescriptor.h"
#include "SymbolTable.h"
#include "ThrowScope.h"
#include "VariableWriteFireDetail.h"
namespace JSC {
class JSSymbolTableObject : public JSScope {
public:
typedef JSScope Base;
static const unsigned StructureFlags = Base::StructureFlags | OverridesGetPropertyNames;
SymbolTable* symbolTable() const { return m_symbolTable.get(); }
JS_EXPORT_PRIVATE static bool deleteProperty(JSCell*, ExecState*, PropertyName);
JS_EXPORT_PRIVATE static void getOwnNonIndexPropertyNames(JSObject*, ExecState*, PropertyNameArray&, EnumerationMode);
static ptrdiff_t offsetOfSymbolTable() { return OBJECT_OFFSETOF(JSSymbolTableObject, m_symbolTable); }
DECLARE_EXPORT_INFO;
protected:
JSSymbolTableObject(VM& vm, Structure* structure, JSScope* scope)
: Base(vm, structure, scope)
{
}
JSSymbolTableObject(VM& vm, Structure* structure, JSScope* scope, SymbolTable* symbolTable)
: Base(vm, structure, scope)
{
ASSERT(symbolTable);
setSymbolTable(vm, symbolTable);
}
void setSymbolTable(VM& vm, SymbolTable* symbolTable)
{
ASSERT(!m_symbolTable);
symbolTable->singletonScope()->notifyWrite(vm, this, "Allocated a scope");
m_symbolTable.set(vm, this, symbolTable);
}
static void visitChildren(JSCell*, SlotVisitor&);
private:
WriteBarrier<SymbolTable> m_symbolTable;
};
template<typename SymbolTableObjectType>
inline bool symbolTableGet(
SymbolTableObjectType* object, PropertyName propertyName, PropertySlot& slot)
{
SymbolTable& symbolTable = *object->symbolTable();
ConcurrentJSLocker locker(symbolTable.m_lock);
SymbolTable::Map::iterator iter = symbolTable.find(locker, propertyName.uid());
if (iter == symbolTable.end(locker))
return false;
SymbolTableEntry::Fast entry = iter->value;
ASSERT(!entry.isNull());
ScopeOffset offset = entry.scopeOffset();
// Defend against the inspector asking for a var after it has been optimized out.
if (!object->isValidScopeOffset(offset))
return false;
slot.setValue(object, entry.getAttributes() | DontDelete, object->variableAt(offset).get());
return true;
}
template<typename SymbolTableObjectType>
inline bool symbolTableGet(
SymbolTableObjectType* object, PropertyName propertyName, PropertyDescriptor& descriptor)
{
SymbolTable& symbolTable = *object->symbolTable();
ConcurrentJSLocker locker(symbolTable.m_lock);
SymbolTable::Map::iterator iter = symbolTable.find(locker, propertyName.uid());
if (iter == symbolTable.end(locker))
return false;
SymbolTableEntry::Fast entry = iter->value;
ASSERT(!entry.isNull());
ScopeOffset offset = entry.scopeOffset();
// Defend against the inspector asking for a var after it has been optimized out.
if (!object->isValidScopeOffset(offset))
return false;
descriptor.setDescriptor(object->variableAt(offset).get(), entry.getAttributes() | DontDelete);
return true;
}
template<typename SymbolTableObjectType>
inline bool symbolTableGet(
SymbolTableObjectType* object, PropertyName propertyName, PropertySlot& slot,
bool& slotIsWriteable)
{
SymbolTable& symbolTable = *object->symbolTable();
ConcurrentJSLocker locker(symbolTable.m_lock);
SymbolTable::Map::iterator iter = symbolTable.find(locker, propertyName.uid());
if (iter == symbolTable.end(locker))
return false;
SymbolTableEntry::Fast entry = iter->value;
ASSERT(!entry.isNull());
ScopeOffset offset = entry.scopeOffset();
// Defend against the inspector asking for a var after it has been optimized out.
if (!object->isValidScopeOffset(offset))
return false;
slot.setValue(object, entry.getAttributes() | DontDelete, object->variableAt(offset).get());
slotIsWriteable = !entry.isReadOnly();
return true;
}
template<typename SymbolTableObjectType>
ALWAYS_INLINE void symbolTablePutTouchWatchpointSet(VM& vm, SymbolTableObjectType* object, PropertyName propertyName, JSValue value, WriteBarrierBase<Unknown>* reg, WatchpointSet* set)
{
reg->set(vm, object, value);
if (set)
VariableWriteFireDetail::touch(vm, set, object, propertyName);
}
template<typename SymbolTableObjectType>
ALWAYS_INLINE void symbolTablePutInvalidateWatchpointSet(VM& vm, SymbolTableObjectType* object, PropertyName propertyName, JSValue value, WriteBarrierBase<Unknown>* reg, WatchpointSet* set)
{
reg->set(vm, object, value);
if (set)
set->invalidate(vm, VariableWriteFireDetail(object, propertyName)); // Don't mess around - if we had found this statically, we would have invalidated it.
}
enum class SymbolTablePutMode {
Touch,
Invalidate
};
template<SymbolTablePutMode symbolTablePutMode, typename SymbolTableObjectType>
inline bool symbolTablePut(SymbolTableObjectType* object, ExecState* exec, PropertyName propertyName, JSValue value, bool shouldThrowReadOnlyError, bool ignoreReadOnlyErrors, bool& putResult)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
WatchpointSet* set = nullptr;
WriteBarrierBase<Unknown>* reg;
{
SymbolTable& symbolTable = *object->symbolTable();
// FIXME: This is very suspicious. We shouldn't need a GC-safe lock here.
// https://bugs.webkit.org/show_bug.cgi?id=134601
GCSafeConcurrentJSLocker locker(symbolTable.m_lock, vm.heap);
SymbolTable::Map::iterator iter = symbolTable.find(locker, propertyName.uid());
if (iter == symbolTable.end(locker))
return false;
bool wasFat;
SymbolTableEntry::Fast fastEntry = iter->value.getFast(wasFat);
ASSERT(!fastEntry.isNull());
if (fastEntry.isReadOnly() && !ignoreReadOnlyErrors) {
if (shouldThrowReadOnlyError)
throwTypeError(exec, scope, ASCIILiteral(ReadonlyPropertyWriteError));
putResult = false;
return true;
}
ScopeOffset offset = fastEntry.scopeOffset();
// Defend against the inspector asking for a var after it has been optimized out.
if (!object->isValidScopeOffset(offset))
return false;
set = iter->value.watchpointSet();
reg = &object->variableAt(offset);
}
// I'd prefer we not hold lock while executing barriers, since I prefer to reserve
// the right for barriers to be able to trigger GC. And I don't want to hold VM
// locks while GC'ing.
if (symbolTablePutMode == SymbolTablePutMode::Invalidate)
symbolTablePutInvalidateWatchpointSet(vm, object, propertyName, value, reg, set);
else
symbolTablePutTouchWatchpointSet(vm, object, propertyName, value, reg, set);
putResult = true;
return true;
}
template<typename SymbolTableObjectType>
inline bool symbolTablePutTouchWatchpointSet(
SymbolTableObjectType* object, ExecState* exec, PropertyName propertyName, JSValue value,
bool shouldThrowReadOnlyError, bool ignoreReadOnlyErrors, bool& putResult)
{
ASSERT(!Heap::heap(value) || Heap::heap(value) == Heap::heap(object));
return symbolTablePut<SymbolTablePutMode::Touch>(object, exec, propertyName, value, shouldThrowReadOnlyError, ignoreReadOnlyErrors, putResult);
}
template<typename SymbolTableObjectType>
inline bool symbolTablePutInvalidateWatchpointSet(
SymbolTableObjectType* object, ExecState* exec, PropertyName propertyName, JSValue value,
bool shouldThrowReadOnlyError, bool ignoreReadOnlyErrors, bool& putResult)
{
ASSERT(!Heap::heap(value) || Heap::heap(value) == Heap::heap(object));
return symbolTablePut<SymbolTablePutMode::Invalidate>(object, exec, propertyName, value, shouldThrowReadOnlyError, ignoreReadOnlyErrors, putResult);
}
} // namespace JSC
| 3,161 |
22,688 | /******************************************************************************
* Copyright 2018 The Apollo Authors. 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.
*****************************************************************************/
#ifndef CYBER_PARAMETER_PARAMETER_SERVER_H_
#define CYBER_PARAMETER_PARAMETER_SERVER_H_
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "cyber/proto/parameter.pb.h"
#include "cyber/parameter/parameter.h"
#include "cyber/service/service.h"
namespace apollo {
namespace cyber {
class Node;
/**
* @class ParameterServer
* @brief Parameter Service is a very important function of auto-driving.
* If you want to set a key-value, and hope other nodes to get the value,
* Routing, sensor internal/external references are set by Parameter Service
* ParameterServer can set a parameter, and then you can get/list
* paramter(s) by start a ParameterClient to send responding request
* @warning You should only have one ParameterServer works
*/
class ParameterServer {
public:
using Param = apollo::cyber::proto::Param;
using NodeName = apollo::cyber::proto::NodeName;
using ParamName = apollo::cyber::proto::ParamName;
using BoolResult = apollo::cyber::proto::BoolResult;
using Params = apollo::cyber::proto::Params;
/**
* @brief Construct a new ParameterServer object
*
* @param node shared_ptr of the node handler
*/
explicit ParameterServer(const std::shared_ptr<Node>& node);
/**
* @brief Set the Parameter object
*
* @param parmeter parameter to be set
*/
void SetParameter(const Parameter& parmeter);
/**
* @brief Get the Parameter object
*
* @param parameter_name name of the parameer want to get
* @param parameter pointer to store parameter want to get
* @return true get parameter success
* @return false parameter not exists
*/
bool GetParameter(const std::string& parameter_name, Parameter* parameter);
/**
* @brief get all the parameters
*
* @param parameters result Paramter vector
*/
void ListParameters(std::vector<Parameter>* parameters);
private:
std::shared_ptr<Node> node_;
std::shared_ptr<Service<ParamName, Param>> get_parameter_service_;
std::shared_ptr<Service<Param, BoolResult>> set_parameter_service_;
std::shared_ptr<Service<NodeName, Params>> list_parameters_service_;
std::mutex param_map_mutex_;
std::unordered_map<std::string, Param> param_map_;
};
} // namespace cyber
} // namespace apollo
#endif // CYBER_PARAMETER_PARAMETER_SERVER_H_
| 921 |
2,583 | package org.altbeacon.beacon.utils;
import android.annotation.TargetApi;
import android.os.Build;
import android.util.Base64;
import android.util.Log;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconParser;
/**
* Utility class for working beacons that include Eddystone-TLM (telemetry) information
* Created by dyoung on 12/21/15.
*/
public class EddystoneTelemetryAccessor {
private static final String TAG = "EddystoneTLMAccessor";
/**
* Extracts the raw Eddystone telemetry bytes from the extra data fields of an associated beacon.
* This is useful for passing the telemetry to Google's backend services.
* @param beacon
* @return the bytes of the telemetry frame
*/
public byte[] getTelemetryBytes(Beacon beacon) {
if (beacon.getExtraDataFields().size() >= 5) {
Beacon telemetryBeacon = new Beacon.Builder()
.setDataFields(beacon.getExtraDataFields())
.build();
BeaconParser telemetryParser = new BeaconParser()
.setBeaconLayout(BeaconParser.EDDYSTONE_TLM_LAYOUT);
byte[] telemetryBytes = telemetryParser.getBeaconAdvertisementData(telemetryBeacon);
Log.d(TAG, "Rehydrated telemetry bytes are :" + byteArrayToString(telemetryBytes));
return telemetryBytes;
}
else {
return null;
}
}
/**
* Extracts the raw Eddystone telemetry bytes from the extra data fields of an associated beacon
* and base64 encodes them. This is useful for passing the telemetry to Google's backend
* services.
* @param beacon
* @return base64 encoded telemetry bytes
*/
@TargetApi(Build.VERSION_CODES.FROYO)
public String getBase64EncodedTelemetry(Beacon beacon) {
byte[] bytes = getTelemetryBytes(beacon);
if (bytes != null) {
String base64EncodedTelemetry = Base64.encodeToString(bytes, Base64.DEFAULT);
// 12-21 00:17:18.844 20180-20180/? D/EddystoneTLMAccessor: Rehydrated telemetry bytes are :20 00 00 00 88 29 18 4d 00 00 18 4d 00 00
// 12-21 00:17:18.844 20180-20180/? D/EddystoneTLMAccessor: Base64 telemetry bytes are :IAAAAIgpGE0AABhNAAA=
Log.d(TAG, "Base64 telemetry bytes are :"+base64EncodedTelemetry);
return base64EncodedTelemetry;
}
else {
return null;
}
}
private String byteArrayToString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(String.format("%02x", bytes[i]));
sb.append(" ");
}
return sb.toString().trim();
}
}
| 1,127 |
6,989 | #!/usr/bin/env python
import os.path
import config
import experiment_lib
import catboost as cb
class CatBoostExperimentEarlyStopping(experiment_lib.ExperimentEarlyStopping):
def __init__(self, **kwargs):
super(CatBoostExperimentEarlyStopping, self).__init__(**kwargs)
def get_estimator(self, cat_cols):
return cb.CatBoostRegressor(
verbose=True,
loss_function='RMSE',
thread_count=16,
cat_features=cat_cols,
n_estimators=9999,
)
def predict_with_best_estimator(self, X_test):
return self.best_estimator.predict(X_test, ntree_end=self.best_iteration + 1)
if __name__ == "__main__":
dataset_path = config.preprocessed_dataset_path
CatBoostExperimentEarlyStopping(
train_path=os.path.join(config.preprocessed_dataset_path, 'train'),
test_path=os.path.join(config.preprocessed_dataset_path, 'test'),
cd_path=os.path.join(config.preprocessed_dataset_path, 'cd'),
output_folder_path=os.path.join(config.training_output_path, 'CatBoostExperimentEarlyStopping'),
header_in_data=False
).run()
| 496 |
799 | import demistomock as demisto
import OnboardingIntegration
def test_frequency(mocker):
mocker.patch.object(demisto, 'params',
return_value={'frequency': '1'})
mocker.patch.object(demisto, 'command',
return_value='fetch-incidents')
mocker.patch.object(demisto, 'incidents')
OnboardingIntegration.main()
assert demisto.incidents.call_count == 1
def test_no_settings(mocker):
mocker.patch.object(demisto, 'params',
return_value={})
mocker.patch.object(demisto, 'command',
return_value='fetch-incidents')
mocker.patch.object(demisto, 'incidents')
OnboardingIntegration.main()
assert demisto.incidents.call_count == 1
| 336 |
652 | <filename>src/uhs/atomizer/sentinel/server.hpp
// Copyright (c) 2021 MIT Digital Currency Initiative,
// Federal Reserve Bank of Boston
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef OPENCBDC_TX_SRC_SENTINEL_SERVER_H_
#define OPENCBDC_TX_SRC_SENTINEL_SERVER_H_
#include "uhs/sentinel/interface.hpp"
#include "uhs/transaction/messages.hpp"
#include "util/rpc/blocking_server.hpp"
#include "util/rpc/format.hpp"
namespace cbdc::sentinel::rpc {
/// RPC server for a sentinel.
class server {
public:
/// Constructor. Registers the sentinel implementation with the RPC
/// server using a request handler callback.
/// \param impl pointer to a sentinel implementation.
/// \param srv pointer to a blocking RPC server.
server(
interface* impl, // TODO: convert sentinel::controller to
// contain a shared_ptr to an implementation
std::unique_ptr<cbdc::rpc::blocking_server<request, response>>
srv);
private:
interface* m_impl;
std::unique_ptr<cbdc::rpc::blocking_server<request, response>> m_srv;
};
}
#endif // OPENCBDC_TX_SRC_SENTINEL_SERVER_H_
| 539 |
348 | {"nom":"Saint-Pierre-de-Cernières","circ":"3ème circonscription","dpt":"Eure","inscrits":177,"abs":93,"votants":84,"blancs":1,"nuls":4,"exp":79,"res":[{"nuance":"MDM","nom":"<NAME>","voix":52},{"nuance":"FN","nom":"M. <NAME>","voix":27}]} | 99 |
445 | /////////////////////////////////////////////////////////////////////////
// $Id: soundosx.h,v 1.2 2008/01/26 22:24:02 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
// This file (SOUNDOSX.H) written and donated by <NAME>
#ifdef macintosh
#include "bochs.h"
// Do not include OSX sound headers here;
// They define types Float64 and Float32,
// which are already used elsewhere in bochs.
// All OSX-specific types are hidden inside
// soundosx.cc, where nobody else has to see them.
// uncomment one of these two:
#if BX_WITH_MACOS
#define BX_SOUND_OSX_use_quicktime
#else
#define BX_SOUND_OSX_use_converter
//#define BX_SOUND_OSX_use_quicktime
#endif
#define BX_SOUND_OSX_NBUF 8 // number of buffers for digital output
class bx_sound_osx_c : public bx_sound_output_c {
public:
bx_sound_osx_c(bx_sb16_c *sb16);
BX_SOUND_VIRTUAL ~bx_sound_osx_c();
// if virtual functions are used, we have to override them
// and define our own. Otherwise this file will just implement
// the original functions
#ifdef BX_USE_SOUND_VIRTUAL
BX_SOUND_VIRTUAL int waveready();
BX_SOUND_VIRTUAL int midiready();
BX_SOUND_VIRTUAL int openmidioutput(char *device);
BX_SOUND_VIRTUAL int sendmidicommand(int delta, int command, int length, Bit8u data[]);
BX_SOUND_VIRTUAL int closemidioutput();
BX_SOUND_VIRTUAL int openwaveoutput(char *device);
BX_SOUND_VIRTUAL int startwaveplayback(int frequency, int bits, int stereo, int format);
BX_SOUND_VIRTUAL int sendwavepacket(int length, Bit8u data[]);
BX_SOUND_VIRTUAL int stopwaveplayback();
BX_SOUND_VIRTUAL int closewaveoutput();
#endif
#ifdef BX_SOUND_OSX_use_converter
void nextbuffer(int *outDataSize, void **outData);
#endif
private:
bx_sb16_c *sb16;
int MidiOpen;
int WaveOpen;
Bit8u WaveData[BX_SOUND_OSX_NBUF][BX_SOUND_OUTPUT_WAVEPACKETSIZE];
int WaveLength[BX_SOUND_OSX_NBUF];
int head, tail; // buffer pointers
#ifdef BX_SOUND_OSX_use_converter
int WavePlaying;
#endif
};
#endif // macintosh
| 829 |
583 | <gh_stars>100-1000
#pragma once
#include <string>
#include <cstdint>
// sizeof(Address) should always be sizeof(void*).
class Address {
public:
Address();
Address(void* ptr);
Address(uintptr_t addr);
void set(void* ptr) {
m_ptr = ptr;
}
template <typename T>
Address get(T offset) const {
return Address((uintptr_t)m_ptr + offset);
}
template <typename T>
Address add(T offset) const {
return Address((uintptr_t)m_ptr + offset);
}
template <typename T>
Address sub(T offset) const {
return Address((uintptr_t)m_ptr - offset);
}
template <typename T>
T as() const {
return (T)m_ptr;
}
// to is like as but dereferences that shit.
template <typename T>
T to() const {
return *(T*)m_ptr;
}
Address deref() const {
return to<void*>();
}
void* ptr() const {
return m_ptr;
}
operator uintptr_t() const {
return (uintptr_t)m_ptr;
}
operator void*() const {
return m_ptr;
}
bool operator ==(bool val) {
return ((m_ptr && val) || (!m_ptr && !val));
}
bool operator !=(bool val) {
return !(*this == val);
}
bool operator ==(uintptr_t val) {
return ((uintptr_t)m_ptr == val);
}
bool operator !=(uintptr_t val) {
return !(*this == val);
}
bool operator ==(void* val) {
return (m_ptr == val);
}
bool operator !=(void* val) {
return !(*this == val);
}
private:
void* m_ptr;
};
typedef Address Offset;
| 724 |
374 | <reponame>DatabasesWorks/passiflora-symphytum-configurable-fields<filename>widgets/field_widgets/numberfieldwizard.cpp
/*
* Copyright (c) 2012 <NAME> <<EMAIL>>
*/
//-----------------------------------------------------------------------------
// Hearders
//-----------------------------------------------------------------------------
#include "numberfieldwizard.h"
#include "ui_numberfieldwizard.h"
#include "../../components/metadataengine.h"
#include "../../utils/metadatapropertiesparser.h"
//-----------------------------------------------------------------------------
// Public
//-----------------------------------------------------------------------------
NumberFieldWizard::NumberFieldWizard(const QString &fieldName,
QWidget *parent,
AbstractFieldWizard::EditMode editMode) :
AbstractFieldWizard(fieldName, parent, editMode),
ui(new Ui::NumberFieldWizard)
{
ui->setupUi(this);
connect(ui->backButton, SIGNAL(clicked()),
this, SIGNAL(backSignal()));
connect(ui->finishButton, SIGNAL(clicked()),
this, SIGNAL(finishSignal()));
connect(ui->notationComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(updateNotationBox()));
ui->finishButton->setFocus();
}
NumberFieldWizard::~NumberFieldWizard()
{
delete ui;
}
void NumberFieldWizard::getFieldProperties(QString &displayProperties,
QString &editProperties,
QString &triggerProperties)
{
//create display properties metadata string
if (ui->requiredFieldCheckBox->isChecked())
displayProperties.append("markEmpty:1;");
if (ui->markNegativeCheckBox->isChecked())
displayProperties.append("markNegative:1;");
displayProperties.append(QString("precision:%1;")
.arg(ui->precisionSpinBox->value()));
//display mode
QString displayMode;
switch (ui->notationComboBox->currentIndex()) {
case 0:
displayMode = "auto";
break;
case 1:
displayMode = "decimal";
break;
case 2:
displayMode = "scientific";
break;
default:
displayMode = "auto";
break;
}
displayProperties.append("displayMode:" + displayMode + ";");
//create edit properties metadata string
if (ui->requiredFieldCheckBox->isChecked())
editProperties.append("noEmpty:1;");
//create trigger properties metadata string
//nothing for now
Q_UNUSED(triggerProperties);
}
void NumberFieldWizard::loadField(const int fieldId, const int collectionId)
{
AbstractFieldWizard::loadField(fieldId, collectionId);
MetadataEngine *meta = &MetadataEngine::getInstance();
//display properties
QString displayProperties = meta->getFieldProperties(meta->DisplayProperty,
fieldId, collectionId);
MetadataPropertiesParser displayParser(displayProperties);
if (displayParser.size()) {
if (displayParser.getValue("markNegative") == "1")
ui->markNegativeCheckBox->setChecked(true);
ui->precisionSpinBox->setValue(displayParser.getValue("precision").toInt());
//display mode
QString m = displayParser.getValue("displayMode");
if (m == QString("auto"))
ui->notationComboBox->setCurrentIndex(0);
else if (m == QString("decimal"))
ui->notationComboBox->setCurrentIndex(1);
else if (m == QString("scientific"))
ui->notationComboBox->setCurrentIndex(2);
}
//edit properties
QString editProperties = meta->getFieldProperties(meta->EditProperty,
fieldId, collectionId);
MetadataPropertiesParser editParser(editProperties);
if (editParser.size()) {
if (editParser.getValue("noEmpty") == "1")
ui->requiredFieldCheckBox->setChecked(true);
}
}
//-----------------------------------------------------------------------------
// Private slots
//-----------------------------------------------------------------------------
void NumberFieldWizard::updateNotationBox()
{
bool enabled = ui->notationComboBox->currentIndex() != 0;
ui->precisionGroupBox->setEnabled(enabled);
}
| 1,671 |
647 | /*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.copycat.server.storage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import io.atomix.catalyst.buffer.Buffer;
import io.atomix.catalyst.buffer.DirectBuffer;
import io.atomix.catalyst.serializer.Serializer;
import io.atomix.copycat.server.storage.compaction.Compaction;
import io.atomix.copycat.server.storage.util.StorageSerialization;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
/**
* Abstract log test.
*
* @author <NAME>
*/
@Test
public abstract class AbstractLogTest {
protected int entryPadding;
protected int entriesPerSegment = 3;
protected Storage storage;
protected Log log;
String logId;
protected abstract Storage createStorage();
/**
* Creates a new test log.
*/
protected Log createLog() {
return new Log(logId, storage, new Serializer().resolve(new StorageSerialization()).register(TestEntry.class));
}
/**
* Returns a set of tests to run for varied log configurations.
*/
protected Object[] testsFor(Class<? extends LogTest> testClass) throws Throwable {
List<Object> tests = new ArrayList<>();
for (int i = 1; i < 10; i++) {
LogTest test = testClass.newInstance();
test.entriesPerSegment = i;
test.entryPadding = i / 3;
tests.add(test);
}
return tests.toArray(new Object[tests.size()]);
}
protected int entrySize() {
Serializer serializer = new Serializer();
serializer.register(TestEntry.class);
Buffer buffer = DirectBuffer.allocate(1000);
TestEntry entry = new TestEntry();
entry.setPadding(entryPadding);
serializer.writeObject(entry, buffer);
return (int) buffer.position() + Short.BYTES + Long.BYTES + Byte.BYTES;
}
@BeforeMethod
void setLog() throws Exception {
logId = UUID.randomUUID().toString();
storage = createStorage();
log = new Log(logId, storage, new Serializer().resolve(new StorageSerialization()));
log.serializer().register(TestEntry.class);
assertTrue(log.isOpen());
assertFalse(log.isClosed());
assertTrue(log.isEmpty());
}
@AfterMethod
protected void deleteLog() {
try {
if (log.isOpen())
log.close();
} catch (Exception ignore) {
} finally {
assertFalse(log.isOpen());
assertTrue(log.isClosed());
storage.deleteLog(logId);
}
}
/**
* Returns the size of a full segment given the entrySize, entriesPerSegment, and SegmentDescriptor.
*/
int fullSegmentSize() {
return entriesPerSegment * entrySize() + SegmentDescriptor.BYTES;
}
protected Storage.Builder tempStorageBuilder() {
return Storage.builder().withDirectory(new File(String.format("target/test-logs/%s", logId)));
}
@BeforeTest
@AfterTest
protected void cleanLogDir() throws IOException {
Path directory = Paths.get("target/test-logs/");
if (Files.exists(directory)) {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
}
/**
* Appends {@code numEntries} increasingly numbered ByteBuffer wrapped entries to the log.
*/
protected List<Long> appendEntries(int numEntries) {
return appendEntries(numEntries, Compaction.Mode.QUORUM);
}
/**
* Appends {@code numEntries} increasingly numbered ByteBuffer wrapped entries to the log.
*/
protected List<Long> appendEntries(int numEntries, Compaction.Mode mode) {
List<Long> indexes = new ArrayList<>(numEntries);
for (int i = 0; i < numEntries; i++) {
try (TestEntry entry = log.create(TestEntry.class)) {
entry.setTerm(1).setCompactionMode(mode).setPadding(entryPadding);
indexes.add(log.append(entry));
}
}
return indexes;
}
protected static void assertIndexes(List<Long> indexes, int start, int end) {
for (int i = 0, j = start; j <= end; i++, j++)
assertEquals(indexes.get(i).longValue(), j);
}
protected void cleanAndCompact(int startIndex, int endIndex) {
for (int i = startIndex; i <= endIndex; i++) {
log.release(i);
}
log.compactor().compact(Compaction.MAJOR).join();
}
protected void assertCompacted(int startIndex, int endIndex) {
for (int i = startIndex; i <= endIndex; i++) {
assertNull(log.get(i));
}
}
protected void printLog() {
for (int i = 1; i < log.length(); i++) {
System.out.println(log.get(i).toString());
}
}
}
| 2,061 |
1,184 | #include <stdio.h>
#include <math.h>
#define N 1000000
void sieve(int *numbers){
int limit = (int)floor(sqrt(N));
int i;
for(i = 2; i <= limit; i++){
int j, k;
j = k = 0;
while(1){
j = ((int)pow(i, 2)) + (k++ * i);
if(j <= N){
numbers[j] = 0;
}else{
break;
}
}
}
}
int main(){
/*
* Initialize the array with truth
* 0 -> false
* 1 -> true
*/
int primes[N] = {0};
int i;
for(i = 2; i <= N; i++){ primes[i] = 1; }
// Call to the function with N numbers
sieve(primes);
/*
* Funny test
* 1 = Pass
* 0 = Failure
*/
printf("When search the number 2 as a prime: %d\n", primes[2]);
printf("When search the number 137 as a prime: %d\n", primes[137]);
printf("When search the number 233 as a prime: %d\n", primes[233]);
printf("When search the number 997 as a prime: %d\n", primes[997]);
// With !primes[0] I mean, not prime
printf("When search the number 0 as a prime: %d\n", !primes[0]);
printf("When search the number 1 as a prime: %d\n", !primes[1]);
// Count the primes
int count = 0;
for(i = 2; i <= N; i++){
// Is prime
if(primes[i]){
count++;
}
}
printf("How many primes there are in %d: %d", N, count);
return 0;
}
| 700 |
852 | <gh_stars>100-1000
#include <string.h>
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <set>
#include "EventFilter/CSCTFRawToDigi/src/CSCTFEvent.cc"
#include "EventFilter/CSCTFRawToDigi/src/CSCSPEvent.cc"
#include "EventFilter/CSCTFRawToDigi/src/CSCSPRecord.cc"
#include "IORawData/CSCCommissioning/src/FileReaderDDU.cc"
//g++ -o test test.cc -I../../../
int main(int argc, char *argv[]){
using namespace std;
FILE *out;
if( (out=fopen("dump2.raw","wt"))==NULL ){
printf("Cannot open output file: %s (errno=%d)\n","dump2.raw",errno);
return 1;
}
// DDU File Reader
FileReaderDDU reader;
reader.open(argv[1]);
// Event buffer
size_t size, nevents=0;
const unsigned short *buf=0;
// Main cycle
while( (size = reader.read(buf)) /*&& nevents<100*/ ){
unsigned short event[size];
// Swep out C-words
unsigned int index1=12, index2=12;
memcpy(event,buf,12*sizeof(unsigned short));
while( index1 < size ){
if( (buf[index1]&0xF000)!=0xC000 ){
event[index2] = buf[index1];
index1++;
index2++;
} else {
index1++;
}
}
CSCTFEvent tfEvent, qwe;
if(nevents%1000==0) cout<<"Event: "<<nevents<<endl;
/// cout<<" Unpack: "<<
tfEvent.unpack(event,index2);
/// <<endl;
bool log_event = false;
vector<CSCSPEvent> SPs = tfEvent.SPs();
for(int sp=0; sp<SPs.size(); sp++){
/// cout<<" L1A="<<SPs[0].header().L1A()<<endl;
for(unsigned int tbin=0; tbin<SPs[sp].header().nTBINs(); tbin++){
bool mismatch = false;
vector<CSCSP_SPblock> tracks = SPs[sp].record(tbin).tracks();
for(vector<CSCSP_SPblock>::const_iterator track=tracks.begin(); track!=tracks.end(); track++){
unsigned int nStations=0;
if( track->ME1_id() ) nStations++;
if( track->ME2_id() ) nStations++;
if( track->ME3_id() ) nStations++;
if( track->ME4_id() ) nStations++;
if( track->LCTs().size() != nStations ){
mismatch = true;
cout<<" mismatch found in tbin="<<tbin<<": ("<<track->LCTs().size()<<"!="<<nStations<<")";
}
if( mismatch ){
cout<<hex<<" ME1: 0x"<<track->ME1_id()<<" tbin: "<<track->ME1_tbin()<<", "<<dec;
cout<<hex<<" ME2: 0x"<<track->ME2_id()<<" tbin: "<<track->ME2_tbin()<<", "<<dec;
cout<<hex<<" ME3: 0x"<<track->ME3_id()<<" tbin: "<<track->ME3_tbin()<<", "<<dec;
cout<<hex<<" ME4: 0x"<<track->ME4_id()<<" tbin: "<<track->ME4_tbin()<<" "<<dec;
}
}
vector<CSCSP_MEblock> lct = SPs[sp].record(tbin).LCTs();
if( lct.size() ){
cout<<"Event: "<<nevents<<" SP"<<sp<<" L1A="<<SPs[sp].header().L1A()<<" BXN="<<SPs[sp].header().BXN()<<" Orbit counter="<<SPs[sp].counters().orbit_counter()<<endl;
cout<<" Endcap: "<<(SPs[sp].header().endcap()?2:1)<<" sector: "<<SPs[sp].header().sector();
cout<<" tbin: "<<tbin<<" nLCTs: "<<SPs[sp].record(tbin).LCTs().size()<<" (";//<<endl;
}
for(std::vector<CSCSP_MEblock>::const_iterator i=lct.begin(); i!=lct.end(); i++){
cout<<" F"<<((i->spInput()-1)/3+1)<<"/CSC"<<i->csc()<<":{w="<<i->wireGroup()<<",s="<<i->strip()<<"} ";
}
if( lct.size() ) cout<<" )"<<endl;
std::vector<CSCSP_SPblock> trks = SPs[sp].record(tbin).tracks();
if( trks.size() ){ cout<<" Track(s) at BX=: "<<SPs[sp].header().BXN(); }
for(std::vector<CSCSP_SPblock>::const_iterator trk=trks.begin(); trk<trks.end(); trk++){ cout<<" mode="<<trk->mode(); if(trk->mode()==15 && SPs[sp].header().BXN()==380) log_event=true; }
if( trks.size() ){ cout<<endl; }
}
}
if(log_event) fwrite(event,2,index2,out);
nevents++;
}
fclose(out);
return 0;
}
| 1,714 |
9,255 | <reponame>wxj978566042/VirtualAPK_Origin<filename>CoreLibrary/src/main/java/com/didi/virtualapk/internal/PluginContentResolver.java
/*
* Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.didi.virtualapk.internal;
import android.annotation.TargetApi;
import android.content.ContentResolverWrapper;
import android.content.Context;
import android.content.IContentProvider;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Keep;
import com.didi.virtualapk.PluginManager;
import com.didi.virtualapk.delegate.RemoteContentProvider;
/**
* Created by renyugang on 16/12/7.
*/
public class PluginContentResolver extends ContentResolverWrapper {
private PluginManager mPluginManager;
public PluginContentResolver(Context context) {
super(context);
mPluginManager = PluginManager.getInstance(context);
}
@Override
protected IContentProvider acquireProvider(Context context, String auth) {
if (mPluginManager.resolveContentProvider(auth, 0) != null) {
return mPluginManager.getIContentProvider();
}
return super.acquireProvider(context, auth);
}
@Override
protected IContentProvider acquireExistingProvider(Context context, String auth) {
if (mPluginManager.resolveContentProvider(auth, 0) != null) {
return mPluginManager.getIContentProvider();
}
return super.acquireExistingProvider(context, auth);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
protected IContentProvider acquireUnstableProvider(Context context, String auth) {
if (mPluginManager.resolveContentProvider(auth, 0) != null) {
return mPluginManager.getIContentProvider();
}
return super.acquireUnstableProvider(context, auth);
}
@Override
public boolean releaseProvider(IContentProvider provider) {
return true;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public boolean releaseUnstableProvider(IContentProvider icp) {
return true;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void unstableProviderDied(IContentProvider icp) {
}
@TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
@Override
public void appNotRespondingViaProvider(IContentProvider icp) {
}
protected int resolveUserIdFromAuthority(String auth) {
return 0;
}
@Keep
public static Uri wrapperUri(LoadedPlugin loadedPlugin, Uri pluginUri) {
String pkg = loadedPlugin.getPackageName();
String pluginUriString = Uri.encode(pluginUri.toString());
StringBuilder builder = new StringBuilder(RemoteContentProvider.getUri(loadedPlugin.getHostContext()));
builder.append("/?plugin=" + loadedPlugin.getLocation());
builder.append("&pkg=" + pkg);
builder.append("&uri=" + pluginUriString);
Uri wrapperUri = Uri.parse(builder.toString());
return wrapperUri;
}
@Deprecated
public static String getAuthority(Context context) {
return RemoteContentProvider.getAuthority(context);
}
@Deprecated
public static String getUri(Context context) {
return RemoteContentProvider.getUri(context);
}
@Keep
public static Bundle getBundleForCall(Uri uri) {
Bundle bundle = new Bundle();
bundle.putString(RemoteContentProvider.KEY_WRAPPER_URI, uri.toString());
return bundle;
}
}
| 1,436 |
1,188 | package com.javadeobfuscator.deobfuscator.executor.defined.types;
import com.javadeobfuscator.deobfuscator.executor.Context;
import com.javadeobfuscator.deobfuscator.executor.values.*;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.MethodNode;
import com.javadeobfuscator.deobfuscator.utils.PrimitiveUtils;
import java.util.ArrayList;
import java.util.List;
public class JavaConstructor {
private final JavaClass clazz;
private final String desc;
public JavaConstructor(JavaClass clazz, String desc) {
this.clazz = clazz;
this.desc = desc;
}
public JavaClass getClazz() {
return clazz;
}
public JavaClass[] getParameterTypes() {
List<JavaClass> params = new ArrayList<>();
for (Type type : Type.getArgumentTypes(desc)) {
Class<?> primitive = PrimitiveUtils.getPrimitiveByName(type.getClassName());
if (primitive != null) {
params.add(new JavaClass(type.getClassName(), clazz.getContext()));
} else {
params.add(new JavaClass(type.getInternalName(), clazz.getContext()));
}
}
return params.toArray(new JavaClass[params.size()]);
}
public Object newInstance(Context context, JavaValue argsObject)
{
Object[] args;
String[] argTypes;
if(argsObject.value() == null)
{
args = null;
argTypes = null;
}else
{
args = (Object[])((JavaArray)argsObject).value();
argTypes = ((JavaArray)argsObject).getTypeArray();
}
MethodNode method = clazz.getClassNode().methods.stream().filter(m -> m.name.equals("<init>")
&& m.desc.equals(desc)).findFirst().orElse(null);
List<JavaValue> javaArgs = new ArrayList<>();
for(int i = 0; i < args.length; i++)
{
Object arg = args[i];
if(arg instanceof Type)
{
Type type = (Type)arg;
arg = new JavaClass(type.getInternalName().replace('/', '.'), context);
}
if(arg instanceof Boolean)
javaArgs.add(0, new JavaBoolean((Boolean)arg));
else if(arg instanceof Character)
javaArgs.add(0, new JavaCharacter((Character)arg));
else if(arg instanceof Byte)
javaArgs.add(0, new JavaByte((Byte)arg));
else if(arg instanceof Short)
javaArgs.add(0, new JavaShort((Short)arg));
else if(arg instanceof Integer)
javaArgs.add(0, new JavaInteger((Integer)arg));
else if(arg instanceof Float)
javaArgs.add(0, new JavaFloat((Float)arg));
else if(arg instanceof Double)
javaArgs.add(0, new JavaDouble((Double)arg));
else if(arg instanceof Long)
javaArgs.add(0, new JavaLong((Long)arg));
else if(arg != null && arg.getClass().isArray())
javaArgs.add(new JavaArray(arg));
else
javaArgs.add(new JavaObject(arg, argTypes[i]));
}
JavaObject instance = new JavaObject(clazz.getName().replace(".", "/"));
context.provider.invokeMethod(clazz.getName().replace(".", "/"), method.name, method.desc,
instance, javaArgs, context);
return instance.value();
}
public void setAccessible(boolean accessible) {
}
public String getClassName() {
return clazz.getClassNode().name;
}
public String getDesc() {
return desc;
}
}
| 1,526 |
1,350 | <filename>sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricEncryptionAlgorithm.java<gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.microsoft.azure.keyvault.cryptography;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import javax.crypto.NoSuchPaddingException;
/**
* Abstract base class for all asymmetric encryption algorithms.
*
*/
public abstract class AsymmetricEncryptionAlgorithm extends EncryptionAlgorithm {
/**
* Constructor.
*
* @param name The name of the algorithm.
*/
protected AsymmetricEncryptionAlgorithm(String name) {
super(name);
}
/**
* Creates a {@link com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation for encryption that
* uses the specified {@link java.security.KeyPair} and the default {@link java.security.Provider} provider.
*
* @param keyPair The key pair to use.
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
*/
public abstract ICryptoTransform CreateEncryptor(KeyPair keyPair) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException;
/**
* Creates a {@link com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation for encryption that
* uses the specified {@link java.security.KeyPair} and {@link java.security.Provider}.
*
* @param keyPair The key pair to use.
* @param provider The provider to use.
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
*/
public abstract ICryptoTransform CreateEncryptor(KeyPair keyPair, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException;
/**
* Creates a {@link com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation for decryption that
* uses the specified {@link java.security.KeyPair} and the default {@link java.security.Provider} provider.
*
* @param keyPair The key pair to use.
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
*/
public abstract ICryptoTransform CreateDecryptor(KeyPair keyPair) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException;
/**
* Creates a {@link com.microsoft.azure.keyvault.cryptography.ICryptoTransform} implementation for decryption that
* uses the specified {@link java.security.KeyPair} and {@link java.security.Provider}.
*
* @param keyPair The key pair to use.
* @param provider The provider to use.
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
*/
public abstract ICryptoTransform CreateDecryptor(KeyPair keyPair, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException;
}
| 1,056 |
543 | package com.riiablo.serializer;
import android.support.annotation.NonNull;
public enum IntegerStringSerializer implements StringSerializer<Integer> {
INSTANCE;
@Override
@NonNull
public String serialize(@NonNull Integer obj) {
return obj.toString();
}
@Override
@NonNull
public Integer deserialize(@NonNull String obj) {
try {
return Integer.parseInt(obj);
} catch (Throwable t) {
throw new SerializeException(t);
}
}
}
| 161 |
391 | <filename>src/m_utils/time_out.py
"""
Timeout feature from stackoverflow.
usage:
try:
with timeout ( seconds=5 ):
# Do some thing
except Exception, e:
#hadnle run time exception for timeout
"""
import signal
class timeout:
def __init__(self, seconds=1, error_message='Timeout'):
self.seconds = seconds
self.error_message = error_message
def handle_timeout(self, signum, frame):
raise RuntimeError ( self.error_message )
def __enter__(self):
signal.signal ( signal.SIGALRM, self.handle_timeout )
signal.alarm ( self.seconds )
def __exit__(self, type, value, traceback):
signal.alarm ( 0 )
| 274 |
2,539 | /*
LZ5 HC - High Compression Mode of LZ5
Copyright (C) 2011-2015, <NAME>.
Copyright (C) 2015, <NAME> <<EMAIL>>
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ5 source repository : https://github.com/inikep/lz5
- LZ5 public forum : https://groups.google.com/forum/#!forum/lz5c
*/
/* *************************************
* Includes
***************************************/
#define LZ5HC_INCLUDES
#include "lz5common.h"
#include "lz5.h"
#include "lz5hc.h"
/**************************************
* HC Compression
**************************************/
int LZ5_alloc_mem_HC(LZ5HC_Data_Structure* ctx, int compressionLevel)
{
ctx->compressionLevel = compressionLevel;
if (compressionLevel > g_maxCompressionLevel) ctx->compressionLevel = g_maxCompressionLevel;
if (compressionLevel < 1) ctx->compressionLevel = LZ5HC_compressionLevel_default;
ctx->params = LZ5HC_defaultParameters[ctx->compressionLevel];
ctx->hashTable = (U32*) malloc(sizeof(U32)*(((size_t)1 << ctx->params.hashLog3)+((size_t)1 << ctx->params.hashLog)));
if (!ctx->hashTable)
return 0;
ctx->hashTable3 = ctx->hashTable + ((size_t)1 << ctx->params.hashLog);
ctx->chainTable = (U32*) malloc(sizeof(U32)*((size_t)1 << ctx->params.contentLog));
if (!ctx->chainTable)
{
FREEMEM(ctx->hashTable);
ctx->hashTable = NULL;
return 0;
}
return 1;
}
void LZ5_free_mem_HC(LZ5HC_Data_Structure* ctx)
{
if (!ctx) return;
if (ctx->chainTable) FREEMEM(ctx->chainTable);
if (ctx->hashTable) FREEMEM(ctx->hashTable);
ctx->base = NULL;
}
static void LZ5HC_init (LZ5HC_Data_Structure* ctx, const BYTE* start)
{
#ifdef LZ5_RESET_MEM
MEM_INIT((void*)ctx->hashTable, 0, sizeof(U32)*((1 << ctx->params.hashLog) + (1 << ctx->params.hashLog3)));
if (ctx->params.strategy >= LZ5HC_lowest_price)
MEM_INIT(ctx->chainTable, 0x01, sizeof(U32)*(1 << ctx->params.contentLog));
#else
#ifdef _DEBUG
int i, len = sizeof(U32)*((1 << ctx->params.hashLog) + (1 << ctx->params.hashLog3));
unsigned char* bytes = (unsigned char*)ctx->hashTable;
srand(0);
for (i=0; i<len; i++)
bytes[i] = (unsigned char)rand();
#endif
#endif
ctx->nextToUpdate = (U32)((size_t)1 << ctx->params.windowLog);
ctx->base = start - ((size_t)1 << ctx->params.windowLog);
ctx->end = start;
ctx->dictBase = start - ((size_t)1 << ctx->params.windowLog);
ctx->dictLimit = (U32)((size_t)1 << ctx->params.windowLog);
ctx->lowLimit = (U32)((size_t)1 << ctx->params.windowLog);
ctx->last_off = 1;
}
/* Update chains up to ip (excluded) */
FORCE_INLINE void LZ5HC_BinTree_Insert(LZ5HC_Data_Structure* ctx, const BYTE* ip)
{
#if MINMATCH == 3
U32* HashTable3 = ctx->hashTable3;
const BYTE* const base = ctx->base;
const U32 target = (U32)(ip - base);
U32 idx = ctx->nextToUpdate;
while(idx < target)
{
HashTable3[LZ5HC_hash3Ptr(base+idx, ctx->params.hashLog3)] = idx;
idx++;
}
ctx->nextToUpdate = target;
#endif
}
/* Update chains up to "end" (excluded) */
FORCE_INLINE void LZ5HC_BinTree_InsertFull(LZ5HC_Data_Structure* ctx, const BYTE* end, const BYTE* iHighLimit)
{
U32* chainTable = ctx->chainTable;
U32* HashTable = ctx->hashTable;
#if MINMATCH == 3
U32* HashTable3 = ctx->hashTable3;
#endif
U32 idx = ctx->nextToUpdate;
const BYTE* const base = ctx->base;
const U32 dictLimit = ctx->dictLimit;
const U32 maxDistance = (1 << ctx->params.windowLog);
const U32 current = (U32)(end - base);
const U32 lowLimit = (ctx->lowLimit + maxDistance > idx) ? ctx->lowLimit : idx - (maxDistance - 1);
const U32 contentMask = (1 << ctx->params.contentLog) - 1;
const BYTE* const dictBase = ctx->dictBase;
const BYTE* match, *ip;
int nbAttempts;
U32 *ptr0, *ptr1, *HashPos;
U32 matchIndex, delta0, delta1;
size_t mlt;
while(idx < current)
{
ip = base + idx;
if (ip + MINMATCH > iHighLimit) return;
HashPos = &HashTable[LZ5HC_hashPtr(ip, ctx->params.hashLog, ctx->params.searchLength)];
matchIndex = *HashPos;
#if MINMATCH == 3
HashTable3[LZ5HC_hash3Ptr(ip, ctx->params.hashLog3)] = idx;
#endif
// check rest of matches
ptr0 = &chainTable[(idx*2+1) & contentMask];
ptr1 = &chainTable[(idx*2) & contentMask];
delta0 = delta1 = idx - matchIndex;
nbAttempts = ctx->params.searchNum;
*HashPos = idx;
// while ((matchIndex >= dictLimit) && (matchIndex < idx) && (idx - matchIndex) < MAX_DISTANCE && nbAttempts)
while ((matchIndex < current) && (matchIndex < idx) && (matchIndex>=lowLimit) && (nbAttempts))
{
nbAttempts--;
mlt = 0;
if (matchIndex >= dictLimit)
{
match = base + matchIndex;
if (MEM_read24(match) == MEM_read24(ip))
{
mlt = MINMATCH + MEM_count(ip+MINMATCH, match+MINMATCH, iHighLimit);
if (mlt > LZ5_OPT_NUM) break;
}
}
else
{
match = dictBase + matchIndex;
if (MEM_read32(match) == MEM_read32(ip))
{
const BYTE* vLimit = ip + (dictLimit - matchIndex);
if (vLimit > iHighLimit) vLimit = iHighLimit;
mlt = MEM_count(ip+MINMATCH, match+MINMATCH, vLimit) + MINMATCH;
if ((ip+mlt == vLimit) && (vLimit < iHighLimit))
mlt += MEM_count(ip+mlt, base+dictLimit, iHighLimit);
if (mlt > LZ5_OPT_NUM) break;
}
}
if (*(ip+mlt) < *(match+mlt))
{
*ptr0 = delta0;
ptr0 = &chainTable[(matchIndex*2) & contentMask];
if (*ptr0 == (U32)-1) break;
delta0 = *ptr0;
delta1 += delta0;
matchIndex -= delta0;
}
else
{
*ptr1 = delta1;
ptr1 = &chainTable[(matchIndex*2+1) & contentMask];
if (*ptr1 == (U32)-1) break;
delta1 = *ptr1;
delta0 += delta1;
matchIndex -= delta1;
}
}
*ptr0 = (U32)-1;
*ptr1 = (U32)-1;
// LZ5_LOG_MATCH("%d: LZMAX_UPDATE_HASH_BINTREE hash=%d inp=%d,%d,%d,%d (%c%c%c%c)\n", (int)(inp-base), hash, inp[0], inp[1], inp[2], inp[3], inp[0], inp[1], inp[2], inp[3]);
idx++;
}
ctx->nextToUpdate = current;
}
/* Update chains up to ip (excluded) */
FORCE_INLINE void LZ5HC_Insert (LZ5HC_Data_Structure* ctx, const BYTE* ip)
{
U32* chainTable = ctx->chainTable;
U32* HashTable = ctx->hashTable;
#if MINMATCH == 3
U32* HashTable3 = ctx->hashTable3;
#endif
const BYTE* const base = ctx->base;
const U32 target = (U32)(ip - base);
const U32 contentMask = (1 << ctx->params.contentLog) - 1;
U32 idx = ctx->nextToUpdate;
while(idx < target)
{
size_t h = LZ5HC_hashPtr(base+idx, ctx->params.hashLog, ctx->params.searchLength);
chainTable[idx & contentMask] = (U32)(idx - HashTable[h]);
// if (chainTable[idx & contentMask] == 1) chainTable[idx & contentMask] = (U32)0x01010101;
HashTable[h] = idx;
#if MINMATCH == 3
HashTable3[LZ5HC_hash3Ptr(base+idx, ctx->params.hashLog3)] = idx;
#endif
idx++;
}
ctx->nextToUpdate = target;
}
FORCE_INLINE int LZ5HC_FindBestMatch (LZ5HC_Data_Structure* ctx, /* Index table will be updated */
const BYTE* ip, const BYTE* const iLimit,
const BYTE** matchpos)
{
U32* const chainTable = ctx->chainTable;
U32* const HashTable = ctx->hashTable;
const BYTE* const base = ctx->base;
const BYTE* const dictBase = ctx->dictBase;
const U32 dictLimit = ctx->dictLimit;
const U32 maxDistance = (1 << ctx->params.windowLog);
const U32 current = (U32)(ip - base);
const U32 lowLimit = (ctx->lowLimit + maxDistance > current) ? ctx->lowLimit : current - (maxDistance - 1);
const U32 contentMask = (1 << ctx->params.contentLog) - 1;
U32 matchIndex;
const BYTE* match;
int nbAttempts=ctx->params.searchNum;
size_t ml=0, mlt;
matchIndex = HashTable[LZ5HC_hashPtr(ip, ctx->params.hashLog, ctx->params.searchLength)];
match = ip - ctx->last_off;
if (MEM_read24(match) == MEM_read24(ip))
{
ml = MEM_count(ip+MINMATCH, match+MINMATCH, iLimit) + MINMATCH;
*matchpos = match;
return (int)ml;
}
#if MINMATCH == 3
{
U32 matchIndex3 = ctx->hashTable3[LZ5HC_hash3Ptr(ip, ctx->params.hashLog3)];
if (matchIndex3 < current && matchIndex3 >= lowLimit)
{
size_t offset = (size_t)current - matchIndex3;
if (offset < LZ5_SHORT_OFFSET_DISTANCE)
{
match = ip - offset;
if (match > base && MEM_read24(ip) == MEM_read24(match))
{
ml = 3;//MEM_count(ip+MINMATCH, match+MINMATCH, iLimit) + MINMATCH;
*matchpos = match;
}
}
}
}
#endif
while ((matchIndex < current) && (matchIndex>=lowLimit) && (nbAttempts))
{
nbAttempts--;
if (matchIndex >= dictLimit)
{
match = base + matchIndex;
if (*(match+ml) == *(ip+ml) && (MEM_read32(match) == MEM_read32(ip)))
{
mlt = MEM_count(ip+MINMATCH, match+MINMATCH, iLimit) + MINMATCH;
if (!ml || (mlt > ml && LZ5HC_better_price((ip - *matchpos), ml, (ip - match), mlt, ctx->last_off)))
// if (mlt > ml && (LZ5_NORMAL_MATCH_COST(mlt - MINMATCH, (ip - match == ctx->last_off) ? 0 : (ip - match)) < LZ5_NORMAL_MATCH_COST(ml - MINMATCH, (ip - *matchpos == ctx->last_off) ? 0 : (ip - *matchpos)) + (LZ5_NORMAL_LIT_COST(mlt - ml))))
{ ml = mlt; *matchpos = match; }
}
}
else
{
match = dictBase + matchIndex;
if (MEM_read32(match) == MEM_read32(ip))
{
const BYTE* vLimit = ip + (dictLimit - matchIndex);
if (vLimit > iLimit) vLimit = iLimit;
mlt = MEM_count(ip+MINMATCH, match+MINMATCH, vLimit) + MINMATCH;
if ((ip+mlt == vLimit) && (vLimit < iLimit))
mlt += MEM_count(ip+mlt, base+dictLimit, iLimit);
if (!ml || (mlt > ml && LZ5HC_better_price((ip - *matchpos), ml, (ip - match), mlt, ctx->last_off)))
// if (mlt > ml && (LZ5_NORMAL_MATCH_COST(mlt - MINMATCH, (ip - match == ctx->last_off) ? 0 : (ip - match)) < LZ5_NORMAL_MATCH_COST(ml - MINMATCH, (ip - *matchpos == ctx->last_off) ? 0 : (ip - *matchpos)) + (LZ5_NORMAL_LIT_COST(mlt - ml))))
{ ml = mlt; *matchpos = base + matchIndex; } /* virtual matchpos */
}
}
matchIndex -= chainTable[matchIndex & contentMask];
}
return (int)ml;
}
FORCE_INLINE int LZ5HC_FindMatchFast (LZ5HC_Data_Structure* ctx, U32 matchIndex, U32 matchIndex3, /* Index table will be updated */
const BYTE* ip, const BYTE* const iLimit,
const BYTE** matchpos)
{
const BYTE* const base = ctx->base;
const BYTE* const dictBase = ctx->dictBase;
const U32 dictLimit = ctx->dictLimit;
const U32 maxDistance = (1 << ctx->params.windowLog);
const U32 current = (U32)(ip - base);
const U32 lowLimit = (ctx->lowLimit + maxDistance > current) ? ctx->lowLimit : current - (maxDistance - 1);
const BYTE* match;
size_t ml=0, mlt;
match = ip - ctx->last_off;
if (MEM_read24(match) == MEM_read24(ip))
{
ml = MEM_count(ip+MINMATCH, match+MINMATCH, iLimit) + MINMATCH;
*matchpos = match;
return (int)ml;
}
#if MINMATCH == 3
if (matchIndex3 < current && matchIndex3 >= lowLimit)
{
size_t offset = (size_t)current - matchIndex3;
if (offset < LZ5_SHORT_OFFSET_DISTANCE)
{
match = ip - offset;
if (match > base && MEM_read24(ip) == MEM_read24(match))
{
ml = 3;//MEM_count(ip+MINMATCH, match+MINMATCH, iLimit) + MINMATCH;
*matchpos = match;
}
}
}
#endif
if ((matchIndex < current) && (matchIndex>=lowLimit))
{
if (matchIndex >= dictLimit)
{
match = base + matchIndex;
if (*(match+ml) == *(ip+ml) && (MEM_read32(match) == MEM_read32(ip)))
{
mlt = MEM_count(ip+MINMATCH, match+MINMATCH, iLimit) + MINMATCH;
if (!ml || (mlt > ml && LZ5HC_better_price((ip - *matchpos), ml, (ip - match), mlt, ctx->last_off)))
// if (ml==0 || ((mlt > ml) && LZ5_NORMAL_MATCH_COST(mlt - MINMATCH, (ip - match == ctx->last_off) ? 0 : (ip - match)) < LZ5_NORMAL_MATCH_COST(ml - MINMATCH, (ip - *matchpos == ctx->last_off) ? 0 : (ip - *matchpos)) + (LZ5_NORMAL_LIT_COST(mlt - ml))))
{ ml = mlt; *matchpos = match; }
}
}
else
{
match = dictBase + matchIndex;
if (MEM_read32(match) == MEM_read32(ip))
{
const BYTE* vLimit = ip + (dictLimit - matchIndex);
if (vLimit > iLimit) vLimit = iLimit;
mlt = MEM_count(ip+MINMATCH, match+MINMATCH, vLimit) + MINMATCH;
if ((ip+mlt == vLimit) && (vLimit < iLimit))
mlt += MEM_count(ip+mlt, base+dictLimit, iLimit);
if (!ml || (mlt > ml && LZ5HC_better_price((ip - *matchpos), ml, (ip - match), mlt, ctx->last_off)))
// if (ml==0 || ((mlt > ml) && LZ5_NORMAL_MATCH_COST(mlt - MINMATCH, (ip - match == ctx->last_off) ? 0 : (ip - match)) < LZ5_NORMAL_MATCH_COST(ml - MINMATCH, (ip - *matchpos == ctx->last_off) ? 0 : (ip - *matchpos)) + (LZ5_NORMAL_LIT_COST(mlt - ml))))
{ ml = mlt; *matchpos = base + matchIndex; } /* virtual matchpos */
}
}
}
return (int)ml;
}
FORCE_INLINE int LZ5HC_FindMatchFaster (LZ5HC_Data_Structure* ctx, U32 matchIndex, /* Index table will be updated */
const BYTE* ip, const BYTE* const iLimit,
const BYTE** matchpos)
{
const BYTE* const base = ctx->base;
const BYTE* const dictBase = ctx->dictBase;
const U32 dictLimit = ctx->dictLimit;
const U32 maxDistance = (1 << ctx->params.windowLog);
const U32 current = (U32)(ip - base);
const U32 lowLimit = (ctx->lowLimit + maxDistance > current) ? ctx->lowLimit : current - (maxDistance - 1);
const BYTE* match;
size_t ml=0, mlt;
match = ip - ctx->last_off;
if (MEM_read24(match) == MEM_read24(ip))
{
ml = MEM_count(ip+MINMATCH, match+MINMATCH, iLimit) + MINMATCH;
*matchpos = match;
return (int)ml;
}
if (matchIndex < current && matchIndex >= lowLimit)
{
if (matchIndex >= dictLimit)
{
match = base + matchIndex;
if (*(match+ml) == *(ip+ml) && (MEM_read32(match) == MEM_read32(ip)))
{
mlt = MEM_count(ip+MINMATCH, match+MINMATCH, iLimit) + MINMATCH;
if (mlt > ml) { ml = mlt; *matchpos = match; }
}
}
else
{
match = dictBase + matchIndex;
if (MEM_read32(match) == MEM_read32(ip))
{
const BYTE* vLimit = ip + (dictLimit - matchIndex);
if (vLimit > iLimit) vLimit = iLimit;
mlt = MEM_count(ip+MINMATCH, match+MINMATCH, vLimit) + MINMATCH;
if ((ip+mlt == vLimit) && (vLimit < iLimit))
mlt += MEM_count(ip+mlt, base+dictLimit, iLimit);
if (mlt > ml) { ml = mlt; *matchpos = base + matchIndex; } /* virtual matchpos */
}
}
}
return (int)ml;
}
FORCE_INLINE int LZ5HC_FindMatchFastest (LZ5HC_Data_Structure* ctx, U32 matchIndex, /* Index table will be updated */
const BYTE* ip, const BYTE* const iLimit,
const BYTE** matchpos)
{
const BYTE* const base = ctx->base;
const BYTE* const dictBase = ctx->dictBase;
const U32 dictLimit = ctx->dictLimit;
const U32 maxDistance = (1 << ctx->params.windowLog);
const U32 current = (U32)(ip - base);
const U32 lowLimit = (ctx->lowLimit + maxDistance > current) ? ctx->lowLimit : current - (maxDistance - 1);
const BYTE* match;
size_t ml=0, mlt;
if (matchIndex < current && matchIndex >= lowLimit)
{
if (matchIndex >= dictLimit)
{
match = base + matchIndex;
if (*(match+ml) == *(ip+ml) && (MEM_read32(match) == MEM_read32(ip)))
{
mlt = MEM_count(ip+MINMATCH, match+MINMATCH, iLimit) + MINMATCH;
if (mlt > ml) { ml = mlt; *matchpos = match; }
}
}
else
{
match = dictBase + matchIndex;
if (MEM_read32(match) == MEM_read32(ip))
{
const BYTE* vLimit = ip + (dictLimit - matchIndex);
if (vLimit > iLimit) vLimit = iLimit;
mlt = MEM_count(ip+MINMATCH, match+MINMATCH, vLimit) + MINMATCH;
if ((ip+mlt == vLimit) && (vLimit < iLimit))
mlt += MEM_count(ip+mlt, base+dictLimit, iLimit);
if (mlt > ml) { ml = mlt; *matchpos = base + matchIndex; } /* virtual matchpos */
}
}
}
return (int)ml;
}
FORCE_INLINE size_t LZ5HC_GetWiderMatch (
LZ5HC_Data_Structure* ctx,
const BYTE* const ip,
const BYTE* const iLowLimit,
const BYTE* const iHighLimit,
size_t longest,
const BYTE** matchpos,
const BYTE** startpos)
{
U32* const chainTable = ctx->chainTable;
U32* const HashTable = ctx->hashTable;
const BYTE* const base = ctx->base;
const U32 dictLimit = ctx->dictLimit;
const BYTE* const lowPrefixPtr = base + dictLimit;
const U32 maxDistance = (1 << ctx->params.windowLog);
const U32 current = (U32)(ip - base);
const U32 lowLimit = (ctx->lowLimit + maxDistance > current) ? ctx->lowLimit : current - (maxDistance - 1);
const U32 contentMask = (1 << ctx->params.contentLog) - 1;
const BYTE* const dictBase = ctx->dictBase;
const BYTE* match;
U32 matchIndex;
int nbAttempts = ctx->params.searchNum;
/* First Match */
matchIndex = HashTable[LZ5HC_hashPtr(ip, ctx->params.hashLog, ctx->params.searchLength)];
match = ip - ctx->last_off;
if (MEM_read24(match) == MEM_read24(ip))
{
size_t mlt = MEM_count(ip+MINMATCH, match+MINMATCH, iHighLimit) + MINMATCH;
int back = 0;
while ((ip+back>iLowLimit) && (match+back > lowPrefixPtr) && (ip[back-1] == match[back-1])) back--;
mlt -= back;
if (mlt > longest)
{
*matchpos = match+back;
*startpos = ip+back;
longest = (int)mlt;
}
}
#if MINMATCH == 3
{
U32 matchIndex3 = ctx->hashTable3[LZ5HC_hash3Ptr(ip, ctx->params.hashLog3)];
if (matchIndex3 < current && matchIndex3 >= lowLimit)
{
size_t offset = (size_t)current - matchIndex3;
if (offset < LZ5_SHORT_OFFSET_DISTANCE)
{
match = ip - offset;
if (match > base && MEM_read24(ip) == MEM_read24(match))
{
size_t mlt = MEM_count(ip + MINMATCH, match + MINMATCH, iHighLimit) + MINMATCH;
int back = 0;
while ((ip + back > iLowLimit) && (match + back > lowPrefixPtr) && (ip[back - 1] == match[back - 1])) back--;
mlt -= back;
if (!longest || (mlt > longest && LZ5HC_better_price((ip + back - *matchpos), longest, (ip - match), mlt, ctx->last_off)))
// if (!longest || (mlt > longest && LZ5_NORMAL_MATCH_COST(mlt - MINMATCH, (ip - match == ctx->last_off) ? 0 : (ip - match)) < LZ5_NORMAL_MATCH_COST(longest - MINMATCH, (ip+back - *matchpos == ctx->last_off) ? 0 : (ip+back - *matchpos)) + LZ5_NORMAL_LIT_COST(mlt - longest)))
{
*matchpos = match + back;
*startpos = ip + back;
longest = (int)mlt;
}
}
}
}
}
#endif
while ((matchIndex < current) && (matchIndex>=lowLimit) && (nbAttempts))
{
nbAttempts--;
if (matchIndex >= dictLimit)
{
match = base + matchIndex;
if (MEM_read32(match) == MEM_read32(ip))
{
size_t mlt = MINMATCH + MEM_count(ip+MINMATCH, match+MINMATCH, iHighLimit);
int back = 0;
while ((ip+back>iLowLimit)
&& (match+back > lowPrefixPtr)
&& (ip[back-1] == match[back-1]))
back--;
mlt -= back;
if (!longest || (mlt > longest && LZ5HC_better_price((ip+back - *matchpos), longest, (ip - match), mlt, ctx->last_off)))
{
longest = (int)mlt;
*matchpos = match+back;
*startpos = ip+back;
}
}
}
else
{
match = dictBase + matchIndex;
if (MEM_read32(match) == MEM_read32(ip))
{
size_t mlt;
int back=0;
const BYTE* vLimit = ip + (dictLimit - matchIndex);
if (vLimit > iHighLimit) vLimit = iHighLimit;
mlt = MEM_count(ip+MINMATCH, match+MINMATCH, vLimit) + MINMATCH;
if ((ip+mlt == vLimit) && (vLimit < iHighLimit))
mlt += MEM_count(ip+mlt, base+dictLimit, iHighLimit);
while ((ip+back > iLowLimit) && (matchIndex+back > lowLimit) && (ip[back-1] == match[back-1])) back--;
mlt -= back;
if (mlt > longest) { longest = (int)mlt; *matchpos = base + matchIndex + back; *startpos = ip+back; }
}
}
matchIndex -= chainTable[matchIndex & contentMask];
}
return longest;
}
FORCE_INLINE int LZ5HC_GetAllMatches (
LZ5HC_Data_Structure* ctx,
const BYTE* const ip,
const BYTE* const iLowLimit,
const BYTE* const iHighLimit,
size_t best_mlen,
LZ5HC_match_t* matches)
{
U32* const chainTable = ctx->chainTable;
U32* const HashTable = ctx->hashTable;
U32* const HashTable3 = ctx->hashTable3;
const BYTE* const base = ctx->base;
const U32 dictLimit = ctx->dictLimit;
const BYTE* const lowPrefixPtr = base + dictLimit;
const U32 maxDistance = (1 << ctx->params.windowLog);
const U32 current = (U32)(ip - base);
const U32 lowLimit = (ctx->lowLimit + maxDistance > current) ? ctx->lowLimit : current - (maxDistance - 1);
const U32 contentMask = (1 << ctx->params.contentLog) - 1;
const BYTE* const dictBase = ctx->dictBase;
const BYTE* match;
U32 matchIndex;
int nbAttempts = ctx->params.searchNum;
// bool fullSearch = (ctx->params.fullSearch >= 2);
int mnum = 0;
U32* HashPos, *HashPos3;
if (ip + MINMATCH > iHighLimit) return 0;
/* First Match */
HashPos = &HashTable[LZ5HC_hashPtr(ip, ctx->params.hashLog, ctx->params.searchLength)];
matchIndex = *HashPos;
#if MINMATCH == 3
HashPos3 = &HashTable3[LZ5HC_hash3Ptr(ip, ctx->params.hashLog3)];
if ((*HashPos3 < current) && (*HashPos3 >= lowLimit))
{
size_t offset = current - *HashPos3;
if (offset < LZ5_SHORT_OFFSET_DISTANCE)
{
match = ip - offset;
if (match > base && MEM_read24(ip) == MEM_read24(match))
{
size_t mlt = MEM_count(ip + MINMATCH, match + MINMATCH, iHighLimit) + MINMATCH;
int back = 0;
while ((ip + back > iLowLimit) && (match + back > lowPrefixPtr) && (ip[back - 1] == match[back - 1])) back--;
mlt -= back;
matches[mnum].off = (int)offset;
matches[mnum].len = (int)mlt;
matches[mnum].back = -back;
mnum++;
}
}
}
*HashPos3 = current;
#endif
chainTable[current & contentMask] = (U32)(current - matchIndex);
*HashPos = current;
ctx->nextToUpdate++;
while ((matchIndex < current) && (matchIndex>=lowLimit) && (nbAttempts))
{
nbAttempts--;
if (matchIndex >= dictLimit)
{
match = base + matchIndex;
if ((/*fullSearch ||*/ ip[best_mlen] == match[best_mlen]) && (MEM_read24(match) == MEM_read24(ip)))
{
size_t mlt = MINMATCH + MEM_count(ip+MINMATCH, match+MINMATCH, iHighLimit);
int back = 0;
while ((ip+back>iLowLimit)
&& (match+back > lowPrefixPtr)
&& (ip[back-1] == match[back-1]))
back--;
mlt -= back;
if (mlt > best_mlen)
{
best_mlen = mlt;
matches[mnum].off = (int)(ip - match);
matches[mnum].len = (int)mlt;
matches[mnum].back = -back;
mnum++;
}
if (best_mlen > LZ5_OPT_NUM) break;
}
}
else
{
match = dictBase + matchIndex;
if (MEM_read32(match) == MEM_read32(ip))
{
size_t mlt;
int back=0;
const BYTE* vLimit = ip + (dictLimit - matchIndex);
if (vLimit > iHighLimit) vLimit = iHighLimit;
mlt = MEM_count(ip+MINMATCH, match+MINMATCH, vLimit) + MINMATCH;
if ((ip+mlt == vLimit) && (vLimit < iHighLimit))
mlt += MEM_count(ip+mlt, base+dictLimit, iHighLimit);
while ((ip+back > iLowLimit) && (matchIndex+back > lowLimit) && (ip[back-1] == match[back-1])) back--;
mlt -= back;
if (mlt > best_mlen)
{
best_mlen = mlt;
matches[mnum].off = (int)(ip - match);
matches[mnum].len = (int)mlt;
matches[mnum].back = -back;
mnum++;
}
if (best_mlen > LZ5_OPT_NUM) break;
}
}
matchIndex -= chainTable[matchIndex & contentMask];
}
return mnum;
}
FORCE_INLINE int LZ5HC_BinTree_GetAllMatches (
LZ5HC_Data_Structure* ctx,
const BYTE* const ip,
const BYTE* const iHighLimit,
size_t best_mlen,
LZ5HC_match_t* matches)
{
U32* const chainTable = ctx->chainTable;
U32* const HashTable = ctx->hashTable;
const BYTE* const base = ctx->base;
const U32 dictLimit = ctx->dictLimit;
const U32 maxDistance = (1 << ctx->params.windowLog);
const U32 current = (U32)(ip - base);
const U32 lowLimit = (ctx->lowLimit + maxDistance > current) ? ctx->lowLimit : current - (maxDistance - 1);
const U32 contentMask = (1 << ctx->params.contentLog) - 1;
const BYTE* const dictBase = ctx->dictBase;
const BYTE* match;
int nbAttempts = ctx->params.searchNum;
int mnum = 0;
U32 *ptr0, *ptr1;
U32 matchIndex, delta0, delta1;
size_t mlt = 0;
U32* HashPos, *HashPos3;
if (ip + MINMATCH > iHighLimit) return 0;
/* First Match */
HashPos = &HashTable[LZ5HC_hashPtr(ip, ctx->params.hashLog, ctx->params.searchLength)];
matchIndex = *HashPos;
#if MINMATCH == 3
HashPos3 = &ctx->hashTable3[LZ5HC_hash3Ptr(ip, ctx->params.hashLog3)];
if ((*HashPos3 < current) && (*HashPos3 >= lowLimit))
{
size_t offset = current - *HashPos3;
if (offset < LZ5_SHORT_OFFSET_DISTANCE)
{
match = ip - offset;
if (match > base && MEM_read24(ip) == MEM_read24(match))
{
mlt = MEM_count(ip + MINMATCH, match + MINMATCH, iHighLimit) + MINMATCH;
matches[mnum].off = (int)offset;
matches[mnum].len = (int)mlt;
matches[mnum].back = 0;
mnum++;
}
}
*HashPos3 = current;
}
#endif
*HashPos = current;
ctx->nextToUpdate++;
// check rest of matches
ptr0 = &chainTable[(current*2+1) & contentMask];
ptr1 = &chainTable[(current*2) & contentMask];
delta0 = delta1 = current - matchIndex;
while ((matchIndex < current) && (matchIndex>=lowLimit) && (nbAttempts))
{
nbAttempts--;
mlt = 0;
if (matchIndex >= dictLimit)
{
match = base + matchIndex;
if (MEM_read24(match) == MEM_read24(ip))
{
mlt = MINMATCH + MEM_count(ip+MINMATCH, match+MINMATCH, iHighLimit);
if (mlt > best_mlen)
{
best_mlen = mlt;
matches[mnum].off = (int)(ip - match);
matches[mnum].len = (int)mlt;
matches[mnum].back = 0;
mnum++;
}
if (best_mlen > LZ5_OPT_NUM) break;
}
}
else
{
match = dictBase + matchIndex;
if (MEM_read32(match) == MEM_read32(ip))
{
const BYTE* vLimit = ip + (dictLimit - matchIndex);
if (vLimit > iHighLimit) vLimit = iHighLimit;
mlt = MEM_count(ip+MINMATCH, match+MINMATCH, vLimit) + MINMATCH;
if ((ip+mlt == vLimit) && (vLimit < iHighLimit))
mlt += MEM_count(ip+mlt, base+dictLimit, iHighLimit);
if (mlt > best_mlen)
{
best_mlen = mlt;
matches[mnum].off = (int)(ip - match);
matches[mnum].len = (int)mlt;
matches[mnum].back = 0;
mnum++;
}
if (best_mlen > LZ5_OPT_NUM) break;
}
}
if (*(ip+mlt) < *(match+mlt))
{
*ptr0 = delta0;
ptr0 = &chainTable[(matchIndex*2) & contentMask];
// printf("delta0=%d\n", delta0);
if (*ptr0 == (U32)-1) break;
delta0 = *ptr0;
delta1 += delta0;
matchIndex -= delta0;
}
else
{
*ptr1 = delta1;
ptr1 = &chainTable[(matchIndex*2+1) & contentMask];
// printf("delta1=%d\n", delta1);
if (*ptr1 == (U32)-1) break;
delta1 = *ptr1;
delta0 += delta1;
matchIndex -= delta1;
}
}
*ptr0 = (U32)-1;
*ptr1 = (U32)-1;
return mnum;
}
typedef enum { noLimit = 0, limitedOutput = 1 } limitedOutput_directive;
/*
LZ5 uses 3 types of codewords from 2 to 4 bytes long:
- 1_OO_LL_MMM OOOOOOOO - 10-bit offset, 3-bit match length, 2-bit literal length
- 00_LLL_MMM OOOOOOOO OOOOOOOO - 16-bit offset, 3-bit match length, 3-bit literal length
- 010_LL_MMM OOOOOOOO OOOOOOOO OOOOOOOO - 24-bit offset, 3-bit match length, 2-bit literal length
- 011_LL_MMM - last offset, 3-bit match length, 2-bit literal length
*/
FORCE_INLINE int LZ5HC_encodeSequence (
LZ5HC_Data_Structure* ctx,
const BYTE** ip,
BYTE** op,
const BYTE** anchor,
int matchLength,
const BYTE* const match,
limitedOutput_directive limitedOutputBuffer,
BYTE* oend)
{
int length;
BYTE* token;
/* Encode Literal length */
length = (int)(*ip - *anchor);
token = (*op)++;
if ((limitedOutputBuffer) && ((*op + (length>>8) + length + (2 + 1 + LASTLITERALS)) > oend)) return 1; /* Check output limit */
if (*ip-match >= LZ5_SHORT_OFFSET_DISTANCE && *ip-match < LZ5_MID_OFFSET_DISTANCE && (U32)(*ip-match) != 0)
{
if (length>=(int)RUN_MASK) { int len; *token=(RUN_MASK<<ML_BITS); len = length-RUN_MASK; for(; len > 254 ; len-=255) *(*op)++ = 255; *(*op)++ = (BYTE)len; }
else *token = (BYTE)(length<<ML_BITS);
}
else
{
if (length>=(int)RUN_MASK2) { int len; *token=(RUN_MASK2<<ML_BITS); len = length-RUN_MASK2; for(; len > 254 ; len-=255) *(*op)++ = 255; *(*op)++ = (BYTE)len; }
else *token = (BYTE)(length<<ML_BITS);
}
/* Copy Literals */
MEM_wildCopy(*op, *anchor, (*op) + length);
*op += length;
/* Encode Offset */
if ((U32)(*ip-match) == 0)
{
*token+=(3<<ML_RUN_BITS2);
}
else
{
ctx->last_off = (U32)(*ip-match);
if (ctx->last_off < LZ5_SHORT_OFFSET_DISTANCE)
{
*token+=(BYTE)((4+(ctx->last_off>>8))<<ML_RUN_BITS2);
**op=(BYTE)ctx->last_off; (*op)++;
}
else
if (*ip-match < LZ5_MID_OFFSET_DISTANCE)
{
MEM_writeLE16(*op, (U16)ctx->last_off); *op+=2;
}
else
{
*token+=(2<<ML_RUN_BITS2);
MEM_writeLE24(*op, (U32)ctx->last_off); *op+=3;
}
}
/* Encode MatchLength */
length = (int)(matchLength-MINMATCH);
if ((limitedOutputBuffer) && (*op + (length>>8) + (1 + LASTLITERALS) > oend)) return 1; /* Check output limit */
if (length>=(int)ML_MASK) { *token+=ML_MASK; length-=ML_MASK; for(; length > 509 ; length-=510) { *(*op)++ = 255; *(*op)++ = 255; } if (length > 254) { length-=255; *(*op)++ = 255; } *(*op)++ = (BYTE)length; }
else *token += (BYTE)(length);
LZ5HC_DEBUG("%u: ENCODE literals=%u off=%u mlen=%u out=%u\n", (U32)(*ip - ctx->inputBuffer), (U32)(*ip - *anchor), (U32)(*ip-match), (U32)matchLength, 2+(U32)(*op - ctx->outputBuffer));
/* Prepare next loop */
*ip += matchLength;
*anchor = *ip;
return 0;
}
#define SET_PRICE(pos, mlen, offset, litlen, price) \
{ \
while (last_pos < pos) { opt[last_pos+1].price = 1<<30; last_pos++; } \
opt[pos].mlen = (int)mlen; \
opt[pos].off = (int)offset; \
opt[pos].litlen = (int)litlen; \
opt[pos].price = (int)price; \
LZ5_LOG_PARSER("%d: SET price[%d/%d]=%d litlen=%d len=%d off=%d\n", (int)(inr-source), pos, last_pos, opt[pos].price, opt[pos].litlen, opt[pos].mlen, opt[pos].off); \
}
static int LZ5HC_compress_optimal_price (
LZ5HC_Data_Structure* ctx,
const BYTE* source,
char* dest,
int inputSize,
int maxOutputSize,
limitedOutput_directive limit
)
{
LZ5HC_optimal_t opt[LZ5_OPT_NUM + 4];
LZ5HC_match_t matches[LZ5_OPT_NUM + 1];
const BYTE *inr;
size_t res, cur, cur2, skip_num = 0;
size_t i, llen, litlen, mlen, best_mlen, price, offset, best_off, match_num, last_pos;
const BYTE* ip = (const BYTE*) source;
const BYTE* anchor = ip;
const BYTE* const iend = ip + inputSize;
const BYTE* const mflimit = iend - MFLIMIT;
const BYTE* const matchlimit = (iend - LASTLITERALS);
BYTE* op = (BYTE*) dest;
BYTE* const oend = op + maxOutputSize;
const size_t sufficient_len = ctx->params.sufficientLength;
const int faster_get_matches = (ctx->params.fullSearch == 0);
/* init */
ctx->inputBuffer = (const BYTE*)source;
ctx->outputBuffer = (const BYTE*)dest;
ctx->end += inputSize;
ip++;
/* Main Loop */
while (ip < mflimit)
{
memset(opt, 0, sizeof(LZ5HC_optimal_t));
last_pos = 0;
llen = ip - anchor;
// check rep
mlen = MEM_count(ip, ip - ctx->last_off, matchlimit);
if (mlen >= MINMATCH)
{
LZ5_LOG_PARSER("%d: start try REP rep=%d mlen=%d\n", (int)(ip-source), ctx->last_off, mlen);
if (mlen > sufficient_len || mlen >= LZ5_OPT_NUM)
{
best_mlen = mlen; best_off = 0; cur = 0; last_pos = 1;
goto encode;
}
do
{
litlen = 0;
price = LZ5HC_get_price(llen, 0, mlen - MINMATCH) - llen;
if (mlen > last_pos || price < (size_t)opt[mlen].price)
SET_PRICE(mlen, mlen, 0, litlen, price);
mlen--;
}
while (mlen >= MINMATCH);
}
best_mlen = (last_pos) ? last_pos : MINMATCH;
if (faster_get_matches && last_pos)
match_num = 0;
else
{
if (ctx->params.strategy == LZ5HC_optimal_price)
{
LZ5HC_Insert(ctx, ip);
match_num = LZ5HC_GetAllMatches(ctx, ip, ip, matchlimit, best_mlen, matches);
}
else
{
if (ctx->params.fullSearch < 2)
LZ5HC_BinTree_Insert(ctx, ip);
else
LZ5HC_BinTree_InsertFull(ctx, ip, matchlimit);
match_num = LZ5HC_BinTree_GetAllMatches(ctx, ip, matchlimit, best_mlen, matches);
}
}
LZ5_LOG_PARSER("%d: match_num=%d last_pos=%d\n", (int)(ip-source), match_num, last_pos);
if (!last_pos && !match_num) { ip++; continue; }
if (match_num && (size_t)matches[match_num-1].len > sufficient_len)
{
best_mlen = matches[match_num-1].len;
best_off = matches[match_num-1].off;
cur = 0;
last_pos = 1;
goto encode;
}
// set prices using matches at position = 0
for (i = 0; i < match_num; i++)
{
mlen = (i>0) ? (size_t)matches[i-1].len+1 : best_mlen;
best_mlen = (matches[i].len < LZ5_OPT_NUM) ? matches[i].len : LZ5_OPT_NUM;
LZ5_LOG_PARSER("%d: start Found mlen=%d off=%d best_mlen=%d last_pos=%d\n", (int)(ip-source), matches[i].len, matches[i].off, best_mlen, last_pos);
while (mlen <= best_mlen)
{
litlen = 0;
price = LZ5HC_get_price(llen + litlen, matches[i].off, mlen - MINMATCH) - llen;
if (mlen > last_pos || price < (size_t)opt[mlen].price)
SET_PRICE(mlen, mlen, matches[i].off, litlen, price);
mlen++;
}
}
if (last_pos < MINMATCH) { ip++; continue; }
opt[0].rep = opt[1].rep = ctx->last_off;
opt[0].mlen = opt[1].mlen = 1;
// check further positions
for (skip_num = 0, cur = 1; cur <= last_pos; cur++)
{
inr = ip + cur;
if (opt[cur-1].mlen == 1)
{
litlen = opt[cur-1].litlen + 1;
if (cur != litlen)
{
price = opt[cur - litlen].price + LZ5_LIT_ONLY_COST(litlen);
LZ5_LOG_PRICE("%d: TRY1 opt[%d].price=%d price=%d cur=%d litlen=%d\n", (int)(inr-source), cur - litlen, opt[cur - litlen].price, price, cur, litlen);
}
else
{
price = LZ5_LIT_ONLY_COST(llen + litlen) - llen;
LZ5_LOG_PRICE("%d: TRY2 price=%d cur=%d litlen=%d llen=%d\n", (int)(inr-source), price, cur, litlen, llen);
}
}
else
{
litlen = 1;
price = opt[cur - 1].price + LZ5_LIT_ONLY_COST(litlen);
LZ5_LOG_PRICE("%d: TRY3 price=%d cur=%d litlen=%d litonly=%d\n", (int)(inr-source), price, cur, litlen, LZ5_LIT_ONLY_COST(litlen));
}
mlen = 1;
best_mlen = 0;
LZ5_LOG_PARSER("%d: TRY price=%d opt[%d].price=%d\n", (int)(inr-source), price, cur, opt[cur].price);
if (cur > last_pos || price <= (size_t)opt[cur].price) // || ((price == opt[cur].price) && (opt[cur-1].mlen == 1) && (cur != litlen)))
SET_PRICE(cur, mlen, best_mlen, litlen, price);
if (cur == last_pos) break;
if (opt[cur].mlen > 1)
{
mlen = opt[cur].mlen;
offset = opt[cur].off;
if (offset < 1)
{
opt[cur].rep = opt[cur-mlen].rep;
LZ5_LOG_PARSER("%d: COPYREP1 cur=%d mlen=%d rep=%d\n", (int)(inr-source), cur, mlen, opt[cur-mlen].rep);
}
else
{
opt[cur].rep = (int)offset;
LZ5_LOG_PARSER("%d: COPYREP2 cur=%d offset=%d rep=%d\n", (int)(inr-source), cur, offset, opt[cur].rep);
}
}
else
{
opt[cur].rep = opt[cur-1].rep; // copy rep
}
LZ5_LOG_PARSER("%d: CURRENT price[%d/%d]=%d off=%d mlen=%d litlen=%d rep=%d\n", (int)(inr-source), cur, last_pos, opt[cur].price, opt[cur].off, opt[cur].mlen, opt[cur].litlen, opt[cur].rep);
// check rep
// best_mlen = 0;
mlen = MEM_count(inr, inr - opt[cur].rep, matchlimit);
if (mlen >= MINMATCH && mlen > best_mlen)
{
LZ5_LOG_PARSER("%d: try REP rep=%d mlen=%d\n", (int)(inr-source), opt[cur].rep, mlen);
LZ5_LOG_PARSER("%d: Found REP mlen=%d off=%d rep=%d opt[%d].off=%d\n", (int)(inr-source), mlen, 0, opt[cur].rep, cur, opt[cur].off);
if (mlen > sufficient_len || cur + mlen >= LZ5_OPT_NUM)
{
best_mlen = mlen;
best_off = 0;
LZ5_LOG_PARSER("%d: REP sufficient_len=%d best_mlen=%d best_off=%d last_pos=%d\n", (int)(inr-source), sufficient_len, best_mlen, best_off, last_pos);
last_pos = cur + 1;
goto encode;
}
if (opt[cur].mlen == 1)
{
litlen = opt[cur].litlen;
if (cur != litlen)
{
price = opt[cur - litlen].price + LZ5HC_get_price(litlen, 0, mlen - MINMATCH);
LZ5_LOG_PRICE("%d: TRY1 opt[%d].price=%d price=%d cur=%d litlen=%d\n", (int)(inr-source), cur - litlen, opt[cur - litlen].price, price, cur, litlen);
}
else
{
price = LZ5HC_get_price(llen + litlen, 0, mlen - MINMATCH) - llen;
LZ5_LOG_PRICE("%d: TRY2 price=%d cur=%d litlen=%d llen=%d\n", (int)(inr-source), price, cur, litlen, llen);
}
}
else
{
litlen = 0;
price = opt[cur].price + LZ5HC_get_price(litlen, 0, mlen - MINMATCH);
LZ5_LOG_PRICE("%d: TRY3 price=%d cur=%d litlen=%d getprice=%d\n", (int)(inr-source), price, cur, litlen, LZ5HC_get_price(litlen, 0, mlen - MINMATCH));
}
best_mlen = mlen;
if (faster_get_matches)
skip_num = best_mlen;
LZ5_LOG_PARSER("%d: Found REP mlen=%d off=%d price=%d litlen=%d price[%d]=%d\n", (int)(inr-source), mlen, 0, price, litlen, cur - litlen, opt[cur - litlen].price);
do
{
if (cur + mlen > last_pos || price <= (size_t)opt[cur + mlen].price) // || ((price == opt[cur + mlen].price) && (opt[cur].mlen == 1) && (cur != litlen))) // at equal price prefer REP instead of MATCH
SET_PRICE(cur + mlen, mlen, 0, litlen, price);
mlen--;
}
while (mlen >= MINMATCH);
}
if (faster_get_matches && skip_num > 0)
{
skip_num--;
continue;
}
best_mlen = (best_mlen > MINMATCH) ? best_mlen : MINMATCH;
if (ctx->params.strategy == LZ5HC_optimal_price)
{
LZ5HC_Insert(ctx, inr);
match_num = LZ5HC_GetAllMatches(ctx, inr, ip, matchlimit, best_mlen, matches);
LZ5_LOG_PARSER("%d: LZ5HC_GetAllMatches match_num=%d\n", (int)(inr-source), match_num);
}
else
{
if (ctx->params.fullSearch < 2)
LZ5HC_BinTree_Insert(ctx, inr);
else
LZ5HC_BinTree_InsertFull(ctx, inr, matchlimit);
match_num = LZ5HC_BinTree_GetAllMatches(ctx, inr, matchlimit, best_mlen, matches);
LZ5_LOG_PARSER("%d: LZ5HC_BinTree_GetAllMatches match_num=%d\n", (int)(inr-source), match_num);
}
if (match_num > 0 && (size_t)matches[match_num-1].len > sufficient_len)
{
cur -= matches[match_num-1].back;
best_mlen = matches[match_num-1].len;
best_off = matches[match_num-1].off;
last_pos = cur + 1;
goto encode;
}
// set prices using matches at position = cur
for (i = 0; i < match_num; i++)
{
mlen = (i>0) ? (size_t)matches[i-1].len+1 : best_mlen;
cur2 = cur - matches[i].back;
best_mlen = (cur2 + matches[i].len < LZ5_OPT_NUM) ? (size_t)matches[i].len : LZ5_OPT_NUM - cur2;
LZ5_LOG_PARSER("%d: Found1 cur=%d cur2=%d mlen=%d off=%d best_mlen=%d last_pos=%d\n", (int)(inr-source), cur, cur2, matches[i].len, matches[i].off, best_mlen, last_pos);
if (mlen < (size_t)matches[i].back + 1)
mlen = matches[i].back + 1;
while (mlen <= best_mlen)
{
if (opt[cur2].mlen == 1)
{
litlen = opt[cur2].litlen;
if (cur2 != litlen)
price = opt[cur2 - litlen].price + LZ5HC_get_price(litlen, matches[i].off, mlen - MINMATCH);
else
price = LZ5HC_get_price(llen + litlen, matches[i].off, mlen - MINMATCH) - llen;
}
else
{
litlen = 0;
price = opt[cur2].price + LZ5HC_get_price(litlen, matches[i].off, mlen - MINMATCH);
}
LZ5_LOG_PARSER("%d: Found2 pred=%d mlen=%d best_mlen=%d off=%d price=%d litlen=%d price[%d]=%d\n", (int)(inr-source), matches[i].back, mlen, best_mlen, matches[i].off, price, litlen, cur - litlen, opt[cur - litlen].price);
// if (cur2 + mlen > last_pos || ((matches[i].off != opt[cur2 + mlen].off) && (price < opt[cur2 + mlen].price)))
if (cur2 + mlen > last_pos || price < (size_t)opt[cur2 + mlen].price)
{
SET_PRICE(cur2 + mlen, mlen, matches[i].off, litlen, price);
}
mlen++;
}
}
} // for (skip_num = 0, cur = 1; cur <= last_pos; cur++)
best_mlen = opt[last_pos].mlen;
best_off = opt[last_pos].off;
cur = last_pos - best_mlen;
encode: // cur, last_pos, best_mlen, best_off have to be set
for (i = 1; i <= last_pos; i++)
{
LZ5_LOG_PARSER("%d: price[%d/%d]=%d off=%d mlen=%d litlen=%d rep=%d\n", (int)(ip-source+i), i, last_pos, opt[i].price, opt[i].off, opt[i].mlen, opt[i].litlen, opt[i].rep);
}
LZ5_LOG_PARSER("%d: cur=%d/%d best_mlen=%d best_off=%d rep=%d\n", (int)(ip-source+cur), cur, last_pos, best_mlen, best_off, opt[cur].rep);
opt[0].mlen = 1;
while (1)
{
mlen = opt[cur].mlen;
offset = opt[cur].off;
opt[cur].mlen = (int)best_mlen;
opt[cur].off = (int)best_off;
best_mlen = mlen;
best_off = offset;
if (mlen > cur) break;
cur -= mlen;
}
for (i = 0; i <= last_pos;)
{
LZ5_LOG_PARSER("%d: price2[%d/%d]=%d off=%d mlen=%d litlen=%d rep=%d\n", (int)(ip-source+i), i, last_pos, opt[i].price, opt[i].off, opt[i].mlen, opt[i].litlen, opt[i].rep);
i += opt[i].mlen;
}
cur = 0;
while (cur < last_pos)
{
LZ5_LOG_PARSER("%d: price3[%d/%d]=%d off=%d mlen=%d litlen=%d rep=%d\n", (int)(ip-source+cur), cur, last_pos, opt[cur].price, opt[cur].off, opt[cur].mlen, opt[cur].litlen, opt[cur].rep);
mlen = opt[cur].mlen;
if (mlen == 1) { ip++; cur++; continue; }
offset = opt[cur].off;
cur += mlen;
LZ5_LOG_ENCODE("%d: ENCODE literals=%d off=%d mlen=%d ", (int)(ip-source), (int)(ip-anchor), (int)(offset), mlen);
res = LZ5HC_encodeSequence(ctx, &ip, &op, &anchor, (int)mlen, ip - offset, limit, oend);
LZ5_LOG_ENCODE("out=%d\n", (int)((char*)op - dest));
if (res) return 0;
LZ5_LOG_PARSER("%d: offset=%d rep=%d\n", (int)(ip-source), offset, ctx->last_off);
}
}
/* Encode Last Literals */
{
int lastRun = (int)(iend - anchor);
// if (inputSize > LASTLITERALS && lastRun < LASTLITERALS) { printf("ERROR: lastRun=%d\n", lastRun); }
if ((limit) && (((char*)op - dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize)) return 0; /* Check output limit */
if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun > 254 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; }
else *op++ = (BYTE)(lastRun<<ML_BITS);
LZ5_LOG_ENCODE("%d: ENCODE_LAST literals=%d out=%d\n", (int)(ip-source), (int)(iend-anchor), (int)((char*)op -dest));
memcpy(op, anchor, iend - anchor);
op += iend-anchor;
}
/* End */
return (int) ((char*)op-dest);
}
static int LZ5HC_compress_lowest_price (
LZ5HC_Data_Structure* ctx,
const char* source,
char* dest,
int inputSize,
int maxOutputSize,
limitedOutput_directive limit
)
{
const BYTE* ip = (const BYTE*) source;
const BYTE* anchor = ip;
const BYTE* const iend = ip + inputSize;
const BYTE* const mflimit = iend - MFLIMIT;
const BYTE* const matchlimit = (iend - LASTLITERALS);
BYTE* op = (BYTE*) dest;
BYTE* const oend = op + maxOutputSize;
int ml, ml2, ml0;
const BYTE* ref=NULL;
const BYTE* start2=NULL;
const BYTE* ref2=NULL;
const BYTE* start0;
const BYTE* ref0;
const BYTE* lowPrefixPtr = ctx->base + ctx->dictLimit;
/* init */
ctx->inputBuffer = (const BYTE*)source;
ctx->outputBuffer = (const BYTE*)dest;
ctx->end += inputSize;
ip++;
/* Main Loop */
while (ip < mflimit)
{
LZ5HC_Insert(ctx, ip);
ml = LZ5HC_FindBestMatch (ctx, ip, matchlimit, (&ref));
if (!ml) { ip++; continue; }
{
int back = 0;
while ((ip + back > anchor) && (ref + back > lowPrefixPtr) && (ip[back - 1] == ref[back - 1])) back--;
ml -= back;
ip += back;
ref += back;
}
/* saved, in case we would skip too much */
start0 = ip;
ref0 = ref;
ml0 = ml;
_Search:
if (ip+ml >= mflimit) goto _Encode;
LZ5HC_Insert(ctx, ip);
ml2 = (int)LZ5HC_GetWiderMatch(ctx, ip + ml - 2, anchor, matchlimit, 0, &ref2, &start2);
if (ml2 == 0) goto _Encode;
{
int price, best_price;
U32 off0=0, off1=0;
const BYTE *pos, *best_pos;
// find the lowest price for encoding ml bytes
best_pos = ip;
best_price = 1<<30;
off0 = (U32)(ip - ref);
off1 = (U32)(start2 - ref2);
for (pos = ip + ml; pos >= start2; pos--)
{
int common0 = (int)(pos - ip);
if (common0 >= MINMATCH)
{
price = (int)LZ5_CODEWORD_COST(ip - anchor, (off0 == ctx->last_off) ? 0 : off0, common0 - MINMATCH);
{
int common1 = (int)(start2 + ml2 - pos);
if (common1 >= MINMATCH)
price += (int)LZ5_CODEWORD_COST(0, (off1 == off0) ? 0 : (off1), common1 - MINMATCH);
else
price += LZ5_LIT_ONLY_COST(common1) - 1;
}
if (price < best_price)
{
best_price = price;
best_pos = pos;
}
}
else
{
price = (int)LZ5_CODEWORD_COST(start2 - anchor, (off1 == ctx->last_off) ? 0 : off1, ml2 - MINMATCH);
if (price < best_price)
best_pos = pos;
break;
}
}
// LZ5HC_DEBUG("%u: TRY last_off=%d literals=%u off=%u mlen=%u literals2=%u off2=%u mlen2=%u best=%d\n", (U32)(ip - ctx->inputBuffer), ctx->last_off, (U32)(ip - anchor), off0, (U32)ml, (U32)(start2 - anchor), off1, ml2, (U32)(best_pos - ip));
ml = (int)(best_pos - ip);
}
if (ml < MINMATCH)
{
ip = start2;
ref = ref2;
ml = ml2;
goto _Search;
}
_Encode:
if (start0 < ip)
{
if (LZ5HC_more_profitable((ip - ref), ml,(start0 - ref0), ml0, (ref0 - ref), ctx->last_off))
{
ip = start0;
ref = ref0;
ml = ml0;
}
}
if (LZ5HC_encodeSequence(ctx, &ip, &op, &anchor, ml, ref, limit, oend)) return 0;
}
/* Encode Last Literals */
{
int lastRun = (int)(iend - anchor);
if ((limit) && (((char*)op - dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize)) return 0; /* Check output limit */
if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun > 254 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; }
else *op++ = (BYTE)(lastRun<<ML_BITS);
memcpy(op, anchor, iend - anchor);
op += iend-anchor;
}
/* End */
return (int) (((char*)op)-dest);
}
static int LZ5HC_compress_price_fast (
LZ5HC_Data_Structure* ctx,
const char* source,
char* dest,
int inputSize,
int maxOutputSize,
limitedOutput_directive limit
)
{
const BYTE* ip = (const BYTE*) source;
const BYTE* anchor = ip;
const BYTE* const iend = ip + inputSize;
const BYTE* const mflimit = iend - MFLIMIT;
const BYTE* const matchlimit = (iend - LASTLITERALS);
BYTE* op = (BYTE*) dest;
BYTE* const oend = op + maxOutputSize;
int ml, ml2=0;
const BYTE* ref=NULL;
const BYTE* start2=NULL;
const BYTE* ref2=NULL;
const BYTE* lowPrefixPtr = ctx->base + ctx->dictLimit;
U32* HashTable = ctx->hashTable;
#if MINMATCH == 3
U32* HashTable3 = ctx->hashTable3;
#endif
const BYTE* const base = ctx->base;
U32* HashPos, *HashPos3;
/* init */
ctx->inputBuffer = (const BYTE*)source;
ctx->outputBuffer = (const BYTE*)dest;
ctx->end += inputSize;
ip++;
/* Main Loop */
while (ip < mflimit)
{
HashPos = &HashTable[LZ5HC_hashPtr(ip, ctx->params.hashLog, ctx->params.searchLength)];
#if MINMATCH == 3
HashPos3 = &HashTable3[LZ5HC_hash3Ptr(ip, ctx->params.hashLog3)];
ml = LZ5HC_FindMatchFast (ctx, *HashPos, *HashPos3, ip, matchlimit, (&ref));
*HashPos3 = (U32)(ip - base);
#else
ml = LZ5HC_FindMatchFast (ctx, *HashPos, 0, ip, matchlimit, (&ref));
#endif
*HashPos = (U32)(ip - base);
if (!ml) { ip++; continue; }
if ((U32)(ip - ref) == ctx->last_off) { ml2=0; goto _Encode; }
{
int back = 0;
while ((ip+back>anchor) && (ref+back > lowPrefixPtr) && (ip[back-1] == ref[back-1])) back--;
ml -= back;
ip += back;
ref += back;
}
_Search:
if (ip+ml >= mflimit) goto _Encode;
start2 = ip + ml - 2;
HashPos = &HashTable[LZ5HC_hashPtr(start2, ctx->params.hashLog, ctx->params.searchLength)];
ml2 = LZ5HC_FindMatchFaster(ctx, *HashPos, start2, matchlimit, (&ref2));
*HashPos = (U32)(start2 - base);
if (!ml2) goto _Encode;
{
int back = 0;
while ((start2+back>ip) && (ref2+back > lowPrefixPtr) && (start2[back-1] == ref2[back-1])) back--;
ml2 -= back;
start2 += back;
ref2 += back;
}
// LZ5HC_DEBUG("%u: TRY last_off=%d literals=%u off=%u mlen=%u literals2=%u off2=%u mlen2=%u best=%d\n", (U32)(ip - ctx->inputBuffer), ctx->last_off, (U32)(ip - anchor), off0, (U32)ml, (U32)(start2 - anchor), off1, ml2, (U32)(best_pos - ip));
if (ml2 <= ml) { ml2 = 0; goto _Encode; }
if (start2 <= ip)
{
ip = start2; ref = ref2; ml = ml2;
ml2 = 0;
goto _Encode;
}
if (start2 - ip < 3)
{
ip = start2; ref = ref2; ml = ml2;
ml2 = 0;
goto _Search;
}
if (start2 < ip + ml)
{
int correction = ml - (int)(start2 - ip);
start2 += correction;
ref2 += correction;
ml2 -= correction;
if (ml2 < 3) { ml2 = 0; }
}
_Encode:
if (LZ5HC_encodeSequence(ctx, &ip, &op, &anchor, ml, ref, limit, oend)) return 0;
if (ml2)
{
ip = start2; ref = ref2; ml = ml2;
ml2 = 0;
goto _Search;
}
}
/* Encode Last Literals */
{
int lastRun = (int)(iend - anchor);
if ((limit) && (((char*)op - dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize)) return 0; /* Check output limit */
if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun > 254 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; }
else *op++ = (BYTE)(lastRun<<ML_BITS);
memcpy(op, anchor, iend - anchor);
op += iend-anchor;
}
/* End */
return (int) (((char*)op)-dest);
}
static int LZ5HC_compress_fast (
LZ5HC_Data_Structure* ctx,
const char* source,
char* dest,
int inputSize,
int maxOutputSize,
limitedOutput_directive limit
)
{
const BYTE* ip = (const BYTE*) source;
const BYTE* anchor = ip;
const BYTE* const iend = ip + inputSize;
const BYTE* const mflimit = iend - MFLIMIT;
const BYTE* const matchlimit = (iend - LASTLITERALS);
BYTE* op = (BYTE*) dest;
BYTE* const oend = op + maxOutputSize;
int ml;
const BYTE* ref=NULL;
const BYTE* lowPrefixPtr = ctx->base + ctx->dictLimit;
const BYTE* const base = ctx->base;
U32* HashPos;
U32* HashTable = ctx->hashTable;
const int accel = (ctx->params.searchNum>0)?ctx->params.searchNum:1;
/* init */
ctx->inputBuffer = (const BYTE*)source;
ctx->outputBuffer = (const BYTE*)dest;
ctx->end += inputSize;
ip++;
/* Main Loop */
while (ip < mflimit)
{
HashPos = &HashTable[LZ5HC_hashPtr(ip, ctx->params.hashLog, ctx->params.searchLength)];
ml = LZ5HC_FindMatchFastest (ctx, *HashPos, ip, matchlimit, (&ref));
*HashPos = (U32)(ip - base);
if (!ml) { ip+=accel; continue; }
{
int back = 0;
while ((ip + back > anchor) && (ref + back > lowPrefixPtr) && (ip[back - 1] == ref[back - 1])) back--;
ml -= back;
ip += back;
ref += back;
}
if (LZ5HC_encodeSequence(ctx, &ip, &op, &anchor, ml, ref, limit, oend)) return 0;
}
/* Encode Last Literals */
{
int lastRun = (int)(iend - anchor);
if ((limit) && (((char*)op - dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize)) return 0; /* Check output limit */
if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun > 254 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; }
else *op++ = (BYTE)(lastRun<<ML_BITS);
memcpy(op, anchor, iend - anchor);
op += iend-anchor;
}
/* End */
return (int) (((char*)op)-dest);
}
static int LZ5HC_compress_generic (void* ctxvoid, const char* source, char* dest, int inputSize, int maxOutputSize, limitedOutput_directive limit)
{
LZ5HC_Data_Structure* ctx = (LZ5HC_Data_Structure*) ctxvoid;
switch(ctx->params.strategy)
{
default:
case LZ5HC_fast:
return LZ5HC_compress_fast(ctx, source, dest, inputSize, maxOutputSize, limit);
case LZ5HC_price_fast:
return LZ5HC_compress_price_fast(ctx, source, dest, inputSize, maxOutputSize, limit);
case LZ5HC_lowest_price:
return LZ5HC_compress_lowest_price(ctx, source, dest, inputSize, maxOutputSize, limit);
case LZ5HC_optimal_price:
case LZ5HC_optimal_price_bt:
return LZ5HC_compress_optimal_price(ctx, (const BYTE* )source, dest, inputSize, maxOutputSize, limit);
}
}
int LZ5_sizeofStateHC(void) { return sizeof(LZ5HC_Data_Structure); }
int LZ5_compress_HC_extStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize)
{
if (((size_t)(state)&(sizeof(void*)-1)) != 0) return 0; /* Error : state is not aligned for pointers (32 or 64 bits) */
LZ5HC_init ((LZ5HC_Data_Structure*)state, (const BYTE*)src);
if (maxDstSize < LZ5_compressBound(srcSize))
return LZ5HC_compress_generic (state, src, dst, srcSize, maxDstSize, limitedOutput);
else
return LZ5HC_compress_generic (state, src, dst, srcSize, maxDstSize, noLimit);
}
int LZ5_compress_HC(const char* src, char* dst, int srcSize, int maxDstSize, int compressionLevel)
{
LZ5HC_Data_Structure state;
LZ5HC_Data_Structure* const statePtr = &state;
int cSize = 0;
if (!LZ5_alloc_mem_HC(statePtr, compressionLevel))
return 0;
cSize = LZ5_compress_HC_extStateHC(statePtr, src, dst, srcSize, maxDstSize);
LZ5_free_mem_HC(statePtr);
return cSize;
}
/**************************************
* Streaming Functions
**************************************/
/* allocation */
LZ5_streamHC_t* LZ5_createStreamHC(int compressionLevel)
{
LZ5_streamHC_t* statePtr = (LZ5_streamHC_t*)malloc(sizeof(LZ5_streamHC_t));
if (!statePtr)
return NULL;
if (!LZ5_alloc_mem_HC((LZ5HC_Data_Structure*)statePtr, compressionLevel))
{
FREEMEM(statePtr);
return NULL;
}
return statePtr;
}
int LZ5_freeStreamHC (LZ5_streamHC_t* LZ5_streamHCPtr)
{
LZ5HC_Data_Structure* statePtr = (LZ5HC_Data_Structure*)LZ5_streamHCPtr;
if (statePtr)
{
LZ5_free_mem_HC(statePtr);
free(LZ5_streamHCPtr);
}
return 0;
}
/* initialization */
void LZ5_resetStreamHC (LZ5_streamHC_t* LZ5_streamHCPtr)
{
LZ5_STATIC_ASSERT(sizeof(LZ5HC_Data_Structure) <= sizeof(LZ5_streamHC_t)); /* if compilation fails here, LZ5_STREAMHCSIZE must be increased */
((LZ5HC_Data_Structure*)LZ5_streamHCPtr)->base = NULL;
}
int LZ5_loadDictHC (LZ5_streamHC_t* LZ5_streamHCPtr, const char* dictionary, int dictSize)
{
LZ5HC_Data_Structure* ctxPtr = (LZ5HC_Data_Structure*) LZ5_streamHCPtr;
if (dictSize > LZ5_DICT_SIZE)
{
dictionary += dictSize - LZ5_DICT_SIZE;
dictSize = LZ5_DICT_SIZE;
}
LZ5HC_init (ctxPtr, (const BYTE*)dictionary);
if (dictSize >= 4) LZ5HC_Insert (ctxPtr, (const BYTE*)dictionary +(dictSize-3));
ctxPtr->end = (const BYTE*)dictionary + dictSize;
return dictSize;
}
/* compression */
static void LZ5HC_setExternalDict(LZ5HC_Data_Structure* ctxPtr, const BYTE* newBlock)
{
if (ctxPtr->end >= ctxPtr->base + 4)
LZ5HC_Insert (ctxPtr, ctxPtr->end-3); /* Referencing remaining dictionary content */
/* Only one memory segment for extDict, so any previous extDict is lost at this stage */
ctxPtr->lowLimit = ctxPtr->dictLimit;
ctxPtr->dictLimit = (U32)(ctxPtr->end - ctxPtr->base);
ctxPtr->dictBase = ctxPtr->base;
ctxPtr->base = newBlock - ctxPtr->dictLimit;
ctxPtr->end = newBlock;
ctxPtr->nextToUpdate = ctxPtr->dictLimit; /* match referencing will resume from there */
}
static int LZ5_compressHC_continue_generic (LZ5HC_Data_Structure* ctxPtr,
const char* source, char* dest,
int inputSize, int maxOutputSize, limitedOutput_directive limit)
{
/* auto-init if forgotten */
if (ctxPtr->base == NULL)
LZ5HC_init (ctxPtr, (const BYTE*) source);
/* Check overflow */
if ((size_t)(ctxPtr->end - ctxPtr->base) > 2 GB)
{
size_t dictSize = (size_t)(ctxPtr->end - ctxPtr->base) - ctxPtr->dictLimit;
if (dictSize > LZ5_DICT_SIZE) dictSize = LZ5_DICT_SIZE;
LZ5_loadDictHC((LZ5_streamHC_t*)ctxPtr, (const char*)(ctxPtr->end) - dictSize, (int)dictSize);
}
/* Check if blocks follow each other */
if ((const BYTE*)source != ctxPtr->end)
LZ5HC_setExternalDict(ctxPtr, (const BYTE*)source);
/* Check overlapping input/dictionary space */
{
const BYTE* sourceEnd = (const BYTE*) source + inputSize;
const BYTE* dictBegin = ctxPtr->dictBase + ctxPtr->lowLimit;
const BYTE* dictEnd = ctxPtr->dictBase + ctxPtr->dictLimit;
if ((sourceEnd > dictBegin) && ((const BYTE*)source < dictEnd))
{
if (sourceEnd > dictEnd) sourceEnd = dictEnd;
ctxPtr->lowLimit = (U32)(sourceEnd - ctxPtr->dictBase);
if (ctxPtr->dictLimit - ctxPtr->lowLimit < 4) ctxPtr->lowLimit = ctxPtr->dictLimit;
}
}
return LZ5HC_compress_generic (ctxPtr, source, dest, inputSize, maxOutputSize, limit);
}
int LZ5_compress_HC_continue (LZ5_streamHC_t* LZ5_streamHCPtr, const char* source, char* dest, int inputSize, int maxOutputSize)
{
if (maxOutputSize < LZ5_compressBound(inputSize))
return LZ5_compressHC_continue_generic ((LZ5HC_Data_Structure*)LZ5_streamHCPtr, source, dest, inputSize, maxOutputSize, limitedOutput);
else
return LZ5_compressHC_continue_generic ((LZ5HC_Data_Structure*)LZ5_streamHCPtr, source, dest, inputSize, maxOutputSize, noLimit);
}
/* dictionary saving */
int LZ5_saveDictHC (LZ5_streamHC_t* LZ5_streamHCPtr, char* safeBuffer, int dictSize)
{
LZ5HC_Data_Structure* streamPtr = (LZ5HC_Data_Structure*)LZ5_streamHCPtr;
int prefixSize = (int)(streamPtr->end - (streamPtr->base + streamPtr->dictLimit));
if (dictSize > LZ5_DICT_SIZE) dictSize = LZ5_DICT_SIZE;
// if (dictSize < 4) dictSize = 0;
if (dictSize > prefixSize) dictSize = prefixSize;
memmove(safeBuffer, streamPtr->end - dictSize, dictSize);
{
U32 endIndex = (U32)(streamPtr->end - streamPtr->base);
streamPtr->end = (const BYTE*)safeBuffer + dictSize;
streamPtr->base = streamPtr->end - endIndex;
streamPtr->dictLimit = endIndex - dictSize;
streamPtr->lowLimit = endIndex - dictSize;
if (streamPtr->nextToUpdate < streamPtr->dictLimit) streamPtr->nextToUpdate = streamPtr->dictLimit;
}
return dictSize;
}
/***********************************
* Deprecated Functions
***********************************/
/* Deprecated compression functions */
/* These functions are planned to start generate warnings by r132 approximately */
int LZ5_compressHC(const char* src, char* dst, int srcSize) { return LZ5_compress_HC (src, dst, srcSize, LZ5_compressBound(srcSize), 0); }
int LZ5_compressHC_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize) { return LZ5_compress_HC(src, dst, srcSize, maxDstSize, 0); }
int LZ5_compressHC_continue (LZ5_streamHC_t* ctx, const char* src, char* dst, int srcSize) { return LZ5_compress_HC_continue (ctx, src, dst, srcSize, LZ5_compressBound(srcSize)); }
int LZ5_compressHC_limitedOutput_continue (LZ5_streamHC_t* ctx, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ5_compress_HC_continue (ctx, src, dst, srcSize, maxDstSize); }
int LZ5_compressHC_withStateHC (void* state, const char* src, char* dst, int srcSize) { return LZ5_compress_HC_extStateHC (state, src, dst, srcSize, LZ5_compressBound(srcSize)); }
int LZ5_compressHC_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ5_compress_HC_extStateHC (state, src, dst, srcSize, maxDstSize); }
| 35,125 |
560 | /*
* Copyright (c) 2015 <NAME> <<EMAIL>>
* All Rights Reserved.
*/
package me.zhanghai.android.douya.settings.info;
import androidx.appcompat.app.AppCompatDelegate;
import me.zhanghai.android.douya.R;
import me.zhanghai.android.douya.settings.info.SettingsEntries.*;
public interface Settings {
StringSettingsEntry ACTIVE_ACCOUNT_NAME = new StringSettingsEntry(
R.string.pref_key_active_account_name, R.string.pref_default_value_empty_string);
StringSettingsEntry RECENT_ONE_ACCOUNT_NAME = new StringSettingsEntry(
R.string.pref_key_recent_one_account_name, R.string.pref_default_value_empty_string);
StringSettingsEntry RECENT_TWO_ACCOUNT_NAME = new StringSettingsEntry(
R.string.pref_key_recent_two_account_name, R.string.pref_default_value_empty_string);
BooleanSettingsEntry SHOW_LONG_URL_FOR_LINK_ENTITY = new BooleanSettingsEntry(
R.string.pref_key_show_long_url_for_link_entity,
R.bool.pref_default_value_show_long_url_for_link_entity);
enum NightMode {
// Disabled because AppCompatDelegate delegates night mode change to the non-existent system
// implementation.
FOLLOW_SYSTEM(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM),
OFF(AppCompatDelegate.MODE_NIGHT_NO),
ON(AppCompatDelegate.MODE_NIGHT_YES),
AUTO(AppCompatDelegate.MODE_NIGHT_AUTO);
private int value;
NightMode(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
EnumSettingsEntry<NightMode> NIGHT_MODE = new EnumSettingsEntry<>(R.string.pref_key_night_mode,
R.string.pref_default_value_night_mode, NightMode.class);
BooleanSettingsEntry AUTO_REFRESH_HOME = new BooleanSettingsEntry(
R.string.pref_key_auto_refresh_home, R.bool.pref_default_value_auto_refresh_home);
BooleanSettingsEntry LONG_CLICK_TO_QUICK_REBROADCAST = new BooleanSettingsEntry(
R.string.pref_key_long_click_to_quick_rebroadcast,
R.bool.pref_default_value_long_click_to_quick_rebroadcast);
BooleanSettingsEntry LONG_CLICK_TO_SHOW_SEND_COMMENT_ACTIVITY = new BooleanSettingsEntry(
R.string.pref_key_long_click_to_show_send_comment_activity,
R.bool.pref_default_value_long_click_to_show_send_comment_activity);
BooleanSettingsEntry SHOW_ALBUM_ART_ON_LOCK_SCREEN = new BooleanSettingsEntry(
R.string.pref_key_show_album_art_on_lock_screen,
R.bool.pref_default_value_show_album_art_on_lock_screen);
BooleanSettingsEntry PROGRESSIVE_THIRD_PARTY_APP = new BooleanSettingsEntry(
R.string.pref_key_progressive_third_party_app,
R.bool.pref_default_value_progressive_third_party_app);
enum OpenUrlWithMethod {
WEBVIEW,
INTENT,
CUSTOM_TABS
}
EnumSettingsEntry<OpenUrlWithMethod> OPEN_URL_WITH_METHOD = new EnumSettingsEntry<>(
R.string.pref_key_open_url_with, R.string.pref_default_value_open_url_with,
OpenUrlWithMethod.class);
BooleanSettingsEntry OPEN_WITH_NATIVE_IN_WEBVIEW = new BooleanSettingsEntry(
R.string.pref_key_open_with_native_in_webview,
R.bool.pref_default_value_open_with_native_in_webview);
BooleanSettingsEntry REQUEST_DESKTOP_SITE_IN_WEBVIEW = new BooleanSettingsEntry(
R.string.pref_key_request_desktop_site_in_webview,
R.bool.pref_default_value_request_desktop_site_in_webview);
BooleanSettingsEntry CREATE_NEW_TASK_FOR_WEBVIEW = new BooleanSettingsEntry(
R.string.pref_key_create_new_task_for_webview,
R.bool.pref_default_value_create_new_task_for_webview);
}
| 1,578 |
343 | #include "stdafx.h"
RH_C_FUNCTION void ON_Xform_Scale( ON_Xform* xf, const ON_PLANE_STRUCT* plane, double xFactor, double yFactor, double zFactor )
{
if( xf && plane )
{
ON_Plane temp = FromPlaneStruct(*plane);
*xf = ON_Xform::ScaleTransformation(temp, xFactor, yFactor, zFactor);
}
}
RH_C_FUNCTION void ON_Xform_Rotation( ON_Xform* xf, double sinAngle, double cosAngle, ON_3DVECTOR_STRUCT rotationAxis, ON_3DPOINT_STRUCT rotationCenter)
{
if( xf )
{
const ON_3dVector* axis = (const ON_3dVector*)&rotationAxis;
const ON_3dPoint* center = (const ON_3dPoint*)&rotationCenter;
xf->Rotation(sinAngle, cosAngle, *axis, *center);
}
}
RH_C_FUNCTION bool ON_Xform_PlaneToPlane( ON_Xform* xf, const ON_PLANE_STRUCT* plane0, const ON_PLANE_STRUCT* plane1, bool rotation)
{
bool rc = false;
if( xf && plane0 && plane1 )
{
ON_Plane temp0 = FromPlaneStruct(*plane0);
ON_Plane temp1 = FromPlaneStruct(*plane1);
if( rotation )
{
xf->Rotation(temp0, temp1);
rc = true;
}
else
{
rc = xf->ChangeBasis(temp0, temp1);
}
}
return rc;
}
RH_C_FUNCTION void ON_Xform_Mirror( ON_Xform* xf, ON_3DPOINT_STRUCT pointOnMirrorPlane, ON_3DVECTOR_STRUCT normalToMirrorPlane)
{
if( xf )
{
const ON_3dPoint* _pt = (const ON_3dPoint*)&pointOnMirrorPlane;
const ON_3dVector* _n = (const ON_3dVector*)&normalToMirrorPlane;
xf->Mirror(*_pt, *_n);
}
}
RH_C_FUNCTION bool ON_Xform_ChangeBasis2( ON_Xform* xf,
ON_3DVECTOR_STRUCT x0, ON_3DVECTOR_STRUCT y0, ON_3DVECTOR_STRUCT z0,
ON_3DVECTOR_STRUCT x1, ON_3DVECTOR_STRUCT y1, ON_3DVECTOR_STRUCT z1)
{
bool rc = false;
if( xf )
{
const ON_3dVector* _x0 = (const ON_3dVector*)&x0;
const ON_3dVector* _y0 = (const ON_3dVector*)&y0;
const ON_3dVector* _z0 = (const ON_3dVector*)&z0;
const ON_3dVector* _x1 = (const ON_3dVector*)&x1;
const ON_3dVector* _y1 = (const ON_3dVector*)&y1;
const ON_3dVector* _z1 = (const ON_3dVector*)&z1;
rc = xf->ChangeBasis(*_x0, *_y0, *_z0, *_x1, *_y1, *_z1);
}
return rc;
}
RH_C_FUNCTION void ON_Xform_PlanarProjection(ON_Xform* xf, const ON_PLANE_STRUCT* plane)
{
if( xf && plane )
{
ON_Plane temp = FromPlaneStruct(*plane);
xf->PlanarProjection(temp);
}
}
RH_C_FUNCTION void ON_Xform_Shear(ON_Xform* xf,
const ON_PLANE_STRUCT* plane,
ON_3DVECTOR_STRUCT x,
ON_3DVECTOR_STRUCT y,
ON_3DVECTOR_STRUCT z)
{
if( xf && plane )
{
ON_Plane t_plane = FromPlaneStruct(*plane);
const ON_3dVector* _x = (const ON_3dVector*)&x;
const ON_3dVector* _y = (const ON_3dVector*)&y;
const ON_3dVector* _z = (const ON_3dVector*)&z;
*xf = ON_Xform::ShearTransformation(t_plane, *_x, *_y, *_z);
}
}
RH_C_FUNCTION bool ON_Xform_IsZeroTransformation(const ON_Xform* xf, double tolerance)
{
bool rc = false;
if (xf)
{
rc = xf->IsZeroTransformation(tolerance);
}
return rc;
}
RH_C_FUNCTION int ON_Xform_IsSimilarity(const ON_Xform* xf)
{
int rc = 0;
if( xf )
{
rc = xf->IsSimilarity();
}
return rc;
}
RH_C_FUNCTION int ON_Xform_IsSimilarity2(const ON_Xform* xf, double tolerance)
{
int rc = 0;
if (xf)
{
rc = xf->IsSimilarity(tolerance);
}
return rc;
}
RH_C_FUNCTION int ON_Xform_DecomposeSimilarity(const ON_Xform* xf, ON_3dVector* translation, double* dilation, ON_Xform* rotation, double tolerance)
{
int rc = 0;
if (xf && translation && dilation && rotation)
rc = xf->DecomposeSimilarity(*translation, *dilation, *rotation, tolerance);
return rc;
}
RH_C_FUNCTION int ON_Xform_IsRigid(const ON_Xform* xf, double tolerance)
{
int rc = 0;
if (xf)
{
rc = xf->IsRigid(tolerance);
}
return rc;
}
RH_C_FUNCTION int ON_Xform_DecomposeRigid(const ON_Xform* xf, ON_3dVector* translation, ON_Xform* rotation, double tolerance)
{
int rc = 0;
if (xf && translation && rotation)
rc = xf->DecomposeRigid(*translation, *rotation, tolerance);
return rc;
}
RH_C_FUNCTION bool ON_Xform_IsAffine(const ON_Xform* xf)
{
bool rc = false;
if (xf)
{
rc = xf->IsAffine();
}
return rc;
}
RH_C_FUNCTION bool ON_Xform_IsLinear(const ON_Xform* xf)
{
bool rc = false;
if (xf)
{
rc = xf->IsLinear();
}
return rc;
}
RH_C_FUNCTION bool ON_Xform_DecomposeAffine(const ON_Xform* xf, ON_3dVector* translation, ON_Xform* linear)
{
bool rc = false;
if (xf && translation && linear)
rc = xf->DecomposeAffine(*translation, *linear);
return rc;
}
RH_C_FUNCTION bool ON_Xform_DecomposeAffine2(const ON_Xform* xf, ON_Xform* linear, ON_3dVector* translation)
{
bool rc = false;
if (xf && translation && linear)
rc = xf->DecomposeAffine(*linear, *translation);
return rc;
}
RH_C_FUNCTION bool ON_Xform_DecomposeAffine3(const ON_Xform* xf, ON_3dVector* translation, ON_Xform* rotation, ON_Xform* orthogonal, ON_3dVector* diagonal)
{
bool rc = false;
if (xf && translation && rotation && orthogonal && diagonal)
rc = xf->DecomposeAffine(*translation, *rotation, *orthogonal, *diagonal);
return rc;
}
RH_C_FUNCTION bool ON_Xform_IsRotation(const ON_Xform* xf)
{
bool rc = false;
if (xf)
{
rc = xf->IsRotation();
}
return rc;
}
RH_C_FUNCTION void ON_Xform_Affineize(ON_Xform* xf)
{
if (xf)
{
xf->Affineize();
}
}
RH_C_FUNCTION void ON_Xform_Linearize(ON_Xform* xf)
{
if (xf)
{
xf->Linearize();
}
}
RH_C_FUNCTION bool ON_Xform_Orthogonalize(ON_Xform* xf, double tolerance)
{
bool rc = false;
if (xf)
{
rc = xf->Orthogonalize(tolerance);
}
return rc;
}
RH_C_FUNCTION bool ON_Xform_DecomposeSymmetric(ON_Xform* xf, ON_Xform* matrix, ON_3dVector* diagonal)
{
bool rc = false;
if (xf && matrix && diagonal)
{
rc = xf->DecomposeSymmetric(*matrix, *diagonal);
}
return rc;
}
RH_C_FUNCTION double ON_Xform_Determinant(const ON_Xform* xf)
{
double rc = 0.0;
if( xf )
rc = xf->Determinant();
return rc;
}
RH_C_FUNCTION bool ON_Xform_Invert( ON_Xform* xf )
{
bool rc = false;
if( xf )
rc = xf->Invert();
return rc;
}
RH_C_FUNCTION void ON_Xform_RotationZYX(ON_Xform* xf, double yaw, double pitch, double roll)
{
if (xf)
xf->RotationZYX(yaw, pitch, roll);
}
RH_C_FUNCTION bool ON_Xform_GetYawPitchRoll(const ON_Xform* xf, double* yaw, double* pitch, double* roll)
{
bool rc = false;
if (xf && yaw && pitch && roll)
rc = xf->GetYawPitchRoll(*yaw, *pitch, *roll);
return rc;
}
RH_C_FUNCTION void ON_Xform_RotationZYZ(ON_Xform* xf, double alpha, double beta, double gamma)
{
if (xf)
xf->RotationZYZ(alpha, beta, gamma);
}
RH_C_FUNCTION bool ON_Xform_GetEulerZYZ(const ON_Xform* xf, double* alpha, double* beta, double* gamma)
{
bool rc = false;
if (xf && alpha && beta && gamma)
rc = xf->GetEulerZYZ(*alpha, *beta, *gamma);
return rc;
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
#if !defined(RHINO3DM_BUILD)
typedef void (CALLBACK* MORPHPOINTPROC)(ON_3DPOINT_STRUCT point, ON_3dPoint* out_point);
class CCustomSpaceMorph : public ON_SpaceMorph
{
public:
CCustomSpaceMorph(double tolerance, bool quickpreview, bool preserveStructure, MORPHPOINTPROC callback)
{
SetTolerance(tolerance);
SetQuickPreview(quickpreview);
SetPreserveStructure(preserveStructure);
m_callback = callback;
}
ON_3dPoint MorphPoint( ON_3dPoint point ) const override
{
ON_3dPoint rc = point;
if( m_callback )
{
ON_3DPOINT_STRUCT* _pt = (ON_3DPOINT_STRUCT*)(&point);
m_callback(*_pt, &rc);
}
return rc;
}
private:
MORPHPOINTPROC m_callback;
};
// not available in stand alone OpenNURBS build
RH_C_FUNCTION bool ON_SpaceMorph_MorphGeometry(ON_Geometry* pGeometry, double tolerance, bool quickpreview, bool preserveStructure, MORPHPOINTPROC callback)
{
bool rc = false;
if( pGeometry && callback )
{
CCustomSpaceMorph sm(tolerance, quickpreview, preserveStructure, callback);
rc = pGeometry->Morph(sm);
}
return rc;
}
RH_C_FUNCTION bool ON_SpaceMorph_MorphGeometry2(ON_Geometry* pGeometry, const ON_SpaceMorph* pConstSpaceMorph)
{
if( pGeometry && pConstSpaceMorph )
return pGeometry->Morph(*pConstSpaceMorph);
return false;
}
RH_C_FUNCTION bool ON_SpaceMorph_MorphPlane(ON_PLANE_STRUCT* pPlane, double tolerance, bool quickpreview, bool preserveStructure, MORPHPOINTPROC callback)
{
bool rc = false;
if (pPlane && callback)
{
CCustomSpaceMorph sm(tolerance, quickpreview, preserveStructure, callback);
ON_Plane temp = FromPlaneStruct(*pPlane);
rc = temp.Morph(sm);
CopyToPlaneStruct(*pPlane, temp);
}
return rc;
}
RH_C_FUNCTION bool ON_SpaceMorph_MorphPlane2(ON_PLANE_STRUCT* pPlane, const ON_SpaceMorph* pConstSpaceMorph)
{
bool rc = false;
if (pPlane && pConstSpaceMorph)
{
ON_Plane temp = FromPlaneStruct(*pPlane);
rc = temp.Morph(*pConstSpaceMorph);
CopyToPlaneStruct(*pPlane, temp);
}
return rc;
}
RH_C_FUNCTION bool ON_SpaceMorph_GetValues(const ON_SpaceMorph* pConstSpaceMorph, double* tolerance, bool* quickpreview, bool* preserveStructure)
{
bool rc = false;
if( pConstSpaceMorph && tolerance && quickpreview && preserveStructure )
{
*tolerance = pConstSpaceMorph->Tolerance();
*quickpreview = pConstSpaceMorph->QuickPreview();
*preserveStructure = pConstSpaceMorph->PreserveStructure();
rc = true;
}
return rc;
}
RH_C_FUNCTION void ON_SpaceMorph_MorphPoint(const ON_SpaceMorph* pConstSpaceMorph, ON_3dPoint* point)
{
if( pConstSpaceMorph && point )
{
*point = pConstSpaceMorph->MorphPoint(*point);
}
}
#endif
RH_C_FUNCTION void ON_SpaceMorph_Delete(ON_SpaceMorph* pSpaceMorph)
{
if( pSpaceMorph )
delete pSpaceMorph;
}
RH_C_FUNCTION ON_Matrix* ON_Matrix_New(int rows, int cols)
{
ON_Matrix* rc = new ON_Matrix(rows, cols);
rc->Zero();
return rc;
}
RH_C_FUNCTION ON_Matrix* ON_Matrix_New2(const ON_Xform* pXform)
{
if( pXform )
return new ON_Matrix(*pXform);
return nullptr;
}
RH_C_FUNCTION void ON_Matrix_Delete(ON_Matrix* pMatrix)
{
if( pMatrix )
delete pMatrix;
}
RH_C_FUNCTION double ON_Matrix_GetValue(const ON_Matrix* pConstMatrix, int row, int column)
{
if( pConstMatrix )
return (*pConstMatrix)[row][column];
return 0;
}
RH_C_FUNCTION void ON_Matrix_SetValue(ON_Matrix* pMatrix, int row, int column, double val)
{
if( pMatrix )
(*pMatrix)[row][column] = val;
}
RH_C_FUNCTION void ON_Matrix_Zero(ON_Matrix* pMatrix)
{
if( pMatrix )
pMatrix->Zero();
}
RH_C_FUNCTION void ON_Matrix_SetDiagonal(ON_Matrix* pMatrix, double value)
{
if( pMatrix )
pMatrix->SetDiagonal(value);
}
RH_C_FUNCTION bool ON_Matrix_Transpose(ON_Matrix* pMatrix)
{
if(pMatrix)
return pMatrix->Transpose();
return false;
}
RH_C_FUNCTION bool ON_Matrix_Swap(ON_Matrix* pMatrix, bool swaprows, int a, int b)
{
bool rc = false;
if( pMatrix )
{
if( swaprows )
rc = pMatrix->SwapRows(a,b);
else
rc = pMatrix->SwapCols(a,b);
}
return rc;
}
RH_C_FUNCTION bool ON_Matrix_Invert(ON_Matrix* pMatrix, double zeroTolerance)
{
bool rc = false;
if(pMatrix)
rc = pMatrix->Invert(zeroTolerance);
return rc;
}
RH_C_FUNCTION void ON_Matrix_Multiply(ON_Matrix* pMatrixRC, const ON_Matrix* pConstMatrixA, const ON_Matrix* pConstMatrixB)
{
if( pMatrixRC && pConstMatrixA && pConstMatrixB )
{
pMatrixRC->Multiply(*pConstMatrixA, *pConstMatrixB);
}
}
RH_C_FUNCTION void ON_Matrix_Add(ON_Matrix* pMatrixRC, const ON_Matrix* pConstMatrixA, const ON_Matrix* pConstMatrixB)
{
if( pMatrixRC && pConstMatrixA && pConstMatrixB )
{
pMatrixRC->Add(*pConstMatrixA, *pConstMatrixB);
}
}
RH_C_FUNCTION void ON_Matrix_Scale(ON_Matrix* pMatrix, double scale)
{
if( pMatrix )
pMatrix->Scale(scale);
}
RH_C_FUNCTION int ON_Matrix_RowReduce(ON_Matrix* pMatrix, double zero_tol, double* determinant, double* pivot)
{
int rc = 0;
if( pMatrix && determinant && pivot )
rc = pMatrix->RowReduce(zero_tol, *determinant, *pivot);
return rc;
}
RH_C_FUNCTION int ON_Matrix_RowReduce2(ON_Matrix* pMatrix, double zero_tol, /*ARRAY*/double* b, double* pivot)
{
int rc = 0;
if( pMatrix && b )
rc = pMatrix->RowReduce(zero_tol, b, pivot);
return rc;
}
RH_C_FUNCTION int ON_Matrix_RowReduce3(ON_Matrix* pMatrix, double zero_tol, /*ARRAY*/ON_3dPoint* b, double* pivot)
{
int rc = 0;
if( pMatrix && b )
rc = pMatrix->RowReduce(zero_tol, b, pivot);
return rc;
}
RH_C_FUNCTION bool ON_Matrix_BackSolve(ON_Matrix* pMatrix, double zero_tol, int bSize, /*ARRAY*/const double* b, /*ARRAY*/double* x)
{
bool rc = false;
if( pMatrix && b && x )
rc = pMatrix->BackSolve(zero_tol, bSize, b, x);
return rc;
}
RH_C_FUNCTION bool ON_Matrix_BackSolve2(ON_Matrix* pMatrix, double zero_tol, int bSize, /*ARRAY*/const ON_3dPoint* b, /*ARRAY*/ON_3dPoint* x)
{
bool rc = false;
if( pMatrix && b && x )
rc = pMatrix->BackSolve(zero_tol, bSize, b, x);
return rc;
}
RH_C_FUNCTION bool ON_Matrix_GetBool(const ON_Matrix* pConstMatrix, int which)
{
const int idxIsRowOrthoganal = 0;
const int idxIsRowOrthoNormal = 1;
const int idxIsColumnOrthoganal = 2;
const int idxIsColumnOrthoNormal = 3;
bool rc = false;
if( pConstMatrix )
{
switch (which)
{
case idxIsRowOrthoganal:
rc = pConstMatrix->IsRowOrthoganal();
break;
case idxIsRowOrthoNormal:
rc = pConstMatrix->IsRowOrthoNormal();
break;
case idxIsColumnOrthoganal:
rc = pConstMatrix->IsColOrthoganal();
break;
case idxIsColumnOrthoNormal:
rc = pConstMatrix->IsColOrthoNormal();
break;
default:
break;
}
}
return rc;
}
| 6,028 |
302 | <filename>ChromeWorker/converter.cpp
#include "converter.h"
#include <regex>
std::string ws2s(const std::wstring& wstr)
{
typedef std::codecvt_utf8<wchar_t> convert_typeX;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.to_bytes(wstr);
}
std::wstring s2ws(const std::string& str)
{
typedef std::codecvt_utf8<wchar_t> convert_typeX;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.from_bytes(str);
}
| 206 |
819 | /*
Copyright 2017 Google 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.
*/
#include "seurat/compressor/resampler/box_downsampler.h"
#include "ion/math/range.h"
#include "ion/math/vector.h"
#include "seurat/base/array2d_util.h"
#include "seurat/image/image.h"
namespace seurat {
namespace compressor {
using image::Image4f;
using ion::math::Range1f;
using ion::math::Vector2f;
using ion::math::Vector2i;
Image4f BoxDownsampler::Resample(const Image4f& image,
const Vector2i& target_size) const {
CHECK_NE(target_size, image.GetSize());
CHECK_LE(2, target_size[0]);
CHECK_LE(2, target_size[1]);
CHECK_LE(target_size[0], image.Width());
CHECK_LE(target_size[1], image.Height());
Image4f resized_image(target_size);
// Account for the half pixel border around the texture. The goal is to match
// as close as possible the regions of the source image and of the downsampled
// image between texture coordinates [0.5, texture_size-0.5]. This amounts to
// subtracting 1 from both texture extents when computing the x and y scaling
// factors.
Vector2f scaling(
static_cast<float>(image.Width() - 1) / (target_size[0] - 1),
static_cast<float>(image.Height() - 1) / (target_size[1] - 1));
for (int y = 0; y < target_size[1]; ++y) {
for (int x = 0; x < target_size[0]; ++x) {
// Range of the box filter within the initial image.
Range1f x_range((x - 0.5f) * scaling[0], (x + 0.5f) * scaling[0]);
Range1f y_range((y - 0.5f) * scaling[1], (y + 0.5f) * scaling[1]);
// Set downsampled image pixel to the average value. The box filter
// average is clamped to [0,1] and quantized.
resized_image.At(x, y) = ComputeBoxAverage(image, x_range, y_range)
.ClampToUnit()
.AsColorUI8()
.AsColorF();
}
}
return resized_image;
}
} // namespace compressor
} // namespace seurat
| 951 |
1,232 | /*-
* <<
* DBus
* ==
* Copyright (C) 2016 - 2019 Bridata
* ==
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* >>
*/
package com.creditease.dbus.tools;
import com.creditease.dbus.commons.Constants;
import com.creditease.dbus.commons.ZkNode;
import com.creditease.dbus.commons.ZkService;
import com.creditease.dbus.tools.common.ConfUtils;
import com.google.common.base.Strings;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* Created by 201605240095 on 2016/7/25.
*/
public class ZkConfBatchModifier {
private static Logger logger = LoggerFactory.getLogger(ZkConfBatchModifier.class);
public static final String UTF8 = "utf-8";
public static void main(String[] args) throws Exception {
//if (!(args.length == 3 || args.length == 4)) {
// logger.info("Please provide legal parameters(the last arg is optional): baseNode oldString newString [checker]. Eg: /DBus zk1:2181 zk1:2181,zk2:2181 :2181");
// return;
//}
//logger.info(String.format("Try to replace %s by %s", args[1], args[2]));
Properties props = ConfUtils.loadZKProperties();
String zkServer = props.getProperty(Constants.ZOOKEEPER_SERVERS);
if (Strings.isNullOrEmpty(zkServer)) {
logger.error("Zookeeper server cannot be null!");
return;
}
ZkService zkService = new ZkService(zkServer);
List<String> canal = zkService.getChildren("/DBus/Canal");
for (String c : canal) {
List<String> cluster = zkService.getChildren(String.format("/DBus/Canal/%s/otter/canal/cluster", c));
if (cluster == null || cluster.size() == 0) {
continue;
}
String destinations = zkService.getChildren(String.format("/DBus/Canal/%s/otter/canal/destinations", c)).get(0);
String filter = String.format("/DBus/Canal/%s/otter/canal/destinations/%s/1001/filter", c, destinations);
if (zkService.isExists(filter)) {
zkService.deleteNode(filter);
System.out.println(String.format("delete %s success", filter));
}
}
zkService.close();
//String basePath = args[0];
//String oldString = args[1];
//String newString = args[2];
//if (!basePath.startsWith(Constants.DBUS_ROOT)) {
// logger.error("The base path is not start with " + Constants.DBUS_ROOT + ". Please check!");
// return;
//}
//
//String checker = null;
//if (args.length == 4) {
// checker = args[3];
//}
//
//ZkService zkService = new ZkService(zkServer);
//
//ZkNode baseNode = new ZkNode(basePath); // Name name name Todo not start with refuse; 直接搞指定path底下的。
//baseNode.setPath(basePath);
//
//
//byte[] data = zkService.getData(baseNode.getPath());
//if (data != null && data.length > 0) {
// String orignialContent = new String(data, UTF8);
//
// if (StringUtils.isNotBlank(checker) && orignialContent.indexOf(oldString) == -1 && orignialContent.indexOf(checker) != -1) {
// logger.warn(String.format("Found checker --- %s, But not found %s at %s", checker, oldString, baseNode.getPath()));
// }
//
// if (orignialContent.indexOf(oldString) != -1) {
// logger.info(String.format("Found %s at %s in \n%s", oldString, baseNode.getPath(), orignialContent));
// String newContent = orignialContent.replace(oldString, newString);
// zkService.setData(baseNode.getPath(), newContent.getBytes(UTF8));
// }
//
//}
//
//replaceContentRecursively(zkService, baseNode, oldString, newString, checker);
//zkService.close();
}
private static List<ZkNode> replaceContentRecursively(ZkService zkService, ZkNode parent, String oldString, String newString, String checker) {
List<ZkNode> childrenNodes = new ArrayList();
List<String> children = null;
try {
children = zkService.getChildren(parent.getPath());
if (children.size() > 0) {
for (String nodeName : children) {
ZkNode node = new ZkNode(nodeName);
String path = parent.getPath() + "/" + nodeName;
if (parent.getPath().equals("/")) { //我们的地址是 /DBus/xxx的形式。需要对第一个 / 进行特殊处理.
path = parent.getPath() + nodeName;
}
node.setPath(path);
byte[] data = zkService.getData(path);
if (data != null && data.length > 0) {
String orignialContent = new String(data, UTF8);
if (StringUtils.isNotBlank(checker) && orignialContent.indexOf(oldString) == -1 && orignialContent.indexOf(checker) != -1) {
logger.warn(String.format("Found checker --- %s, But not found %s at %s", checker, oldString, path));
}
if (orignialContent.indexOf(oldString) != -1) {
logger.info(String.format("Found %s at %s in \n%s", oldString, path, orignialContent));
String newContent = orignialContent.replace(oldString, newString);
zkService.setData(path, newContent.getBytes(UTF8));
}
}
childrenNodes.add(node);
}
for (ZkNode node : childrenNodes) {
replaceContentRecursively(zkService, node, oldString, newString, checker);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return childrenNodes;
}
}
| 3,018 |
5,133 | /*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.ap.test.nestedsource.exceptions;
/**
*
* @author <NAME> <<EMAIL>>
*/
public class Bucket {
String userId;
public Bucket(String userId) {
this.userId = userId;
}
public User getUser() throws NoSuchUser {
throw new NoSuchUser();
}
}
| 164 |
2,313 | <filename>src/core/NEON/kernels/arm_gemm/transforms/a64_transpose_interleave_12_2x4.hpp
/*
* Copyright (c) 2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#pragma once
#ifdef __aarch64__
namespace {
void a64_transpose_interleave_12_2x4(uint16_t *out, const uint16_t *in, size_t width, size_t in_stride, size_t height)
{
uint16_t *pad_row = reinterpret_cast<uint16_t *>(alloca(width * sizeof(uint16_t)));
if (height % 4) {
memset(pad_row, 0, width * sizeof(uint16_t));
}
size_t out_stride = 12 * roundup<size_t>(height, 4) * sizeof(uint16_t);
__asm__ __volatile__(
"cmp %x[height], #0x8\n"
"blt 10f\n"
"1:" // Main row loop: Head
"mov x28, %x[in]\n"
"mov x27, %x[out]\n"
"add x26, x28, %x[in_stride]\n"
"add x25, x26, %x[in_stride]\n"
"add x24, x25, %x[in_stride]\n"
"add x23, x24, %x[in_stride]\n"
"add x22, x23, %x[in_stride]\n"
"add x21, x22, %x[in_stride]\n"
"add x20, x21, %x[in_stride]\n"
"add %x[in], x20, %x[in_stride]\n"
"sub %x[height], %x[height], #0x8\n"
"mov x19, %x[width]\n"
"cmp x19, #0x18\n"
"blt 3f\n"
"2:" // Main row loop: Unroll column loop
"ldr q18, [x28], #0x10\n"
"sub x19, x19, #0x18\n"
"ldr q23, [x26], #0x10\n"
"cmp x19, #0x18\n"
"ldr q16, [x25], #0x10\n"
"zip1 v22.8h, v18.8h, v16.8h\n"
"ldr q17, [x28], #0x10\n"
"zip2 v21.8h, v18.8h, v16.8h\n"
"ldr q12, [x26], #0x10\n"
"ldr q16, [x25], #0x10\n"
"zip1 v20.8h, v17.8h, v16.8h\n"
"ldr q18, [x28], #0x10\n"
"zip2 v11.8h, v17.8h, v16.8h\n"
"ldr q10, [x26], #0x10\n"
"ldr q17, [x25], #0x10\n"
"zip1 v9.8h, v18.8h, v17.8h\n"
"ldr q16, [x24], #0x10\n"
"zip2 v8.8h, v18.8h, v17.8h\n"
"ldr q19, [x23], #0x10\n"
"ldr q7, [x22], #0x10\n"
"zip1 v17.8h, v23.8h, v16.8h\n"
"ldr q6, [x24], #0x10\n"
"zip2 v16.8h, v23.8h, v16.8h\n"
"ldr q5, [x23], #0x10\n"
"zip1 v4.8h, v22.8h, v17.8h\n"
"ldr q3, [x22], #0x10\n"
"zip2 v2.8h, v22.8h, v17.8h\n"
"ldr q18, [x21], #0x10\n"
"zip1 v1.8h, v21.8h, v16.8h\n"
"ldr q0, [x24], #0x10\n"
"zip2 v31.8h, v21.8h, v16.8h\n"
"ldr q30, [x23], #0x10\n"
"zip1 v16.8h, v12.8h, v6.8h\n"
"ldr q29, [x22], #0x10\n"
"zip1 v28.8h, v20.8h, v16.8h\n"
"ldr q27, [x21], #0x10\n"
"zip2 v26.8h, v20.8h, v16.8h\n"
"ldr q21, [x20], #0x10\n"
"zip1 v17.8h, v19.8h, v18.8h\n"
"ldr q25, [x21], #0x10\n"
"zip2 v19.8h, v19.8h, v18.8h\n"
"zip1 v18.8h, v5.8h, v27.8h\n"
"ldr q24, [x20], #0x10\n"
"zip1 v16.8h, v7.8h, v21.8h\n"
"ldr q23, [x20], #0x10\n"
"zip1 v22.8h, v17.8h, v16.8h\n"
"zip2 v20.8h, v17.8h, v16.8h\n"
"str q4, [x27, #0x0]\n"
"zip2 v16.8h, v7.8h, v21.8h\n"
"str q2, [x27, #0x10]\n"
"zip1 v17.8h, v19.8h, v16.8h\n"
"str q1, [x27, #0x20]\n"
"zip2 v21.8h, v19.8h, v16.8h\n"
"str q31, [x27, #0x30]\n"
"zip1 v16.8h, v3.8h, v24.8h\n"
"str q28, [x27, #0x40]\n"
"zip1 v19.8h, v18.8h, v16.8h\n"
"str q26, [x27, #0x50]\n"
"zip2 v18.8h, v18.8h, v16.8h\n"
"str q22, [x27, #0x60]\n"
"zip2 v16.8h, v12.8h, v6.8h\n"
"str q20, [x27, #0x70]\n"
"zip1 v20.8h, v11.8h, v16.8h\n"
"str q17, [x27, #0x80]\n"
"zip2 v17.8h, v11.8h, v16.8h\n"
"str q21, [x27, #0x90]\n"
"zip1 v16.8h, v10.8h, v0.8h\n"
"str q19, [x27, #0xa0]\n"
"zip1 v19.8h, v9.8h, v16.8h\n"
"str q18, [x27, #0xb0]\n"
"add x27, x27, %x[out_stride]\n"
"zip2 v18.8h, v9.8h, v16.8h\n"
"str q20, [x27, #0x0]\n"
"zip2 v16.8h, v10.8h, v0.8h\n"
"str q17, [x27, #0x10]\n"
"zip1 v17.8h, v8.8h, v16.8h\n"
"str q19, [x27, #0x20]\n"
"zip2 v16.8h, v8.8h, v16.8h\n"
"str q18, [x27, #0x30]\n"
"zip2 v18.8h, v5.8h, v27.8h\n"
"str q17, [x27, #0x40]\n"
"zip2 v17.8h, v3.8h, v24.8h\n"
"str q16, [x27, #0x50]\n"
"zip1 v16.8h, v18.8h, v17.8h\n"
"str q16, [x27, #0x60]\n"
"zip2 v16.8h, v18.8h, v17.8h\n"
"str q16, [x27, #0x70]\n"
"zip1 v18.8h, v30.8h, v25.8h\n"
"zip1 v17.8h, v29.8h, v23.8h\n"
"zip1 v16.8h, v18.8h, v17.8h\n"
"str q16, [x27, #0x80]\n"
"zip2 v16.8h, v18.8h, v17.8h\n"
"str q16, [x27, #0x90]\n"
"zip2 v18.8h, v30.8h, v25.8h\n"
"zip2 v17.8h, v29.8h, v23.8h\n"
"zip1 v16.8h, v18.8h, v17.8h\n"
"str q16, [x27, #0xa0]\n"
"zip2 v16.8h, v18.8h, v17.8h\n"
"str q16, [x27, #0xb0]\n"
"add x27, x27, %x[out_stride]\n"
"bge 2b\n"
"3:" // Main row loop: Unroll column loop skip
"cmp x19, #0xc\n"
"blt 5f\n"
"4:" // Main row loop: Column loop
"ldr q18, [x28], #0x10\n"
"sub x19, x19, #0xc\n"
"ldr q20, [x26], #0x10\n"
"cmp x19, #0xc\n"
"ldr q16, [x25], #0x10\n"
"zip1 v19.8h, v18.8h, v16.8h\n"
"ldr d17, [x28], #0x8\n"
"zip2 v23.8h, v18.8h, v16.8h\n"
"ldr d22, [x26], #0x8\n"
"ldr d16, [x25], #0x8\n"
"zip1 v21.8h, v17.8h, v16.8h\n"
"ldr q16, [x24], #0x10\n"
"ldr q31, [x23], #0x10\n"
"zip1 v18.8h, v20.8h, v16.8h\n"
"ldr d17, [x24], #0x8\n"
"zip2 v16.8h, v20.8h, v16.8h\n"
"ldr d30, [x23], #0x8\n"
"zip1 v29.8h, v19.8h, v18.8h\n"
"ldr q28, [x22], #0x10\n"
"zip2 v20.8h, v19.8h, v18.8h\n"
"ldr q27, [x21], #0x10\n"
"zip1 v19.8h, v23.8h, v16.8h\n"
"ldr q26, [x20], #0x10\n"
"zip2 v18.8h, v23.8h, v16.8h\n"
"ldr d25, [x22], #0x8\n"
"zip1 v16.8h, v22.8h, v17.8h\n"
"zip1 v24.8h, v21.8h, v16.8h\n"
"ldr d23, [x21], #0x8\n"
"zip2 v22.8h, v21.8h, v16.8h\n"
"ldr d21, [x20], #0x8\n"
"zip1 v17.8h, v31.8h, v27.8h\n"
"str q29, [x27, #0x0]\n"
"zip1 v16.8h, v28.8h, v26.8h\n"
"str q20, [x27, #0x10]\n"
"zip1 v20.8h, v17.8h, v16.8h\n"
"str q19, [x27, #0x20]\n"
"zip2 v19.8h, v17.8h, v16.8h\n"
"str q18, [x27, #0x30]\n"
"zip2 v18.8h, v31.8h, v27.8h\n"
"str q24, [x27, #0x40]\n"
"zip2 v16.8h, v28.8h, v26.8h\n"
"str q22, [x27, #0x50]\n"
"zip1 v17.8h, v18.8h, v16.8h\n"
"str q20, [x27, #0x60]\n"
"zip2 v16.8h, v18.8h, v16.8h\n"
"str q19, [x27, #0x70]\n"
"zip1 v18.8h, v30.8h, v23.8h\n"
"str q17, [x27, #0x80]\n"
"zip1 v17.8h, v25.8h, v21.8h\n"
"str q16, [x27, #0x90]\n"
"zip1 v16.8h, v18.8h, v17.8h\n"
"str q16, [x27, #0xa0]\n"
"zip2 v16.8h, v18.8h, v17.8h\n"
"str q16, [x27, #0xb0]\n"
"add x27, x27, %x[out_stride]\n"
"bge 4b\n"
"5:" // Main row loop: Column loop skip
"cmp x19, #0x4\n"
"blt 7f\n"
"6:" // Main row loop: width 4 loop: loop
"ldr d17, [x28], #0x8\n"
"sub x19, x19, #0x4\n"
"ldr d18, [x26], #0x8\n"
"cmp x19, #0x4\n"
"ldr d16, [x25], #0x8\n"
"zip1 v17.8h, v17.8h, v16.8h\n"
"ldr d16, [x24], #0x8\n"
"ldr d21, [x23], #0x8\n"
"zip1 v16.8h, v18.8h, v16.8h\n"
"ldr d20, [x22], #0x8\n"
"ldr d19, [x21], #0x8\n"
"zip1 v18.8h, v17.8h, v16.8h\n"
"zip2 v17.8h, v17.8h, v16.8h\n"
"ldr d16, [x20], #0x8\n"
"str q18, [x27, #0x0]\n"
"zip1 v18.8h, v21.8h, v19.8h\n"
"str q17, [x27, #0x10]\n"
"zip1 v17.8h, v20.8h, v16.8h\n"
"zip1 v16.8h, v18.8h, v17.8h\n"
"str q16, [x27, #0x60]\n"
"zip2 v16.8h, v18.8h, v17.8h\n"
"str q16, [x27, #0x70]\n"
"add x27, x27, #0x20\n"
"bge 6b\n"
"7:" // Main row loop: width 4 loop: skip
"cmp x19, #0x1\n"
"blt 9f\n"
"8:" // Main row loop: width 1 loop: loop
"ldr h18, [x28], #0x2\n"
"sub x19, x19, #0x1\n"
"ldr h17, [x26], #0x2\n"
"cmp x19, #0x1\n"
"ldr h16, [x25], #0x2\n"
"zip1 v18.8h, v18.8h, v16.8h\n"
"ldr h16, [x24], #0x2\n"
"ldr h20, [x23], #0x2\n"
"zip1 v16.8h, v17.8h, v16.8h\n"
"ldr h19, [x22], #0x2\n"
"ldr h17, [x21], #0x2\n"
"zip1 v18.8h, v18.8h, v16.8h\n"
"ldr h16, [x20], #0x2\n"
"zip1 v17.8h, v20.8h, v17.8h\n"
"str d18, [x27, #0x0]\n"
"zip1 v16.8h, v19.8h, v16.8h\n"
"zip1 v16.8h, v17.8h, v16.8h\n"
"str d16, [x27, #0x60]\n"
"add x27, x27, #0x8\n"
"bge 8b\n"
"9:" // Main row loop: width 1 loop: skip
"add %x[out], %x[out], #0xc0\n"
"cmp %x[height], #0x8\n"
"bge 1b\n"
"cbz %x[height], 20f\n"
"10:" // Main loop skip
"11:" // Tail row loop: Head
"mov x28, %x[in]\n"
"mov x27, %x[out]\n"
"add x26, x28, %x[in_stride]\n"
"add x25, x26, %x[in_stride]\n"
"add x24, x25, %x[in_stride]\n"
"add %x[in], x24, %x[in_stride]\n"
"cmp %x[height], #0x3\n"
"csel x24, x24, %x[pad_row], GT\n"
"csel x25, x25, %x[pad_row], GE\n"
"cmp %x[height], #0x1\n"
"csel x26, x26, %x[pad_row], GT\n"
"sub %x[height], %x[height], #0x4\n"
"mov x19, %x[width]\n"
"cmp x19, #0x18\n"
"blt 13f\n"
"12:" // Tail row loop: Unroll column loop
"ldr q18, [x28], #0x10\n"
"sub x19, x19, #0x18\n"
"ldr q19, [x26], #0x10\n"
"cmp x19, #0x18\n"
"ldr q16, [x25], #0x10\n"
"zip1 v28.8h, v18.8h, v16.8h\n"
"ldr q17, [x28], #0x10\n"
"zip2 v27.8h, v18.8h, v16.8h\n"
"ldr q26, [x26], #0x10\n"
"ldr q16, [x25], #0x10\n"
"zip1 v25.8h, v17.8h, v16.8h\n"
"ldr q18, [x28], #0x10\n"
"zip2 v24.8h, v17.8h, v16.8h\n"
"ldr q23, [x26], #0x10\n"
"ldr q16, [x25], #0x10\n"
"zip1 v22.8h, v18.8h, v16.8h\n"
"ldr q17, [x24], #0x10\n"
"zip2 v21.8h, v18.8h, v16.8h\n"
"ldr q20, [x24], #0x10\n"
"zip1 v16.8h, v19.8h, v17.8h\n"
"zip2 v18.8h, v19.8h, v17.8h\n"
"ldr q19, [x24], #0x10\n"
"zip1 v17.8h, v28.8h, v16.8h\n"
"zip2 v16.8h, v28.8h, v16.8h\n"
"str q17, [x27, #0x0]\n"
"zip1 v17.8h, v27.8h, v18.8h\n"
"str q16, [x27, #0x10]\n"
"zip2 v16.8h, v27.8h, v18.8h\n"
"str q17, [x27, #0x20]\n"
"zip1 v17.8h, v26.8h, v20.8h\n"
"str q16, [x27, #0x30]\n"
"zip1 v16.8h, v25.8h, v17.8h\n"
"str q16, [x27, #0x40]\n"
"zip2 v16.8h, v25.8h, v17.8h\n"
"str q16, [x27, #0x50]\n"
"add x27, x27, %x[out_stride]\n"
"zip2 v18.8h, v26.8h, v20.8h\n"
"zip1 v17.8h, v23.8h, v19.8h\n"
"zip1 v16.8h, v24.8h, v18.8h\n"
"str q16, [x27, #0x0]\n"
"zip2 v16.8h, v24.8h, v18.8h\n"
"str q16, [x27, #0x10]\n"
"zip1 v16.8h, v22.8h, v17.8h\n"
"str q16, [x27, #0x20]\n"
"zip2 v16.8h, v22.8h, v17.8h\n"
"str q16, [x27, #0x30]\n"
"zip2 v17.8h, v23.8h, v19.8h\n"
"zip1 v16.8h, v21.8h, v17.8h\n"
"str q16, [x27, #0x40]\n"
"zip2 v16.8h, v21.8h, v17.8h\n"
"str q16, [x27, #0x50]\n"
"add x27, x27, %x[out_stride]\n"
"bge 12b\n"
"13:" // Tail row loop: Unroll column loop skip
"cmp x19, #0xc\n"
"blt 15f\n"
"14:" // Tail row loop: Column loop
"ldr q18, [x28], #0x10\n"
"sub x19, x19, #0xc\n"
"ldr q24, [x26], #0x10\n"
"cmp x19, #0xc\n"
"ldr q16, [x25], #0x10\n"
"zip1 v23.8h, v18.8h, v16.8h\n"
"ldr d17, [x28], #0x8\n"
"zip2 v22.8h, v18.8h, v16.8h\n"
"ldr d21, [x26], #0x8\n"
"ldr d16, [x25], #0x8\n"
"zip1 v20.8h, v17.8h, v16.8h\n"
"ldr q16, [x24], #0x10\n"
"zip1 v19.8h, v24.8h, v16.8h\n"
"ldr d18, [x24], #0x8\n"
"zip2 v17.8h, v24.8h, v16.8h\n"
"zip1 v16.8h, v23.8h, v19.8h\n"
"str q16, [x27, #0x0]\n"
"zip2 v16.8h, v23.8h, v19.8h\n"
"str q16, [x27, #0x10]\n"
"zip1 v16.8h, v22.8h, v17.8h\n"
"str q16, [x27, #0x20]\n"
"zip2 v16.8h, v22.8h, v17.8h\n"
"str q16, [x27, #0x30]\n"
"zip1 v17.8h, v21.8h, v18.8h\n"
"zip1 v16.8h, v20.8h, v17.8h\n"
"str q16, [x27, #0x40]\n"
"zip2 v16.8h, v20.8h, v17.8h\n"
"str q16, [x27, #0x50]\n"
"add x27, x27, %x[out_stride]\n"
"bge 14b\n"
"15:" // Tail row loop: Column loop skip
"cmp x19, #0x4\n"
"blt 17f\n"
"16:" // Tail row loop: width 4 loop: loop
"ldr d18, [x28], #0x8\n"
"sub x19, x19, #0x4\n"
"ldr d17, [x26], #0x8\n"
"cmp x19, #0x4\n"
"ldr d16, [x25], #0x8\n"
"zip1 v18.8h, v18.8h, v16.8h\n"
"ldr d16, [x24], #0x8\n"
"zip1 v17.8h, v17.8h, v16.8h\n"
"zip1 v16.8h, v18.8h, v17.8h\n"
"str q16, [x27, #0x0]\n"
"zip2 v16.8h, v18.8h, v17.8h\n"
"str q16, [x27, #0x10]\n"
"add x27, x27, #0x20\n"
"bge 16b\n"
"17:" // Tail row loop: width 4 loop: skip
"cmp x19, #0x1\n"
"blt 19f\n"
"18:" // Tail row loop: width 1 loop: loop
"ldr h17, [x28], #0x2\n"
"sub x19, x19, #0x1\n"
"ldr h18, [x26], #0x2\n"
"cmp x19, #0x1\n"
"ldr h16, [x25], #0x2\n"
"zip1 v17.8h, v17.8h, v16.8h\n"
"ldr h16, [x24], #0x2\n"
"zip1 v16.8h, v18.8h, v16.8h\n"
"zip1 v16.8h, v17.8h, v16.8h\n"
"str d16, [x27, #0x0]\n"
"add x27, x27, #0x8\n"
"bge 18b\n"
"19:" // Tail row loop: width 1 loop: skip
"add %x[out], %x[out], #0x60\n"
"cmp %x[height], #0x1\n"
"bge 11b\n"
"20:" // Done
: [height] "+&r" (height), [in] "+&r" (in), [out] "+&r" (out)
: [in_stride] "r" (in_stride), [out_stride] "r" (out_stride), [pad_row] "r" (pad_row), [width] "r" (width)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28"
);
}
} // anonymous namespace
template<>
void Transform<12, 4, true, VLType::None>(
bfloat16 *out, const bfloat16 *in, int stride, int x0, int xmax, int k0, int kmax)
{
a64_transpose_interleave_12_2x4(
reinterpret_cast<uint16_t *>(out),
reinterpret_cast<const uint16_t *>(in + k0 * stride + x0),
(xmax-x0) * sizeof(bfloat16) / 2,
stride * sizeof(bfloat16),
(kmax-k0)
);
}
#endif
| 10,169 |
435 | <gh_stars>100-1000
{
"copyright_text": "Creative Commons Attribution license (reuse allowed)",
"description": "According to industry surveys [1], the number one hassle of data\nscientists is cleaning the data to analyze it. Textbook statistical\nmodeling is sufficient for noisy signals, but errors of a discrete\nnature break standard tools of machine learning. I will discuss how to\neasily run machine learning on data tables with two common dirty-data\nproblems: missing values and non-normalized entries. On both problems, I\nwill show how to run standard machine-learning tools such as\nscikit-learn in the presence of such errors. The talk will be didactic\nand will discuss simple software solutions. It will build on the latest\nimprovements to scikit-learn for missing values and the DirtyCat package\n[2] for non normalized entries. I will also summarize theoretical\nanalyses in recent machine learning publications.\n\nThis talk targets data practitioners. Its goal are to help data\nscientists to be more efficient analysing data with such errors and\nunderstanding their impacts.\n\nWith missing values, I will use simple arguments and examples to outline\nhow to obtain asymptotically good predictions [3]. Two components are\nkey: imputation and adding an indicator of missingness. I will explain\ntheoretical guidelines for these, and I will show how to implement these\nideas in practice, with scikit-learn as a learner, or as a preprocesser.\n\nFor non-normalized categories, I will show that using their string\nrepresentations to \u201cvectorize\u201d them, creating vectorial representations\ngives a simple but powerful solution that can be plugged in standard\nstatistical analysis tools [4].\n\n| [1] Kaggle, the state of ML and data science 2017\n https://www.kaggle.com/surveys/2017\n| [2] https://dirty-cat.github.io/stable/\n| [3] <NAME>, <NAME>, <NAME>, and <NAME>\u00ebl\n (2019). \u201cOn the consistency of supervised learning with missing\n values\u201d. https://arxiv.org/abs/1902.06931\n| [4] <NAME>, <NAME>\u00ebl, and K\u00e9<NAME>\u00e1zs. \"Similarity\n encoding for learning with dirty categorical variables.\" Machine\n Learning 107.8-10 (2018): 1477 https://arxiv.org/abs/1806.00979",
"duration": 2572,
"language": "eng",
"recorded": "2019-07-11",
"related_urls": [
{
"label": "Conference schedule",
"url": "https://ep2019.europython.eu/schedule/"
}
],
"speakers": [
"<NAME>"
],
"tags": [
"Big Data",
"Data",
"Data Science",
"Machine-Learning",
"Scientific Libraries (Numpy/Pandas/SciKit/...)"
],
"thumbnail_url": "https://i.ytimg.com/vi/dw5u4nth6_M/maxresdefault.jpg",
"title": "Machine learning on non curated data",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=dw5u4nth6_M"
}
]
}
| 901 |
343 | // Copyright 2013 Google 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.
//
// This file declares the TraceFileWriter class, which encapsulates
// functionality for writing buffers of data to a trace file. This uses raw
// unbuffered writing to disk, and as such only writes multiples of the disk
// sector size.
//
// Intended use:
//
// TraceFileWriter w;
// if (!w.Open(path))
// ...
//
// // Use w.block_size() to make sure we are getting data with the appropriate
// // block size.
//
// if (!w.WriteHeader(process_info))
// ...
// while (...) {
// if (!w.WriteRecord(buffer, length))
// ...
// }
//
// if (!w.Close())
// ...
#ifndef SYZYGY_TRACE_SERVICE_TRACE_FILE_WRITER_H_
#define SYZYGY_TRACE_SERVICE_TRACE_FILE_WRITER_H_
#include "base/files/file_path.h"
#include "base/win/scoped_handle.h"
#include "syzygy/trace/service/process_info.h"
namespace trace {
namespace service {
// A trace file writer encapsulates the bare minimum functionality necessary for
// writing a trace file. It is not thread-safe.
class TraceFileWriter {
public:
// Constructor.
TraceFileWriter();
// Destructor.
~TraceFileWriter();
// Given information about a process, generates a suggested base filename for
// a trace.
// @param process_info Information about the process for which we are creating
// a trace file.
// @returns A suggested basename for the trace file.
static base::FilePath GenerateTraceFileBaseName(
const ProcessInfo& process_info);
// Opens a trace file at the given path.
// @param path The path of the trace file to write.
// @returns true on success, false otherwise.
bool Open(const base::FilePath& path);
// Writes the header to the trace file. A trace file is associated with a
// single running process, so we require a populated process-info struct.
// @param process_info Information about the process to which this trace file
// pertains.
// @returns true on success, false otherwise.
bool WriteHeader(const ProcessInfo& process_info);
// Writes a record of data to disk.
// @param data The record to be written. This must contain a RecordPrefix.
// This currently only supports records that contain a
// TraceFileSegmenHeader.
// @param length The maximum length of continuous data that may be
// contained in the record. The actual length is stored in the header, but
// this is necessary to ensure that the header is valid.
// @returns true on success, false otherwise.
bool WriteRecord(const void* data, size_t length);
// Closes the trace file.
// @returns true on success, false otherwise.
// @note If this is not called manually the trace-file will close itself when
// the writer goes out of scope.
bool Close();
// @returns the path to the trace file.
// @note This is only valid after Open has returned successfully.
base::FilePath path() const { return path_; }
// @returns the block size.
// @note This is only valid after Open has returned successfully.
size_t block_size() const { return block_size_; }
protected:
// The path to the trace file being written.
base::FilePath path_;
// The handle to the file that's being written to.
base::win::ScopedHandle handle_;
// The block size being used by the trace file writer.
size_t block_size_;
private:
DISALLOW_COPY_AND_ASSIGN(TraceFileWriter);
};
} // namespace service
} // namespace trace
#endif // SYZYGY_TRACE_SERVICE_TRACE_FILE_WRITER_H_
| 1,205 |
3,542 | /*
* Copyright 2018 YCSB Contributors. 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. See accompanying
* LICENSE file.
*/
package site.ycsb.db.tablestore;
import java.util.*;
import java.util.function.*;
import site.ycsb.*;
import com.alicloud.openservices.tablestore.*;
import com.alicloud.openservices.tablestore.model.*;
import org.apache.log4j.Logger;
/**
* TableStore Client for YCSB.
*/
public class TableStoreClient extends DB {
private static SyncClient client;
private int maxVersions = 1;
private String primaryKeyName;
private static final Logger LOGGER = Logger.getLogger(TableStoreClient.class);
// nasty here as currently there is no support of JEP218
private void setIntegerProperty(
Properties properties,
String propertyName,
ClientConfiguration clientConfiguration,
Function<Integer, Boolean> qualifyFunction,
BiConsumer<ClientConfiguration, Integer> setFunction) throws DBException {
String propertyString = properties.getProperty(propertyName);
if (propertyString != null) {
Integer propertyInteger = new Integer(propertyString);
if (qualifyFunction.apply(propertyInteger).booleanValue()) {
setFunction.accept(clientConfiguration, propertyInteger);
} else {
String errorMessage = "Illegal argument." + propertyName + ":" + propertyString;
LOGGER.error(errorMessage);
throw new DBException(errorMessage);
}
}
}
@Override
public void init() throws DBException {
Properties properties = getProperties();
String accessID = properties.getProperty("alibaba.cloud.tablestore.access_id");
String accessKey = properties.getProperty("alibaba.cloud.tablestore.access_key");
String endPoint = properties.getProperty("alibaba.cloud.tablestore.end_point");
String instanceName = properties.getProperty("alibaba.cloud.tablestore.instance_name");
String maxVersion = properties.getProperty("alibaba.cloud.tablestore.max_version", "1");
maxVersions = Integer.parseInt(maxVersion);
primaryKeyName = properties.getProperty("alibaba.cloud.tablestore.primary_key", "");
ClientConfiguration clientConfiguration = new ClientConfiguration();
setIntegerProperty(
properties,
"alibaba.cloud.tablestore.connection_timeout",
clientConfiguration,
(Integer t) -> t > 0,
(ClientConfiguration c, Integer t) -> c.setConnectionTimeoutInMillisecond(t.intValue()));
setIntegerProperty(
properties,
"alibaba.cloud.tablestore.socket_timeout",
clientConfiguration,
(Integer t) -> t > 0,
(ClientConfiguration c, Integer t) -> c.setSocketTimeoutInMillisecond(t.intValue()));
setIntegerProperty(
properties,
"alibaba.cloud.tablestore.max_connections",
clientConfiguration,
(Integer t) -> t > 0,
(ClientConfiguration c, Integer t) -> c.setMaxConnections(t.intValue()));
try {
synchronized (TableStoreClient.class) {
if (client == null) {
client = new SyncClient(endPoint, accessID, accessKey, instanceName, clientConfiguration);
LOGGER.info("new tablestore sync client\tendpoint:" + endPoint + "\tinstanceName:" + instanceName);
}
}
} catch (IllegalArgumentException e) {
throw new DBException("Illegal argument passed in. Check the format of your parameters.", e);
}
}
private void setResult(Set<String> fields, Map<String, ByteIterator> result, Row row) {
if (row != null) {
if (fields != null) {
for (String field : fields) {
result.put(field, new StringByteIterator((row.getColumn(field).toString())));
}
} else {
for (Column column : row.getColumns()) {
result.put(column.getName(), new StringByteIterator(column.getValue().asString()));
}
}
}
}
private Status dealWithTableStoreException(TableStoreException e) {
if (e.getErrorCode().contains("OTSRowOperationConflict")) {
return Status.ERROR;
}
LOGGER.error(e);
return Status.ERROR;
}
@Override
public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) {
try {
// set primary key
PrimaryKeyColumn[] primaryKeyColumns = new PrimaryKeyColumn[1];
primaryKeyColumns[0] = new PrimaryKeyColumn(primaryKeyName, PrimaryKeyValue.fromString(key));
PrimaryKey primaryKey = new PrimaryKey(primaryKeyColumns);
// set table_name
SingleRowQueryCriteria singleRowQueryCriteria = new SingleRowQueryCriteria(table, primaryKey);
singleRowQueryCriteria.setMaxVersions(maxVersions);
// set columns
if (fields != null) {
singleRowQueryCriteria.addColumnsToGet(fields.toArray(new String[0]));
}
// set get_row request
GetRowRequest getRowRequest = new GetRowRequest();
getRowRequest.setRowQueryCriteria(singleRowQueryCriteria);
// operate
GetRowResponse getRowResponse = client.getRow(getRowRequest);
// set the result
setResult(fields, result, getRowResponse.getRow());
return Status.OK;
} catch (TableStoreException e) {
return dealWithTableStoreException(e);
} catch (Exception e) {
LOGGER.error(e);
return Status.ERROR;
}
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
try {
// set primary key
PrimaryKeyColumn[] startKey = new PrimaryKeyColumn[1];
startKey[0] = new PrimaryKeyColumn(primaryKeyName, PrimaryKeyValue.fromString(startkey));
PrimaryKeyColumn[] endKey = new PrimaryKeyColumn[1];
endKey[0] = new PrimaryKeyColumn(primaryKeyName, PrimaryKeyValue.INF_MAX);
RangeRowQueryCriteria criteria = new RangeRowQueryCriteria(table);
criteria.setInclusiveStartPrimaryKey(new PrimaryKey(startKey));
criteria.setExclusiveEndPrimaryKey(new PrimaryKey(endKey));
criteria.setMaxVersions(maxVersions);
// set columns
if (fields != null) {
criteria.addColumnsToGet(fields.toArray(new String[0]));
}
// set limit
criteria.setLimit(recordcount);
// set the request
GetRangeRequest getRangeRequest = new GetRangeRequest();
getRangeRequest.setRangeRowQueryCriteria(criteria);
GetRangeResponse getRangeResponse = client.getRange(getRangeRequest);
// set the result
List<Row> rows = getRangeResponse.getRows();
for (Row row : rows) {
HashMap<String, ByteIterator> values = new HashMap<>();
setResult(fields, values, row);
result.add(values);
}
return Status.OK;
} catch (TableStoreException e) {
return dealWithTableStoreException(e);
} catch (Exception e) {
LOGGER.error(e);
return Status.ERROR;
}
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
try {
PrimaryKeyColumn[] primaryKeyColumns = new PrimaryKeyColumn[1];
primaryKeyColumns[0] = new PrimaryKeyColumn(primaryKeyName, PrimaryKeyValue.fromString(key));
PrimaryKey primaryKey = new PrimaryKey(primaryKeyColumns);
RowUpdateChange rowUpdateChange = new RowUpdateChange(table, primaryKey);
for (Map.Entry<String, ByteIterator> entry: values.entrySet()) {
rowUpdateChange.put(entry.getKey(), ColumnValue.fromString(entry.getValue().toString()));
}
UpdateRowRequest updateRowRequest = new UpdateRowRequest();
updateRowRequest.setRowChange(rowUpdateChange);
client.updateRow(updateRowRequest);
return Status.OK;
} catch (TableStoreException e) {
return dealWithTableStoreException(e);
} catch (Exception e) {
LOGGER.error(e);
return Status.ERROR;
}
}
@Override
public Status insert(String table, String key, Map<String, ByteIterator> values) {
try {
// set the primary key
PrimaryKeyColumn[] primaryKeyColumns = new PrimaryKeyColumn[1];
primaryKeyColumns[0] = new PrimaryKeyColumn(primaryKeyName, PrimaryKeyValue.fromString(key));
PrimaryKey primaryKey = new PrimaryKey(primaryKeyColumns);
RowPutChange rowPutChange = new RowPutChange(table, primaryKey);
// set the columns
for (Map.Entry<String, ByteIterator> entry: values.entrySet()) {
rowPutChange.addColumn(entry.getKey(), ColumnValue.fromString(entry.getValue().toString()));
}
// set the putRow request
PutRowRequest putRowRequest = new PutRowRequest();
putRowRequest.setRowChange(rowPutChange);
// operate
client.putRow(putRowRequest);
return Status.OK;
} catch (TableStoreException e) {
return dealWithTableStoreException(e);
} catch (Exception e) {
LOGGER.error(e);
return Status.ERROR;
}
}
@Override
public Status delete(String table, String key) {
try {
PrimaryKeyColumn[] primaryKeyColumns = new PrimaryKeyColumn[1];
primaryKeyColumns[0] = new PrimaryKeyColumn(primaryKeyName, PrimaryKeyValue.fromString(key));
PrimaryKey primaryKey = new PrimaryKey(primaryKeyColumns);
RowDeleteChange rowDeleteChange = new RowDeleteChange(table, primaryKey);
DeleteRowRequest deleteRowRequest = new DeleteRowRequest();
deleteRowRequest.setRowChange(rowDeleteChange);
client.deleteRow(deleteRowRequest);
return Status.OK;
} catch (TableStoreException e) {
return dealWithTableStoreException(e);
} catch (Exception e) {
LOGGER.error(e);
return Status.ERROR;
}
}
} | 3,554 |
486 | package jflex.maven.plugin.testsuite;
import com.google.common.base.Joiner;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import jflex.core.OptionUtils;
import jflex.exceptions.GeneratorException;
import jflex.exceptions.SilentExit;
import jflex.logging.Out;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Javac;
import org.apache.tools.ant.types.Path;
public class ExecUtils {
private ExecUtils() {}
private static final String JAVA_VERSION = "1.7";
public static final String NL = System.getProperty("line.separator");
/**
* Convert two Lists with String elements into one array containing all elements.
*
* @param a a List with String elements
* @param b a List with String elements
* @return an array containing all elements of a then b
*/
private static String[] toArray(List<String> a, List<String> b) {
if (a == null) a = new ArrayList<>();
if (b == null) b = new ArrayList<>();
String[] cmdline = new String[a.size() + b.size()];
int n = 0;
for (String aElem : a) cmdline[n++] = aElem;
for (String bElem : b) cmdline[n++] = bElem;
return cmdline;
}
/**
* Call javac on javaSourceFiles in input dir. If javaSourceFiles is {@code null}, all {@code
* *.java} files in the directory will be compiled.
*
* @param javaSourceFiles A list of files to compile, or {@code null}
* @param dir Source directory.
*/
public static TestResult execJavac(
List<String> javaSourceFiles, File dir, String additionalJars, String encoding)
throws FileNotFoundException {
// javac fails if an input file doesn't exist
checkFilesExist(javaSourceFiles, dir);
Project p = new Project();
Path path = new Path(p, dir.toString());
Javac javac = new Javac();
javac.setProject(p);
javac.setSrcdir(path);
javac.setDestdir(dir);
javac.setTarget(JAVA_VERSION);
javac.setSource(JAVA_VERSION);
javac.setSourcepath(new Path(p, "")); // Only compile explicitly specified source files
if (javaSourceFiles != null) {
javac.setIncludes(Joiner.on(' ').join(javaSourceFiles));
}
javac.setEncoding(encoding);
Path classPath = javac.createClasspath();
// Locate the jflex jar in the user's Maven local repository
classPath.setPath(additionalJars);
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream outSafe = System.err;
System.setErr(new PrintStream(out));
try {
javac.execute();
return new TestResult(out.toString(), true);
} catch (BuildException e) {
return new TestResult(e + NL + out.toString() + NL + "classpath: " + classPath, false);
} finally {
System.setErr(outSafe);
}
}
/** Call jflex with command line and input files. */
public static TestResult execJFlex(List<String> cmdline, List<String> files) {
String[] cmd = toArray(cmdline, files);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
OptionUtils.setDefaultOptions();
Out.setOutputStream(out);
jflex.Main.generate(cmd);
return new TestResult(out.toString(), true);
} catch (GeneratorException e) {
return new TestResult(out.toString(), false);
} catch (SilentExit e) {
return new TestResult(out.toString(), false);
}
}
/**
* Call main method of specified class with command line and input files.
*
* @param path the directory in which to search for the class
* @param additionalJars
*/
public static TestResult execClass(
String theClass,
String path,
List<String> files,
List<File> additionalJars,
String outputFileEncoding,
List<String> cmdline)
throws UnsupportedEncodingException {
String[] cmd = toArray(cmdline, files);
Class<?> c;
Method main;
Class<?>[] sig = {String[].class};
// System.out.println("exec class "+theClass);
// System.out.println("cmdline "+cmdline+"\nfiles: "+files);
CustomClassLoader l = new CustomClassLoader(path);
// Locate the shaded jar in the lib directory
// TODO(regisd) Alternatively, we could load JFlex and its dependency graph.
try {
for (File jar : additionalJars) {
// We are in $basedir/testsuite/testcases
l.addPath(jar);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
try {
c = l.loadClass(theClass, true);
} catch (ClassNotFoundException e) {
System.out.println("no such class: " + e);
return null;
}
try {
main = c.getMethod("main", sig);
} catch (NoSuchMethodException e) {
System.out.println("no main: " + e);
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean success = true;
// System.out.println("loaded class "+theClass);
PrintStream stdOut = System.out;
System.setOut(new PrintStream(out, true));
try {
Object[] params = {cmd};
main.invoke(null, params);
System.setOut(stdOut);
} catch (IllegalAccessException e) {
System.setOut(stdOut);
System.out.println("main not public :" + e + main);
return null;
} catch (InvocationTargetException e) {
System.setOut(stdOut);
System.out.println("test subject threw exception :" + e);
success = false;
}
// System.out.println("finished exec class "+theClass);
return new TestResult(out.toString(outputFileEncoding), success);
}
/**
* Checks that all files exist in the given directory.
*
* @throws FileNotFoundException when a file doesn't exist.
*/
private static void checkFilesExist(List<String> files, File dir) throws FileNotFoundException {
if (files != null) {
for (String src : files) {
File f = new File(dir, src);
if (!f.isFile()) {
throw new FileNotFoundException(f.getPath());
}
}
}
}
}
| 2,262 |
4,012 | <gh_stars>1000+
/*
*
* Copyright (c) 2019, NVIDIA CORPORATION.
*
* 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 ai.rapids.cudf;
enum MaskState {
UNALLOCATED(0),
UNINITIALIZED(1),
ALL_VALID(2),
ALL_NULL(3);
private static final MaskState[] MASK_STATES = MaskState.values();
final int nativeId;
MaskState(int nativeId) {
this.nativeId = nativeId;
}
static MaskState fromNative(int nativeId) {
for (MaskState type : MASK_STATES) {
if (type.nativeId == nativeId) {
return type;
}
}
throw new IllegalArgumentException("Could not translate " + nativeId + " into a MaskState");
}
}
| 387 |
533 | <reponame>thejprasadi/Sinhala-Text-To_Speech
import argparse
import tensorflow as tf
from synthesizer import Synthesizer
from models import create_model
from hparams import hparams, hparams_debug_string
from util import audio
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
'--checkpoint_path', required=True, help='path to model checkpoint'
)
parser.add_argument(
'--export_path', required=True, help='path to export model'
)
args = parser.parse_args()
builder = tf.saved_model.builder.SavedModelBuilder(args.export_path)
synth = Synthesizer()
synth.load(args.checkpoint_path)
inputs = tf.saved_model.utils.build_tensor_info(synth.model.inputs)
input_lengths = tf.saved_model.utils.build_tensor_info(
synth.model.input_lengths
)
w_o = audio.inv_spectrogram_tensorflow(
synth.model.linear_outputs
)
wav_output = tf.saved_model.utils.build_tensor_info(w_o)
alignment = tf.saved_model.utils.build_tensor_info(synth.model.alignments)
prediction_signature = (
tf.saved_model.signature_def_utils.build_signature_def(
inputs={
'inputs': inputs,
"input_lengths": input_lengths
},
outputs={
'wav_output': wav_output,
'alignment': alignment
},
method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME)
)
with synth.session as sess:
builder.add_meta_graph_and_variables(
sess=sess,
tags=[tf.saved_model.tag_constants.SERVING],
signature_def_map={'predict': prediction_signature}
)
builder.save()
print("exported .pb to", args.export_path)
| 788 |
3,301 | <filename>core/src/main/java/com/alibaba/alink/operator/common/recommendation/AlsModelInfo.java
package com.alibaba.alink.operator.common.recommendation;
import org.apache.flink.ml.api.misc.param.Params;
import com.alibaba.alink.operator.common.clustering.RecommendationModelInfo;
import com.alibaba.alink.operator.common.utils.PrettyDisplayUtils;
import com.alibaba.alink.params.recommendation.AlsTrainParams;
import java.util.HashMap;
import java.util.Map;
public class AlsModelInfo extends RecommendationModelInfo {
private static final long serialVersionUID = -7248721538070702182L;
/**
* Distinct user number.
*/
private int userNum;
/**
* Distinct item number.
*/
private int itemNum;
/**
* sample number.
*/
private int totalSamples;
/**
* Params
*/
private Params meta;
public AlsModelInfo() {
}
public AlsModelInfo(int userNum, int itemNum, int totalSamples, Params meta) {
this.userNum = userNum;
this.itemNum = itemNum;
this.totalSamples = totalSamples;
this.meta = meta;
}
@Override
public int getUserNumber() {
return userNum;
}
@Override
public int getItemNumber() {
return itemNum;
}
@Override
public int getTotalSamples() {
return totalSamples;
}
public int getNumFactors() {
return meta.get(AlsTrainParams.RANK);
}
public int getNumIters() {
return meta.get(AlsTrainParams.NUM_ITER);
}
public double getLambda() {
return meta.get(AlsTrainParams.LAMBDA);
}
@Override
public String toString() {
StringBuilder sbd = new StringBuilder();
sbd.append(modelSummaryHead("ALS"));
Map <String, Object> config = new HashMap <>();
config.put("NumFactors", getNumFactors());
config.put("NumIters", getNumIters());
config.put("Lambda", getLambda());
sbd.append(PrettyDisplayUtils.displayHeadline("Train Parameters", '-'));
sbd.append(PrettyDisplayUtils.displayMap(config, 5, true));
return sbd.toString();
}
}
| 688 |
1,590 | {
"title": "Create data export Event Hub destination",
"description": "Create an Event hub destination with an Id.",
"parameters": {
"baseDomain": "azureiotcentral.com",
"subdomain": "appsubdomain",
"destinationId": "destination1",
"api-version": "1.1-preview",
"body": {
"displayName": "Event Hub",
"type": "eventhubs@v1",
"authorization": {
"type": "connectionString",
"connectionString": "Endpoint=sb://[hubName].servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=[Key];EntityPath=entityPath1"
}
}
},
"responses": {
"200": {
"body": {
"id": "destination1",
"displayName": "Event Hub",
"type": "eventhubs@v1",
"authorization": {
"type": "connectionString",
"connectionString": "Endpoint=sb://[hubName].servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=*****;EntityPath=entityPath1"
},
"status": "waiting"
}
}
}
}
| 442 |
335 | /*
* Copyright 2019-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
package org.vividus.bdd.variable.ui;
import static com.github.valfirst.slf4jtest.LoggingEvent.error;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import java.util.List;
import com.github.valfirst.slf4jtest.TestLogger;
import com.github.valfirst.slf4jtest.TestLoggerFactory;
import org.apache.commons.lang3.NotImplementedException;
import org.junit.jupiter.api.Test;
import org.vividus.ui.context.UiContext;
class ContextProvidingDynamicVariableTests
{
private static final TestLogger LOGGER = TestLoggerFactory
.getTestLogger(AbstractContextProvidingDynamicVariable.class);
@Test
void shouldReturnMinuseOneInCaseOfMissingContext()
{
var dynamicVariable = new AbstractContextProvidingDynamicVariable(mock(UiContext.class))
{
@Override
public String getValue()
{
return getContextRectValue(r -> {
throw new NotImplementedException();
});
}
};
assertEquals("-1", dynamicVariable.getValue());
assertThat(LOGGER.getLoggingEvents(), is(List
.of(error("Unable to get coordinate, context is not set"))));
}
}
| 707 |
448 | <filename>src/test/java/com/googlecode/concurrentlinkedhashmap/generator/UniformIntegerGenerator.java
/**
* Copyright (c) 2010 Yahoo! 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. See accompanying
* LICENSE file.
*/
package com.googlecode.concurrentlinkedhashmap.generator;
import java.util.Random;
/**
* Generates integers randomly uniform from an interval.
*
* @author <NAME>
* @see <a href="http://research.yahoo.com/Web_Information_Management/YCSB">YCSB</a>
*/
public class UniformIntegerGenerator extends IntegerGenerator {
Random _random;
int _lb, _ub, _interval;
/**
* Creates a generator that will return integers uniformly randomly from the
* interval [lb,ub] inclusive (that is, lb and ub are possible values)
*
* @param lb the lower bound (inclusive) of generated values
* @param ub the upper bound (inclusive) of generated values
*/
public UniformIntegerGenerator(int lb, int ub) {
_random = new Random();
_lb = lb;
_ub = ub;
_interval = _ub - _lb + 1;
}
@Override
public int nextInt() {
int ret = _random.nextInt(_interval) + _lb;
setLastInt(ret);
return ret;
}
}
| 563 |
2,268 | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef C_IMPACT_EFFECTS_H
#define C_IMPACT_EFFECTS_H
#ifdef _WIN32
#pragma once
#endif
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Purpose: DustParticle emitter
//-----------------------------------------------------------------------------
class CDustParticle : public CSimpleEmitter
{
public:
CDustParticle( const char *pDebugName ) : CSimpleEmitter( pDebugName ) {}
//Create
static CDustParticle *Create( const char *pDebugName="dust" )
{
return new CDustParticle( pDebugName );
}
//Roll
virtual float UpdateRoll( SimpleParticle *pParticle, float timeDelta )
{
pParticle->m_flRoll += pParticle->m_flRollDelta * timeDelta;
pParticle->m_flRollDelta += pParticle->m_flRollDelta * ( timeDelta * -8.0f );
#ifdef _XBOX
//Cap the minimum roll
if ( fabs( pParticle->m_flRollDelta ) < 0.1f )
{
pParticle->m_flRollDelta = ( pParticle->m_flRollDelta > 0.0f ) ? 0.1f : -0.1f;
}
#else
if ( fabs( pParticle->m_flRollDelta ) < 0.5f )
{
pParticle->m_flRollDelta = ( pParticle->m_flRollDelta > 0.0f ) ? 0.5f : -0.5f;
}
#endif // _XBOX
return pParticle->m_flRoll;
}
//Velocity
virtual void UpdateVelocity( SimpleParticle *pParticle, float timeDelta )
{
Vector saveVelocity = pParticle->m_vecVelocity;
//Decellerate
static float dtime;
static float decay;
if ( dtime != timeDelta )
{
dtime = timeDelta;
float expected = 0.5;
decay = exp( log( 0.0001f ) * dtime / expected );
}
pParticle->m_vecVelocity = pParticle->m_vecVelocity * decay;
#ifdef _XBOX
//Cap the minimum speed
if ( pParticle->m_vecVelocity.LengthSqr() < (8.0f*8.0f) )
{
VectorNormalize( saveVelocity );
pParticle->m_vecVelocity = saveVelocity * 8.0f;
}
#else
if ( pParticle->m_vecVelocity.LengthSqr() < (32.0f*32.0f) )
{
VectorNormalize( saveVelocity );
pParticle->m_vecVelocity = saveVelocity * 32.0f;
}
#endif // _XBOX
}
//Alpha
virtual float UpdateAlpha( const SimpleParticle *pParticle )
{
float tLifetime = pParticle->m_flLifetime / pParticle->m_flDieTime;
float ramp = 1.0f - tLifetime;
//Non-linear fade
if ( ramp < 0.75f )
ramp *= ramp;
return ramp;
}
private:
CDustParticle( const CDustParticle & ); // not defined, not accessible
};
void GetColorForSurface( trace_t *trace, Vector *color );
#include "tier0/memdbgoff.h"
#endif // C_IMPACT_EFFECTS_H
| 1,003 |
5,133 | <reponame>Saljack/mapstruct
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.ap.test.nestedbeans.unmappable;
import java.util.List;
public class CarDto {
private String name;
private int year;
private List<WheelDto> wheels;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public List<WheelDto> getWheels() {
return wheels;
}
public void setWheels(List<WheelDto> wheels) {
this.wheels = wheels;
}
}
| 312 |
632 | <filename>src/dictionary/ion_master_table.h
/******************************************************************************/
/**
@file ion_master_table.h
@author <NAME>, <NAME>, <NAME>, <NAME>
@brief Master table API.
@details At compile time, the master table is either used, OR it is not
included at all. The directive, ION_USING_MASTER_TABLE controls
this.
If the master table is used, the assumption is that the user does
not bypass the master table and call dictionary_create directly.
If the master table is not used, the user must provide IDs directly
to dictionary creation and the onus is on the user to resolve
conflicts, if they occur.
@copyright Copyright 2017
The University of British Columbia,
IonDB Project Contributors (see AUTHORS.md)
@par Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
@par 1.Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
@par 2.Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
@par 3.Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
@par THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/******************************************************************************/
#if !defined(ION_MASTER_TABLE_H_)
#define ION_MASTER_TABLE_H_
#if defined(__cplusplus)
extern "C" {
#endif
#include "dictionary.h"
#include "../file/sd_stdio_c_iface.h"
#include "../file/kv_stdio_intercept.h"
#include "bpp_tree/bpp_tree_handler.h"
#include "flat_file/flat_file_dictionary_handler.h"
#include "open_address_file_hash/open_address_file_hash_dictionary_handler.h"
#include "open_address_hash/open_address_hash_dictionary_handler.h"
#include "skip_list/skip_list_handler.h"
#include "linear_hash/linear_hash_handler.h"
#define ION_MASTER_TABLE_CALCULATE_POS -1
#define ION_MASTER_TABLE_WRITE_FROM_END -2
#define ION_MASTER_TABLE_RECORD_SIZE(cp) (sizeof((cp)->id) + sizeof((cp)->use_type) + sizeof((cp)->type) + sizeof((cp)->key_size) + sizeof((cp)->value_size) + sizeof((cp)->dictionary_size) + sizeof((cp)->dictionary_type) + sizeof((cp)->dictionary_status))
#if ION_USING_MASTER_TABLE
/**
@brief File name for IonDB master table.
@details Needs to be relatively short for devices.
*/
#define ION_MASTER_TABLE_FILENAME "ion_mt.tbl"
/**
@brief ID of the master table.
*/
#define ION_MASTER_TABLE_ID 0
/**
@brief Flag used when searching master table; search for first instance
matching criteria.
*/
#define ION_MASTER_TABLE_FIND_FIRST 1
/**
@brief Flag used when searching master table; search for last instance
matching criteria.
*/
#define ION_MASTER_TABLE_FIND_LAST -1
/**
@brief Master table resposible for managing instances.
*/
extern ion_dictionary_id_t ion_master_table_next_id;
/**
@brief Master table file.
*/
extern FILE *ion_master_table_file;
/**
@brief Write a record to the master table.
@details Automatically, this call will reposition the file position
back to where it was once the call is complete.
@param[in] config
A pointer to a previously allocated config object to write from.
@param[in] where
An integral value representing where to write to in the file.
This file offset is byte-aligned, not record aligned, in general.
Two special flags can be passed in here:
- @c ION_MASTER_TABLE_CALCULATE_POS
Calculate the position based on the passed-in config id.
- @c ION_MASTER_TABLE_WRITE_FROM_END
Write the record at the end of the file.
@returns An error code describing the result of the call.
*/
ion_err_t
ion_master_table_write(
ion_dictionary_config_info_t *config,
long where
);
/**
@brief Opens the master table.
@details Can be safely called multiple times without closing.
*/
ion_err_t
ion_init_master_table(
void
);
/**
@brief Closes the master table.
*/
ion_err_t
ion_close_master_table(
void
);
/**
@brief Closes the master table and all dictionary instances within it.
@details For this method to work properly, all dictionary instances must already
be closed or must have been closed previously and are now re-opened.
*/
ion_err_t
ion_close_all_master_table(
void
);
/**
@brief Deletes the master table.
*/
ion_err_t
ion_delete_master_table(
void
);
/**
@brief Creates a dictionary through use of the master table.
@param handler
A pointer to an allocated and initialized dictionary handler
object that contains all implementation specific data
and function pointers.
@param dictionary
A pointer to an allocated dictionary object, which will be
written into when opened.
@param key_type
The type of key to be used with this dictionary, which
determines the key comparison operator.
@param key_size
The size of the key type to be used with this dictionary.
@param value_size
The size of the value type to be used with this dictionary.
@param dictionary_size
The dictionary implementation specific dictionary size
parameter.
@returns An error code describing the result of the operation.
*/
ion_err_t
ion_master_table_create_dictionary(
ion_dictionary_handler_t *handler,
ion_dictionary_t *dictionary,
ion_key_type_t key_type,
ion_key_size_t key_size,
ion_value_size_t value_size,
ion_dictionary_size_t dictionary_size
);
/**
@brief Looks up the config of the given id.
@param id
The identifier identifying the dictionary metadata in the
master table which is to be looked up.
@param config
A pointer to an already allocated configuration object
that will be read into from the master table.
*/
ion_err_t
ion_lookup_in_master_table(
ion_dictionary_id_t id,
ion_dictionary_config_info_t *config
);
/**
@brief Find first or last dictionary in master table with a given use.
@param config
A pointer to an already allocated configuration object
that will be used to open the found dictionary.
@param use_type
The integral usage type for the dictionary. This is
user defined.
@param whence
Whether to find the first or the last dictionary
having @p use_type. This can take exactly two values,
@ref ION_MASTER_TABLE_FIND_FIRST or
@ref ION_MASTER_TABLE_FIND_LAST.
@returns @c err_ok if a dictionary having usage type @p use_type
is found, otherwise an error code properly describing
the situation and outcome.
*/
ion_err_t
ion_find_by_use_master_table(
ion_dictionary_config_info_t *config,
ion_dict_use_t use_type,
char whence
);
/**
@brief Deletes a dictionary from the master table.
@param id
The identifier identifying the dictionary metadata in the
master table.
@returns An error code describing the result of the operation.
*/
ion_err_t
ion_delete_from_master_table(
ion_dictionary_id_t id
);
/**
@brief Finds the target dictionary and opens it.
@param handler
A pointer to the handler object to be initialized.
@param dictionary
A pointer to the dictionary object to open.
@param id
The identifier identifying the dictionary metadata in the
master table.
@returns An error code describing the result of the operation.
*/
ion_err_t
ion_open_dictionary(
ion_dictionary_handler_t *handler,
ion_dictionary_t *dictionary,
ion_dictionary_id_t id
);
/**
@brief Closes a given dictionary.
@param dictionary
A pointer to the dictionary object to close.
*/
ion_err_t
ion_close_dictionary(
ion_dictionary_t *dictionary
);
/**
@brief Deletes a given dictionary instance and deletes it from the master
table.
@param dictionary
A pointer to the dictionary object to delete.
@param id
The identifier identifying the dictionary metadata in the
master table. Required to delete a closed dictionary without
reopening it.
*/
ion_err_t
ion_delete_dictionary(
ion_dictionary_t *dictionary,
ion_dictionary_id_t id
);
/**
@brief Retrieves the type of dictionary stored under a particular id in the
master table.
@param type
The type of dictionary instance to initialize the handler to.
@param handler
A pointer to the handler to be set.
@returns An error code describing the result of the operation.
*/
ion_err_t
ion_switch_handler(
ion_dictionary_type_t type,
ion_dictionary_handler_t *handler
);
/**
@brief Returns the next dictionary ID, then increments.
@param id
An identifier pointer to be written into.
@returns An error code describing the result of the operation.
*/
ion_err_t
ion_master_table_get_next_id(
ion_dictionary_id_t *id
);
/**
@brief Retrieves the type of dictionary stored under a particular id in the
master table.
@param id
The identifier identifying the dictionary metadata in the
master table.
@returns The type of dictionary implementation corresponding to the id.
*/
ion_dictionary_type_t
ion_get_dictionary_type(
ion_dictionary_id_t id
);
#if defined(__cplusplus)
}
#endif /* C++ Guard */
#endif /* ION_USING_MASTER_TABLE */
#endif /* ION_MASTER_TABLE_H_ */
| 3,340 |
703 | #include <FoundationTest/FoundationTestPCH.h>
#include <Foundation/Configuration/CVar.h>
ezCVarInt CVar_TestPlugin1InitializedCount("TestPlugin1InitCount", 0, ezCVarFlags::None, "How often Plugin1 has been initialized.");
ezCVarInt CVar_TestPlugin1UninitializedCount("TestPlugin1UninitCount", 0, ezCVarFlags::None, "How often Plugin1 has been uninitialized.");
ezCVarInt CVar_TestPlugin1Reloaded("TestPlugin1Reloaded", 0, ezCVarFlags::None, "How often Plugin1 has been reloaded (counts init AND de-init).");
ezCVarInt CVar_TestPlugin2InitializedCount("TestPlugin2InitCount", 0, ezCVarFlags::None, "How often Plugin2 has been initialized.");
ezCVarInt CVar_TestPlugin2UninitializedCount("TestPlugin2UninitCount", 0, ezCVarFlags::None, "How often Plugin2 has been uninitialized.");
ezCVarInt CVar_TestPlugin2Reloaded("TestPlugin2Reloaded", 0, ezCVarFlags::None, "How often Plugin2 has been reloaded (counts init AND de-init).");
ezCVarBool CVar_TestPlugin2FoundDependencies("TestPlugin2FoundDependencies", false, ezCVarFlags::None, "Whether Plugin2 found all its dependencies (other plugins).");
EZ_CREATE_SIMPLE_TEST(Configuration, Plugin)
{
CVar_TestPlugin1InitializedCount = 0;
CVar_TestPlugin1UninitializedCount = 0;
CVar_TestPlugin1Reloaded = 0;
CVar_TestPlugin2InitializedCount = 0;
CVar_TestPlugin2UninitializedCount = 0;
CVar_TestPlugin2Reloaded = 0;
CVar_TestPlugin2FoundDependencies = false;
#if EZ_ENABLED(EZ_SUPPORTS_DYNAMIC_PLUGINS)
EZ_TEST_BLOCK(ezTestBlock::Enabled, "LoadPlugin")
{
EZ_TEST_BOOL(ezPlugin::LoadPlugin(ezFoundationTest_Plugin2) == EZ_SUCCESS);
EZ_TEST_BOOL(ezPlugin::LoadPlugin(ezFoundationTest_Plugin2, ezPluginLoadFlags::PluginIsOptional) == EZ_SUCCESS); // loading already loaded plugin is always a success
EZ_TEST_INT(CVar_TestPlugin1InitializedCount, 1);
EZ_TEST_INT(CVar_TestPlugin2InitializedCount, 1);
EZ_TEST_INT(CVar_TestPlugin1UninitializedCount, 0);
EZ_TEST_INT(CVar_TestPlugin2UninitializedCount, 0);
EZ_TEST_INT(CVar_TestPlugin1Reloaded, 0);
EZ_TEST_INT(CVar_TestPlugin2Reloaded, 0);
EZ_TEST_BOOL(CVar_TestPlugin2FoundDependencies);
// this will fail the FoundationTests, as it logs an error
// EZ_TEST_BOOL(ezPlugin::LoadPlugin("Test") == EZ_FAILURE); // plugin does not exist
}
EZ_TEST_BLOCK(ezTestBlock::Enabled, "UnloadPlugin")
{
CVar_TestPlugin2FoundDependencies = false;
ezPlugin::UnloadAllPlugins();
EZ_TEST_INT(CVar_TestPlugin1InitializedCount, 1);
EZ_TEST_INT(CVar_TestPlugin2InitializedCount, 1);
EZ_TEST_INT(CVar_TestPlugin1UninitializedCount, 1);
EZ_TEST_INT(CVar_TestPlugin2UninitializedCount, 1);
EZ_TEST_INT(CVar_TestPlugin1Reloaded, 0);
EZ_TEST_INT(CVar_TestPlugin2Reloaded, 0);
EZ_TEST_BOOL(CVar_TestPlugin2FoundDependencies);
EZ_TEST_BOOL(ezPlugin::LoadPlugin("Test", ezPluginLoadFlags::PluginIsOptional) == EZ_FAILURE); // plugin does not exist
}
#endif
}
| 1,083 |
348 | <filename>docs/data/leg-t2/017/01705411.json
{"nom":"Saint-Trojan-les-Bains","circ":"5ème circonscription","dpt":"Charente-Maritime","inscrits":1135,"abs":621,"votants":514,"blancs":45,"nuls":16,"exp":453,"res":[{"nuance":"LR","nom":"<NAME>","voix":249},{"nuance":"DIV","nom":"<NAME>","voix":204}]} | 121 |
2,833 | #!/usr/bin/env python
from getpass import getpass
from pprint import pprint
from netmiko import ConnectHandler
device = {
"device_type": "cisco_ios",
"host": "cisco1.lasthop.io",
"username": "pyclass",
"password": getpass(),
}
with ConnectHandler(**device) as net_connect:
output = net_connect.send_command("show ip interface brief", use_genie=True)
print()
pprint(output)
print()
| 145 |
848 | {
"kernel_name": "opticalFlowOpenCV",
"description": "Run OpenCV's Optical Flow algorithm on pair of images",
"kernel_type": "cpp",
"device_type": "cpu",
"kernel_lib" : "libs/libOpticalFlowOpenCV.so",
"num_cu": 12,
"param_list" : {
"of_algorithm": {"type": "string"}
}
}
| 127 |
2,392 | // This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2016 <NAME> <<EMAIL>>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "per_vertex_point_to_plane_quadrics.h"
#include "quadric_binary_plus_operator.h"
#include <Eigen/QR>
#include <cassert>
#include <cmath>
IGL_INLINE void igl::per_vertex_point_to_plane_quadrics(
const Eigen::MatrixXd & V,
const Eigen::MatrixXi & F,
const Eigen::MatrixXi & EMAP,
const Eigen::MatrixXi & EF,
const Eigen::MatrixXi & EI,
std::vector<
std::tuple<Eigen::MatrixXd,Eigen::RowVectorXd,double> > & quadrics)
{
using namespace std;
typedef std::tuple<Eigen::MatrixXd,Eigen::RowVectorXd,double> Quadric;
const int dim = V.cols();
//// Quadrics per face
//std::vector<Quadric> face_quadrics(F.rows());
// Initialize each vertex quadric to zeros
quadrics.resize(
V.rows(),
// gcc <=4.8 can't handle initializer lists correctly
Quadric{Eigen::MatrixXd::Zero(dim,dim),Eigen::RowVectorXd::Zero(dim),0});
Eigen::MatrixXd I = Eigen::MatrixXd::Identity(dim,dim);
// Rather initial with zeros, initial with a small amount of energy pull
// toward original vertex position
const double w = 1e-10;
for(int v = 0;v<V.rows();v++)
{
std::get<0>(quadrics[v]) = w*I;
Eigen::RowVectorXd Vv = V.row(v);
std::get<1>(quadrics[v]) = w*-Vv;
std::get<2>(quadrics[v]) = w*Vv.dot(Vv);
}
// Generic nD qslim from "Simplifying Surfaces with Color and Texture
// using Quadric Error Metric" (follow up to original QSlim)
for(int f = 0;f<F.rows();f++)
{
int infinite_corner = -1;
for(int c = 0;c<3;c++)
{
if(
std::isinf(V(F(f,c),0)) ||
std::isinf(V(F(f,c),1)) ||
std::isinf(V(F(f,c),2)))
{
assert(infinite_corner == -1 && "Should only be one infinite corner");
infinite_corner = c;
}
}
// Inputs:
// p 1 by n row point on the subspace
// S m by n matrix where rows coorespond to orthonormal spanning
// vectors of the subspace to which we're measuring distance (usually
// a plane, m=2)
// weight scalar weight
// Returns quadric triple {A,b,c} so that A-2*b+c measures the quadric
const auto subspace_quadric = [&I](
const Eigen::RowVectorXd & p,
const Eigen::MatrixXd & S,
const double weight)->Quadric
{
// Dimension of subspace
const int m = S.rows();
// Weight face's quadric (v'*A*v + 2*b'*v + c) by area
// e1 and e2 should be perpendicular
Eigen::MatrixXd A = I;
Eigen::RowVectorXd b = -p;
double c = p.dot(p);
for(int i = 0;i<m;i++)
{
Eigen::RowVectorXd ei = S.row(i);
for(int j = 0;j<i;j++) assert(std::abs(S.row(j).dot(ei)) < 1e-10);
A += -ei.transpose()*ei;
b += p.dot(ei)*ei;
c += -pow(p.dot(ei),2);
}
// gcc <=4.8 can't handle initializer lists correctly: needs explicit
// cast
return Quadric{ weight*A, weight*b, weight*c };
};
if(infinite_corner == -1)
{
// Finite (non-boundary) face
Eigen::RowVectorXd p = V.row(F(f,0));
Eigen::RowVectorXd q = V.row(F(f,1));
Eigen::RowVectorXd r = V.row(F(f,2));
Eigen::RowVectorXd pq = q-p;
Eigen::RowVectorXd pr = r-p;
// Gram Determinant = squared area of parallelogram
double area = sqrt(pq.squaredNorm()*pr.squaredNorm()-pow(pr.dot(pq),2));
Eigen::RowVectorXd e1 = pq.normalized();
Eigen::RowVectorXd e2 = (pr-e1.dot(pr)*e1).normalized();
Eigen::MatrixXd S(2,V.cols());
S<<e1,e2;
Quadric face_quadric = subspace_quadric(p,S,area);
// Throw at each corner
for(int c = 0;c<3;c++)
{
quadrics[F(f,c)] = quadrics[F(f,c)] + face_quadric;
}
}else
{
// cth corner is infinite --> edge opposite cth corner is boundary
// Boundary edge vector
const Eigen::RowVectorXd p = V.row(F(f,(infinite_corner+1)%3));
Eigen::RowVectorXd ev = V.row(F(f,(infinite_corner+2)%3)) - p;
const double length = ev.norm();
ev /= length;
// Face neighbor across boundary edge
int e = EMAP(f+F.rows()*infinite_corner);
int opp = EF(e,0) == f ? 1 : 0;
int n = EF(e,opp);
int nc = EI(e,opp);
assert(
((F(f,(infinite_corner+1)%3) == F(n,(nc+1)%3) &&
F(f,(infinite_corner+2)%3) == F(n,(nc+2)%3)) ||
(F(f,(infinite_corner+1)%3) == F(n,(nc+2)%3)
&& F(f,(infinite_corner+2)%3) == F(n,(nc+1)%3))) &&
"Edge flaps not agreeing on shared edge");
// Edge vector on opposite face
const Eigen::RowVectorXd eu = V.row(F(n,nc)) - p;
assert(!std::isinf(eu(0)));
// Matrix with vectors spanning plane as columns
Eigen::MatrixXd A(ev.size(),2);
A<<ev.transpose(),eu.transpose();
// Use QR decomposition to find basis for orthogonal space
Eigen::HouseholderQR<Eigen::MatrixXd> qr(A);
const Eigen::MatrixXd Q = qr.householderQ();
const Eigen::MatrixXd N =
Q.topRightCorner(ev.size(),ev.size()-2).transpose();
assert(N.cols() == ev.size());
assert(N.rows() == ev.size()-2);
Eigen::MatrixXd S(N.rows()+1,ev.size());
S<<ev,N;
Quadric boundary_edge_quadric = subspace_quadric(p,S,length);
for(int c = 0;c<3;c++)
{
if(c != infinite_corner)
{
quadrics[F(f,c)] = quadrics[F(f,c)] + boundary_edge_quadric;
}
}
}
}
}
| 2,640 |
8,586 | <filename>src/common/fs/test/TempFileTest.cpp
/* Copyright (c) 2018 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*/
#include <gtest/gtest.h>
#include "common/base/Base.h"
#include "common/fs/TempFile.h"
namespace nebula {
namespace fs {
TEST(TempFile, Basic) {
// auto deletion
{
const char *path = "/tmp/tmp.XXXXXX";
std::string actual_path;
{
TempFile tmp(path);
// same length
ASSERT_EQ(::strlen(path), ::strlen(tmp.path()));
// not equal to the template
ASSERT_STRNE(path, tmp.path());
// match to the pattern
const std::regex pattern(R"(/tmp/tmp\.[0-9a-zA-Z]{6})");
ASSERT_TRUE(std::regex_match(tmp.path(), pattern)) << tmp.path();
// accessible
ASSERT_EQ(0, ::access(tmp.path(), F_OK));
// save the path
actual_path = tmp.path();
}
// now not accessible
ASSERT_EQ(-1, ::access(actual_path.c_str(), F_OK));
}
// no deletion
{
const char *path = "/tmp/tmp.XXXXXX";
std::string actual_path;
{
TempFile tmp(path, false);
// same length
ASSERT_EQ(::strlen(path), ::strlen(tmp.path()));
// not equal to the template
ASSERT_STRNE(path, tmp.path());
// match to the pattern
const std::regex pattern(R"(/tmp/tmp\.[0-9a-zA-Z]{6})");
ASSERT_TRUE(std::regex_match(tmp.path(), pattern)) << tmp.path();
// accessible
ASSERT_EQ(0, ::access(tmp.path(), F_OK));
// save the path
actual_path = tmp.path();
}
// now not accessible
ASSERT_EQ(0, ::access(actual_path.c_str(), F_OK));
ASSERT_EQ(0, ::unlink(actual_path.c_str()));
}
}
} // namespace fs
} // namespace nebula
| 746 |
348 | <reponame>mikiec84/ichnaea<gh_stars>100-1000
from datetime import timedelta
from ichnaea.api.locate.constants import DataSource, MAX_WIFIS_IN_CLUSTER
from ichnaea.api.locate.score import station_score
from ichnaea.api.locate.source import PositionSource
from ichnaea.api.locate.tests.base import BaseSourceTest
from ichnaea.api.locate.wifi import WifiPositionMixin
from ichnaea.tests.factories import WifiShardFactory
from ichnaea import util
class WifiTestPositionSource(WifiPositionMixin, PositionSource):
fallback_field = None
source = DataSource.internal
def should_search(self, query, results):
return self.should_search_wifi(query, results)
def search(self, query):
return self.search_wifi(query)
class TestWifi(BaseSourceTest):
Source = WifiTestPositionSource
def test_wifi(self, geoip_db, http_session, session, source):
wifi = WifiShardFactory(radius=5, samples=50)
wifi2 = WifiShardFactory(
lat=wifi.lat, lon=wifi.lon + 0.00001, radius=5, samples=100
)
session.flush()
query = self.model_query(geoip_db, http_session, session, wifis=[wifi, wifi2])
query.wifi[0].signalStrength = -60
query.wifi[1].signalStrength = -80
results = source.search(query)
self.check_model_results(results, [wifi], lon=wifi.lon + 0.000004)
assert results.best().score > 1.0
def test_wifi_no_position(self, geoip_db, http_session, session, source):
wifi = WifiShardFactory()
wifi2 = WifiShardFactory(lat=wifi.lat, lon=wifi.lon)
wifi3 = WifiShardFactory(lat=None, lon=wifi.lon, radius=None)
session.flush()
query = self.model_query(
geoip_db, http_session, session, wifis=[wifi, wifi2, wifi3]
)
results = source.search(query)
self.check_model_results(results, [wifi])
def test_wifi_temp_blocked(self, geoip_db, http_session, session, source):
today = util.utcnow()
yesterday = today - timedelta(days=1)
wifi = WifiShardFactory(radius=200)
wifi2 = WifiShardFactory(
lat=wifi.lat,
lon=wifi.lon + 0.00001,
radius=300,
created=yesterday,
modified=today,
block_first=yesterday.date(),
block_last=yesterday.date(),
block_count=1,
)
session.flush()
query = self.model_query(geoip_db, http_session, session, wifis=[wifi, wifi2])
results = source.search(query)
self.check_model_results(results, None)
def test_wifi_permanent_blocked(self, geoip_db, http_session, session, source):
now = util.utcnow()
last_week = now - timedelta(days=7)
three_months = now - timedelta(days=90)
four_months = now - timedelta(days=120)
wifi = WifiShardFactory(radius=200)
wifi2 = WifiShardFactory(
lat=wifi.lat,
lon=wifi.lon + 0.00001,
radius=300,
created=four_months,
modified=now,
block_first=three_months.date(),
block_last=last_week.date(),
block_count=4,
)
session.flush()
query = self.model_query(geoip_db, http_session, session, wifis=[wifi, wifi2])
results = source.search(query)
self.check_model_results(results, None)
def test_check_empty(self, geoip_db, http_session, session, source):
query = self.model_query(geoip_db, http_session, session)
results = source.result_list()
assert not source.should_search(query, results)
def test_empty(
self, geoip_db, http_session, raven, redis, session_tracker, session, source
):
query = self.model_query(geoip_db, http_session, session)
results = source.search(query)
self.check_model_results(results, None)
session_tracker(0)
def test_few_candidates(self, geoip_db, http_session, session, source):
wifis = WifiShardFactory.create_batch(2)
session.flush()
query = self.model_query(geoip_db, http_session, session, wifis=[wifis[0]])
results = source.search(query)
self.check_model_results(results, None)
def test_few_matches(self, geoip_db, http_session, session, source):
wifis = WifiShardFactory.create_batch(3)
wifis[0].lat = None
session.flush()
query = self.model_query(geoip_db, http_session, session, wifis=wifis[:2])
results = source.search(query)
self.check_model_results(results, None)
def test_ignore_outlier(self, geoip_db, http_session, session, source):
wifi = WifiShardFactory()
wifis = WifiShardFactory.create_batch(3, lat=wifi.lat, lon=wifi.lon, radius=5)
wifis[0].lat = wifi.lat + 0.00001
wifis[1].lat = wifi.lat + 0.00002
wifis[2].lat = wifi.lat + 1.0
session.flush()
query = self.model_query(geoip_db, http_session, session, wifis=[wifi] + wifis)
results = source.search(query)
self.check_model_results(results, [wifi], lat=wifi.lat + 0.00001)
assert round(results.best().score, 4) == 0.15
def test_not_closeby(self, geoip_db, http_session, session, source):
wifi = WifiShardFactory()
wifis = [
WifiShardFactory(lat=wifi.lat + 0.00001, lon=wifi.lon),
WifiShardFactory(lat=wifi.lat + 1.0, lon=wifi.lon),
WifiShardFactory(lat=wifi.lat + 1.00001, lon=wifi.lon),
]
session.flush()
query = self.model_query(
geoip_db, http_session, session, wifis=[wifi, wifis[1]]
)
results = source.search(query)
self.check_model_results(results, None)
def test_multiple_clusters(self, geoip_db, http_session, session, source):
wifi11 = WifiShardFactory()
wifi12 = WifiShardFactory(lat=wifi11.lat, lon=wifi11.lon)
wifi21 = WifiShardFactory(lat=wifi11.lat + 1.0, lon=wifi11.lon + 1.0)
wifi22 = WifiShardFactory(lat=wifi21.lat, lon=wifi21.lon)
session.flush()
query = self.model_query(
geoip_db, http_session, session, wifis=[wifi11, wifi12, wifi21, wifi22]
)
query.wifi[0].signalStrength = -100
query.wifi[1].signalStrength = -80
query.wifi[2].signalStrength = -100
query.wifi[3].signalStrength = -54
results = source.search(query)
self.check_model_results(results, [wifi11, wifi21])
def test_cluster_score_over_size(self, geoip_db, http_session, session, source):
now = util.utcnow()
yesterday = now - timedelta(days=1)
last_week = now - timedelta(days=7)
three_months = now - timedelta(days=90)
four_months = now - timedelta(days=120)
wifi11 = WifiShardFactory(samples=20, created=last_week, modified=yesterday)
wifi12 = WifiShardFactory(
lat=wifi11.lat + 0.00003,
lon=wifi11.lon,
samples=30,
created=yesterday,
modified=now,
)
wifi13 = WifiShardFactory(
lat=wifi11.lat - 0.00003,
lon=wifi11.lon,
samples=10,
created=yesterday,
modified=now,
)
wifi21 = WifiShardFactory(
lat=wifi11.lat + 1.0,
lon=wifi11.lon + 1.0,
samples=40,
created=four_months,
modified=three_months,
)
wifi22 = WifiShardFactory(
lat=wifi21.lat,
lon=wifi21.lon,
samples=50,
created=three_months,
modified=last_week,
)
session.flush()
query = self.model_query(
geoip_db,
http_session,
session,
wifis=[wifi11, wifi12, wifi13, wifi21, wifi22],
)
results = source.search(query)
assert len(results) == 2
best_result = results.best()
assert round(best_result.lat, 7) == round(wifi21.lat, 7)
assert round(best_result.lon, 7) == round(wifi21.lon, 7)
assert round(best_result.accuracy, 2) == 10.0
assert round(best_result.score, 2) == round(
station_score(wifi21, now) + station_score(wifi22, now), 2
)
other_result = [res for res in results if res.score < best_result.score][0]
assert round(other_result.lat, 4) == round(wifi11.lat, 4)
assert round(other_result.lon, 4) == round(wifi11.lon, 4)
def test_top_results_in_noisy_cluster(
self, geoip_db, http_session, session, source
):
now = util.utcnow()
# all these should wind up in the same cluster since
# the WiFis are spaced in increments of (+0.1m, +0.12m)
wifi1 = WifiShardFactory.build()
wifis = []
for i in range(0, MAX_WIFIS_IN_CLUSTER + 10):
wifis.append(
WifiShardFactory(
lat=wifi1.lat + i * 0.000001,
lon=wifi1.lon + i * 0.0000012,
samples=100 - i,
)
)
session.flush()
# calculate expected result
score = sum([station_score(wifi, now) for wifi in wifis])
query = self.model_query(geoip_db, http_session, session, wifis=wifis)
for i, entry in enumerate(query.wifi):
entry.signalStrength = -50 - i
results = source.search(query)
result = results.best()
assert round(result.lat, 4) == round(wifi1.lat, 4)
assert round(result.lon, 4) == round(wifi1.lon, 4)
assert round(result.score, 4) == round(score, 4)
def test_weight(self, geoip_db, http_session, session, source):
wifi1 = WifiShardFactory.build()
wifis = []
for i in range(4):
wifis.append(
WifiShardFactory(
lat=wifi1.lat + i * 0.0001, lon=wifi1.lon + i * 0.00012
)
)
session.flush()
query = self.model_query(geoip_db, http_session, session, wifis=wifis)
query.wifi[0].signalStrength = -10
query.wifi[0].age = 0
query.wifi[1].signalStrength = -40
query.wifi[1].age = 8000
query.wifi[2].signalStrength = -70
query.wifi[2].age = 16000
query.wifi[3].signalStrength = -100
results = source.search(query)
result = results.best()
assert round(result.lat, 7) == wifi1.lat + 0.0000009
assert round(result.lon, 7) == wifi1.lon + 0.0000006
assert round(result.accuracy, 2) == 39.51
| 5,077 |
645 | // Copyright 2012 Viewfinder. All rights reserved.
// Author: <NAME>.
#ifndef VIEWFINDER_SERVER_UTILS_H
#define VIEWFINDER_SERVER_UTILS_H
#import "JsonUtils.h"
#import "Server.pb.h"
bool IsS3RequestTimeout(int status, const Slice& data);
string EncodeAssetKey(const Slice& url, const Slice& fingerprint);
bool DecodeAssetKey(Slice key, Slice* url, Slice* fingerprint);
bool ParseAuthResponse(
AuthResponse* r, const string& data);
bool ParseErrorResponse(
ErrorResponse* r, const string& data);
bool ParsePingResponse(
PingResponse* p, const string& data);
bool ParseQueryContactsResponse(
QueryContactsResponse* r, ContactSelection* cs,
int limit, const string& data);
bool ParseQueryEpisodesResponse(
QueryEpisodesResponse* r, vector<EpisodeSelection>* v,
int limit, const string& data);
bool ParseQueryFollowedResponse(
QueryFollowedResponse* r, const string& data);
bool ParseQueryNotificationsResponse(
QueryNotificationsResponse* r, NotificationSelection* ns,
int limit, const string& data);
bool ParseQueryUsersResponse(
QueryUsersResponse* r, const string& data);
bool ParseQueryViewpointsResponse(
QueryViewpointsResponse* r, vector<ViewpointSelection>* v,
int limit, const string& data);
bool ParseResolveContactsResponse(
ResolveContactsResponse* r, const string& data);
bool ParseServerSubscriptionMetadata(
ServerSubscriptionMetadata* sub, const JsonRef& dict);
bool ParseUploadContactsResponse(
UploadContactsResponse* r, const string& data);
bool ParseUploadEpisodeResponse(
UploadEpisodeResponse* r, const string& data);
#endif // VIEWFINDER_SERVER_UTILS_H
| 524 |
2,151 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef IOS_CHROME_BROWSER_UI_COMMANDS_SNACKBAR_COMMANDS_H_
#define IOS_CHROME_BROWSER_UI_COMMANDS_SNACKBAR_COMMANDS_H_
#import <Foundation/Foundation.h>
@class MDCSnackbarMessage;
// Commands related to Snackbar.
@protocol SnackbarCommands
// Shows a snackbar with |message|.
- (void)showSnackbarMessage:(MDCSnackbarMessage*)message;
@end
#endif // IOS_CHROME_BROWSER_UI_COMMANDS_SNACKBAR_COMMANDS_H_
| 216 |
10,016 | <reponame>eas5/zaproxy
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2017 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.view.panelsearch.items;
import java.awt.Color;
import javax.swing.JComponent;
import javax.swing.JSpinner;
import org.zaproxy.zap.view.panelsearch.ComponentWithBackground;
import org.zaproxy.zap.view.panelsearch.HighlightedComponent;
import org.zaproxy.zap.view.panelsearch.HighlighterUtils;
import org.zaproxy.zap.view.panelsearch.JComponentWithBackground;
import org.zaproxy.zap.view.panelsearch.SearchQuery;
public class SpinnerSearch extends AbstractComponentSearch<JSpinner> {
private static final String HIGHLIGHTED_EDITOR = "highlightedEditorComponent";
@Override
protected boolean isSearchMatchingInternal(JSpinner component, SearchQuery query) {
return query.match(component.getValue().toString());
}
@Override
protected HighlightedComponent highlightInternal(JSpinner component) {
HighlightedComponent highlightedUpAndDownComponent =
HighlighterUtils.highlightBackground(
new JComponentWithBackground(component),
HighlighterUtils.getHighlightColor());
HighlightedComponent highlightedEditorComponent =
HighlighterUtils.highlightBackground(
new SpinnerSearchComponentWithBackground(component),
HighlighterUtils.getHighlightColor());
highlightedUpAndDownComponent.put(HIGHLIGHTED_EDITOR, highlightedEditorComponent);
return highlightedUpAndDownComponent;
}
@Override
protected void undoHighlightInternal(
HighlightedComponent highlightedComponent, JSpinner component) {
HighlightedComponent highlightedUpAndDownComponent = highlightedComponent;
HighlightedComponent highlightedEditorComponent =
highlightedUpAndDownComponent.get(HIGHLIGHTED_EDITOR);
HighlighterUtils.undoHighlightBackground(
new JComponentWithBackground(component), highlightedUpAndDownComponent);
HighlighterUtils.undoHighlightBackground(
new SpinnerSearchComponentWithBackground(component), highlightedEditorComponent);
}
private static class SpinnerSearchComponentWithBackground extends ComponentWithBackground {
private JSpinner component;
public SpinnerSearchComponentWithBackground(JSpinner component) {
this.component = component;
}
@Override
public Object getComponent() {
return component;
}
@Override
public void setBackground(Color color) {
getEditor().setBackground(color);
}
private JComponent getEditor() {
return component.getEditor();
}
@Override
public Color getBackground() {
return getEditor().getBackground();
}
@Override
public void setOpaque(boolean isOpaque) {
getEditor().setOpaque(isOpaque);
}
@Override
public boolean isOpaque() {
return getEditor().isOpaque();
}
}
}
| 1,371 |
1,340 | <filename>Sources/MetalPetalObjectiveC/include/MTIContext+Internal.h
//
// MTIContext+Internal.h
// MetalPetal
//
// Created by <NAME> on 07/01/2018.
//
#import <Metal/Metal.h>
#import <MetalKit/MetalKit.h>
#import <CoreImage/CoreImage.h>
#import <CoreVideo/CoreVideo.h>
#if __has_include(<MetalPetal/MetalPetal.h>)
#import <MetalPetal/MTIContext.h>
#else
#import "MTIContext.h"
#endif
@class MTIImage;
@protocol MTIKernelConfiguration, MTIKernel, MTIImagePromise;
NS_ASSUME_NONNULL_BEGIN
__attribute__((objc_subclassing_restricted))
@interface MTIImagePromiseRenderTarget : NSObject
@property (nonatomic,strong,readonly,nullable) id<MTLTexture> texture;
- (BOOL)retainTexture;
- (void)releaseTexture;
@end
typedef NSString * MTIContextPromiseAssociatedValueTableName NS_EXTENSIBLE_STRING_ENUM;
typedef NSString * MTIContextImageAssociatedValueTableName NS_EXTENSIBLE_STRING_ENUM;
@class MTIFunctionDescriptor, MTISamplerDescriptor, MTIRenderPipeline, MTIComputePipeline, MTITextureDescriptor;
@interface MTIContext (Internal)
#pragma mark - Render Target
- (nullable MTIImagePromiseRenderTarget *)newRenderTargetWithReusableTextureDescriptor:(MTITextureDescriptor *)textureDescriptor error:(NSError **)error NS_SWIFT_NAME(makeRenderTarget(reusableTextureDescriptor:));
- (MTIImagePromiseRenderTarget *)newRenderTargetWithTexture:(id<MTLTexture>)texture NS_SWIFT_NAME(makeRenderTarget(texture:));
#pragma mark - Lock
- (void)lockForRendering;
- (void)unlockForRendering;
#pragma mark - Cache
- (nullable id<MTLFunction>)functionWithDescriptor:(MTIFunctionDescriptor *)descriptor error:(NSError **)error;
- (nullable id<MTLSamplerState>)samplerStateWithDescriptor:(MTISamplerDescriptor *)descriptor error:(NSError **)error;
- (nullable MTIRenderPipeline *)renderPipelineWithDescriptor:(MTLRenderPipelineDescriptor *)descriptor error:(NSError **)error;
- (nullable MTIComputePipeline *)computePipelineWithDescriptor:(MTLComputePipelineDescriptor *)descriptor error:(NSError **)error;
- (nullable id)kernelStateForKernel:(id<MTIKernel>)kernel configuration:(nullable id<MTIKernelConfiguration>)configuration error:(NSError **)error;
#pragma mark - Privately Used Caches
/* Weak to strong tables */
- (nullable id)valueForPromise:(id<MTIImagePromise>)promise inTable:(MTIContextPromiseAssociatedValueTableName)tableName;
- (void)setValue:(nullable id)value forPromise:(id<MTIImagePromise>)promise inTable:(MTIContextPromiseAssociatedValueTableName)tableName;
- (nullable id)valueForImage:(MTIImage *)image inTable:(MTIContextImageAssociatedValueTableName)tableName;
- (void)setValue:(nullable id)value forImage:(MTIImage *)image inTable:(MTIContextImageAssociatedValueTableName)tableName;
/* MTIImagePromise (weak) to MTIImagePromiseRenderTarget (weak) table. */
- (void)setRenderTarget:(MTIImagePromiseRenderTarget *)renderTarget forPromise:(id<MTIImagePromise>)promise;
- (nullable MTIImagePromiseRenderTarget *)renderTargetForPromise:(id<MTIImagePromise>)promise;
@end
NS_ASSUME_NONNULL_END
| 1,045 |
2,338 | <filename>clang-tools-extra/test/modularize/Inputs/MissingHeader/Level1A.h
#define MACRO_1A 1
| 37 |
708 | <filename>source/usb/cdc/usbd_core_cdc.c
/**
* @file usbd_core_cdc.c
* @brief Communication Device Class driver
*
* DAPLink Interface Firmware
* Copyright (c) 2009-2016, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#include "string.h"
#include "RTL.h"
#include "rl_usb.h"
#include "usb_for_lib.h"
/*
* USB Device Endpoint 0 Event Callback - CDC specific handling (Setup Request To Interface)
* Parameters: none
* Return Value: TRUE - Setup class request ok, FALSE - Setup class request not supported
*/
__weak BOOL USBD_EndPoint0_Setup_CDC_ReqToIF(void)
{
if ((USBD_SetupPacket.wIndexL == usbd_cdc_acm_cif_num) || /* IF number correct? */
(USBD_SetupPacket.wIndexL == usbd_cdc_acm_dif_num)) {
switch (USBD_SetupPacket.bRequest) {
case CDC_SEND_ENCAPSULATED_COMMAND:
USBD_EP0Data.pData = USBD_EP0Buf; /* data to be received, see USBD_EVT_OUT */
return (__TRUE);
case CDC_GET_ENCAPSULATED_RESPONSE:
if (USBD_CDC_ACM_GetEncapsulatedResponse()) {
USBD_EP0Data.pData = USBD_EP0Buf; /* point to data to be sent */
USBD_DataInStage(); /* send requested data */
return (__TRUE);
}
break;
case CDC_SET_COMM_FEATURE:
USBD_EP0Data.pData = USBD_EP0Buf; /* data to be received, see USBD_EVT_OUT */
return (__TRUE);
case CDC_GET_COMM_FEATURE:
if (USBD_CDC_ACM_GetCommFeature(USBD_SetupPacket.wValue)) {
USBD_EP0Data.pData = USBD_EP0Buf; /* point to data to be sent */
USBD_DataInStage(); /* send requested data */
return (__TRUE);
}
break;
case CDC_CLEAR_COMM_FEATURE:
if (USBD_CDC_ACM_ClearCommFeature(USBD_SetupPacket.wValue)) {
USBD_StatusInStage(); /* send Acknowledge */
return (__TRUE);
}
break;
case CDC_SET_LINE_CODING:
USBD_EP0Data.pData = USBD_EP0Buf; /* data to be received, see USBD_EVT_OUT */
return (__TRUE);
case CDC_GET_LINE_CODING:
if (USBD_CDC_ACM_GetLineCoding()) {
USBD_EP0Data.pData = USBD_EP0Buf; /* point to data to be sent */
USBD_DataInStage(); /* send requested data */
return (__TRUE);
}
break;
case CDC_SET_CONTROL_LINE_STATE:
if (USBD_CDC_ACM_SetControlLineState(USBD_SetupPacket.wValue)) {
USBD_StatusInStage(); /* send Acknowledge */
return (__TRUE);
}
break;
case CDC_SEND_BREAK:
if (USBD_CDC_ACM_SendBreak(USBD_SetupPacket.wValue)) {
USBD_StatusInStage(); /* send Acknowledge */
return (__TRUE);
}
break;
}
}
return (__FALSE);
}
/*
* USB Device Endpoint 0 Event Callback - CDC specific handling (Out Request To Interface)
* Parameters: none
* Return Value: TRUE - Out class request ok, FALSE - Out class request not supported
*/
__weak BOOL USBD_EndPoint0_Out_CDC_ReqToIF(void)
{
if ((USBD_SetupPacket.wIndexL == usbd_cdc_acm_cif_num) || /* IF number correct? */
(USBD_SetupPacket.wIndexL == usbd_cdc_acm_dif_num)) {
switch (USBD_SetupPacket.bRequest) {
case CDC_SEND_ENCAPSULATED_COMMAND:
if (USBD_CDC_ACM_SendEncapsulatedCommand()) {
USBD_StatusInStage(); /* send Acknowledge */
return (__TRUE);
}
break;
case CDC_SET_COMM_FEATURE:
if (USBD_CDC_ACM_SetCommFeature(USBD_SetupPacket.wValue)) {
USBD_StatusInStage(); /* send Acknowledge */
return (__TRUE);
}
break;
case CDC_SET_LINE_CODING:
if (USBD_CDC_ACM_SetLineCoding()) {
USBD_StatusInStage(); /* send Acknowledge */
return (__TRUE);
}
break;
}
}
return (__FALSE);
}
| 2,876 |
3,100 | <reponame>cloudhaacker/xenia
/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2014 <NAME>. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/cpu/testing/util.h"
using namespace xe;
using namespace xe::cpu;
using namespace xe::cpu::hir;
using namespace xe::cpu::testing;
using xe::cpu::ppc::PPCContext;
TEST_CASE("LOAD_VECTOR_SHL", "[instr]") {
TestFunction test([](HIRBuilder& b) {
StoreVR(b, 3, b.LoadVectorShl(b.Truncate(LoadGPR(b, 4), INT8_TYPE)));
b.Return();
});
test.Run([](PPCContext* ctx) { ctx->r[4] = 0; },
[](PPCContext* ctx) {
auto result = ctx->v[3];
REQUIRE(result == vec128b(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15));
});
test.Run([](PPCContext* ctx) { ctx->r[4] = 7; },
[](PPCContext* ctx) {
auto result = ctx->v[3];
REQUIRE(result == vec128b(7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22));
});
test.Run([](PPCContext* ctx) { ctx->r[4] = 15; },
[](PPCContext* ctx) {
auto result = ctx->v[3];
REQUIRE(result == vec128b(15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30));
});
test.Run([](PPCContext* ctx) { ctx->r[4] = 16; },
[](PPCContext* ctx) {
auto result = ctx->v[3];
REQUIRE(result == vec128b(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15));
});
}
TEST_CASE("LOAD_VECTOR_SHR", "[instr]") {
TestFunction test([](HIRBuilder& b) {
StoreVR(b, 3, b.LoadVectorShr(b.Truncate(LoadGPR(b, 4), INT8_TYPE)));
b.Return();
});
test.Run([](PPCContext* ctx) { ctx->r[4] = 0; },
[](PPCContext* ctx) {
auto result = ctx->v[3];
REQUIRE(result == vec128b(16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31));
});
test.Run([](PPCContext* ctx) { ctx->r[4] = 7; },
[](PPCContext* ctx) {
auto result = ctx->v[3];
REQUIRE(result == vec128b(9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24));
});
test.Run([](PPCContext* ctx) { ctx->r[4] = 15; },
[](PPCContext* ctx) {
auto result = ctx->v[3];
REQUIRE(result == vec128b(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16));
});
test.Run([](PPCContext* ctx) { ctx->r[4] = 16; },
[](PPCContext* ctx) {
auto result = ctx->v[3];
REQUIRE(result == vec128b(16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31));
});
}
| 1,779 |
2,151 | <reponame>russjohnson09/sdl_core
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "testutil.h"
#include "apr_general.h"
#include "apr_network_io.h"
#include "apr_errno.h"
static void test_bad_input(abts_case *tc, void *data)
{
struct {
const char *ipstr;
const char *mask;
apr_status_t expected_rv;
} testcases[] =
{
/* so we have a few good inputs in here; sue me */
{"my.host.name", NULL, APR_EINVAL}
,{"127.0.0.256", NULL, APR_EBADIP}
,{"127.0.0.1", NULL, APR_SUCCESS}
,{"127.0.0.1", "32", APR_SUCCESS}
,{"127.0.0.1", "1", APR_SUCCESS}
,{"127.0.0.1", "15", APR_SUCCESS}
,{"127.0.0.1", "-1", APR_EBADMASK}
,{"127.0.0.1", "0", APR_EBADMASK}
,{"127.0.0.1", "33", APR_EBADMASK}
,{"127.0.0.1", "255.0.0.0", APR_SUCCESS}
,{"127.0.0.1", "255.0", APR_EBADMASK}
,{"127.0.0.1", "255.255.256.0", APR_EBADMASK}
,{"127.0.0.1", "abc", APR_EBADMASK}
,{"127", NULL, APR_SUCCESS}
,{"127.0.0.1.2", NULL, APR_EBADIP}
,{"127.0.0.1.2", "8", APR_EBADIP}
,{"127", "255.0.0.0", APR_EBADIP} /* either EBADIP or EBADMASK seems fine */
#if APR_HAVE_IPV6
,{"::1", NULL, APR_SUCCESS}
,{"::1", "20", APR_SUCCESS}
,{"::ffff:9.67.113.15", NULL, APR_EBADIP} /* yes, this is goodness */
,{"fe80::", "16", APR_SUCCESS}
,{"fe80::", "255.0.0.0", APR_EBADMASK}
,{"fe80::1", "0", APR_EBADMASK}
,{"fe80::1", "-1", APR_EBADMASK}
,{"fe80::1", "1", APR_SUCCESS}
,{"fe80::1", "33", APR_SUCCESS}
,{"fe80::1", "128", APR_SUCCESS}
,{"fe80::1", "129", APR_EBADMASK}
#else
/* do some IPv6 stuff and verify that it fails with APR_EBADIP */
,{"::ffff:192.168.127.12", NULL, APR_EBADIP}
#endif
};
int i;
apr_ipsubnet_t *ipsub;
apr_status_t rv;
for (i = 0; i < (sizeof testcases / sizeof testcases[0]); i++) {
rv = apr_ipsubnet_create(&ipsub, testcases[i].ipstr, testcases[i].mask, p);
ABTS_INT_EQUAL(tc, testcases[i].expected_rv, rv);
}
}
static void test_singleton_subnets(abts_case *tc, void *data)
{
const char *v4addrs[] = {
"127.0.0.1", "192.168.3.11", "172.16.58.3", "172.16.58.3", "172.16.31.10",
"192.168.127.12", "172.16.58.3", "192.168.127.12", "192.168.3.11",
"172.16.58.3"
};
apr_ipsubnet_t *ipsub;
apr_sockaddr_t *sa;
apr_status_t rv;
int i, j, rc;
for (i = 0; i < sizeof v4addrs / sizeof v4addrs[0]; i++) {
rv = apr_ipsubnet_create(&ipsub, v4addrs[i], NULL, p);
ABTS_TRUE(tc, rv == APR_SUCCESS);
for (j = 0; j < sizeof v4addrs / sizeof v4addrs[0]; j++) {
rv = apr_sockaddr_info_get(&sa, v4addrs[j], APR_INET, 0, 0, p);
ABTS_TRUE(tc, rv == APR_SUCCESS);
rc = apr_ipsubnet_test(ipsub, sa);
if (!strcmp(v4addrs[i], v4addrs[j])) {
ABTS_TRUE(tc, rc != 0);
}
else {
ABTS_TRUE(tc, rc == 0);
}
}
}
/* same for v6? */
}
static void test_interesting_subnets(abts_case *tc, void *data)
{
struct {
const char *ipstr, *mask;
int family;
char *in_subnet, *not_in_subnet;
} testcases[] =
{
{"9.67", NULL, APR_INET, "192.168.127.12", "10.1.2.3"}
,{"172.16.31.10", "16", APR_INET, "192.168.127.12", "10.1.2.3"}
,{"172.16.31.10", "255.255.0.0", APR_INET, "192.168.127.12", "10.1.2.3"}
,{"192.168.127.12", "16", APR_INET, "192.168.127.12", "10.1.2.3"}
,{"192.168.127.12", "255.255.255.0", APR_INET, "192.168.127.12", "10.1.2.3"}
,{"127", NULL, APR_INET, "127.0.0.1", "10.1.2.3"}
,{"127.0.0.1", "8", APR_INET, "127.0.0.1", "10.1.2.3"}
#if APR_HAVE_IPV6
,{"192.168.3.11", "8", APR_INET6, "::ffff:192.168.3.11", "fdf8:f53e:61e4::18"} /* PR 54047 */
,{"fe80::", "8", APR_INET6, "fe80::1", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b"}
,{"ff01::", "8", APR_INET6, "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b", "fe80::1"}
,{"3FFE:8160::", "28", APR_INET6, "fdf8:f53e:61e4::18", "fdf8:f53e:61e4::18"}
,{"127.0.0.1", NULL, APR_INET6, "::ffff:127.0.0.1", "fe80::1"}
,{"127.0.0.1", "8", APR_INET6, "::ffff:127.0.0.1", "fe80::1"}
#endif
};
apr_ipsubnet_t *ipsub;
apr_sockaddr_t *sa;
apr_status_t rv;
int i, rc;
for (i = 0; i < sizeof testcases / sizeof testcases[0]; i++) {
rv = apr_ipsubnet_create(&ipsub, testcases[i].ipstr, testcases[i].mask, p);
ABTS_TRUE(tc, rv == APR_SUCCESS);
rv = apr_sockaddr_info_get(&sa, testcases[i].in_subnet, testcases[i].family, 0, 0, p);
ABTS_TRUE(tc, rv == APR_SUCCESS);
ABTS_TRUE(tc, sa != NULL);
if (!sa) continue;
rc = apr_ipsubnet_test(ipsub, sa);
ABTS_TRUE(tc, rc != 0);
rv = apr_sockaddr_info_get(&sa, testcases[i].not_in_subnet, testcases[i].family, 0, 0, p);
ABTS_TRUE(tc, rv == APR_SUCCESS);
rc = apr_ipsubnet_test(ipsub, sa);
ABTS_TRUE(tc, rc == 0);
}
}
static void test_badmask_str(abts_case *tc, void *data)
{
char buf[128];
ABTS_STR_EQUAL(tc, apr_strerror(APR_EBADMASK, buf, sizeof buf),
"The specified network mask is invalid.");
}
static void test_badip_str(abts_case *tc, void *data)
{
char buf[128];
ABTS_STR_EQUAL(tc, apr_strerror(APR_EBADIP, buf, sizeof buf),
"The specified IP address is invalid.");
}
abts_suite *testipsub(abts_suite *suite)
{
suite = ADD_SUITE(suite)
abts_run_test(suite, test_bad_input, NULL);
abts_run_test(suite, test_singleton_subnets, NULL);
abts_run_test(suite, test_interesting_subnets, NULL);
abts_run_test(suite, test_badmask_str, NULL);
abts_run_test(suite, test_badip_str, NULL);
return suite;
}
| 4,403 |
675 | <gh_stars>100-1000
"""
# Test pdpbox for regression problem
### dataset: Kaggle Rossmann store dataset
"""
import pandas as pd
import numpy as np
import sys
sys.path.insert(0, "../../")
from pdpbox import pdp, get_dataset
"""
## get dataset
"""
test_ross = get_dataset.ross()
ross_data = test_ross["data"]
ross_features = test_ross["features"]
ross_model = test_ross["rf_model"]
ross_target = test_ross["target"]
"""
## Numeric and Binary feature: weekofyear and SchoolHoliday
"""
pdp_weekofyear_SchoolHoliday = pdp.pdp_interact(
model=ross_model,
dataset=ross_data,
model_features=ross_features,
features=["weekofyear", "SchoolHoliday"],
)
"""
"""
fig, axes = pdp.pdp_interact_plot(
pdp_interact_out=pdp_weekofyear_SchoolHoliday,
feature_names=["weekofyear", "SchoolHoliday"],
plot_type="contour",
x_quantile=True,
plot_pdp=False,
)
_ = axes["pdp_inter_ax"].set_yticklabels(["Not SchoolHoliday", "SchoolHoliday"])
"""
"""
fig, axes = pdp.pdp_interact_plot(
pdp_interact_out=pdp_weekofyear_SchoolHoliday,
feature_names=["weekofyear", "SchoolHoliday"],
plot_type="contour",
x_quantile=True,
plot_pdp=True,
)
_ = axes["pdp_inter_ax"]["_pdp_inter_ax"].set_yticklabels(
["Not SchoolHoliday", "SchoolHoliday"]
)
"""
"""
fig, axes = pdp.pdp_interact_plot(
pdp_interact_out=pdp_weekofyear_SchoolHoliday,
feature_names=["weekofyear", "SchoolHoliday"],
plot_type="grid",
plot_pdp=False,
)
"""
"""
fig, axes = pdp.pdp_interact_plot(
pdp_interact_out=pdp_weekofyear_SchoolHoliday,
feature_names=["weekofyear", "SchoolHoliday"],
plot_type="grid",
plot_pdp=True,
)
"""
"""
"""
## Onehot encoding and Binary feature: StoreType and SchoolHoliday
"""
pdp_StoreType_SchoolHoliday = pdp.pdp_interact(
model=ross_model,
dataset=ross_data,
model_features=ross_features,
features=[
["StoreType_a", "StoreType_b", "StoreType_c", "StoreType_d"],
"SchoolHoliday",
],
)
"""
"""
fig, axes = pdp.pdp_interact_plot(
pdp_interact_out=pdp_StoreType_SchoolHoliday,
feature_names=["StoreType", "SchoolHoliday"],
plot_type="grid",
plot_pdp=False,
)
"""
"""
fig, axes = pdp.pdp_interact_plot(
pdp_interact_out=pdp_StoreType_SchoolHoliday,
feature_names=["StoreType", "SchoolHoliday"],
plot_type="grid",
plot_pdp=True,
)
"""
"""
| 986 |
Subsets and Splits