content
stringlengths
10
4.9M
The Finn has proved himself as a potential contender for the championship battle on the back of a well-earned victory in the Russian Grand Prix. And although he received warm congratulations from a host of drivers – including Hamilton – after the race, he thinks the pleasantries will ultimately stop. Asked about what Hamilton had said to him as they met each other in parc ferme, Bottas said: "He congratulated me. It's very very nice of him to be very professional about everything so far and he's been in front of me now… he's done a great job and I think vice versa. "So I think we're working well as a team but I'd say also we did today against the Ferrari drivers. It's going to be a long year with a lot of fighting with all these cars. "At some point things might get a bit more tricky on track - and if and when it comes to the championship fight, it might be less talking and more fighting on track." Confidence lift While Mercedes' bosses think Bottas will be unaffected by taking his maiden win, the man himself believes he will gain some new-found confidence from the result. For having delivered a strong victory, it has lifted his belief and desire to do it again. "For sure, getting the first win is something special," he said. "Even though you always believe in yourself because there's no point being here or doing this if you don't believe in your skill. If you think that you are not able to win then definitely you should stay home. "But, actually getting the confirmation and getting the result [is important]. Because results are what matters in this world. How many points you score, how many races you can win, how many times you be on the podium - that's the name of the game. "And getting that first win, it definitely gives me confidence that I can do it even though I've always knew I had the ability. "But now it's done, I just want to do it again and again. It's not that simple this year. It's going to be always a massive fight at least for the first half of the year. It's going to be a fight with four different drivers."
/** * @Author Benjamini Buganzi * @Date 26/03/2022. */ @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired UserRepository userRepository; @Override @Transactional public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByPhone(username) .orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username)); return UserDetailsImpl.build(user); } public String generateOTP() { String passphrase = ""; for (int i = 1; i <= 5; i++) { passphrase = passphrase + new Random().nextInt(10); } return passphrase; } }
package com.tech.gulimall.product.exception; import com.tech.gulimall.common.exception.BizException; import com.tech.gulimall.common.exception.enums.BizCodeEnum; import com.tech.gulimall.common.utils.R; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.HashMap; /*** * @Description: 统一异常处理类 * @Author: phil * @Date: 2021/11/5 12:15 */ @Slf4j @RestControllerAdvice(basePackages = "com.tech.gulimall.product.controller") public class GulimallExceptionControllerAdvice { /** * @Description: 业务处理异常 * @Param: [e] * @return: com.tech.gulimall.common.utils.R * @Author: phil * @Date: 2021/11/8 19:22 */ @ExceptionHandler(value = BizException.class) public R handleValidException (BizException e) { log.error("业务处理异常{},异常类型:{}", e.getMessage(), e.getClass()); return R.error(BizCodeEnum.BIZ_EXCEPTION.getCode(), BizCodeEnum.BIZ_EXCEPTION.getMsg()).put("data", e.getMessage()); } /** * @Description: 数据校验异常 * @Param: [e] * @return: com.tech.gulimall.common.utils.R * @Author: phil * @Date: 2021/11/5 12:27 */ @ExceptionHandler(value = MethodArgumentNotValidException.class) public R handleValidException (MethodArgumentNotValidException e) { log.error("数据校验出现问题{},异常类型:{}", e.getMessage(), e.getClass()); BindingResult bindingResult = e.getBindingResult(); HashMap<String, String> errorMap = new HashMap<>(10); for (FieldError fieldError : bindingResult.getFieldErrors()) { errorMap.put(fieldError.getField(), fieldError.getDefaultMessage()); } return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", errorMap); } /** * @Description: 默认异常处理 * @Param: [e] * @return: com.tech.gulimall.common.utils.R * @Author: phil * @Date: 2021/11/5 12:29 */ @ExceptionHandler(value = Throwable.class) public R handleException(Throwable e) { log.error("未知异常{},异常类型{}", e.getMessage(), e.getClass()); return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMsg()); } }
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2020, <NAME> // 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. // // 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. // //---------------------------------------------------------------------------- //! //! @file //! Attributes of a tag in an HLS playlist. //! //---------------------------------------------------------------------------- #pragma once #include "tshls.h" namespace ts { namespace hls { //! //! Attributes of a tag in an HLS playlist. //! @ingroup hls //! class TSDUCKDLL TagAttributes { public: //! //! Constructor. //! @param [in] params String parameter of the tag in the playlist line. //! TagAttributes(const UString& params = UString()); //! //! Reload the contents of the attributes. //! @param [in] params String parameter of the tag in the playlist line. //! void reload(const UString& params = UString()); //! //! Clear the content of the attributes. //! void clear() { _map.clear(); } //! //! Chek if an attribute is present. //! @param [in] name Attribute name. //! @return True if the attribute is present. //! bool present(const UString& name) const; //! //! Get the value of a string attribute. //! @param [in] name Attribute name. //! @param [in] defValue Default value if not present. //! @return Attribute value. //! UString value(const UString& name, const UString& defValue = UString()) const; //! //! Get the value of an integer attribute. //! @tparam INT An integer type. //! @param [out] val Decoded value. //! @param [in] name Attribute name. //! @param [in] defValue Default value if not present. //! template <typename INT, typename std::enable_if<std::is_integral<INT>::value>::type* = nullptr> void getIntValue(INT& val, const UString& name, INT defValue = static_cast<INT>(0)) const { if (!value(name).toInteger(val)) { val = defValue; } } //! //! Get the value of a numerical attribute in milli-units. //! @tparam INT An integer type. //! @param [out] val Decoded value. If the value is an integer, return this value times 1000. //! If the value is a decimal one, use 3 decimal digits. Examples: "90" -> 90000, //! "1.12" -> 1120, "32.1234" -> 32123. //! @param [in] name Attribute name. //! @param [in] defValue Default value if not present. //! template <typename INT, typename std::enable_if<std::is_integral<INT>::value>::type* = nullptr> void getMilliValue(INT& val, const UString& name, INT defValue = static_cast<INT>(0)) const { if (!ToMilliValue(val, value(name))) { val = defValue; } } //! //! Get the value of a String in milli-units. //! @tparam INT An integer type. //! @param [out] value Decoded value. If the value is an integer, return this value times 1000. //! If the value is a decimal one, use 3 decimal digits. Examples: "90" -> 90000, //! "1.12" -> 1120, "32.1234" -> 32123. //! @param [in] str String to decode. //! @return True on success, false on error. //! template <typename INT, typename std::enable_if<std::is_integral<INT>::value>::type* = nullptr> static bool ToMilliValue(INT& value, const UString& str) { const size_t dot = str.find(u'.'); INT i = static_cast<INT>(0); INT j = static_cast<INT>(0); if (str.substr(0, dot).toInteger(i) && (dot == NPOS || str.substr(dot+1).toJustifiedLeft(3, u'0', true).toInteger(j))) { value = (i * 1000) + j; return true; } else { return false; } } private: std::map<UString, UString> _map; }; } }
/** * @param m current index pos of String A * @param n current index pos of String B */ private static int editDistance(String A, String B, int m, int n) { if (m < 0 && n < 0) { return 0; } else if (m < 0 || n < 0) { return Math.abs(m - n); } if (A.charAt(m) == B.charAt(n)) { return editDistance(A, B, m - 1, n - 1); } else { int deleteACharacter = editDistance(A, B, m - 1, n) + 1; int replaceACharacterWithBCharacter = editDistance(A, B, m - 1, n - 1) + 1; int insertCharacterIntoA = editDistance(A, B, m, n - 1) + 1; return Math.min(deleteACharacter, Math.min(replaceACharacterWithBCharacter, insertCharacterIntoA)); } }
<filename>examples/ru.iiec.cxxdroid/sources/com/google/android/gms/internal/ads/f80.java package com.google.android.gms.internal.ads; import android.content.SharedPreferences; import org.json.JSONObject; /* access modifiers changed from: package-private */ public final class f80 extends a80<String> { f80(int i2, String str, String str2) { super(i2, str, str2, null); } /* Return type fixed from 'java.lang.Object' to match base method */ @Override // com.google.android.gms.internal.ads.a80 public final /* synthetic */ String a(SharedPreferences sharedPreferences) { return sharedPreferences.getString(a(), (String) c()); } /* Return type fixed from 'java.lang.Object' to match base method */ @Override // com.google.android.gms.internal.ads.a80 public final /* synthetic */ String a(JSONObject jSONObject) { return jSONObject.optString(a(), (String) c()); } /* JADX DEBUG: Method arguments types fixed to match base method, original types: [android.content.SharedPreferences$Editor, java.lang.Object] */ @Override // com.google.android.gms.internal.ads.a80 public final /* synthetic */ void a(SharedPreferences.Editor editor, String str) { editor.putString(a(), str); } }
X = int(input()) kyu = [8, 7, 6, 5, 4, 3, 2] rate = [600, 800, 1000, 1200, 1400, 1600, 1800] flag = True for k, r in zip(kyu, rate): if X < r: print(k) flag = False break if flag: print(1)
<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 xds import ( "encoding/json" "errors" "fmt" "strings" "time" envoy_config_bootstrap_v3 "github.com/envoyproxy/go-control-plane/envoy/config/bootstrap/v3" envoy_config_cluster_v3 "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3" "github.com/golang/protobuf/jsonpb" "github.com/golang/protobuf/ptypes/duration" "mosn.io/mosn/istio/istio1106/xds/conv" "mosn.io/mosn/pkg/admin/server" "mosn.io/mosn/pkg/istio" "mosn.io/mosn/pkg/log" ) func init() { istio.RegisterParseAdsConfig(UnmarshalResources) } // UnmarshalResources register istio.ParseAdsConfig func UnmarshalResources(dynamic, static json.RawMessage) (istio.XdsStreamConfig, error) { ads, err := unmarshalResources(dynamic, static) if err != nil { return nil, err } // register admin api server.RegisterAdminHandleFunc("/stats", ads.statsForIstio) return ads, nil } // unmarshalResources used in order to convert bootstrap_v2 json to pb struct (go-control-plane), some fields must be exchanged format func unmarshalResources(dynamic, static json.RawMessage) (*AdsConfig, error) { dynamicResources, err := unmarshalDynamic(dynamic) if err != nil { return nil, err } staticResources, err := unmarshalStatic(static) if err != nil { return nil, err } cfg := &AdsConfig{ xdsInfo: istio.GetGlobalXdsInfo(), converter: conv.NewConverter(), previousInfo: newApiState(), } // update static config to mosn config if err := cfg.loadClusters(staticResources); err != nil { return nil, err } if err := cfg.loadStaticResources(staticResources); err != nil { return nil, err } if err := cfg.loadADSConfig(dynamicResources); err != nil { return nil, err } return cfg, nil } func duration2String(duration *duration.Duration) string { d := time.Duration(duration.Seconds)*time.Second + time.Duration(duration.Nanos)*time.Nanosecond x := fmt.Sprintf("%.9f", d.Seconds()) x = strings.TrimSuffix(x, "000") x = strings.TrimSuffix(x, "000") return x + "s" } func unmarshalDynamic(dynamic json.RawMessage) (*envoy_config_bootstrap_v3.Bootstrap_DynamicResources, error) { // no dynamic resource, returns nil error if len(dynamic) <= 0 { return nil, nil } dynamicResources := &envoy_config_bootstrap_v3.Bootstrap_DynamicResources{} resources := map[string]json.RawMessage{} if err := json.Unmarshal(dynamic, &resources); err != nil { log.DefaultLogger.Errorf("fail to unmarshal dynamic_resources: %v", err) return nil, err } adsConfigRaw, ok := resources["ads_config"] if !ok { log.DefaultLogger.Errorf("ads_config not found") return nil, errors.New("lack of ads_config") } adsConfig := map[string]json.RawMessage{} if err := json.Unmarshal([]byte(adsConfigRaw), &adsConfig); err != nil { log.DefaultLogger.Errorf("fail to unmarshal ads_config: %v", err) return nil, err } if refreshDelayRaw, ok := adsConfig["refresh_delay"]; ok { refreshDelay := duration.Duration{} if err := json.Unmarshal([]byte(refreshDelayRaw), &refreshDelay); err != nil { log.DefaultLogger.Errorf("fail to unmarshal refresh_delay: %v", err) return nil, err } d := duration2String(&refreshDelay) b, _ := json.Marshal(&d) adsConfig["refresh_delay"] = json.RawMessage(b) } b, err := json.Marshal(&adsConfig) if err != nil { log.DefaultLogger.Errorf("fail to marshal refresh_delay: %v", err) return nil, err } resources["ads_config"] = json.RawMessage(b) b, err = json.Marshal(&resources) if err != nil { log.DefaultLogger.Errorf("fail to marshal ads_config: %v", err) return nil, err } if err := jsonpb.UnmarshalString(string(b), dynamicResources); err != nil { log.DefaultLogger.Errorf("fail to unmarshal dynamic_resources: %v", err) return nil, err } if err := dynamicResources.Validate(); err != nil { log.DefaultLogger.Errorf("invalid dynamic_resources: %v", err) return nil, err } return dynamicResources, nil } func unmarshalStatic(static json.RawMessage) (*envoy_config_bootstrap_v3.Bootstrap_StaticResources, error) { if len(static) <= 0 { return nil, nil } staticResources := &envoy_config_bootstrap_v3.Bootstrap_StaticResources{} resources := map[string]json.RawMessage{} if err := json.Unmarshal([]byte(static), &resources); err != nil { log.DefaultLogger.Errorf("fail to unmarshal static_resources: %v", err) return nil, err } var data []byte if clustersRaw, ok := resources["clusters"]; ok { clusters := []json.RawMessage{} if err := json.Unmarshal([]byte(clustersRaw), &clusters); err != nil { log.DefaultLogger.Errorf("fail to unmarshal clusters: %v", err) return nil, err } for i, clusterRaw := range clusters { cluster := map[string]json.RawMessage{} if err := json.Unmarshal([]byte(clusterRaw), &cluster); err != nil { log.DefaultLogger.Errorf("fail to unmarshal cluster: %v", err) return nil, err } cb := envoy_config_cluster_v3.CircuitBreakers{} b, err := json.Marshal(&cb) if err != nil { log.DefaultLogger.Errorf("fail to marshal circuit_breakers: %v", err) return nil, err } cluster["circuit_breakers"] = json.RawMessage(b) b, err = json.Marshal(&cluster) if err != nil { log.DefaultLogger.Errorf("fail to marshal cluster: %v", err) return nil, err } clusters[i] = json.RawMessage(b) } b, err := json.Marshal(&clusters) if err != nil { log.DefaultLogger.Errorf("fail to marshal clusters: %v", err) return nil, err } data = b } resources["clusters"] = json.RawMessage(data) b, err := json.Marshal(&resources) if err != nil { log.DefaultLogger.Errorf("fail to marshal resources: %v", err) return nil, err } if err := jsonpb.UnmarshalString(string(b), staticResources); err != nil { log.DefaultLogger.Errorf("fail to unmarshal static_resources: %v", err) return nil, err } if err := staticResources.Validate(); err != nil { log.DefaultLogger.Errorf("Invalid static_resources: %v", err) return nil, err } return staticResources, nil }
<gh_stars>0 package table import ( "strings" "testing" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" ) type tableSuite struct{ suite.Suite } var table = T([]string{"abc", "def", "ghi"}) var tableEmpty = T([]string{}) func TestTable(t *testing.T) { suite.Run(t, new(tableSuite)) } func (s *tableSuite) TestSkipToWhenResult() { require.Equal(s.T(), T([]string{"def", "ghi"}), table.SkipTo(LineContaining("d"))) } func (s *tableSuite) TestSkipToNoResult() { require.Equal(s.T(), T(nil), table.SkipTo(LineContaining("j"))) } func (s *tableSuite) TestTakeToWhenThereIsMatch() { require.Equal(s.T(), T([]string{"abc"}), table.TakeTo(LineContaining("d"))) } func (s *tableSuite) TestTakeToWhenNoMatch() { require.Equal(s.T(), T([]string{"abc", "def", "ghi"}), table.TakeTo(LineContaining("j"))) } func (s *tableSuite) TestIgnoreLines() { require.Equal(s.T(), T([]string{"abc"}), table.IgnoreLines([]string{"def", "ghi"})) } func (s *tableSuite) TestIgnoreLinesNoMatch() { require.Equal(s.T(), table, table.IgnoreLines([]string{"xyz"})) } func (s *tableSuite) TestIgnoreLinesEmptyIgnore() { require.Equal(s.T(), table, table.IgnoreLines([]string{})) } func (s *tableSuite) TestIgnoreLinesEmptyTable() { require.Equal(s.T(), tableEmpty, tableEmpty.IgnoreLines([]string{"xyz"})) } func (s *tableSuite) TestIgnoreLinesEmptyTableAndIgnore() { require.Equal(s.T(), tableEmpty, tableEmpty.IgnoreLines([]string{})) } func (s *tableSuite) TestFields() { testcases := []struct { input string result []field }{ { input: "a b", result: []field{ {"a b", 0}}, }, { input: "a b", result: []field{ {"a", 0}, {"b", 3}}, }, { input: "a b ", result: []field{ {"a", 0}, {"b ", 3}}, }, { input: "a b ", result: []field{ {"a", 0}, {"b", 3}}, }, { input: " a b", result: []field{ {"a", 2}, {"b", 5}}, }, { input: "a b c", result: []field{ {"a", 0}, {"b", 3}, {"c", 6}}, }, { input: "a b c d", result: []field{ {"a", 0}, {"b c", 3}, {"d", 8}}, }, } for _, t := range testcases { require.Equal(s.T(), t.result, extractFields(t.input)) } } func (s *tableSuite) TestColumnOnRealData() { // TODO: This test shows that parser does not deal well with runes which are longer than one // byte. parser should be reworked to correctly with UTF. lines := ` Grain Bids Change (¢/bu) Basis Change NOT ON THE RIVER SRW Wheat 4.6450-4.6550 DN 0.75 7H to 8H UNCH Corn 3.6575-3.6775 DN 1.5 7H to 9H UNCH Soybeans 8.5175 DN 0.75 -21H UNCH ON THE RIVER SRW Wheat 4.6450-4.7250 DN 0.75 7H to 15H UNCH Corn 3.6775-3.7075 DN 1.5 9H to 12H UNCH Soybeans 8.5175-8.5575 DN 0.75 -21H to -17H UNCH` result, err := columns(strings.Split(lines, "\n"), 5) require.Nil(s.T(), err) require.Equal(s.T(), []column{{0, 9}, {11, 24}, {26, 42}, {48, 60}, {70, 76}}, result) } func (s *tableSuite) TestColumnOnSingleColumn() { lines := []string{"a", "abc", "defg"} result, err := columns(lines, 1) require.Nil(s.T(), err) require.Equal(s.T(), []column{{0, 4}}, result) } func (s *tableSuite) TestColumnOnThreeColumn() { lines := ` a a b b abc d g ghjkz e` result, err := columns(strings.Split(lines, "\n"), 3) require.Nil(s.T(), err) require.Equal(s.T(), []column{{0, 1}, {4, 9}, {11, 12}}, result) } func (s *tableSuite) TestColumnWhenOverlap() { lines := ` aaaaaaa a b b abc d g ghjkz e` _, err := columns(strings.Split(lines, "\n"), 3) require.NotNil(s.T(), err) } func (s *tableSuite) TestColumnWhenAlmostOverlap() { lines := ` aaaa a b abc g ghjkz` result, err := columns(strings.Split(lines, "\n"), 2) require.Nil(s.T(), err) require.Equal(s.T(), []column{{0, 4}, {5, 10}}, result) } // nolint: dupl func (s *tableSuite) TestParseAligned() { lines := ` aaa bb ccc aa bb cc` result, err := ParseAligned(strings.Split(lines, "\n"), 3) require.Nil(s.T(), err) require.Equal(s.T(), [][]string{ {"", "", ""}, // first line is empty {"aaa ", " bb ", " ccc"}, {"aa ", " bb ", " cc"}, }, result.Lines()) } func (s *tableSuite) TestParseAlignedExtendsColumnIfPossible() { lines := ` aax bb aa bb` result, err := ParseAligned(strings.Split(lines, "\n"), 2) require.Nil(s.T(), err) require.Equal(s.T(), [][]string{ {"", ""}, // first line is empty {"aax", " bb"}, // it was possible to extend the first column {"aa ", " bb"}, }, result.Lines()) } func (s *tableSuite) TestParseAlignedGuessColumnsFromLinesWithWrongLength() { lines := ` aax bb ccc ddd aa bb cc dd aaaaa cc ddddd` result, err := ParseAligned(strings.Split(lines, "\n"), 4) require.Nil(s.T(), err) require.Equal(s.T(), [][]string{ {"", "", "", ""}, {"aax", " bb ", " ccc", " ddd"}, // it was possible to extend the first column {"aa ", " bb ", " cc ", "dd"}, {"aaa", "aa ", " cc ", "dddd"}, // extending aa to aaaaa would overlap the second column }, result.Lines()) } // nolint: dupl func (s *tableSuite) TestParseAlignedColumnsAreExtendedTowardsLineEnd() { lines := ` 11 22 33 11 222 3333` result, err := ParseAligned(strings.Split(lines, "\n"), 3) require.Nil(s.T(), err) require.Equal(s.T(), [][]string{ {"", "", ""}, {"11 ", " 22 ", " 33"}, {"11 ", "222 ", "3333"}, }, result.Lines()) }
On Divorce: A Feminist Christian Perspective Divorce is not only a personal choice, but also a sign of the lack of confidence in the institution of marriage. The issue of divorce raises questions that are sociological, theological, experiential, philosophical and political. This article traces the arguments with particular reference to the situation in Taiwan where women have no right to initiate divorce. It surveys the biblical and theological arguments, locating issues of divorce in the area of gender justice within patriarchal systems. Marriage, as well as divorce, is complex. To impose a monolithic definition of divorce is to fail to recognize the diversity of marital conflict and breakdown, generally to the advantage of a patriarchal society. This was as true of Hebrew society as it is of modern Taiwan, with its history of political struggle. The article concludes by challenging the Taiwanese churches to provide insights for people in their relationships with one another and with God.
<reponame>mjwestcott/fennel from typing import Any, Callable from fennel.client.aio.actions import send from fennel.client.aio.results import AsyncResult from fennel.job import Job class Task: def __init__(self, name: str, func: Callable, retries: int, app): self.name = name self.func = func self.max_retries = retries self.app = app async def delay(self, *args: Any, **kwargs: Any) -> AsyncResult: """ Enqueue a task for execution by the workers. Similar to asyncio.create_task (but also works with non-async functions and runs on our Redis-backed task queue with distributed workers, automatic retry, and result storage with configurable TTL). The `args` and `kwargs` will be passed through to the task when executed. Examples -------- >>> @app.task(retries=1) >>> async def foo(x, bar=None): ... asyncio.sleep(x) ... if bar == "mystr": ... return False ... return True ... >>> await foo.delay(1) >>> await foo.delay(2, bar="mystr") """ job = Job( task=self.name, args=list(args), kwargs=kwargs, tries=0, max_retries=self.max_retries, ) await send(self.app, job) return AsyncResult(job=job, app=self.app) def __call__(self, *args: Any, **kwargs: Any) -> Any: """ Call the task-decorated function as a normal Python function. The fennel system will be completed bypassed. Examples -------- >>> @app.task >>> def foo(x): ... return x ... >>> foo(7) 7 """ return self.func(*args, **kwargs) def __repr__(self) -> str: return f"Task(name={self.name})"
/** * @author <a href="mailto:[email protected]">Julien Viet</a> * @author <a href="http://tfox.org">Tim Fox</a> */ public class PCKS12OptionsImpl implements PKCS12Options, Cloneable { private String password; private String path; private Buffer value; public PCKS12OptionsImpl() { super(); } public PCKS12OptionsImpl(PKCS12Options other) { super(); this.password = other.getPassword(); this.path = other.getPath(); this.value = other.getValue(); } public PCKS12OptionsImpl(JsonObject json) { super(); this.password = json.getString("password"); this.path = json.getString("path"); byte[] value = json.getBinary("value"); this.value = value != null ? Buffer.buffer(value) : null; } public String getPassword() { return password; } public PKCS12Options setPassword(String password) { this.password = password; return this; } public String getPath() { return path; } public PKCS12Options setPath(String path) { this.path = path; return this; } public Buffer getValue() { return value; } public PKCS12Options setValue(Buffer value) { this.value = value; return this; } @Override public PKCS12Options clone() { return new PCKS12OptionsImpl(this); } }
<reponame>devmatteini/dag use crate::cli::get_env; use crate::cli::handlers::common::{check_has_assets, fetch_release_for}; use crate::cli::handlers::{HandlerError, HandlerResult}; use crate::cli::select; use crate::github::client::GithubClient; use crate::github::release::{Asset, Release}; use crate::github::tagged_asset::TaggedAsset; use crate::github::{Repository, GITHUB_TOKEN}; pub struct UntagHandler { repository: Repository, } impl UntagHandler { pub fn new(repository: Repository) -> Self { UntagHandler { repository } } pub fn run(&self) -> HandlerResult { let client = GithubClient::new(get_env(GITHUB_TOKEN)); let release = Self::fetch_latest_release(&client, &self.repository)?; check_has_assets(&release)?; let selected_asset = Self::ask_select_asset(release.assets)?; let untagged = TaggedAsset::untag(&release.tag, &selected_asset); println!("{}", untagged); Ok(()) } fn fetch_latest_release( client: &GithubClient, repository: &Repository, ) -> Result<Release, HandlerError> { fetch_release_for(client, repository, None) } fn ask_select_asset(assets: Vec<Asset>) -> select::AskSelectAssetResult { select::ask_select_asset( assets, select::Messages { select_prompt: "Pick the asset to untag", quit_select: "No asset selected", }, ) } }
<reponame>snuggery/snuggery import {isJsonObject} from '@angular-devkit/core'; import {AbstractCommand} from '../../command/abstract-command'; export class HelpProjectsCommand extends AbstractCommand { static paths = [['help', 'projects']]; static usage = AbstractCommand.Usage({ category: 'Workspace information commands', description: 'Show information about all projects', }); async execute(): Promise<void> { const {workspace, report} = this.context; if (workspace == null) { report.reportInfo('No workspace configuration found.\n'); return; } const { projects, extensions: {cli}, } = workspace; const {currentProject, format} = this; let defaultProject: string | null = null; if (isJsonObject(cli!) && typeof cli.defaultProject === 'string') { ({defaultProject} = cli); } report.reportInfo( 'The current workspace contains the following projects:\n', ); for (const [projectName, {root, extensions}] of projects) { report.reportInfo( `- \`${format.code(projectName)}\`: a \`${format.code( typeof extensions.projectType === 'string' ? extensions.projectType : 'library', )}\` project at \`${format.code(root)}\``, ); switch (projectName) { case currentProject: report.reportInfo( ` This is the current project based on the working directory`, ); break; case defaultProject: report.reportInfo(` This is the default project`); break; } } report.reportSeparator(); report.reportInfo('For more information about a project, run\n'); report.reportInfo(` ${this.cli.binaryName} help project <project name>\n`); } }
On December 31, 2012, the US Food and Drug Administration (FDA) announced its approval of a new drug to treat multidrug-resistant tuberculosis (MDR-TB). The agency granted bedaquiline (Sirturo) “fast-track” approval, assessing its efficacy by a surrogate measure rather than an actual clinical outcome. The criterion was the capacity of the drug, compared with placebo, to convert a patient's sputum culture from positive to negative for Mycobacterium tuberculosis when added to a standard MDR-TB regimen. Ideally, drug approvals are based on large trials that randomize thousands of patients and measure actual clinical outcomes. By contrast, the pivotal studies for bedaquiline were relatively small; the initial finding on sputum culture conversion came from an 8-week trial of 47 patients. A follow-up study enrolled another 161 patients. By 24 weeks, 79% of patients taking bedaquiline in the second study had undergone sputum culture conversion, compared with 58% in the placebo group. The difference in each substudy was not significant at later points.1,2 However, 5 times as many patients given the experimental drug died—10 of 79, vs 2 of 81 in the control group.1,2 Five of the 10 deaths in patients given the new drug were caused by tuberculosis, indicating treatment failure, as were the 2 deaths in the control group. No single cause explained the remaining excess deaths in the bedaquiline group, but several could have been related to hepatotoxicity. Bedaquiline was also found to cause QT prolongation, which can result in fatal ventricular fibrillation; now that the drug is approved, that fact and the excess mortality will be noted in a black box warning on its label. Multidrug-resistant tuberculosis is an important clinical and public health problem, particularly outside the United States, with limited treatment options. Few innovative anti-infective products have been brought to market in recent years, and the FDA faces considerable pressure to accept less stringent standards for approving such products. Bedaquiline also had an appealingly novel mechanism of action: inhibition of mycobacterial ATP synthetase. But did these factors justify the decision to allow its use based only on a measure of sputum changes in the face of contradictory evidence from clinical end points such as treatment failure and death? Although in recent years the FDA has been prompt in its review timelines, it is still under pressure from the pharmaceutical industry and others to approve drugs more quickly and more often. Since 1992, the salaries of FDA scientists who review new drugs have been subsidized by “user fees” paid by the industry, to make up for recurring congressional budget shortfalls. Decision making under such time pressure may subsequently lead to unanticipated safety problems.3 As 2012 ended, FDA reviewers faced both the deadline imposed by the user-fee program as well as demands from the industry that it increase its annual number of drug approvals (which it did, by a large margin over its past performance).4 Recent years have revealed several problems with drugs evaluated on the basis of surrogate measures alone. Rosiglitazone (Avandia) was approved based on its ability to reduce hemoglobin A 1c levels in patients with diabetes. However, 8 years later the drug was found to significantly increase the risk of myocardial infarction; it is now hardly ever used. Ezetimibe (Vytorin, Zetia) was approved because it lowered low-density lipoprotein cholesterol levels through a novel mechanism; however, 10 years after approval the drug has not yet been convincingly shown to reduce the risk of cardiac events. On the other hand, surrogate measures have sometimes helped to speed approval of effective drugs; for example, viral load is a reliable predictor of the efficacy of medications for human immunodeficiency virus/AIDS, lowering low-density lipoprotein cholesterol levels using a statin correlates with a reduction in cardiac risk, and reducing blood pressure has been shown to help prevent stroke and other cardiovascular events. By law, if the FDA grants a drug accelerated approval based on a surrogate measure, its manufacturer must conduct an additional trial to confirm the appropriateness of the initial decision. However, for bedaquiline, the agency agreed that enrollment in that confirmatory trial would not have to start until late 2013 or 2014, with study results not required until 2022.5 Given the contradictory evidence at hand, it is not clear why the agency did not defer its decision about approval until further outcome evidence was available and demand it sooner than 2022. (A different view was taken by the consumer group Public Citizen. In a letter to the FDA dated December 21, 2012, the group not only urged the agency to withhold approval for the drug but also questioned whether it was ethically acceptable to continue any trials of a product that conferred no outcome benefit but increased the risk of death 5-fold.6) Further research might reveal that the novel mechanism of action of bedaquiline could prove helpful to patients with MDR-TB. But adequate clinical outcome data are not available to demonstrate that this is the case, and there is worrisome evidence in the opposite direction. The economics of this decision are also provocative. Because of the rarity of MDR-TB in the United States (<100 cases in 2011), bedaquiline qualifies for “orphan drug” status, which provides the company with substantial federal research and development credits and other financial benefits. In addition, an FDA program provides that a company that wins approval for a drug to treat a neglected disease can receive a “voucher” from the agency, granting it expedited review of any other new product of its choice; bedaquiline has won such a voucher. The value of these vouchers has been estimated at several hundred million dollars,7 both because of the extended sales time it can transfer to another product with much larger market potential and because the law permits such vouchers to be sold to other companies to use on their own products.8 Thus, the potential financial benefit-risk profile of bedaquiline for its manufacturer appears to be clearer than its potential clinical benefit-risk profile for patients. The FDA's approach to surrogate measures will be an important test of its scientific and political mettle in the coming years. Although the agency will face increasing pressure to accept easily reached laboratory or imaging measures of efficacy, it should embrace these criteria only when they are well linked to efficacy, and it must require prompt confirmation of such presumed associations if a drug must be approved on the basis of such surrogate measures. When, as with bedaquiline, favorable findings on a surrogate measure run counter to data on clearly important clinical outcomes such as disease progression and death, the agency should withhold its decision until more evidence is available to resolve the conflicting signals, rather than being obliged to make an approval decision prematurely based on what may turn out to be inadequate information. Back to top Article Information Corresponding Author: Jerry Avorn, MD, Division of Pharmacoepidemiology and Pharmacoeconomics, Department of Medicine, Brigham and Women's Hospital, Harvard Medical School, Boston, MA 02120 ([email protected]). Published Online: February 21, 2013. 10.1001/jama.2013.623. Corrected on March 8, 2013. Conflict of Interest Disclosures: The author has completed and submitted the ICMJE Form for Disclosure of Potential Conflicts of Interest and none were reported.
friends=input() friends=friends.split() friends_all=friends[0] friends_cakes=friends[1] person=int(friends_all)+1 cakes=input() cakes_amount=0 for a in cakes.split(): cakes_amount+=int(a) one_person=cakes_amount//person if cakes_amount%person!=0: one_person+=1 else: pass print(one_person)
package com.jiawang.core.bean.factory; import com.jiawang.util.BeanUtils; import java.util.Map; /** * 项目名称 : writer_spring_boot * 创建者 : 黎家望 * 创建时间 : 2019-06 15:54 * bean工厂 * * @author : LiJiWang */ public class BeanFactory { private static Map<String, Object> beanNameMap = null; /** * 添加初始集合缓存 * * @param map 集合 */ public static void addMap(Map<String, Object> map) { BeanFactory.beanNameMap = map; } /** * 根据名称获取bean * * @param beanName bean的名称 * @return 结果 */ public Object getBeanByName(String beanName) { return beanNameMap.get(beanName); } /** * 根据字节码获取bean * * @param classType 字节码对象 * @param <T> 具体的实例 * @return 返回这个实例 * @throws Exception 可能无法转换 */ public static <T> T getBeanByType(Class<T> classType) throws Exception { String className = classType.getName(); String beanName = BeanUtils.classToBeanName(className); return (T) beanNameMap.get(beanName); } }
from typing import Set, Optional, Type, List, Tuple from autofit.mapper.model import ModelInstance from autofit.mapper.prior.abstract import Prior from autofit.mapper.prior_model.collection import CollectionPriorModel from autofit.mapper.prior_model.prior_model import PriorModel from autofit.mapper.variable import Plate from autofit.messages.abstract import AbstractMessage from autofit.non_linear.paths.abstract import AbstractPaths from autofit.tools.namer import namer from .abstract import AbstractModelFactor class HierarchicalFactor(PriorModel): _plates: Tuple[Plate, ...] = () def __init__( self, distribution: Type[AbstractMessage], optimiser=None, name: Optional[str] = None, **kwargs, ): """ Associates variables in the graph with a distribution. That is, the optimisation prefers instances of the variables which better match the distribution. Both the distribution and variables sampled from it are optimised during a factor optimisation. This allows expectations from other factors to influence the optimisation of the distribution and vice-versa. Each HierarchicalFactor actually generates multiple factors - one for each associated variables - as this avoids optimisation of a high dimensionality factor. Question: would it make sense to experiment with a hierarchical factor that optimises all variables samples from a distribution simultaneously? Parameters ---------- distribution A distribution from which variables are drawn optimiser An optional optimiser for this factor name An optional name for this factor kwargs Constants or Priors passed to the distribution to parameterize it. For example, a GaussianPrior requires mean and sigma arguments Examples -------- factor = g.HierarchicalFactor( af.GaussianPrior, mean=af.GaussianPrior( mean=100, sigma=10 ), sigma=af.GaussianPrior( mean=10, sigma=5 ) ) factor.add_sampled_variable( prior ) """ super().__init__(distribution, **kwargs) self._name = name or namer(self.__class__.__name__) self._factors = list() self.optimiser = optimiser @property def name(self): return self._name @property def prior_model(self): return self @property def plates(self): return self._plates def add_drawn_variable(self, prior: Prior): """ Add a variable which is drawn from the distribution. This is likely the attribute of a FactorModel in the graph. Parameters ---------- prior A variable which is sampled from the distribution. """ self._factors.append(_HierarchicalFactor(self, prior)) @property def factors(self) -> List["_HierarchicalFactor"]: """ One factor is generated for each variable sampled from the distribution. """ return self._factors class _HierarchicalFactor(AbstractModelFactor): def __init__( self, distribution_model: HierarchicalFactor, drawn_prior: Prior, ): """ A factor that links a variable to a parameterised distribution. Parameters ---------- distribution_model A prior model which parameterizes a distribution from which it is assumed the variable is drawn drawn_prior A prior representing a variable which was drawn from the distribution """ self.distribution_model = distribution_model self.drawn_prior = drawn_prior def _factor(**kwargs): argument = kwargs.pop("argument") arguments = dict() for name_, array in kwargs.items(): prior_id = int(name_.split("_")[1]) prior = distribution_model.prior_with_id(prior_id) arguments[prior] = array result = distribution_model.instance_for_arguments(arguments)(argument) return result prior_variable_dict = {prior.name: prior for prior in distribution_model.priors} prior_variable_dict["argument"] = drawn_prior super().__init__( prior_model=CollectionPriorModel( distribution_model=distribution_model, drawn_prior=drawn_prior ), factor=_factor, optimiser=distribution_model.optimiser, prior_variable_dict=prior_variable_dict, name=distribution_model.name, ) @property def variable(self): return self.drawn_prior def log_likelihood_function(self, instance): return instance.distribution_model(instance.drawn_prior) @property def priors(self) -> Set[Prior]: """ The set of priors associated with this factor. This is the priors used to parameterize the distribution, plus an additional prior for the variable drawn from the distribution. """ priors = super().priors priors.add(self.drawn_prior) return priors @property def analysis(self): return self def visualize( self, paths: AbstractPaths, instance: ModelInstance, during_analysis: bool ): pass
def time_external(self, time_external): self._time_external = time_external
/** * Finishes the savePlot after getting the note. * * @param note The note. */ private void doSavePlot(final String note) { SharedPreferences prefs = getPreferences(MODE_PRIVATE); String treeUriStr = prefs.getString(PREF_TREE_URI, null); if (treeUriStr == null) { Utils.errMsg(this, "There is no data directory set"); return; } String msg; String format = "yyyy-MM-dd_HH-mm"; SimpleDateFormat df = new SimpleDateFormat(format, Locale.US); String fileName = "PolarPPG-" + df.format(mStopTime) + ".png"; try { Uri treeUri = Uri.parse(treeUriStr); String treeDocumentId = DocumentsContract.getTreeDocumentId(treeUri); Uri docTreeUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, treeDocumentId); ContentResolver resolver = this.getContentResolver(); ParcelFileDescriptor pfd; Uri docUri = DocumentsContract.createDocument(resolver, docTreeUri, "image/png", fileName); pfd = getContentResolver(). openFileDescriptor(docUri, "w"); try (FileOutputStream strm = new FileOutputStream(pfd.getFileDescriptor())) { final LinkedList<Number> vals = mPlotter.getmSeries().getyVals(); final int nSamples = vals.size(); Bitmap bm = PpgImage.createImage(this, mSamplingRate, mStopTime.toString(), mDeviceId, mFirmware, mBatteryLevel, note, mStopHR, String.format(Locale.US, "%.1f " + "sec", nSamples / (double) mSamplingRate), vals); bm.compress(Bitmap.CompressFormat.PNG, 80, strm); strm.close(); msg = "Wrote " + docUri.getLastPathSegment(); Log.d(TAG, msg); Utils.infoMsg(this, msg); } } catch (IOException ex) { msg = "Error saving plot"; Log.e(TAG, msg); Log.e(TAG, Log.getStackTraceString(ex)); Utils.excMsg(this, msg, ex); } }
Alternative Packet Forwarding for Otherwise Discarded Packets Packets in multihop wireless networks are often discarded due to missing routes, packet collision, unreachable next-hop or bit error. As a remedy to these problems, this paper presents alternative packet- forwarding mechanisms that will reduce the likelihood of discarding packets. In addition to this, a new packet-buffering solution is proposed. By combining these two methods, reduced packet loss was achieved in addition to preserved network resources. This was confirmed through simulations, where a comparison between our proposed solutions and standard forwarding showed up to 50% reduction in packet loss.
// DeleteMeasurement deletes a measurement and all related series. func (e *Engine) DeleteMeasurement(name string, seriesKeys []string) error { if err := e.DeleteSeries(seriesKeys); err != nil { return err } e.fieldsMu.Lock() defer e.fieldsMu.Unlock() if err := e.DeleteSeries(seriesKeys); err != nil { return err } delete(e.measurementFields, name) return nil }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { final static char X = 'X'; final static char O = '0'; final static char NONE = '.'; public static boolean isSolved(char[][] map, char player){ for (int i=0; i<3; ++i){ if ((map[i][0] == player && map[i][1] == player && map[i][2] == player) || map[0][i] == player && map[1][i] == player && map[2][i] == player) return true; } if ((map[0][0] == player && map[1][1] == player && map[2][2] == player) || map[0][2] == player && map[1][1] == player && map[2][0] == player) return true; return false; } public static boolean isTie(char[][] map){ for (int i=0; i<3; ++i){ for (int j=0; j<3; ++j){ if (map[i][j] == NONE) return false; } } return true; } public static void main (String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int numX = 0; int numO = 0; char[][] map = new char[3][3]; for (int i=0; i<3; ++i){ for (int j=0; j<3; ++j){ map[i][j] = (char)reader.read(); if (map[i][j] == X) ++numX; else if (map[i][j] == O) ++numO; } reader.readLine(); } boolean xWon = isSolved(map, X); boolean oWon = isSolved(map, O); if (Math.abs(numX-numO) > 1 || numO > numX || (xWon && oWon) || oWon && numX > numO || xWon && numX == numO) System.out.println("illegal"); else if (xWon) System.out.println("the first player won"); else if (oWon) System.out.println("the second player won"); else if (isTie(map)) System.out.println("draw"); else if (numO == numX) System.out.println("first"); else System.out.println("second"); } }
import * as React from 'react'; import styled from 'styled-components'; import axios, { AxiosError } from 'axios'; import { FormattedMessage, defineMessages } from 'react-intl'; import { useDispatch } from 'react-redux'; import { Input, TextSpan } from '../../components'; import { addUser } from '../../redux/actions'; import { ErrorCode, User } from '../../types'; import { Colors } from '../../styles'; const Copy = defineMessages({ ErrorInvalidUserName: { id: 'ErrorInvalidUserName', defaultMessage: 'Please enter a user name', }, ErrorInvalidPassword: { id: 'ErrorInvalidPassword', defaultMessage: 'Password must be more than 8 characters', }, ErrorCreatingUser: { id: 'ErrorCreatingUser', defaultMessage: 'Unable to create account. Try again.', }, ErrorEmailTaken: { id: 'ErrorEmailTaken', defaultMessage: 'Email already taken.', }, RegisterFormSubmit: { id: 'Submit', defaultMessage: 'Sign Up', }, }); const enum Classes { FormContainer = 'create-account-form-container', InputContainer = 'create-account-form-input-container', ErrorMessage = 'create-account-form-error-message', } export const enum RegisterFormTestID { Form = 'create-account-form', EmailInput = 'create-account-form-email-input', UserNameInput = 'create-account-form-username-input', PasswordInput = '<PASSWORD>', SubmitButton = 'create-account-form-submit-button', } export const RegisterForm = () => { const [email, setEmail] = React.useState(''); const [userName, setUserName] = React.useState(''); const [password, setPassword] = React.useState(''); const [errorMessage, setErrorMessage] = React.useState< JSX.Element | string | null >(null); const dispatch = useDispatch(); React.useEffect(() => { if (!email && !userName && !password) { setErrorMessage(null); } }, [email, userName, password]); const clearFields = () => { setEmail(''); setUserName(''); setPassword(''); setErrorMessage(null); }; const MIN_PASSWORD_LENGTH = 8; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (userName.length === 0) { setErrorMessage(<FormattedMessage {...Copy.ErrorInvalidUserName} />); return; } if (password.length < MIN_PASSWORD_LENGTH) { setErrorMessage(<FormattedMessage {...Copy.ErrorInvalidPassword} />); return; } try { const url = '/api/users/create'; const res = await axios.post<User>( url, { email, userName, password, }, { withCredentials: true }, ); dispatch(addUser({ id: res.data.id, userName })); clearFields(); } catch (e) { const err: AxiosError<{ errorCode: number }> = e; err.response.data.errorCode === ErrorCode.EMAIL_ALREADY_TAKEN ? setErrorMessage(<FormattedMessage {...Copy.ErrorEmailTaken} />) : setErrorMessage(<FormattedMessage {...Copy.ErrorCreatingUser} />); } }; const disableButton = !email || !userName || !password; return ( <StyledRegisterForm errorMessage={!!errorMessage} onSubmit={(e) => handleSubmit(e)} data-testid={RegisterFormTestID.Form} > <div className={Classes.FormContainer}> <Input> <label htmlFor='email'>Email</label> <input type='email' id='email' placeholder='Enter email' autoComplete='email' value={email} onChange={(e) => setEmail(e.target.value)} required data-testid={RegisterFormTestID.EmailInput} /> </Input> <Input> <label htmlFor='username'>User Name</label> <input type='text' id='username' placeholder='Enter user name' autoComplete='username' value={userName} onChange={(e) => setUserName(e.target.value)} required data-testid={RegisterFormTestID.UserNameInput} /> </Input> <Input> <label htmlFor='password'>Password</label> <input type='password' id='password' placeholder='Enter password' autoComplete='current-password' value={password} onChange={(e) => setPassword(e.target.value)} required data-testid={RegisterFormTestID.PasswordInput} /> </Input> <button type='submit' disabled={disableButton} style={{ cursor: disableButton ? 'auto' : 'pointer', }} data-testid={RegisterFormTestID.SubmitButton} > <FormattedMessage {...Copy.RegisterFormSubmit} /> </button> </div> <TextSpan className={Classes.ErrorMessage}> {errorMessage ? errorMessage : 'A'} </TextSpan> </StyledRegisterForm> ); }; interface StyledProps { errorMessage: boolean; } const StyledRegisterForm = styled.form<StyledProps>` .${Classes.FormContainer} { margin-bottom: 10px; display: flex; align-items: center; justify-content: center; } button { height: 46px; padding: 10px; background: black; color: ${Colors.mintGreen}; border-color: black; border-radius: 4px; } .${Classes.ErrorMessage} { font-size: 14px; font-weight: bold; color: ${Colors.errorRed}; margin-top: 20px; line-height: 16px; min-height: 16px; visibility: ${(props) => (props.errorMessage ? 'visible' : 'hidden')}; } @media screen and (max-width: 900px) { .${Classes.FormContainer} { flex-direction: column; } button { width: 225px; } } `;
Beginning of Story Content Team Canada's Olympic brain trust will meet Wednesday in Toronto to shorten its "list" for the 2014 Sochi Games and discuss what to do with injured superstar Steven Stamkos. According to the IIHF, there is nothing in the Olympic roster guidelines explicitly preventing an injured player from being chosen to the roster. 'Extraordinary circumstances' End of Story Content One day after the NHL's GM meetings , Team Canada's Olympic brain trust will meet Wednesday in Toronto to shorten its "list" for the 2014 Sochi Games. In addition to some already-difficult decisions, a new one popped up: What to do with Steven Stamkos The 23-year-old superstar is an unexpected question mark after Monday's awful tibia break that's sidelined him for an as yet undetermined period of time. Stamkos underwent what Tampa called successful surgery on Tuesday, and anyone with a soul roots for a magnificent comeback as quickly as possible."Thanks to all my family, friends, and fans for all the well wishes! I will be back as soon as possible !!," he tweeted hours after suffering the setback.No doubt Stamkos, a fitness freak, will be motivated to push himself to the limit. His Lightning are an early-season success story and he's a lock for Sochi, if healthy.At Monday night's Hall of Fame ceremony, Hockey Canada officials indicated they would name Stamkos to the 25-man roster sometime in late December and see how things unfold. They will discuss his injury during this meeting, have the most information on his condition and are in the best position to judge the wisdom of such a move.Can they do it? The answer appears to be yes.According to the International Ice Hockey Federation, there is nothing in the Olympic roster guidelines explicitly preventing an injured player from being chosen to the roster. The original group of 25 must be submitted by New Year's Eve. Team Canada is expected to reveal its players slightly beforehand, while the United States will unveil its selections on Jan. 1 at the Winter Classic.As in previous Games, the final 25 names don't need to be officially registered until 24 hours before the first game. That's Feb. 12 for Canada. From New Year's until that deadline, only injured players or those going through "extraordinary circumstances" (such as a family issue, God forbid) can be replaced For example, Team Canada had Jeff Carter ready to play in Vancouver when Ryan Getzlaf was hurt right before competition. The U.S. did replace injured defencemen Mike Komisarek and Paul Martin with Tim Gleason and Ryan Whitney.However, when Russia head coach Slava Bykov said he would change his roster prior to the Olympics if he felt someone played his way off the team, the NHL and NHLPA objected. The IIHF made it clear it would not accept such a maneuver.Ultimately, IIHF Sports Director Dave Fitzpatrick would have a significant say, but, as previously mentioned, the regulations don't foresee naming injured players. And, there's something to be said for allowing the best to compete on this enormous stage.By late December, we'll probably have a better idea of Stamkos's recovery, which may make all of this moot. But, if it is Canada's plan to put him there on a provisional basis, it doesn't appear to be against the rules.
Congresswoman Nancy Pelosi has made a fool of herself again in public but just in time, she gives relevance to this article that I have been working on. Do those politicians really have any idea what they are talking about? They claim that their Catholicism is firm, but find it inappropriate to “impose” it on others. They take an active public role that requires them to support the exact opposite basic moral teaching, and — impose it on others. Are they just crossing their fingers behind their back like a child playing a game? I think that they have talked themselves into believing that this kind of public position can be reasonable. How did this peculiar nonsensical attitude come about? I am referring to the more visible and persistent ones like Congresswoman Nancy Pelosi, Vice President Joe Biden, Terry McAuliffe former DNC Chairman, and Health and Human Services Secretary Kathleen Sebelius, New York governor Andrew Cuomo…do I have room to continue the list? Pelosi is a special case in that she seems want to revive the old structure that existed during the breakup of the Roman Empire and update it to Princess-bishopric with her “Catholic friends”. It smacks of the later Reformation except the difference is that she supports contra-faith beliefs and Martin Luther objected to them. Biden has indicated that he has pursued a political career keeping his Catholicism [God’s truth] out of it. I have managed to live a reasonably long life (thank you Lord) and have successfully supported a family and nursed a wife through illness. Retirement income and being reasonably free of illness myself (thank you Lord) has allowed me shift my thinking from mostly survival mode to a more luxurious contemplation mode. In this mode, a person begins to wonder about some of the things he heard in his lifetime, but did not really fully comprehend. Strange sounding ideas coming from adult leaders of our society. So many strange sounding ideas in almost three quarters of a century. Well it is time to try and understand this one: Being Catholic and NOT being Catholic at the same time. Probably the best sources for some understanding would be the sources of authority in politics often referred to for this strange phenomenon, the late Senator Ted Kennedy and his brother fondly known as JFK (John F. Kennedy). I meet Ted Kennedy briefly years ago when he and his first wife, Joan, were given a tour of the Peace Corps camp Crozier in Puerto Rico. This was 1962 and I was training for a school building project in Gabon, West Africa. He had just been elected to fill his brother’s vacated senate seat, then president John F. Kennedy, in a special election after two years of an appointed “seat warmer” Benjamin A. Smith II. It was necessary to use Mr. Smith strategically because Ted Kennedy was not yet old enough to run. I recall that there was something unsettling about Kennedy in person. He did not seem to be exceptional and I felt that it was not quite right to run American politics as a family business. Often party and name takes precedence, as George Cabot Lodge II (Republican, also a family carry forward) came the closest to beating Ted Kennedy for this seat. Ted Kennedy is gone now after a long career in federal government service. I was not a fan of his as you have read, I did however especially admire his brother-in-law Sargent Schriver the first Peace Corps Director, whom I was provilaged to meet and talk with. Shriver was, according to a son, a daily Catholic Mass attendee even when traveling. The three Kennedy brothers (to include Robert F. Kennedy) and Schriver had a strong influence on American life. They are remembered still in recent American history (after JFK’s congressional and senate career) from his presidential win in 1960 to the present day. JFK’s time as president had many good features and I am only concentrating on his Catholicism here as it pertains to politics. JFK’s Famous Speech. I believe in an America where the separation of church and state is absolute, where no Catholic prelate would tell the president (should he be Catholic) how to act, and no Protestant minister would tell his parishioners for whom to vote; where no church or church school is granted any public funds or political preference……….. where there is no Catholic vote, no anti-Catholic vote, no bloc voting of any kind………Whatever issue may come before me as president — on birth control, divorce, censorship, gambling or any other subject — I will make my decision in accordance with these views, in accordance with what my conscience tells me to be the national interest, and without regard to outside religious pressures or dictates. And no power or threat of punishment could cause me to decide otherwise. (John F. Kennedy, Speech to Greater Houston Ministerial Association, 1960 – bold added to text, selected portions of speech shown) This speech of John Kennedy appeased those who were afraid of direct involvement in American politics by the Vatican. How he would be an employee of the pope who would call John directly about some passport problem or lack of FBI interest in enforcement of some aspect of Canon law, and John would fix it. Of course this kind of allegiance means that the Protestant ministers of the South would probably have had to leave a message with the White House operator. But, this speech leaves one wondering exactly what he meant or even if he knew more fully what he was saying. What I think he said is this, His conscience will guide him and if it differs from Church teaching he will disregard that teaching. Was he saying that his conscience was not formed by Catholic teaching? On what magnitude or importance of a problem would he disregard Church teaching? Everything? In other words was he declaring that he would, if elected, ignore God’s law substituting secular thinking and thus lead a large population to ignore the lesson of Genesis 3? He did not approve of religious groups voting as a block. So what about political groups or blocks? Political party leaders and the numerous special interest group lobbyists in Washington can be allowed to pressure anyone. It is not block action or influence he did not like, it was from a particular group. So that leaves the question, how does he justify ignoring God’s will and then claiming to want to follow his will by calling himself Catholic? This is an understandable state of human existence when we look to our own lives. We all must examine our consciences and reconcile ourselves to God. But, what we are understanding here is a rule or an accepted behavior being proposed, not a failure to abide. Isn’t what he was saying the same as, I am Catholic when I want to be, and that is acceptable behavior? What about non-negotiable issues? Does this just mean that whatever religious affiliation may have shaped your life, gave it meaning and clarity, doesn’t matter in order to get elected? Or is it true that there is no pretense at all. Maybe Ted Kennedy Can Help Us Understand Better. Ted Kennedy gives us some insight into this quandary by trying to fill in some detail. In 1983 (erroneously when last checked attributed to 1969 here) he gave a speech at Rev. Jerry Falwell’s Liberty College regarding religion and politics in America. This speech tries to give a more detailed reasoning in order to ease the conscience of those who wish to trade their religious dogma for a political career. President Kennedy, who said that “no religious body should seek to impose its will,” also urged religious leaders to state their views and give their commitment when the public debate involved ethical issues. In drawing the line between imposed will and essential witness, we keep church and state separate, and at the same time we recognize that the City of God should speak to the civic duties of men and women. (Ted Kennedy, Liberty College speech, 1983 – bold added to text) So, exactly how “imposed will” works in politics I can only guess means the imposition of law as opposed to “witness”, which means just speaking about an issue. If this is so, we are left with not only a Church but religious individuals who are restricted to wanting a law dealing with a moral issue but can’t say so. For example: We can speak about the misery that rape causes but we would be restricted from declaring support for a law against rape! Absurd. He continues: The real transgression occurs when religion wants government to tell citizens how to live uniquely personal parts of their lives. The failure of Prohibition proves the futility of such an attempt when a majority or even a substantial minority happens to disagree. Some questions may be inherently individual ones, or people may be sharply divided about whether they are. In such cases, like Prohibition and abortion, the proper role of religion is to appeal to the conscience of the individual, not the coercive power of the state. But there are other questions which are inherently public in nature, which we must decide together as a nation, and where religion and religious values can and should speak to our common conscience. The issue of nuclear war is a compelling example. It is a moral issue; it will be decided by government, not by each individual; and to give any effect to the moral values of their creed, people of faith must speak directly about public policy. Now Do We Understand? We have now some understanding of how the Kennedy approach works, you define those things which you consider have to do with the individual only, and declare those things off limits to governmental action – hence you as a government official have no right to interfere regardless of your religions teachings. Sounds nice and neat until we realize that the declaration that an issue is “uniquely personal” can be faulty according to a person’s faith teaching or any other source of moral understanding. Such is the case with abortion. It is very clear in Catholic teaching that an unborn is a human person that has a right to life, it was clear in 1960 and 1983. (Catechism of the Catholic Church or CCC) 1959 The natural law, the Creator’s very good work, provides the solid foundation on which man can build the structure of moral rules to guide his choices. It also provides the indispensable moral foundation for building the human community. Finally, it provides the necessary basis for the civil law with which it is connected, whether by a reflection that draws conclusions from its principles, or by additions of a positive and juridical nature. 1960 The precepts of natural law are not perceived by everyone clearly and immediately. In the present situation sinful man needs grace and revelation so moral and religious truths may be known “by everyone with facility, with firm certainty and with no admixture of error.”The natural law provides revealed law and grace with a foundation prepared by God and in accordance with the work of the Spirit. In the speech, Ted Kennedy also tried to provide a set of four rules for determining when it is proper to apply a conscience formed by religious values. This attempt to legislate outside of the legislature, or simply moralize, put Mr. Kennedy in the position of trying to redefine the role of the Church in American life. He also seemed to be creating rules that only apply to religion, it is unclear that if a lawmaker was in favor of Prohibition and was not religious or could have been an atheist, if it would be alright to support Prohibition because he wanted to stop drunkenness and the harm it causes to innocent people. In the first rule, he cautioned people when speaking from religions authority (such as the Bible), that a person interpret correctly, and gives some examples of his interpretation as a guide to correctness. He proceeded to define what is an acceptable name to give to a religious organization and then he self-righteously warned against being self-righteous. Second, he says that honest conviction is the only justification a person needs in order to legitimately disagree with the Catholic Church. Of course the Church has a different teaching on this: CCC 88 – The Church’s Magisterium exercises the authority it holds from Christ to the fullest extent when it defines dogmas, that is, when it proposes, in a form obliging the Christian people to an irrevocable adherence of faith, truths contained in divine Revelation or also when it proposes, in a definitive way, truths having a necessary connection with these. Third, he did not like phantom issues or false charges and he would let us know which was which. Apparently this test was ignored in later election campaigns by most politicians, presumably because it was meant only for religious people. Fourth, with some justification I think he said we must respect the motives of those who disagree. This advice has also generally been disregarded in later election campaigns as it was in 1983 during the presidencyor Ronald Reagan. What Have We Learned? So, I come away from these explanations for a wall of separation between the Catholic life and the rest of the world unconvinced that they are meaningful rules at all! I see those speeches as just generalized appeasement nonsense for political ends that has soaked into the American consciences to her detriment. I do however like at least one sentence of Ted Kennedy’s speech were he said, “Separation of church and state cannot mean an absolute separation between moral principles and political power.” Did either of them really need to say anything more? This Man Said It Best of All. And let us with caution indulge the supposition that morality can be maintained without religion. Whatever may be conceded to the influence of refined education on minds of peculiar structure, reason and experience both forbid us to expect that national morality can prevail in exclusion of religious principle. (George Washington, Farewell Address, 1796) © 2013. Howard Duncan. All Rights Reserved.
#include <stdio.h> #include <algorithm> using namespace std; int main() { int n, m; scanf("%d%d", &n, &m); int bd, bh; scanf("%d%d", &bd, &bh); long long ans = bd + bh - 1; while (--m) { int nd, nh; scanf("%d%d", &nd, &nh); int hh = nh - bh, dd = nd - bd; if (hh < 0) hh = -hh; if (hh > dd) { puts("IMPOSSIBLE"); return 0; } ans = max(ans, (long long)(max(bh, nh) + (dd - hh) / 2)); bd = nd, bh = nh; } ans = max(ans, (long long)(n - bd + bh)); printf("%lld", ans); }
def update_keepkey_pass_encoding_ui(self): self.wdgKeepkeyPassEncoding.setVisible(self.local_config.hw_type == HWType.keepkey)
multimon_monitor_t *multimon_get_monitor(int tag_mask) { multimon_monitor_t *monitor = multimon_monitor_list.head_monitor; while(monitor && !(monitor->tag_mask & tag_mask)) monitor = monitor->next; return monitor ? monitor : multimon_monitor_list.head_monitor; } void multimon_update() { if (XineramaIsActive(wm_global.display)) { // load new monitor information int number; XineramaScreenInfo *scr_info = XineramaQueryScreens(wm_global.display, &number); // search for removed monitors and update of not removed multimon_monitor_t *monitor = multimon_monitor_list.head_monitor; multimon_monitor_t *next_monitor; bool found_monitor; while(monitor) { found_monitor = false; for (int i = 0; i < number; i++) { if (scr_info[i].x_org == monitor->x && scr_info[i].y_org == monitor->y) { found_monitor = true; // update monitor monitor->w = scr_info[i].width; monitor->h = scr_info[i].height; } } next_monitor = monitor->next; if (!found_monitor) { // delete monitor if (monitor->next) monitor->next->prev = monitor->prev; if (monitor->prev) monitor->prev->next = monitor->next; multimon_monitor_list.size--; multimon_monitor_list.head_monitor->tag_mask = multimon_monitor_list.head_monitor->tag_mask | monitor->tag_mask; if (monitor == multimon_monitor_list.head_monitor) multimon_monitor_list.head_monitor = monitor->next; free(monitor); } monitor = next_monitor; } // search for new monitors for (int i = 0; i < number; i++) { monitor = multimon_monitor_list.head_monitor; if (!monitor) { // add monitor next_monitor = malloc(sizeof(multimon_monitor_t)); next_monitor->x = scr_info[i].x_org; next_monitor->y = scr_info[i].y_org; next_monitor->w = scr_info[i].width; next_monitor->h = scr_info[i].height; next_monitor->tag_mask = -1; next_monitor->active_tag_mask = 0; next_monitor->next = NULL; next_monitor->prev = NULL; multimon_monitor_list.size = 1; multimon_monitor_list.head_monitor = next_monitor; } while (monitor) { if (monitor->x == scr_info[i].x_org && monitor->y == scr_info[i].y_org) break; if (monitor->next == NULL) { // add monitor next_monitor = malloc(sizeof(multimon_monitor_t)); next_monitor->x = scr_info[i].x_org; next_monitor->y = scr_info[i].y_org; next_monitor->w = scr_info[i].width; next_monitor->h = scr_info[i].height; next_monitor->tag_mask = 0; next_monitor->active_tag_mask = 0; next_monitor->next = NULL; next_monitor->prev = monitor; monitor->next = next_monitor; multimon_monitor_list.size++; break; } monitor = monitor->next; } } // free new monitor information XFree(scr_info); } } void multimon_init() { multimon_update(); multimon_monitor_t *monitor = multimon_get_monitor(wm_global.tag_mask); monitor->active_tag_mask = wm_global.tag_mask; wm_global.x = monitor->x; wm_global.y = monitor->y; wm_global.w = monitor->w; wm_global.h = monitor->h; } void multimon_on_retag(int tag_mask) { multimon_update(); multimon_monitor_t *monitor_old = multimon_get_monitor(wm_global.tag_mask); multimon_monitor_t *monitor_new = multimon_get_monitor(tag_mask); if (monitor_old != monitor_new) wm_global.tag_mask = 0; wm_global.x = monitor_new->x; wm_global.y = monitor_new->y; wm_global.w = monitor_new->w; wm_global.h = monitor_new->h; } void multimon_move_tag_mask_to_monitor(multimon_monitor_t *old, multimon_monitor_t *new) { wm_clients_unmap(new->active_tag_mask); old->tag_mask = old->tag_mask ^ wm_global.tag_mask; old->active_tag_mask = 0; new->tag_mask = new->tag_mask ^ wm_global.tag_mask; new->active_tag_mask = wm_global.tag_mask; wm_global.x = new->x; wm_global.y = new->y; wm_global.w = new->w; wm_global.h = new->h; wm_clients_arrange(); } void multimon_move_tag_mask_to_next_monitor() { multimon_update(); multimon_monitor_t *monitor = multimon_get_monitor(wm_global.tag_mask); if (monitor, monitor->next) multimon_move_tag_mask_to_monitor(monitor, monitor->next); } void multimon_move_tag_mask_to_prev_monitor() { multimon_update(); multimon_monitor_t *monitor = multimon_get_monitor(wm_global.tag_mask); if (monitor, monitor->prev) multimon_move_tag_mask_to_monitor(monitor, monitor->prev); }
/** * Appends a {@link String} representation of an {@link Object}'s accessible fields to a {@link StringBuilder}. * found in a given {@link Object} * @param fields an array of {@link Field} * @param obj the {@link Object} to represent * @param stringBuilder the {@link StringBuilder} to add the representation to * @return the number of represented {@link Field}(s) */ private static final int appendFields(final Field[] fields,final Object obj,final StringBuilder stringBuilder){ int numberOfFields=fields.length; if(numberOfFields>0){ final String objectName=obj.getClass().getSimpleName(); for(final Field field : fields){ field.setAccessible(true); String fieldName="NOT-SET"; try { fieldName=field.getName(); final Object fieldValue = field.get(obj); final Class<?> fieldTypeClass = field.getType(); String stringValue="NULL"; if(fieldValue!=null){ stringValue=fieldValue.toString(); } if(fieldTypeClass.equals(Logger.class)){ continue; }else if(fieldTypeClass.equals(String.class)){ stringBuilder.append(fieldName).append("='").append(stringValue).append("',\n"); }else{ stringBuilder.append(fieldName).append("=").append(stringValue).append(",\n"); } } catch (final IllegalArgumentException e) { LOGGER.error("Class {} does not contain field {}",objectName,fieldName,e); numberOfFields--; } catch (final IllegalAccessException e) { LOGGER.error("Field {} of Class {} is not accessible",fieldName,objectName,e); numberOfFields--; } } } return numberOfFields; }
// AddAddress appends the specified TCP address to the list of known addresses // this node is/was known to be reachable at. func (l *LinkNode) AddAddress(addr net.Addr) error { for _, a := range l.Addresses { if a.String() == addr.String() { return nil } } l.Addresses = append(l.Addresses, addr) return l.Sync() }
// Despawn enemy on collision with player's laser. pub fn despawn_system( mut cmds: Commands, mut red_laser_query: Query< ( Entity, &Transform, &Sprite, ), With<Laser>, >, mut enemy_query: Query< ( Entity, &Transform, &Sprite, ), With<Enemy>, >, mut active_enemy: ResMut<ActiveEnemies> ) { for ( red_laser_entity, red_laser_trans, red_laser_sprite ) in red_laser_query.iter_mut() { for ( enemy_entity, enemy_trans, enemy_sprite ) in enemy_query.iter_mut() { let red_laser_scale = Vec3::truncate(red_laser_trans.scale); let enemy_scale = Vec3::truncate(enemy_trans.scale); let on_collision = collide( red_laser_trans.translation, red_laser_sprite.custom_size.unwrap() * red_laser_scale, enemy_trans.translation, enemy_sprite.custom_size.unwrap() * enemy_scale, ); if let Some(_) = on_collision { cmds .entity(enemy_entity) .despawn(); active_enemy.0 -= 1; cmds .entity(red_laser_entity) .despawn(); } } } }
A Florida Panhandle officer shot and killed a teenage boy early Tuesday after the teen ran over another officer's leg, police said. According to information released by the Pensacola Police Department, William Goodman, 17, was killed after an officer fired shots into his 2009 Chevrolet Corvette. The injured officer was treated and released at an area emergency room and the officer who shot Goodman is on paid administrative leave pending an investigation by the Florida Department of Law Enforcement, police said. Officers were trying to stop Goodman after numerous reports that he was driving recklessly and at excessive speeds. They said Goodman fled from them at speeds approaching 100 miles per hour. Top News Photos of the Week Goodman repeatedly rammed police vehicles after officers surrounded his car and tried to arrest him, police said. The dead teen was scheduled for a court appearance next month on charges from earlier this year. According to prosecutors, Goodman killed a pedestrian in March while illegally passing another vehicle. The Pensacola News Journal reported in August that Goodman, then 16, was charged with vehicular manslaughter and reckless driving with injuries in connection with the death of 66-year-old Michael M. Labelle of Sand Lake, Mich. Police said Goodman was speeding through a residential neighborhood and struck Labelle and his wife when he tried to pass another car. Copyright Associated Press
<reponame>iosliutingxin/MWeng_PreviewModule // // UZMediator.h // UzaiModuleApp // // Created by leijian on 16/6/30. // Copyright © 2016年 Uzai. All rights reserved. // #import <Foundation/Foundation.h> typedef void (^UZUrlRouterCallbackBlock)(void); @interface UZMediatorManager : NSObject + (instancetype)sharedInstance; // 远程App调用入口 - (id)performActionWithUrl:(NSURL *)url completion:(void(^)(NSDictionary *info))completion; // 本地组件调用入口 - (id)performTarget:(NSString *)targetName action:(NSString *)actionName params:(NSDictionary *)params; @end
/** * @brief base constructor. * @param worker may gets run by several threads. */ base(blub::async::dispatcher &worker) : t_base(worker) , m_numInTilesInTask(0) { }
/** * initComponents, This initializes the components of the JFormDesigner panel. This function is * automatically generated by JFormDesigner from the JFD form design file, and should not be * modified by hand. This function can be modified, if needed, by using JFormDesigner. */ private void initComponents() { timeTextField = new JTextField(); toggleTimeMenuButton = new JButton(); spinnerPanel = new JPanel(); increaseButton = new JButton(); decreaseButton = new JButton(); setLayout(new FormLayout( "pref:grow, 3*(pref)", "fill:pref:grow")); timeTextField.setMargin(new Insets(1, 3, 2, 2)); timeTextField.setBorder(new CompoundBorder( new MatteBorder(1, 1, 1, 1, new Color(122, 138, 153)), new EmptyBorder(1, 3, 2, 2))); timeTextField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { setTextFieldToValidStateIfNeeded(); } }); add(timeTextField, CC.xy(1, 1)); toggleTimeMenuButton.setText("v"); toggleTimeMenuButton.setFocusPainted(false); toggleTimeMenuButton.setFocusable(false); toggleTimeMenuButton.setFont(new Font("Segoe UI", Font.PLAIN, 8)); toggleTimeMenuButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { zEventToggleTimeMenuButtonMousePressed(e); } }); add(toggleTimeMenuButton, CC.xy(3, 1)); { spinnerPanel.setLayout(new FormLayout( "default", "fill:pref:grow, fill:default:grow")); ((FormLayout) spinnerPanel.getLayout()).setRowGroups(new int[][]{{1, 2}}); increaseButton.setFocusPainted(false); increaseButton.setFocusable(false); increaseButton.setFont(new Font("Arial", Font.PLAIN, 8)); increaseButton.setText("+"); spinnerPanel.add(increaseButton, CC.xy(1, 1)); decreaseButton.setFocusPainted(false); decreaseButton.setFocusable(false); decreaseButton.setFont(new Font("Arial", Font.PLAIN, 8)); decreaseButton.setText("-"); spinnerPanel.add(decreaseButton, CC.xy(1, 2)); } add(spinnerPanel, CC.xy(4, 1)); }
import numpy as np import skimage.draw as skdraw def vis_bbox(bbox,img,color=(255,0,0),modify=False,alpha=0.2): im_h,im_w = img.shape[0:2] x1,y1,x2,y2 = bbox x1 = max(0,min(x1,im_w-1)) x2 = max(x1,min(x2,im_w-1)) y1 = max(0,min(y1,im_h-1)) y2 = max(y1,min(y2,im_h-1)) r = [y1,y1,y2,y2] c = [x1,x2,x2,x1] if modify==True: img_ = img else: img_ = np.copy(img) if len(img.shape)==2: color = (color[0],) rr,cc = skdraw.polygon(r,c,img.shape[:2]) skdraw.set_color(img_,(rr,cc),color,alpha=alpha) rr,cc = skdraw.polygon_perimeter(r,c,img.shape[:2]) if len(img.shape)==3: for k in range(3): img_[rr,cc,k] = color[k] elif len(img.shape)==2: img_[rr,cc]=color[0] return img_ def create_att(bbox,prev_att,att_value): im_h,im_w = prev_att.shape[0:2] x1,y1,x2,y2 = bbox x1 = int(max(0,min(x1,im_w-1))) x2 = int(max(x1,min(x2,im_w-1))) y1 = int(max(0,min(y1,im_h-1))) y2 = int(max(y1,min(y2,im_h-1))) r = [y1,y1,y2,y2] c = [x1,x2,x2,x1] att = 0*prev_att att[y1:y2,x1:x2] = att_value return np.maximum(prev_att,att) def compute_iou(bbox1,bbox2,verbose=False): x1,y1,x2,y2 = bbox1 x1_,y1_,x2_,y2_ = bbox2 x1_in = max(x1,x1_) y1_in = max(y1,y1_) x2_in = min(x2,x2_) y2_in = min(y2,y2_) intersection = compute_area(bbox=[x1_in,y1_in,x2_in,y2_in],invalid=0.0) area1 = compute_area(bbox1) area2 = compute_area(bbox2) union = area1 + area2 - intersection iou = intersection / (union + 1e-6) if verbose: return iou, intersection, union return iou def compute_area(bbox,invalid=None): x1,y1,x2,y2 = bbox if (x2 <= x1) or (y2 <= y1): area = invalid else: area = (x2 - x1 + 1) * (y2 - y1 + 1) return area def point_in_box(pt,bbox): x1,y1,x2,y2 = bbox x,y = pt is_inside = False if x>x1 and x<x2 and y>y1 and y<y2: is_inside=True return is_inside def compute_center(bbox): x1,y1,x2,y2 = bbox xc = 0.5*(x1+x2) yc = 0.5*(y1+y2) return (xc,yc)
package dev.morphia.aggregation.stages; /** * Randomly selects the specified number of documents from its input. * * @aggregation.expression $skip */ public class Skip extends Stage { private final long size; protected Skip(long size) { super("$skip"); this.size = size; } /** * Creates a new stage with the given skip size * * @param size the skip size * @return the new stage * @deprecated use {@link #skip(long)} */ @Deprecated(forRemoval = true) public static Skip of(long size) { return new Skip(size); } /** * Creates a new stage with the given skip size * * @param size the skip size * @return the new stage * @since 2.2 */ public static Skip skip(long size) { return new Skip(size); } /** * @return the size * @morphia.internal */ public long getSize() { return size; } }
def put_course_info(orgUnitId, json_data): url = DOMAIN + "/lp/{}/courses/{}".format(LP_VERSION, orgUnitId) response = requests.put(url, headers=HEADERS, json=json_data) code_log(response, "PUT course offering info org unit {}".format(orgUnitId))
/** * Send a request to the QLDB database to delete the specified ledger. * Disables deletion protection before sending the deletion request. * * @param ledgerName * Name of the ledger to be deleted. * @return DeleteLedgerResult. */ public static DeleteLedgerResult delete(final String ledgerName) { log.info("Attempting to delete the ledger with name: {}...", ledgerName); DeleteLedgerRequest request = new DeleteLedgerRequest().withName(ledgerName); DeleteLedgerResult result = client.deleteLedger(request); log.info("Success."); return result; }
<filename>src/components/Image/index.tsx<gh_stars>1000+ import React, { useState, useEffect, useRef } from 'react'; import clsx from 'clsx'; import useForwardRef from '../../hooks/useForwardRef'; export interface ImageProps extends React.ImgHTMLAttributes<HTMLImageElement> { className?: string; src: string; lazy?: boolean; fluid?: boolean; } export const Image = React.forwardRef<HTMLImageElement, ImageProps>((props, ref) => { const { className, src: oSrc, lazy, fluid, children, ...other } = props; const [src, setSrc] = useState(''); const imgRef = useForwardRef(ref); const savedSrc = useRef(''); const lazyLoaded = useRef(false); useEffect(() => { if (!lazy) return undefined; const observer = new IntersectionObserver(([entry]) => { if (entry.isIntersecting) { setSrc(savedSrc.current); lazyLoaded.current = true; observer.unobserve(entry.target); } }); if (imgRef.current) { observer.observe(imgRef.current); } return () => { observer.disconnect(); }; }, [imgRef, lazy]); useEffect(() => { savedSrc.current = oSrc; setSrc(lazy && !lazyLoaded.current ? '' : oSrc); }, [lazy, oSrc]); return ( <img className={clsx('Image', { 'Image--fluid': fluid }, className)} src={src} alt="" ref={imgRef} {...other} /> ); });
def generate(self) -> None: if len(self.merged_values.keys()) > 1: raise ValueError( "The merged values should only have one top level key for the root element" ) root_element_key = list(self.merged_values.keys())[0] root_element_name = root_element_key logger.debug(f"Creating XML element root for {root_element_name}") root = minidom.Document() xml = root.createElement(root_element_name) root.appendChild(xml) sub_elements = self.merged_values[root_element_key] for element_key, element_val in sub_elements.items(): if isinstance(element_val, bool): element_val_str = "true" if element_val else "false" else: element_val_str = str(element_val) if root_element_name == "ServerSettings": e = root.createElement("property") e.setAttribute("name", element_key) e.setAttribute("value", element_val_str) logger.debug( f"Created element property name={element_key}, value={element_val_str}" ) xml.appendChild(e) elif root_element_name == "adminTools": e = root.createElement(element_key) if isinstance(element_val, Iterable): for el_sub_val in element_val: el_sub_name = list(el_sub_val.keys())[0] el_sub = root.createElement(el_sub_name) for k1, v1 in el_sub_val[el_sub_name].items(): el_sub.setAttribute(k1, str(v1)) logger.debug(f"Created element {el_sub_name} ") e.appendChild(el_sub) xml.appendChild(e) xml_str = root.toprettyxml(encoding="UTF-8") with open(Path(SERVER_INSTALL_DIR, self.out_file), "wb") as of: of.write(xml_str)
/** * Calculate a normal from a vertex cloud. * * \note We could make a higher quality version that takes all vertices into account. * Currently it finds 4 outer most points returning its normal. */ void BM_verts_calc_normal_from_cloud_ex( BMVert **varr, int varr_len, float r_normal[3], float r_center[3], int *r_index_tangent) { const float varr_len_inv = 1.0f / (float)varr_len; float center[3] = {0.0f, 0.0f, 0.0f}; for (int i = 0; i < varr_len; i++) { madd_v3_v3fl(center, varr[i]->co, varr_len_inv); } int co_a_index = 0; const float *co_a = NULL; { float dist_sq_max = -1.0f; for (int i = 0; i < varr_len; i++) { const float dist_sq_test = len_squared_v3v3(varr[i]->co, center); if (!(dist_sq_test <= dist_sq_max)) { co_a = varr[i]->co; co_a_index = i; dist_sq_max = dist_sq_test; } } } float dir_a[3]; sub_v3_v3v3(dir_a, co_a, center); normalize_v3(dir_a); const float *co_b = NULL; float dir_b[3] = {0.0f, 0.0f, 0.0f}; { float dist_sq_max = -1.0f; for (int i = 0; i < varr_len; i++) { if (varr[i]->co == co_a) { continue; } float dir_test[3]; sub_v3_v3v3(dir_test, varr[i]->co, center); project_plane_normalized_v3_v3v3(dir_test, dir_test, dir_a); const float dist_sq_test = len_squared_v3(dir_test); if (!(dist_sq_test <= dist_sq_max)) { co_b = varr[i]->co; dist_sq_max = dist_sq_test; copy_v3_v3(dir_b, dir_test); } } } if (varr_len <= 3) { normal_tri_v3(r_normal, center, co_a, co_b); goto finally; } normalize_v3(dir_b); const float *co_a_opposite = NULL; const float *co_b_opposite = NULL; { float dot_a_min = FLT_MAX; float dot_b_min = FLT_MAX; for (int i = 0; i < varr_len; i++) { const float *co_test = varr[i]->co; float dot_test; if (co_test != co_a) { dot_test = dot_v3v3(dir_a, co_test); if (dot_test < dot_a_min) { dot_a_min = dot_test; co_a_opposite = co_test; } } if (co_test != co_b) { dot_test = dot_v3v3(dir_b, co_test); if (dot_test < dot_b_min) { dot_b_min = dot_test; co_b_opposite = co_test; } } } } normal_quad_v3(r_normal, co_a, co_b, co_a_opposite, co_b_opposite); finally: if (r_center != NULL) { copy_v3_v3(r_center, center); } if (r_index_tangent != NULL) { *r_index_tangent = co_a_index; } }
/* * Copyright Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at: * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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.amazon.ionpathextraction; import static com.amazon.ionpathextraction.internal.Preconditions.checkArgument; import com.amazon.ion.IonReader; import com.amazon.ionpathextraction.internal.Annotations; import com.amazon.ionpathextraction.internal.PathExtractorConfig; import com.amazon.ionpathextraction.pathcomponents.PathComponent; import java.util.ArrayList; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; /** * {@link PathExtractor} builder. */ public final class PathExtractorBuilder<T> { private static final boolean DEFAULT_MATCH_RELATIVE_PATHS = false; private static final boolean DEFAULT_CASE_INSENSITIVE = false; private final List<SearchPath<T>> searchPaths = new ArrayList<>(); private boolean matchRelativePaths; private boolean matchCaseInsensitive; private PathExtractorBuilder() { } /** * Creates a new builder with standard configuration. * * @return new standard builder instance. */ public static <T> PathExtractorBuilder<T> standard() { PathExtractorBuilder<T> builder = new PathExtractorBuilder<>(); builder.matchCaseInsensitive = DEFAULT_CASE_INSENSITIVE; builder.matchRelativePaths = DEFAULT_MATCH_RELATIVE_PATHS; return builder; } /** * Instantiates a thread safe {@link PathExtractor} configured by this builder. * * @return new {@link PathExtractor} instance. */ public PathExtractor<T> build() { return new PathExtractorImpl<>(searchPaths, new PathExtractorConfig(matchRelativePaths, matchCaseInsensitive)); } /** * Sets matchRelativePaths config. When true the path extractor will accept readers at any depth, when false the * reader must be at depth zero. * * <BR> * defaults to false. * * @param matchRelativePaths new config value. * @return builder for chaining. */ public PathExtractorBuilder<T> withMatchRelativePaths(final boolean matchRelativePaths) { this.matchRelativePaths = matchRelativePaths; return this; } /** * Sets matchCaseInsensitive config. When true the path extractor will match fields ignoring case, when false the * path extractor will mach respecting the path components case. * * <BR> * defaults to false. * * @param matchCaseInsensitive new config value. * @return builder for chaining. */ public PathExtractorBuilder<T> withMatchCaseInsensitive(final boolean matchCaseInsensitive) { this.matchCaseInsensitive = matchCaseInsensitive; return this; } /** * Register a callback for a search path. * * @param searchPathAsIon string representation of a search path. * @param callback callback to be registered. * @return builder for chaining. * @see PathExtractorBuilder#withSearchPath(List, BiFunction, String[]) */ public PathExtractorBuilder<T> withSearchPath(final String searchPathAsIon, final Function<IonReader, Integer> callback) { checkArgument(callback != null, "callback cannot be null"); withSearchPath(searchPathAsIon, (reader, t) -> callback.apply(reader)); return this; } /** * Register a callback for a search path. * * @param searchPathAsIon string representation of a search path. * @param callback callback to be registered. * @return builder for chaining. * @see PathExtractorBuilder#withSearchPath(List, BiFunction, String[]) */ public PathExtractorBuilder<T> withSearchPath(final String searchPathAsIon, final BiFunction<IonReader, T, Integer> callback) { checkArgument(searchPathAsIon != null, "searchPathAsIon cannot be null"); checkArgument(callback != null, "callback cannot be null"); SearchPath<T> searchPath = SearchPathParser.parse(searchPathAsIon, callback); searchPaths.add(searchPath); return this; } /** * Register a callback for a search path. * * @param pathComponents search path as a list of path components. * @param callback callback to be registered. * @param annotations annotations used with this search path. * @return builder for chaining. */ public PathExtractorBuilder<T> withSearchPath(final List<PathComponent> pathComponents, final Function<IonReader, Integer> callback, final String[] annotations) { checkArgument(callback != null, "callback cannot be null"); return withSearchPath(pathComponents, (reader, t) -> callback.apply(reader), annotations); } /** * Register a callback for a search path. * <p> * The callback receives the matcher's {@link IonReader}, positioned on the matching value, so that it can use the * appropriate reader method to access the value. The callback return value is a ‘step-out-N’ instruction. The most * common value is zero, which tells the extractor to continue with the next value at the same depth. A return value * greater than zero may be useful to users who only care about the first match at a particular depth. * </p> * * <p> * Callback implementations <strong>MUST</strong> comply with the following: * </p> * * <ul> * <li> * The reader must not be advanced past the matching value. Violating this will cause the following value to be * skipped. If a value is skipped, neither the value itself nor any of its children will be checked for match * against any of the extractor's registered paths. * </li> * <li> * If the reader is positioned on a container value, its cursor must be at the same depth when the callback returns. * In other words, if the user steps in to the matched value, it must step out an equal number of times. Violating * this will raise an error. * </li> * <li> * Return value must be between zero and the the current reader relative depth, for example the following search * path (foo bar) must return values between 0 and 2 inclusive. * </li> * <li> * When there are nested search paths, e.g. (foo) and (foo bar), the callback for (foo) should not read the reader * value if it's a container. Doing so will advance the reader to the end of the container making impossible to * match (foo bar). * </li> * </ul> * * @param pathComponents search path as a list of path components. * @param callback callback to be registered. * @param annotations annotations used with this search path. * @return builder for chaining. */ public PathExtractorBuilder<T> withSearchPath(final List<PathComponent> pathComponents, final BiFunction<IonReader, T, Integer> callback, final String[] annotations) { checkArgument(pathComponents != null, "pathComponents cannot be null"); checkArgument(callback != null, "callback cannot be null"); checkArgument(annotations != null, "annotations cannot be null"); searchPaths.add(new SearchPath<>(pathComponents, callback, new Annotations(annotations))); return this; } }
def sample_wr(indices): return ( choice(indices) for _ in indices )
def visit(self, filename: str, root: XMLNode) -> Any: self.filename_stack.append(filename) if self._verbose: print(indent_text(filename, self._indent)) def _inner(node: XMLNode): if self._verbose: print(indent_text(node.open_tag(), self._indent)) if node.text: print(indent_text(node.text, self._indent + 1)) self._indent += 1 try: proc = self._get_processor(node.tag + "_init") if proc is not None: rv = proc(node) if rv == "skip": return None self.node_stack.append(node) for i, c in enumerate(node.children): node.children[i] = _inner(c) node.children = [c for c in node.children if c is not None] self.node_stack.pop() proc = self._get_processor(node.tag) if proc is not None: if self._verbose: print(indent_text(node.close_tag(), self._indent - 1)) return proc(node) if self._verbose: print(indent_text(node.close_tag(), self._indent - 1)) return node finally: self._indent -= 1 try: root = root.clone() return _inner(root) finally: self.filename_stack.pop()
<gh_stars>0 package cn.gson.oasys.controller.user; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Order; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.github.pagehelper.util.StringUtil; import com.github.stuxuhai.jpinyin.PinyinException; import com.github.stuxuhai.jpinyin.PinyinFormat; import com.github.stuxuhai.jpinyin.PinyinHelper; import cn.gson.oasys.model.dao.roledao.RoleDao; import cn.gson.oasys.model.dao.user.DeptDao; import cn.gson.oasys.model.dao.user.PositionDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.entity.role.Role; import cn.gson.oasys.model.entity.user.Dept; import cn.gson.oasys.model.entity.user.Position; import cn.gson.oasys.model.entity.user.User; import org.springframework.web.servlet.ModelAndView; import javax.transaction.Transactional; @Controller @RequestMapping("/") public class UserController { @Autowired UserDao udao; @Autowired DeptDao ddao; @Autowired PositionDao pdao; @Autowired RoleDao rdao; @RequestMapping("userlogmanage") public String userlogmanage() { return "user/userlogmanage"; } @RequestMapping("usermanage") public String usermanage(Model model, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "size", defaultValue = "10") int size ) { Sort sort = new Sort(new Order(Direction.ASC, "dept")); Pageable pa = new PageRequest(page, size, sort); Page<User> userspage = udao.findByIsLock(0, pa); List<User> users = userspage.getContent(); model.addAttribute("users", users); model.addAttribute("page", userspage); model.addAttribute("url", "usermanagepaging"); return "user/usermanage"; } @RequestMapping("usermanagepaging") public String userPaging(Model model, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "size", defaultValue = "10") int size, @RequestParam(value = "usersearch", required = false) String usersearch ) { Sort sort = new Sort(new Order(Direction.ASC, "dept")); Pageable pa = new PageRequest(page, size, sort); Page<User> userspage = null; if (StringUtil.isEmpty(usersearch)) { userspage = udao.findByIsLock(0, pa); } else { System.out.println(usersearch); userspage = udao.findnamelike(usersearch, pa); } List<User> users = userspage.getContent(); model.addAttribute("users", users); model.addAttribute("page", userspage); model.addAttribute("url", "usermanagepaging"); return "user/usermanagepaging"; } @RequestMapping(value = "useredit", method = RequestMethod.GET) public String usereditget(@RequestParam(value = "userid", required = false) Long userid, Model model) { if (userid != null) { User user = udao.findOne(userid); model.addAttribute("where", "xg"); model.addAttribute("user", user); } List<Dept> depts = (List<Dept>) ddao.findAll(); List<Position> positions = (List<Position>) pdao.findAll(); List<Role> roles = (List<Role>) rdao.findAll(); model.addAttribute("depts", depts); model.addAttribute("positions", positions); model.addAttribute("roles", roles); return "user/edituser"; } @RequestMapping(value = "useredit", method = RequestMethod.POST) public String usereditpost(User user, @RequestParam("deptid") Long deptid, @RequestParam("positionid") Long positionid, @RequestParam("roleid") Long roleid, @RequestParam(value = "isbackpassword", required = false) boolean isbackpassword, Model model) throws PinyinException { System.out.println(user); System.out.println(deptid); System.out.println(positionid); System.out.println(roleid); Dept dept = ddao.findOne(deptid); Position position = pdao.findOne(positionid); Role role = rdao.findOne(roleid); if (user.getUserId() == null) { String pinyin = PinyinHelper.convertToPinyinString(user.getUserName(), "", PinyinFormat.WITHOUT_TONE); user.setPinyin(pinyin); user.setPassword("<PASSWORD>"); user.setDept(dept); user.setRole(role); user.setPosition(position); user.setFatherId(dept.getDeptmanager()); udao.save(user); } else { User user2 = udao.findOne(user.getUserId()); user2.setUserTel(user.getUserTel()); user2.setRealName(user.getRealName()); user2.setEamil(user.getEamil()); user2.setAddress(user.getAddress()); user2.setUserEdu(user.getUserEdu()); user2.setSchool(user.getSchool()); user2.setIdCard(user.getIdCard()); user2.setBank(user.getBank()); user2.setThemeSkin(user.getThemeSkin()); user2.setSalary(user.getSalary()); user2.setFatherId(dept.getDeptmanager()); if (isbackpassword) { user2.setPassword("<PASSWORD>"); } user2.setDept(dept); user2.setRole(role); user2.setPosition(position); udao.save(user2); } model.addAttribute("success", 1); return "/usermanage"; } @RequestMapping("deleteuser") @Transactional(rollbackOn = Exception.class) public ModelAndView deleteuser(@RequestParam("userid") Long userid, Model model) { User user = udao.findOne(userid); user.setIsLock(1); udao.save(user); Map<String, Object> map = new HashMap<>(); map.put("success", 1); return new ModelAndView("/usermanage",map ); } @RequestMapping("useronlyname") public @ResponseBody boolean useronlyname(@RequestParam("username") String username) { System.out.println(username); User user = udao.findByUserName(username); System.out.println(user); return user == null; } @RequestMapping("selectdept") public @ResponseBody List<Position> selectdept(@RequestParam("selectdeptid") Long deptid) { return pdao.findByDeptidAndNameNotLike(deptid, "%经理"); } }
<reponame>releasehub-com/LaunchDarkly-Docs<gh_stars>0 /** @jsx jsx */ import { FunctionComponent } from 'react' import { jsx } from 'theme-ui' import Icon, { IconName } from '../icon' import Link from '../link' import { SideNavItem } from '../sideNav/types' type QuickLinkType = { iconName: IconName heading: string blurp: string navItems: Array<SideNavItem> } const QuickLink: FunctionComponent<QuickLinkType> = ({ iconName, heading, blurp, navItems }) => { return ( <li sx={{ display: 'flex', mb: 6, '&:last-child': { mb: 0 } }}> <Icon name={iconName} height="2rem" fill="primarySafe" sx={{ p: 1, backgroundColor: 'grayLight', border: '1px solid', borderColor: 'grayMed', borderRadius: '2px', mr: 4, }} /> <div> <h2 sx={{ fontSize: 6, lineHeight: 'medium', mb: 2 }}>{heading}</h2> <h3 sx={{ fontSize: 5, mb: 2 }}>{blurp}</h3> <ul sx={{ listStyle: 'disc', listStylePosition: 'inside' }}> {navItems.map(({ path, label }) => ( <li key={path}> <Link to={path} sx={{ textDecoration: 'none' }}> {label} </Link> </li> ))} </ul> </div> </li> ) } const QuickLinks = () => ( <section sx={{ borderBottom: '1px solid', borderColor: 'grayMed', pb: 6, fontSize: 4 }}> <ul> <QuickLink iconName="compass" heading="Your first flag" blurp="New to LaunchDarkly? Get started in minutes." navItems={[ { path: '/home/getting-started/', label: 'Getting started' }, { path: '/home/getting-started/your-team', label: 'Your team and LaunchDarkly' }, { path: '/home/getting-started/feature-flags', label: 'Creating a feature flag' }, ]} /> <QuickLink iconName="chart-areaspline" heading="Experimentation" blurp="Test frontend and backend changes in real time, on real users." navItems={[ { path: '/home/experimentation/create', label: 'Creating experiments' }, { path: '/home/experimentation/managing', label: 'Managing experiments' }, ]} /> <QuickLink iconName="puzzle-variation" heading="Integrations" blurp="Make LaunchDarkly a seamless part of your workflow." navItems={[ { path: '/integrations/webhooks', label: 'Webhooks' }, { path: '/integrations/code-references', label: 'Code references' }, { path: '/integrations/data-export', label: 'Data Export' }, ]} /> </ul> </section> ) export default QuickLinks
/** * Desktop launcher for level editor * @author mgsx * */ public class DeferredLightingLauncher { public static class EmptyPlugin extends EditorPlugin implements DefaultEditorPlugin{ @Override public void initialize(EditorScreen editor) { } } public static void main (String[] args) { ClassRegistry.instance = new ReflectionClassRegistry(); PdConfiguration.disabled = true; LwjglApplicationConfiguration.disableAudio = true; LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); G3DPlugin.defferedRendering = true; EditorConfiguration editConfig = new EditorConfiguration(); editConfig.plugins.add(new EmptyPlugin()); editConfig.path = args.length > 0 ? args[0] : null; final EditorApplication editor = new EditorApplication(editConfig){ @Override public void create() { Pd.audio.create(new PdConfiguration()); super.create(); } }; new DesktopApplication(editor, config); } }
/**************************************************************************************************************************** RTMP Live Publishing Library Copyright (c) Microsoft Corporation All rights reserved. MIT License 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 #include <mfidl.h> #include <mfapi.h> #include <Mferror.h> #include <wrl.h> #include <memory> #include <map> #include <windows.media.mediaproperties.h> #include "RTMPStreamSinkBase.h" using namespace Microsoft::WRL; using namespace Windows::Media::MediaProperties; using namespace std; namespace Microsoft { namespace Media { namespace RTMP { class RTMPAudioStreamSink : public RTMPStreamSinkBase { public: RTMPAudioStreamSink() { _samplingFrequencyIndex = std::map<unsigned int, BYTE>{ std::pair<unsigned int, BYTE>(96000, 0x0), std::pair<unsigned int, BYTE>(88200, 0x1), std::pair<unsigned int, BYTE>(64000, 0x2), std::pair<unsigned int, BYTE>(48000, 0x3), std::pair<unsigned int, BYTE>(44100, 0x4), std::pair<unsigned int, BYTE>(32000, 0x5), std::pair<unsigned int, BYTE>(24000, 0x6), std::pair<unsigned int, BYTE>(22050, 0x7), std::pair<unsigned int, BYTE>(16000, 0x8), std::pair<unsigned int, BYTE>(12000, 0x9), std::pair<unsigned int, BYTE>(11025, 0xa), std::pair<unsigned int, BYTE>(8000, 0xb), std::pair<unsigned int, BYTE>(7350, 0xc) }; } IFACEMETHOD(ProcessSample)(IMFSample *pSample); IFACEMETHOD(PlaceMarker)(MFSTREAMSINK_MARKER_TYPE eMarkerType, const PROPVARIANT *pvarMarkerValue, const PROPVARIANT *pvarContextValue); virtual HRESULT CreateMediaType(MediaEncodingProfile^ encodingProfile) override; LONGLONG GetLastDTS() override; LONGLONG GetLastPTS() override; protected: std::vector<BYTE> PreparePayload(MediaSampleInfo* pSampleInfo, bool firstPacket = false); void RTMPAudioStreamSink::PrepareTimestamps(MediaSampleInfo* sampleInfo, LONGLONG& PTS, LONGLONG& TSDelta); HRESULT CompleteProcessNextWorkitem(IMFAsyncResult *pAsyncResult) override; std::vector<BYTE> MakeAudioSpecificConfig(MediaSampleInfo* pSampleInfo); std::map<unsigned int, BYTE> _samplingFrequencyIndex; }; } } }
<gh_stars>0 /**************************************************************************** ** ** Copyright (C) 2014 <NAME> <<EMAIL>> ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qandroideventdispatcher.h" #include "androidjnimain.h" #include "androiddeadlockprotector.h" QAndroidEventDispatcher::QAndroidEventDispatcher(QObject *parent) : QUnixEventDispatcherQPA(parent) { if (QtAndroid::blockEventLoopsWhenSuspended()) QAndroidEventDispatcherStopper::instance()->addEventDispatcher(this); } QAndroidEventDispatcher::~QAndroidEventDispatcher() { if (QtAndroid::blockEventLoopsWhenSuspended()) QAndroidEventDispatcherStopper::instance()->removeEventDispatcher(this); } enum States {Running = 0, StopRequest = 1, Stopping = 2}; void QAndroidEventDispatcher::start() { int prevState = m_stopRequest.fetchAndStoreAcquire(Running); if (prevState == Stopping) { m_semaphore.release(); wakeUp(); } else if (prevState == Running) { qWarning("Error: start without corresponding stop"); } //else if prevState == StopRequest, no action needed } void QAndroidEventDispatcher::stop() { if (m_stopRequest.testAndSetAcquire(Running, StopRequest)) wakeUp(); else qWarning("Error: start/stop out of sync"); } void QAndroidEventDispatcher::goingToStop(bool stop) { m_goingToStop.store(stop ? 1 : 0); if (!stop) wakeUp(); } bool QAndroidEventDispatcher::processEvents(QEventLoop::ProcessEventsFlags flags) { if (m_goingToStop.load()) flags |= QEventLoop::ExcludeSocketNotifiers | QEventLoop::X11ExcludeTimers; { AndroidDeadlockProtector protector; if (protector.acquire() && m_stopRequest.testAndSetAcquire(StopRequest, Stopping)) { m_semaphore.acquire(); wakeUp(); } } return QUnixEventDispatcherQPA::processEvents(flags); } QAndroidEventDispatcherStopper *QAndroidEventDispatcherStopper::instance() { static QAndroidEventDispatcherStopper androidEventDispatcherStopper; return &androidEventDispatcherStopper; } void QAndroidEventDispatcherStopper::startAll() { QMutexLocker lock(&m_mutex); if (!m_started.testAndSetOrdered(0, 1)) return; for (QAndroidEventDispatcher *d : qAsConst(m_dispatchers)) d->start(); } void QAndroidEventDispatcherStopper::stopAll() { QMutexLocker lock(&m_mutex); if (!m_started.testAndSetOrdered(1, 0)) return; for (QAndroidEventDispatcher *d : qAsConst(m_dispatchers)) d->stop(); } void QAndroidEventDispatcherStopper::addEventDispatcher(QAndroidEventDispatcher *dispatcher) { QMutexLocker lock(&m_mutex); m_dispatchers.push_back(dispatcher); } void QAndroidEventDispatcherStopper::removeEventDispatcher(QAndroidEventDispatcher *dispatcher) { QMutexLocker lock(&m_mutex); m_dispatchers.erase(std::find(m_dispatchers.begin(), m_dispatchers.end(), dispatcher)); } void QAndroidEventDispatcherStopper::goingToStop(bool stop) { QMutexLocker lock(&m_mutex); for (QAndroidEventDispatcher *d : qAsConst(m_dispatchers)) d->goingToStop(stop); }
/* Copyright(c) 2016-2020 <NAME>. */ /* jshint strict: true, esversion: 6 */ 'use strict'; import * as util from './util'; import * as request_scheduler from './request_scheduler'; import * as azad_order from './order'; import * as azad_table from './table'; let scheduler: request_scheduler.IRequestScheduler = null; let background_port: chrome.runtime.Port = null; let years: number[] = null; let stats_timeout: NodeJS.Timeout = null; const SITE = window.location.href.match( /\/\/([^/]*)/ )[1]; function getScheduler(): request_scheduler.IRequestScheduler { if (!scheduler) { resetScheduler(); } return scheduler; } function getBackgroundPort() { return background_port; } function setStatsTimeout() { const sendStatsMsg = () => { getBackgroundPort().postMessage({ action: 'statistics_update', statistics: getScheduler().statistics(), years: years, }); } clearTimeout(stats_timeout); stats_timeout = setTimeout( () => { setStatsTimeout(); sendStatsMsg(); }, 2000 ); } function resetScheduler(): void { if (scheduler) { scheduler.abort(); } scheduler = request_scheduler.create(); setStatsTimeout(); } let cached_years: Promise<number[]> = null; function getYears(): Promise<number[]> { const getPromise = function(): Promise<number[]> { const url = 'https://' + SITE + '/gp/css/order-history?ie=UTF8&ref_=nav_youraccount_orders'; return fetch(url).then( response => response.text() ) .then( text => { const parser = new DOMParser(); const doc = parser.parseFromString( text, 'text/html' ); const snapshot = util.findMultipleNodeValues( '//select[@name="orderFilter"]/option[@value]', doc.documentElement ); const years = snapshot.map( elem => elem.textContent .replace('en', '') // amazon.fr .replace('nel', '') // amazon.it .trim() ).filter( element => (/^\d+$/).test(element) ) .map( (year_string: string) => Number(year_string) ) .filter( year => (year >= 2004) ); return years; }); } if(cached_years == null) { console.log('getYears() needs to do something'); cached_years = getPromise(); } console.log('getYears() returning ', cached_years); return cached_years; } function fetchAndShowOrders(years: number[]): void { if ( document.visibilityState != 'visible' ) { console.log( 'fetchAndShowOrders() returning without doing anything: ' + 'tab is not visible' ); return; } resetScheduler(); getYears().then( all_years => azad_order.getOrdersByYear( years, getScheduler(), all_years[0] ) ).then( orderPromises => { let beautiful = true; if (orderPromises.length >= 500) { beautiful = false; alert('Amazon Order History Reporter Chrome Extension\n\n' + '500 or more orders found. That\'s a lot!\n' + 'We\'ll start you off with a plain table to make display faster.\n' + 'You can click the blue "datatable" button to restore sorting, filtering etc.'); } azad_table.displayOrders(orderPromises, beautiful, false); return document.querySelector('[id="azad_order_table"]'); } ); } function advertiseYears() { getYears().then( years => { console.log('advertising years', years); getBackgroundPort().postMessage({ action: 'advertise_years', years: years }); }); } function registerContentScript() { background_port = chrome.runtime.connect(null, {name: 'azad_inject'}); getBackgroundPort().onMessage.addListener( msg => { switch(msg.action) { case 'dump_order_detail': azad_table.dumpOrderDiagnostics(msg.order_id) break; case 'scrape_years': years = msg.years; fetchAndShowOrders(years); break; case 'clear_cache': getScheduler().clearCache(); alert('Amazon Order History Reporter Chrome Extension\n\n' + 'Cache cleared'); break; case 'abort': resetScheduler(); break; default: console.warn('unknown action: ' + msg.action); } } ); console.log('script registered'); } console.log('Amazon Order History Reporter starting'); registerContentScript(); advertiseYears();
A pilot study exploring the association of morphological changes with 5-HTTLPR polymorphism in OCD patients Background Clinical and pharmacological studies of obsessive-compulsive disorder (OCD) have suggested that the serotonergic systems are involved in the pathogenesis, while structural imaging studies have found some neuroanatomical abnormalities in OCD patients. In the etiopathogenesis of OCD, few studies have performed concurrent assessment of genetic and neuroanatomical variables. Methods We carried out a two-way ANOVA between a variable number of tandem repeat polymorphisms (5-HTTLPR) in the serotonin transporter gene and gray matter (GM) volumes in 40 OCD patients and 40 healthy controls (HCs). Results We found that relative to the HCs, the OCD patients showed significant decreased GM volume in the right hippocampus, and increased GM volume in the left precentral gyrus. 5-HTTLPR polymorphism in OCD patients had a statistical tendency of stronger effects on the right frontal pole than those in HCs. Conclusions Our results showed that the neuroanatomical changes of specific GM regions could be endophenotypes of 5-HTTLPR polymorphism in OCD. Background Obsessive-compulsive disorder (OCD) was made a disease independent of anxiety disorder in DSM-5. One of the reasons for this separation is that the biological bases of OCD and anxiety disorder are different . Structural imaging studies have found neuroanatomical abnormalities in the cortico-striatal-thalamo-cortical (CSTC) circuits in OCD patients . A recent voxelbased morphometry (VBM) systematic review suggested that widespread structural abnormalities may contribute to neurobiological vulnerability to OCD . We previously found the presence of regional gray matter (GM) and white matter (WM) volume abnormalities in OCD patients . Furthermore, positron emission tomography (PET) and functional magnetic resonance imaging (fMRI) have revealed abnormal activities in different nodes of the CSTC circuits in OCD patients compared with healthy controls (HCs) . In our previous fMRI study, we found decreased activations in several brain regions including the orbitofrontal cortex (OFC) and a specific relationship between fMRI activation and symptom subtypes . Meanwhile, family and twin studies have provided evidence for the involvement of a genetic factor in OCD. However, many linkage, association, and genome-wide association studies have failed to identify responsible genes . Molecular genetic studies have focused on some structures, including receptor and transporter proteins, in the serotonergic and dopaminergic system. Based on transporter imaging findings, a PET study found a decrease of serotonin transporter binding in the insular cortex in OCD patients. They suggested that dysfunction of the serotonergic system in the limbic area might be involved in the pathophysiology of OCD. It is possible to hypothesize that a polymorphism in the transcriptional control region upstream of the 5-hydroxytryptamine (serotonin) transporter (5-HTT) coding sequence could be an important factor in conferring susceptibility to OCD . The 5-HTTLPR consists of a 44-bp deletion/insertion yielding a 14-repeat allele (short; S) and a 16-repeat allele (long; L). The S allele reduces the transcriptional efficiency of the 5-HTT gene promotor, resulting in decreased 5-HTT expression and availability. Bloch et al. . suggested the possibility that the L allele is associated with specific OCD subgroups such as childhood-onset OCD. In contrast, Lin et al. found that OCD was associated with the SS homozygous genotype. Some researchers suggested that this L allele could be subdivided further to L A and L G alleles . The L G allele, which is the L allele with an A→G substitution (rs25531), is thought to be similar to the S allele in terms of reuptake efficiency . Rocha et al. found that the L A allele was associated to OCD. Hu et al. found that the L A L A genotype was approximately twice as common in 169 whites with OCD than in 253 ethnically matched controls, and the L A allele was twofold overtransmitted to the patients with OCD. Despite the genetic and neuroanatomical importance, few studies of the etiopathogenesis of OCD have concurrently assessed genetic and neuroanatomical variables. We hypothesized that the widespread structural brain changes in OCD indicate the endophenotype of the 5-HTTLPR polymorphism. Therefore, the aim of this study was to investigate the association of genetic variations of the 5-HTTLPR with neuroanatomical changes in OCD. Subjects We studied 40 OCD patients (20 females and 20 males) who met DSM-IV criteria for OCD and had no DSM-IV Axis I disorders except OCD and major depressive disorder as screened by the Structured Clinical Interview for DSM-IV (SCID). Patients who displayed a comorbid axis I diagnosis, neurological disorder, head injury, serious medical condition, or history of drug/alcohol addiction were excluded. We determined psychiatric diagnoses by a consensus of at least two psychiatrists after screening by SCID. Patients were recruited from among outpatients and inpatients of the Department of Neuropsychiatry, Kyushu University Hospital, Japan. Severity of OCD symptoms was assessed with the Yale-Brown Obsessive Compulsive Scale (Y-BOCS) . Patients were also screened for the presence of depressive symptoms through the administration of the 17-item Hamilton Depression Rating Scale (HDRS) . Forty HCs (26 females and 14 males) who were matched to the patients in age and sex were recruited from the staff of Kyushu University Hospital and related agencies. They had no DSM-IV Axis I disorders as determined by the SCID. They also had no current medical problems, psychiatric histories, neurological disorders, or mental retardation. Handedness was determined according to the Edinburgh Handedness Inventory for both OCD patients and HCs . The study was approved by the local ethics committee <22-111, 491-01>, and each participating patient provided written informed consent after receiving a complete description of the study, which was approved by the institutional review board. VBM data processing Acquired images were first converted from DICOM to NifTI-1 format using dcm2nii software (http://www. mccauslandcenter.sc.edu/mricro/mricron/dcm2nii. html). Data processing and examinations were performed with SPM8 software (developed under the auspices of the Functional Imaging Laboratory, The Wellcome Trust Centre for Neuroimaging at the Institute of Neurology at University College London, UK, http://www.fil.ion.ucl. ac.uk/spm/) in the environment of MATLAB (2011b ver., http://www.mathworks.co.jp/products/matlab/). AC-PC orientation was conducted on all T1-weighted data by an automatic process. Then, we applied the VBM8 toolbox (http://dbm.neuro.uni-jena.de/467/) for preprocessing the structural images by the VBM procedure. This VBM8 algorithm involves image bias correction, tissue classification, and normalization to the standard Montreal Neurological Institute (MNI) space using linear (12-parameter affine) and non-linear transformations. High-dimension DARTEL normalization, which is rather unbiased in its segmentation process, was used as anatomical registration with the default template provided in the VBM8 toolbox. Gray matter (GM) and white matter (WM) segments were modulated only by non-linear components, which allowed comparing the absolute amount of tissue corrected for individual brain volume, that is, correction for total brain volume. Finally, modulated images were smoothed with a Gaussian kernel of 8 mm full width at half maximum. Although we used the East Asian Brains template in the process of affine regularization instead of European Brains, the default parameters were used in all other steps. Finally, 40 OCD patients and 40 HCs were assessed by structural MRI examinations with a 3.0-T MRI scanner. Genotyping A 10-ml venous blood sample was collected in EDTA vacuum tubes. Samples were immediately frozen at −80 °C until extraction of genomic DNA from nucleated white blood cells. Genomic DNA was extracted from peripheral blood leukocytes using a Promega DNA Purification Kit (Promega, Madison, WI, USA). PCR amplification was carried out in a final volume of 15 μl consisting of 50-100 ng genomic DNA, 2.5 mM deoxyribonucleotides, 0.2 μM of forward and reverse primers, PCR buffer (2× GC Buffer I, Takara Bio Inc., Shiga, Japan), and 1.25 U of DNA polymerase (TaKaRa LA Taq, Takara Bio Inc.). Denaturation was carried out at 94 °C for 30 s, annealing at 64 °C for 30 s, and extension at 72 °C for 3 min for 40 cycles. To identify L A and L G alleles, a two-step protocol was performed. Step I: determination of the L or S allele, as described above; and step II: digestion of this amplicon with HapII (Takara Bio Inc.) restriction endonuclease. The assay was designed to include an invariant HapII digest site located 94 bp from the end of the amplicon to provide an internal control for digestion/partial digestion. Products were separated on a 4.0% agarose gel (Agarose-LE, Classic Type, Nacalai Tesque, Inc., Kyoto, Japan) supplemented with ethidium bromide (0.01%, Nacalai Tesque) and visualized under ultraviolet light. Statistical analysis We conducted a two-sample t test, Chi square test, and Fisher's exact test to test for differences in demographic variables between OCD patients and HCs as well as between different variants of the alleles of 5-HTTLPR in OCD patients. The genotype frequencies of OCD patients and HCs were compared using Chi square test after checking the Hardy-Weinberg equilibrium. We divided the patients into L A allele carriers (SL A , L A L G , and L A L A ) and non-L A allele carriers (SS, SL G , and L G L G ). Hu et al. noted that the normalized (to SS genotype) expression value of the L A allele was approximately double the values of the S and L G alleles. Thus, we thought that expressions of genotypes including the L A allele were higher than those of other genotypes. Statistical analysis was performed with SPM8, which implemented a general linear model. First, we performed a two-sample t test to detect the difference in GM volume between patients with OCD and HCs. The initial voxel threshold was set to P < 0.001 uncorrected. Clusters were considered significant that fell below a cluster-corrected family-wise error (FWE), P = 0.05. Next, we performed a two-way factorial analysis of variance between the 5-HTTLPR polymorphism and GM volumes in the OCD patients and HCs. A two-way ANOVA test was applied to assess the relationship between 5-HTTLPR polymorphism (L A or non-L A allele carriers) and GM brain volume changes in the OCD patients and HCs. If a statistical difference was present, a post hoc t test was performed to detect the inter-group difference of brain regions. Age and sex were set as covariates in the statistical analysis. We used a threshold of P < 0.05 cluster-corrected family-wise error (FWE) and P < 0.001 uncorrected with expected voxels per clusters. The P < 0.001 value is commonly used in VBM-based OCD studies . Results In demographic variables of age, gender, and handedness, OCD patients and HCs did not show any significant differences (Table 1). These variables also showed no significant difference between the genotypes of L A allele carriers or non-L A allele carriers in OCD patients ( Table 2). OCD patients had significantly fewer years of education than HCs (Table 1). Non-L A allele carriers, furthermore, had significantly fewer years of education than those of L A allele carriers (Table 2). No significant differences were shown between the two genotypes in OCD regarding illness duration, age of onset, total Y-BOCS, or the 17-item HDRS ( Table 2). The genotype frequencies of our samples did not deviate significantly from the values predicted by the Hardy-Weinberg equation. In morphological changes in OCD, compared to the HCs, the OCD patients showed significant decreased GM volumes in the right hippocampus (extent threshold; k = 763 voxels, P < 0.05, FWE; Table 3; Fig. 1a) and increased GM volume in the left precentral gyrus (extent threshold; k = 797 voxels, P < 0.05, FWE; Table 3; Fig. 1b). In morphological changes associated with the 5-HTTLPR polymorphism, compared to L A allele carriers, non-L A allele carriers showed no significant GM volume difference. As of genotype-diagnosis interaction, although no voxels survived multiple comparison, we observed a tendency that 5-HTTLPR polymorphism in OCD patients had stronger effects on the right frontal pole than those in HCs (P < 0.001, uncorrected; Table 3; Fig. 2). The OCD patients with the L A allele carriers of 5-HTTLPR polymorphism exhibited a statistical tendency of reduction of GM volumes in the right frontal pole compared to the HCs with the L A allele carriers. Discussion In the present study, we found that the OCD patients showed significant decreased GM volume in the right hippocampus and increased GM volume in the left precentral gyrus. Moreover, our study suggested that L A allele carriers of the 5-HTTLPR polymorphism in OCD patients are associated with decreased GM volume in the right frontal pole. Functional neuroimaging studies have been suggested that hippocampus might have an important role in the Table 1 Clinical and demographic characteristics of OCD patients and HCs We found a significant difference between the OCD patients and HCs in the distribution of L A allele carriers or non-L A allele carriers of 5 Illness duration (years, mean ± SD) 11.33 ± 10.10 Age of onset (years, mean ± SD) 23.98 ± 11.24 Total Y-BOCS (total score, mean ± SD) 21.95 ± 6.32 HDRS (17 items) a 6.08 ± 6.87 0.55 ± 0.88 0.000 pathophysiology of OCD . On the other hand, structural imaging studies have been suggested that hippocampal alteration may play an important role in the pathophysiology of OCD . The precentral gyrus is a prominent structure on the surface of the posterior frontal lobe. It is the site of the primary motor cortex (Brodmann area 4). Several researchers have suggested that the precentral gyrus may be involved in the pathophysiology of OCD . Russo et al. suggested that OCD might be considered as a sensory motor disorder where a dysfunction of sensory-motor integration might play an important role in the release of motor compulsions. Our results also showed that the precentral gyrus might be involved in the pathophysiology of OCD. Table 2 Clinical and demographic characteristics of non-L A allele carriers and L A allele carriers in OCD patients The frontal pole comprises the most anterior part of the frontal lobe that approximately covers BA10. During human evolution, the functions in this area resulted in its expansion relative to the rest of the brain . Specifically, the functions include multi-tasking , cognitive branching , prospective memory , conflict resolution , and selection of sub-goals . It is suggested that such a highly advanced cognitive function is affected in OCD . In the field of imaging genetics, many researchers reported an association between the serotonin transporter gene and brain structure. Regarding OCD, Atmaca et al. found a significant genotype-by-side interaction for the OFC. In contrast to the previous result reported by Atmaca et al. , our result suggested that a liability in development of the central nervous system might have occurred in OCD patients who are L A allele carriers. Frodl et al. suggested that the high-activity L A allele with its increased number of 5-HTT transporter proteins, concomitant decrease in serotonin levels, and reduced effects on neuroplastic processes might cause structural changes during major depression. With similar mechanism, the volume decrease in the right frontal pole might have occurred in OCD patients who are L A allele carriers. Table 3 VBM analysis including association of variance between 5-HTTLPR polymorphisms and GM volumes in OCD patients and HCs There are some limitations to this study. First, we divided the patients into L A allele carriers (SL A , L A L G , and L A L A ) and non-L A allele carriers (SS, SL G , and L G L G ). In the view of expression activity, it might be better to divide samples into L A L A and others. Although we could not employ this division because our study included few L A L A genotypes, the difference between L A L A and other genotypes should be explored with larger samples in the future. In addition, our sample size was too small to identify the difference between the effects of L A and non-L A alleles on the brains of OCD patients and HCs. Thus, these findings should be considered preliminary until replicated in a larger sample. The OCD patients had significantly fewer years of education than HCs, and non-L A allele carriers had significantly fewer than L A allele carriers. Education years might affect the difference in GM volumes if education years were proportional to high intelligence. In this study, we did not measure the intelligence quotient (IQ). Larger gray matter volumes are associated with higher IQ . Ideally, the IQ should be measured and set as a covariate in the statistical analysis. Although we examined 5-HTTLPR polymorphism as the sole candidate gene in this study, many other polymorphisms such as glutamate system genes and dopamine system genes may affect the brain morphology of OCD patients. We hope to explore an association between more candidate genetic polymorphisms and brain morphology in the future. Fig. 2 Results of genotype-diagnosis interaction effects on brain morphology. The stronger effects of 5-HTTLPR polymorphism on brain morphology in OCD patients than those in HCs were noted in the right frontal pole (P < 0.001, uncorrected, 〈k〉 = 63.146) Moreover, the OCD patients were concurrently on medication. Our study was not designed to investigate medication effects. Thus, analyses of the effects of different medication types on the hippocampus, precentral gyrus, and frontal pole volumes did not reveal a significant difference. Further studies are necessary to explore possible effects of medication. Finally, the uncorrected threshold used in the present study may not fully protect against results due to chance and the results may include false positives. Therefore, the significant clusters found in the present study need to be validated further. Conclusions We found that relative to the HCs, the OCD patients showed significant decreased GM volume in the right hippocampus, and increased GM volume in the left precentral gyrus. The OCD patients with the L A allele carriers of 5-HTTLPR polymorphism exhibited a statistical tendency of reduction of GM volumes in the right frontal pole compared to the HCs with the L A allele carriers. Our preliminary findings suggest that a variation of the 5-HTTLPR polymorphism might affect brain morphology differently in OCD patients and HCs in the right frontal pole volumes.
def with_idleness(self, idle_timeout: Duration) -> 'WatermarkStrategy': return WatermarkStrategy(self._j_watermark_strategy.withIdleness(idle_timeout._j_duration))
import * as React from 'react'; import { WithStyles } from '@material-ui/core/styles/withStyles'; import { styles } from './styles'; import { IFoundItemsProps } from './FoundItems/types'; import { IPagination } from '@containers/Pagination/types'; import { IActiveSort } from '@interfaces/search'; import { IIndexSignature } from '@interfaces/common'; export interface ISortPanelProps extends WithStyles<typeof styles> { foundItems?: React.FC<IFoundItemsProps>; isProductsExist?: boolean; currentSort?: string; sortParams?: string[]; currentItemsPerPage?: number; pagination?: IPagination; sortParamLocalizedNames?: IIndexSignature; setSortAction?: (activeSortOptions: IActiveSort) => void; } export interface ISortPanelState extends IActiveSort {}
c.NotebookApp.open_browser = True c.NotebookApp.ip = '*' c.NotebookApp.password = u'<PASSWORD>'
Immobilization induces alterations in the outer membrane protein pattern of Yersinia ruckeri. We compared the outer membrane protein (OMP) pattern of 2-day-old immobilized Yersinia ruckericells (IC) with that of early (FC24) and late (FC48) stationary-phase planktonic counterparts. Fifty-five OMPs were identified. Principal component analysis discriminated between the protein maps of FC and IC. Some OMPs involved in bacterial adaptation were accumulated by both FC48 and IC but the expression of other proteins was controlled by the sessile mode of growth.
import '../../lit-datatable'; //# sourceMappingURL=lit-datatable.test.d.ts.map
Magnificent multiple-component artifact from Lost creator J.J. Abrams S. by J.J. Abrams and Doug Dorst Mulholland Books 2013, 472 pages, 6.4 x 9.7 x 1.6 $23 Buy a copy on Amazon This is a book that uses another book to tell its story. S. comes in a box that contains what looks exactly like a well-read, slightly stained library copy of a 1949 novel called Ship of Theseus, by V.M. Straka. There was never a novel by that name, and V.M. Straka is a fictitious character (though the publisher, Hachette, plays along by giving Straka an author’s page on its site). The Ship of Theseus is a novel about a man who gets shanghaied on a ship crewed by evil characters. S. is a copy of that book, filled with handwritten annotations from various people, some of whom have a personal relationship. What’s more, in between the yellowing pages of the book you’ll find postcards, sketches on napkins, old photographs, newspaper clippings, and other ephemera that add more layers to the story. Even if you don’t read S., it is a stunning artifact that will astonish everyone you show it to. – Mark Frauenfelder
/** * As common use of primitive types, Java 8 introduced generic Stream<T> as well as specific stream for each primitive type * * 3 primitive streams: * - IntStream, specific functional interface IntSupplier * - LongStream, specific functional interface LongSupplier * - DoubleStream, specific functional interface DoubleSupplier * They have additional methods about math operations: range, rangeClosed, max, min, average, sum and summaryStatistics * * OBS: There is no BooleanStream although BooleanSupplier exists */ public class PrimitiveStreams { public static void main(String[] args) { // Create IntStream IntStream oneToNine1 = IntStream.range(1,10); // 1...9 IntStream oneToNine2 = IntStream.iterate(1, x -> x + 1).limit(10); LongStream oneToTen = LongStream.rangeClosed(1,10); // 1...10, end value inclusive // Double stream DoubleStream fractions = DoubleStream.iterate(10, d -> d / 2); fractions.limit(3).forEach(System.out::println); // 10.0 5.0 2.5 // Converting Stream<Integer> to IntStream List<Integer> ints = asList(1, 2, 3); IntStream intStream1 = ints.stream().mapToInt(x -> x); int sum = intStream1.sum(); // Stream<Object> to IntStream Stream<String> objStream = Stream.of("lambda", "linq"); IntStream intStream2 = objStream.mapToInt(s -> s.length()); // Generate DoubleStream and convert to IntStream IntStream randomNumbers = DoubleStream.generate(Math::random).mapToInt(x -> (int)(x * 100)); randomNumbers.limit(3).forEach(System.out::println); // Summarizing statics on stream (min, max, average, size and counts) IntSummaryStatistics stats = intStream2.summaryStatistics(); if (stats.getCount() == 0) throw new RuntimeException(); int deviation = stats.getMax() - stats.getMin(); // Handling optionals // get method of each primitive Optional class are getAsInt, getAsLong and getAsDouble // Below example illustrates diff between OptionalInt vs Optional<Integer> IntStream odds = IntStream.iterate(11, x -> x + 2); OptionalInt optFive = odds.filter(x -> x%5 == 0).findFirst(); System.out.println(optFive.getAsInt()); // 15 List<Integer> nums = asList(11, 21, 41, 35); Optional<Integer> result = nums.stream().filter(i ->i % 7 == 0).findFirst(); System.out.println(result.get()); // 21 } }
def has_redis_lock(uuid): try: with redis.lock(str(uuid) + '__lock'): pass except _redis.exceptions.LockError: return True else: return False
Synthesis and Structural Characteristics of all Mono- and Difluorinated 4,6-Dideoxy-d-xylo-hexopyranoses. Protein-carbohydrate interactions are implicated in many biochemical/biological processes that are fundamental to life and to human health. Fluorinated carbohydrate analogues play an important role in the study of these interactions and find application as probes in chemical biology and as drugs/diagnostics in medicine. The availability and/or efficient synthesis of a wide variety of fluorinated carbohydrates is thus of great interest. Here, we report a detailed study on the synthesis of monosaccharides in which the hydroxy groups at their 4- and 6-positions are replaced by all possible mono- and difluorinated motifs. Minimization of protecting group use was a key aim. It was found that introducing electronegative substituents, either as protecting groups or as deoxygenation intermediates, was generally beneficial for increasing deoxyfluorination yields. A detailed structural study of this set of analogues demonstrated that dideoxygenation/fluorination at the 4,6-positions caused very little distortion both in the solid state and in aqueous solution. Unexpected trends in α/β anomeric ratios were identified. Increasing fluorine content always increased the α/β ratio, with very little difference between regio- or stereoisomers, except when 4,6-difluorinated.
// @target:es6 // An ExpressionStatement cannot start with the two token sequence `let [` because // that would make it ambiguous with a `let` LexicalDeclaration whose first LexicalBinding was an ArrayBindingPattern. var let: any; let[0] = 100;
<reponame>shaolonger/nuall-monitor-platform import { Component, OnInit } from '@angular/core'; import * as moment from 'moment'; import { EChartOption } from 'echarts'; import { NzMessageService } from 'ng-zorro-antd/message'; import { UserService } from '@data/service/user.service'; import { LogService } from '@data/service/log.service'; import { Project } from '@data/classes/project.class'; @Component({ selector: 'app-overview', templateUrl: './overview.component.html', styleUrls: ['./overview.component.scss'] }) export class OverviewComponent implements OnInit { // 加载状态 isLoading = false; // 筛选条件 filterForm = { projectIdentifier: '', startTime: '', endTime: '' }; // 项目列表 projectList: Project[] = []; // 异常数据总览 overviewStatistic = { jsErrorLogCount: 0, httpErrorLogCount: 0, resourceLoadErrorLogCount: 0, customErrorLogCount: 0 }; // echarts logTypeList = [ {name: 'JS异常', value: 'jsErrorLog'}, {name: 'HTTP请求异常', value: 'httpErrorLog'}, {name: '资源加载异常', value: 'resourceLoadErrorLog'}, {name: '自定义异常', value: 'customErrorLog'} ]; chartOption: EChartOption = { title: { text: '异常统计总览' }, tooltip: { trigger: 'axis', axisPointer: { type: 'cross', label: { backgroundColor: '#6a7985' } } }, legend: { data: this.logTypeList.map(item => item.name) }, xAxis: [ { type: 'category', boundaryGap: false, data: [] } ], yAxis: [ { type: 'value', minInterval: 1 } ], color: ['#64B5F6', '#FF7043', '#FFE082', '#58d45c'], series: [ { name: 'jsErrorLog', type: 'line', stack: '总量', areaStyle: {}, data: [] }, { name: 'httpErrorLog', type: 'line', stack: '总量', areaStyle: {}, data: [] }, { name: 'resourceLoadErrorLog', type: 'line', stack: '总量', areaStyle: {}, data: [] }, { name: 'customErrorLog', type: 'line', stack: '总量', areaStyle: {}, data: [] }, ] }; constructor( private userService: UserService, private logService: LogService, private message: NzMessageService ) { } ngOnInit(): void { this.getUserRelatedProjectList(); } /** * 根据用户获取关联的项目 */ getUserRelatedProjectList(): void { this.projectList = this.userService.getUserRelatedProjectList(); } /** * 选择日期查询范围 * @param result 日期范围 */ onSelectTimeRange(result: Date[]): void { this.filterForm = { ...this.filterForm, startTime: result[0] ? moment(result[0]).format('YYYY-MM-DD HH:mm:ss') : '', endTime: result[1] ? moment(result[1]).format('YYYY-MM-DD HH:mm:ss') : '', }; this.getPageData(); } /** * 获取页面数据 */ getPageData(): void { this.getOverallByTimeRange(); this.getLogCountByHours(); } /** * 获取总览页信息 */ getOverallByTimeRange(): void { let { projectIdentifier, startTime, endTime } = this.filterForm; if (!projectIdentifier) { this.message.warning('请选择项目'); return; } if (!startTime || !endTime) { this.message.warning('请选择起止时间'); return; } this.isLoading = true; this.logService.getOverallByTimeRange( this.filterForm, res => { console.log('[成功]获取总览页信息', res); this.isLoading = false; const { success, data, msg } = res; if (!success) { this.message.error(msg || '获取总览页信息失败'); } else { this.overviewStatistic = data; } }, err => { console.log('[失败]获取总览页信息', err); this.isLoading = false; } ); } /** * 获取日志统计数据 */ getLogCountByHours(): void { let { projectIdentifier, startTime, endTime } = this.filterForm; if (!projectIdentifier || !startTime || !endTime) { return; } this.isLoading = true; this.logService.getLogCountByHours( this.logTypeList.map(item => item.value), this.filterForm, res => { console.log('[成功]获取日志统计数据', res); this.isLoading = false; let chartData = []; this.logTypeList.map(item => item.name).forEach((name, index) => { let response = res[index]; if (!response.success) { this.message.warning(`${name}统计数据获取失败`); chartData.push({ name: name, data: [] }); return; } chartData.push({ name: name, data: response.data.now }); }); let option = { ...this.chartOption, legend: { data: this.logTypeList.map(item => item.name) }, xAxis: [ { type: 'category', boundaryGap: false, data: Object.keys(chartData[0].data) } ], series: chartData.map(item => ({ name: item.name, type: 'line', stack: '总量', areaStyle: {}, data: Object.values(item.data) })) }; this.chartOption = option; }, err => { console.log('[失败]获取日志统计数据', err); this.isLoading = false; } ); } }
package net.java.sip.communicator.impl.protocol.sip.xcap; import net.java.sip.communicator.impl.protocol.sip.xcap.model.xcapcaps.XCapCapsType; public interface XCapCapsClient { public static final String CONTENT_TYPE = "application/xcap-caps+xml"; public static final String DOCUMENT_FORMAT = "xcap-caps/global/index"; XCapCapsType getXCapCaps() throws XCapException; }
import java.io.*; import java.util.*; public class B implements Runnable { void solve() throws Exception { int n=readInt(); HashMap<String,ArrayList<String>>tel=new HashMap<>(); while (n-->0){ String name=readString(); ArrayList<String>temp=new ArrayList<>(); if (tel.containsKey(name)) temp.addAll(tel.get(name)); int k=readInt(); while (k-->0) temp.add(readString()); tel.put(name,temp); } for (Map.Entry f:tel.entrySet()){ ArrayList<String> last=(ArrayList<String>)f.getValue(); boolean[] flag=new boolean[last.size()]; for (int i=0;i<last.size();i++) for (int j=i+1;j<last.size();j++){ if (suf(last.get(i),last.get(j))) if (last.get(i).length()<last.get(j).length()) flag[i]=true; else flag[j]=true; } ArrayList<String> now=new ArrayList<>(last); for (int i=0;i<flag.length;i++) if (flag[i]) now.remove(last.get(i)); tel.put((String)f.getKey(),now); } out.println(tel.size()); for (Map.Entry f:tel.entrySet()){ out.print(f.getKey()+" "+((ArrayList<String>)f.getValue()).size()+" "); for (String s:(ArrayList<String>)f.getValue()) out.print(s+" "); out.println(); } } boolean suf(String s1, String s2){ int k=1; while (k<=Math.min(s1.length(),s2.length())&&s1.charAt(s1.length()-k)==s2.charAt(s2.length()-k)) k++; return (k-1==Math.min(s1.length(),s2.length())); } public static void main(String[] args) throws Exception{ new B().run(); } public void run(){ try{ init(); solve(); out.close(); }catch (Exception e){ e.printStackTrace(); System.exit(-1); } } BufferedReader in; PrintWriter out; StringTokenizer tok=new StringTokenizer(""); void init() throws IOException{ String filename=""; if (filename.isEmpty()){ in=new BufferedReader(new InputStreamReader(System.in)); out=new PrintWriter(System.out); }else { in=new BufferedReader(new FileReader(filename+".in")); out=new PrintWriter(new FileWriter(filename+".out")); } } String readString(){ while (!tok.hasMoreTokens()){ try{ tok=new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(); } int readInt(){ return Integer.parseInt(readString()); } long readLong(){ return Long.parseLong(readString()); } double readDouble(){ return Double.parseDouble(readString()); } }
/// Render a template with data. pub fn render<W>(&self, template_name: &str, mut data: TomlMap, writer: &mut W) -> Result<()> where W: std::io::Write, { // add variables that extend/override passed data data.extend(self.vars.clone().into_iter()); self.hb.render_to_write(template_name, &data, writer)?; Ok(()) }
<filename>scripts/concolic.py from multiprocessing import Process import signal import subprocess import os import sys import random import json import argparse import datetime import shutil import re start_time = datetime.datetime.now() date = start_time.strftime('%m%d') checker = 0 configs = { 'script_path': os.path.abspath(os.getcwd()), 'crest_path': os.path.abspath('../bin/run_crest'), 'n_exec': 4000, 'date': '0225', 'top_dir': os.path.abspath('../experiments/') } def load_pgm_config(config_file): with open(config_file, 'r') as f: parsed = json.load(f) return parsed def gen_run_cmd(pgm_config, idx, stgy, trial): crest = configs['crest_path'] exec_cmd = pgm_config['exec_cmd'] n_exec = str(configs['n_exec']) # An initial input for each large benchmark if (pgm_config['pgm_name']).find('grep') >= 0: input = "grep.input" if (pgm_config['pgm_name']).find('gawk') >= 0: input = "gawk.input" if (pgm_config['pgm_name']).find('sed') >= 0: input = "sed.input" if (pgm_config['pgm_name']).find('vim') >= 0: input = "vim.input" # An initial input for each small benchmark if pgm_config['pgm_name'] == 'replace': input = "replace.input" if pgm_config['pgm_name'] == 'floppy': input = "floppy.input" if pgm_config['pgm_name'] == 'cdaudio': input = "cdaudio.input" if pgm_config['pgm_name'] == 'kbfiltr': input = "kbfiltr.input" stgy_cmd = '-param' log = "logs/" + "__".join([pgm_config['pgm_name']+str(trial), stgy, str(idx)]) + ".log" weight = configs['script_path']+"/"+str(trial)+"_weights/" + str(idx) + ".w" run_cmd = " ".join([crest, exec_cmd, input, log, n_exec, stgy_cmd, weight]) return (run_cmd, log) def running_function(pgm_config, top_dir, log_dir, group_id, parallel_list, stgy, trial, time, stime): group_dir = top_dir + "/" + str(group_id) os.system(" ".join(["cp -r", pgm_config['pgm_dir'], group_dir])) os.chdir(group_dir) os.chdir(pgm_config['exec_dir']) os.mkdir("logs") dir_name = configs['date']+"__"+pgm_config['pgm_name']+"__"+stgy switch_log = open(configs['top_dir']+"/"+dir_name+"/"+stgy+"_total.log", 'a') for idx in range(parallel_list[group_id-1], parallel_list[group_id]): (run_cmd, log) = gen_run_cmd(pgm_config, idx, stgy, trial) with open(os.devnull, 'wb') as devnull: os.system(run_cmd) current_time = datetime.datetime.now() elapsed_time = str((current_time - start_time).total_seconds()+int(float(stime))) if time < ((current_time - start_time).total_seconds()): checker =1 break else: grep_command = " ".join(["grep", '"It: 4000"', log]) grep_line = (subprocess.Popen(grep_command, stdout=subprocess.PIPE,shell=True).communicate())[0] log_to_write = ", ".join([elapsed_time.ljust(10), str(trial)+"_"+str(idx).ljust(10), grep_line]).strip() + '\n' if log_to_write != "": switch_log.write(log_to_write) switch_log.flush() shutil.move(log, log_dir) switch_log.close() def run_all(pgm_config, n_iter, n_parallel, trial, stgy, time, stime): top_dir = "/".join([configs['top_dir'], configs['date']+"__"+stgy+str(trial), pgm_config['pgm_name']]) log_dir = top_dir + "/logs" os.makedirs(log_dir) pgm_dir = pgm_config["pgm_dir"] procs = [] count = n_iter / n_parallel rest = n_iter % n_parallel parallel_list = [1] p=1 for i in range(1, n_parallel+1): if rest !=0: p = p + count + 1 parallel_list.append(p) rest = rest -1 else: p = p + count parallel_list.append(p) for gid in range(1, n_parallel+1): procs.append(Process(target=running_function, args=(pgm_config, top_dir, log_dir, gid, parallel_list, stgy, trial, time, stime))) for p in procs: p.start() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("pgm_config") parser.add_argument("n_iter") parser.add_argument("n_parallel") parser.add_argument("stgy") parser.add_argument("trial") parser.add_argument("time") parser.add_argument("starttime") args = parser.parse_args() pgm_config = load_pgm_config(args.pgm_config) n_iter = int(args.n_iter) n_parallel = int(args.n_parallel) stgy = args.stgy trial = int(args.trial) time = int(args.time) stime = args.starttime run_all(pgm_config, n_iter, n_parallel, trial, stgy, time, stime)
#include <iostream> #include <stdio.h> #include <time.h> #include <stdlib.h> #include <stdarg.h> #include <cstring> #include "Sort.h" using namespace std; Sort :: Sort(int n,int minim,int maxim) { numar_elemente=n; time_t t; srand((unsigned)time(&t)); vect = (int *)(malloc(numar_elemente * sizeof(int))); for ( int i=0; i<numar_elemente; i++) { vect[i]=(rand()%(maxim-minim))+minim; } } Sort :: Sort (int *a, int n) { numar_elemente=n; vect = (int *)(malloc(numar_elemente * sizeof(int))); for(int i=0; i < numar_elemente; i++) { vect[i]=a[i]; } } Sort :: Sort (int count,...) { numar_elemente=count; vect = (int *)(malloc(numar_elemente* sizeof(int))); va_list vl; va_start(vl,numar_elemente); for (int i=0; i<numar_elemente; i++) { vect[i]=va_arg(vl,int); } va_end(vl); } Sort :: Sort (char *sir) { char *p; int m[101],k=0; p=strtok(sir,","); while(p) { m[k++]=atoi(p); p=strtok(NULL,","); } vect=(int *)(malloc(k* sizeof(int))); numar_elemente=k; for(int i=0; i<numar_elemente; i++) vect[i]=m[i]; } Sort :: Sort ():vect(new int[6] { 1,2,3,4,5,6 }) { numar_elemente=6; } int Sort :: parti (int low, int high,bool ascendent) { if(ascendent==false) { int pivot = vect[high]; int i = (low - 1); for (int j = low; j <= high - 1; j++) { if (vect[j] > pivot) { i++; swap(vect[i],vect[j]); } } swap(vect[i + 1],vect[high]); return (i + 1); } else if(ascendent==true) { int pivot = vect[high]; int i = (low - 1); for (int j = low; j <= high - 1; j++) { if (vect[j] < pivot) { i++; swap(vect[i],vect[j]); } } swap(vect[i + 1],vect[high]); return (i + 1); } } void Sort:: quickSort(int low, int high,bool ascendent) { if (low < high) { int pi = parti(low, high,ascendent); quickSort(low, pi - 1,ascendent); quickSort(pi + 1, high,ascendent); } } void Sort :: QuickSort(bool ascendent) { quickSort(0,numar_elemente-1,ascendent); } void Sort:: InsertSort(bool ascendent) { int i, key, j,n; if(ascendent==false) { for (i = 1; i < numar_elemente; i++) { key = vect[i]; j = i - 1; while (j >= 0 && vect[j] < key) { vect[j + 1] = vect[j]; j = j - 1; } vect[j + 1] = key; } } else if(ascendent==true) { for (i = 1; i < numar_elemente; i++) { key = vect[i]; j = i - 1; while (j >= 0 && vect[j] > key) { vect[j + 1] = vect[j]; j = j - 1; } vect[j + 1] = key; } } } void Sort :: BubbleSort (bool ascendent) { int i,j,n; if(ascendent==false) { for (i = 0; i < numar_elemente-1; i++) for (j = 0; j < numar_elemente-i-1; j++) if (vect[j] < vect[j+1]) swap(vect[j],vect[j+1]); } else if(ascendent==true) { for (i = 0; i < numar_elemente-1; i++) for (j = 0; j < numar_elemente-i-1; j++) if (vect[j] > vect[j+1]) swap(vect[j],vect[j+1]); } } void Sort :: Print() { for(int i=0; i<numar_elemente; i++) cout<<vect[i]<<" "; } int Sort :: GetElementsCount() { return numar_elemente; } int Sort :: GetElementFromIndex(int index) { if(index>=0&&index<numar_elemente) return vect[index]; return -1; }
// NewAPIErrInvalidConfig returns an ErrInvalidConfig, API Error with the given // config name and value. func NewAPIErrInvalidConfig(err error, name, value string) APIError { message := fmt.Sprintf("invalid value for %s: %s", name, value) return NewAPIErr( ClientError, ErrInvalidConfig, errors.WithMessage(err, message), ErrInfoInvalidConfig{ Name: name, Value: value, }, ) }
def construct_object_key(logs_payload: LogsPayload) -> str: log_type = "playbook_executions" _, playbook_name, date_and_hour, _ = logs_payload.logStream.split("/") execution_id = extract_execution_id(logs_payload.logEvents[0]) object_key = "/".join( [ f"{log_type}", f"{playbook_name}", f"{date_and_hour}", f"{execution_id}", f"{uuid.uuid4()}", ] ) return object_key
/** * Linear regression task -- Responsible for pre-processing data from MongoDB into a * Spark Dataset (see RegressionTask parent class), building the Sustain Linear Regression Model using * the parameters in the request, launching the model training, and finally for building the ModelResponse * from the model results. */ public class LinearRegressionTask extends RegressionTask { private static final Logger log = LogManager.getLogger(LinearRegressionTask.class); // Original gRPC request object containing request parameters private final LinearRegressionRequest lrRequest; public LinearRegressionTask(ModelRequest modelRequest, List<String> gisJoins) { this.lrRequest = modelRequest.getLinearRegressionRequest(); this.requestCollection = modelRequest.getCollections(0); // We only support 1 collection currently this.gisJoins = gisJoins; } @Override public SustainRegressionModel buildRegressionModel() { return new SustainLinearRegressionModel.LinearRegressionModelBuilder() .withLoss(this.lrRequest.getLoss()) .withSolver(this.lrRequest.getSolver()) .withAggregationDepth(this.lrRequest.getAggregationDepth()) .withMaxIterations(this.lrRequest.getMaxIterations()) .withElasticNetParam(lrRequest.getElasticNetParam()) .withEpsilon(this.lrRequest.getEpsilon()) .withRegularizationParam(this.lrRequest.getRegularizationParam()) .withTolerance(this.lrRequest.getConvergenceTolerance()) .withFitIntercept(this.lrRequest.getFitIntercept()) .withStandardization(this.lrRequest.getSetStandardization()) .build(); } @Override public ModelResponse buildModelResponse(String gisJoin, SustainRegressionModel model) { if (model instanceof SustainLinearRegressionModel) { SustainLinearRegressionModel sustainLinearRegressionModel = (SustainLinearRegressionModel) model; RegressionResponse modelResults = RegressionResponse.newBuilder() .setTotalIterations(sustainLinearRegressionModel.getTotalIterations()) .setRmseResidual(sustainLinearRegressionModel.getRmse()) .setR2Residual(sustainLinearRegressionModel.getR2()) .setIntercept(sustainLinearRegressionModel.getIntercept()) .addAllSlopeCoefficients(sustainLinearRegressionModel.getCoefficients()) .addAllObjectiveHistory(sustainLinearRegressionModel.getObjectiveHistory()) .build(); return ModelResponse.newBuilder() .setGisJoin(gisJoin) .setRegressionResponse(modelResults) .build(); } log.error("Expected model to be of instance SustainLinearRegressionModel, got {} instead", model.getClass().getSimpleName()); return null; } }
Breaking News Emails Get breaking news alerts and special reports. The news and stories that matter, delivered weekday mornings. Dec. 8, 2015, 6:36 PM GMT / Updated Dec. 8, 2015, 9:55 PM GMT By Maggie Fox Norovirus has sickened 80 Boston College students who ate at a nearby Chipotle restaurant, state health officials said Tuesday. "Initial testing conducted by the State Public Health has shown the presence of norovirus," the health department said in a statement. Although many of the students said they feared they’d been struck with the same E. coli bacteria that made 52 people in nine states sick this fall after eating at Chipotle restaurants, experts said the pattern of illness didn't look like E. coli. “Health officials in Boston believe this is likely a norovirus, which seems consistent with the pattern, in our estimation,” Chipotle spokesman Chris Arnold told NBC News. City health officials ordered the outlet closed after an inspection showed the cooked chicken used to make burritos, tacos and other dishes was being kept at too low a temperature, an employee worked while showing signs of illness and because of the reports of possible foodborne illness. Chipotle said it had voluntarily closed the restaurant in the Brighton section of the city. “All 80 students have confirmed that they ate at the Chipotle Restaurant in Cleveland Circle during the weekend,” Boston College said in a statement. Norovirus is notorious for causing large outbreaks of sickness and it can be spread by a single sick restaurant worker or one sick patron. Simple handwashing is often not enough to prevent its spread. The Centers for Disease Control and Prevention says it’s still not sure what particular food caused the E. coli outbreak at Chipotle. A separate E. coli outbreak that’s made 19 people sick in seven states was linked to celery sold at Costco, 7-11, King Sooper and other stores. Symptoms of both illnesses are similar — diarrhea, stomach cramps and fever. But norovirus is far more likely than E. coli to cause vomiting.
/** * Create a real led * @param type Led type to create * @param id Led ID * @param pin Pin number the led is connected on. Pin number is the sequential from 1 to 24 * @return The real led */ public Led createComponent(final String type, final String id, final PiPins pin) { Led component = null; if ("real".equals(type)) { component = new RealLed(id, pin.getPinNumber()); this.connect((RealLed)component, component.getId(), pin); } Logger.info("Component "+id+ " of type "+type+" created."); return component; }
import numpy import numpy as np import urllib import scipy.optimize import random from collections import defaultdict import nltk import string from nltk.stem.porter import * from sklearn import linear_model import random from collections import Counter, namedtuple stops = set(nltk.corpus.stopwords.words('english')) from nltk.collocations import * from prettytable import PrettyTable from scipy.stats import norm import matplotlib.pyplot as plt from itertools import groupby, chain import pylab as pl import time import datetime #print (datetime.datetime.fromtimestamp(1234817823).strftime('%Y-%m-%d %H:%M:%S')) bAroma_overall = defaultdict(list) bTaste_overall = defaultdict(list) bPalate_overall = defaultdict(list) bappearance_overall = defaultdict(list) ### Assignment 2 DATASET STATISTICS def parseData(fname): for l in urllib.urlopen(fname): yield eval(l) print "Reading data..." data = list(parseData("/home/am/UCSD_CSE190/Assignment2/beeradvocate_200K.json")) #data = list(parseData("/home/am/UCSD_CSE190/Assignment2/Temp.json")) #print "done" #ax2.scatter(np.arange(30), def feature(datum): feat = [1, datum] return feat bABV = [] bAroma = [] #data2 = [d for d in data if d.has_key('user/ageInSeconds')] for d in data: bAroma_overall[d['review/aroma']].append(d['review/overall']) bappearance_overall[d['review/appearance']].append(d['review/overall']) bPalate_overall [d['review/palate']].append(d['review/overall']) bTaste_overall [d['review/taste']].append(d['review/overall']) def xydata(data): X = [] Y = [] for k in data.keys(): X.append(k) Yt = [float(i) for i in data[k]] Y.append(np.mean(Yt)) return X,Y xAroma,yaroma_overall = xydata(bAroma_overall) xappearance,yappearance_overall = xydata(bappearance_overall) xpalate,ypalate_overall = xydata(bPalate_overall) xtaste,ytaste_overall = xydata(bTaste_overall) colors = ['red','green','magenta','purple','orange','brown','maroon','darkred', 'blue','darkblue','hotpink','gold','gray','crimson'] ####### style/Aroma ######## fig1 = plt.figure() ax1 = fig1.add_subplot(111) ax1.scatter(xAroma,yaroma_overall,color=random.choice(colors),s=40,edgecolor='none') ax1.set_title('Rating based on Aroma vs. Avrage Overall Rating ') ax1.set_ylabel('Avrage Overall Ratin') ax1.set_xlabel('Rating based on Aroma') ax1.yaxis.grid() ax1.set_xlim([0.5,6]) plt.show() ###### style/appearance ######## fig2 = plt.figure() ax2 = fig2.add_subplot(111) ax2.scatter(xappearance,yappearance_overall,color=random.choice(colors),s=40,edgecolor='none') ax2.set_title('Rating based on Appearance vs. Avrage Overall Rating') ax2.set_xlabel('Rating Based on Appearance') ax2.set_ylabel('Avrage Overall Rating') ax2.yaxis.grid() ax2.set_xlim([0.5,6]) plt.show() # ###### style/palate ######## fig3 = plt.figure() ax3 = fig3.add_subplot(111) ax3.scatter(xpalate,ypalate_overall,color=random.choice(colors),s=40,edgecolor='none') ax3.set_title('Rating based on Palate vs.Avrage Overall Rating') ax3.set_xlabel('Rating Based on Palate') ax3.set_ylabel('Avrage Overall Rating') ax3.yaxis.grid() ax3.set_xlim([0.5,6]) plt.show() ###### style/taste ######## fig4 = plt.figure() ax4 = fig4.add_subplot(111) ax4.scatter(xtaste,ytaste_overall,color=random.choice(colors),s=40,edgecolor='none') ax4.set_title('Rating based on Taste vs. Avrage Overall Rating') ax4.set_xlabel('Rating based on Taste') ax4.set_ylabel('Avrage Overall Rating') ax4.yaxis.grid() ax4.set_xlim([0.5,6]) plt.show() ###### style/Overall ######## #fig5 = plt.figure() #ax5 = fig5.add_subplot(111) #ax5.scatter(xbrewerId_overall,ybrewerId_overall,color=random.choice(colors),s=20,edgecolor='none') #ax5.set_title('Avrage Review/Overall vs. BrewerId') #ax5.set_xlabel('BrewerId') #ax5.set_ylabel('Avrage Review/Overall') #ax5.set_xlim([0,30000]) #ax5.yaxis.grid() #plt.show()
import { Col } from '.'; describe('Col', () => { it('값이 존재한다.', () => { expect(Col).toBeTruthy(); }); it('스냅샷과 일치한다.', () => { expect(Col).toMatchSnapshot(); }); });
def _simplify (self): if (self.whole < 0 and self.fraction > 0) or (self.whole > 0 and self.fraction < 0): self._fraction += self.whole self._whole = 0 if abs(self.fraction) > 1: fractionOverflow = int(self.fraction) self._whole += fractionOverflow self._fraction -= fractionOverflow
def bookmark(self): return self._bookmark
/* ---------------------------------------------------------------------------- * Creates an instance of the bouncer category. */ bouncer_category::bouncer_category() : mob_category( MOB_CATEGORY_BOUNCERS, "Bouncer", "Bouncers", "Bouncers", al_map_rgb(192, 139, 204) ) { }
<reponame>3mdeb/transmet-authenticator-firmware use proc_macro2::TokenStream as TokenStream2; use quote::quote; use rtic_syntax::{ ast::{App, Local}, Context, Core, Map, }; use crate::codegen::util; pub fn codegen( ctxt: Context, locals: &Map<Local>, core: Core, app: &App, ) -> ( // locals TokenStream2, // pat TokenStream2, ) { assert!(!locals.is_empty()); let runs_once = ctxt.runs_once(); let ident = util::locals_ident(ctxt, app); let mut lt = None; let mut fields = vec![]; let mut items = vec![]; let mut names = vec![]; let mut values = vec![]; let mut pats = vec![]; let mut has_cfgs = false; for (name, local) in locals { let lt = if runs_once { quote!('static) } else { lt = Some(quote!('a)); quote!('a) }; let cfgs = &local.cfgs; has_cfgs |= !cfgs.is_empty(); let section = if local.shared && cfg!(feature = "heterogeneous") { Some(quote!(#[rtic::export::shared])) } else { util::link_section("data", core) }; let expr = &local.expr; let ty = &local.ty; fields.push(quote!( #(#cfgs)* #name: &#lt mut #ty )); items.push(quote!( #(#cfgs)* #section static mut #name: #ty = #expr )); values.push(quote!( #(#cfgs)* #name: &mut #name )); names.push(name); pats.push(quote!( #(#cfgs)* #name )); } if lt.is_some() && has_cfgs { fields.push(quote!(__marker__: core::marker::PhantomData<&'a mut ()>)); values.push(quote!(__marker__: core::marker::PhantomData)); } let locals = quote!( #[allow(non_snake_case)] #[doc(hidden)] pub struct #ident<#lt> { #(#fields),* } impl<#lt> #ident<#lt> { #[inline(always)] unsafe fn new() -> Self { #(#items;)* #ident { #(#values),* } } } ); let ident = ctxt.ident(app); ( locals, quote!(#ident::Locals { #(#pats,)* .. }: #ident::Locals), ) }
<filename>src/unix/timer.c #include <unix_internal.h> /* TODO - validation of timeval and timespecs parameters across board - support for thread and process time(r)s */ //#define UNIX_TIMER_DEBUG #ifdef UNIX_TIMER_DEBUG #define timer_debug(x, ...) do {log_printf("UTMR", "%s: " x, __func__, ##__VA_ARGS__);} while(0) #else #define timer_debug(x, ...) #endif enum unix_timer_type { UNIX_TIMER_TYPE_TIMERFD = 1, UNIX_TIMER_TYPE_POSIX, /* POSIX.1b (timer_create) */ UNIX_TIMER_TYPE_ITIMER }; declare_closure_struct(1, 2, void, posix_timer_expire, struct unix_timer *, ut, u64, expiry, u64, overruns); declare_closure_struct(1, 2, void, itimer_expire, struct unix_timer *, ut, u64, expiry, u64, overruns); declare_closure_struct(1, 2, void, timerfd_timer_expire, struct unix_timer *, ut, u64, expiry, u64, overruns); declare_closure_struct(1, 0, void, unix_timer_free, struct unix_timer *, ut); typedef struct unix_timer { struct fdesc f; /* used for timerfd only; must be first */ process p; int type; boolean interval; clock_id cid; struct timer t; u64 overruns; struct spinlock lock; union { struct { struct siginfo si; int id; thread recipient; /* INVALID_ADDRESS means deliver to process */ struct sigevent sevp; closure_struct(posix_timer_expire, timer_expire); } posix; struct { struct siginfo si; int which; closure_struct(itimer_expire, timer_expire); } itimer; struct { blockq bq; boolean cancel_on_set; boolean canceled; /* by time set */ closure_struct(timerfd_timer_expire, timer_expire); } timerfd; } info; struct refcount refcount; closure_struct(unix_timer_free, free); } *unix_timer; BSS_RO_AFTER_INIT static heap unix_timer_heap; define_closure_function(1, 0, void, unix_timer_free, unix_timer, ut) { timer_debug("ut %p\n", bound(ut)); deallocate(unix_timer_heap, bound(ut), sizeof(struct unix_timer)); } static unix_timer allocate_unix_timer(int type, clock_id cid) { unix_timer ut = allocate(unix_timer_heap, sizeof(struct unix_timer)); if (ut == INVALID_ADDRESS) return ut; ut->p = current->p; ut->type = type; ut->interval = false; ut->cid = cid; init_timer(&ut->t); ut->overruns = 0; spin_lock_init(&ut->lock); init_refcount(&ut->refcount, 1, init_closure(&ut->free, unix_timer_free, ut)); timer_debug("type %d, cid %d, ut %p\n", type, cid, ut); return ut; } static inline void reserve_unix_timer(unix_timer ut) { timer_debug("ut %p\n", ut); refcount_reserve(&ut->refcount); } static inline void release_unix_timer(unix_timer ut) { timer_debug("ut %p\n", ut); refcount_release(&ut->refcount); } static void itimerspec_from_timer(unix_timer ut, struct itimerspec *i) { timestamp remain = 0, interval = 0; if (timer_is_active(&ut->t)) timer_get_remaining(&ut->t, &remain, &interval); timespec_from_time(&i->it_value, remain); timespec_from_time(&i->it_interval, interval); } static void itimerval_from_timer(unix_timer ut, struct itimerval *i) { timestamp remain = 0, interval = 0; if (timer_is_active(&ut->t)) timer_get_remaining(&ut->t, &remain, &interval); timeval_from_time(&i->it_value, remain); timeval_from_time(&i->it_interval, interval); } static inline void remove_unix_timer(unix_timer ut) { remove_timer(kernel_timers, &ut->t, 0); } define_closure_function(1, 2, void, timerfd_timer_expire, unix_timer, ut, u64, expiry, u64, overruns) { unix_timer ut = bound(ut); if (overruns != timer_disabled) { spin_lock(&ut->lock); ut->overruns += overruns; timer_debug("ut %p, interval %ld, %d overruns -> %ld\n", ut, ut->t.interval, overruns, ut->overruns); blockq_wake_one(ut->info.timerfd.bq); notify_dispatch(ut->f.ns, EPOLLIN); boolean interval = ut->interval; spin_unlock(&ut->lock); if (interval) return; } release_unix_timer(ut); } void notify_unix_timers_of_rtc_change(void) { /* XXX TODO: This should be implemented if and when we support explicit setting of wall time via settimeofday(2), clock_settime(2), update detected from hypervisor, etc. Any such setting of the clock should call this function, which in turn should walk through the active unix_timers and cancel them as necessary (if cancel_on_set). */ } sysreturn timerfd_settime(int fd, int flags, const struct itimerspec *new_value, struct itimerspec *old_value) { if (flags & ~(TFD_TIMER_ABSTIME | TFD_TIMER_CANCEL_ON_SET)) return -EINVAL; if (!validate_user_memory(new_value, sizeof(struct itimerspec), false) || (old_value && !validate_user_memory(old_value, sizeof(struct itimerspec), true))) return -EFAULT; unix_timer ut = resolve_fd(current->p, fd); /* macro, may return EBADF */ spin_lock(&ut->lock); sysreturn rv = 0; if (ut->f.type != FDESC_TYPE_TIMERFD) { rv = -EINVAL; goto out; } if (old_value) { itimerspec_from_timer(ut, old_value); } ut->info.timerfd.cancel_on_set = (ut->cid == CLOCK_REALTIME || ut->cid == CLOCK_REALTIME_ALARM) && (flags ^ (TFD_TIMER_ABSTIME | TFD_TIMER_CANCEL_ON_SET)) == 0; remove_unix_timer(ut); ut->overruns = 0; if (new_value->it_value.tv_sec == 0 && new_value->it_value.tv_nsec == 0) goto out; timestamp tinit = time_from_timespec(&new_value->it_value); timestamp interval = time_from_timespec(&new_value->it_interval); boolean absolute = (flags & TFD_TIMER_ABSTIME) != 0; timer_debug("register timer: cid %d, init value %T, absolute %d, interval %T\n", ut->cid, tinit, absolute, interval); if (interval != 0) ut->interval = true; reserve_unix_timer(ut); register_timer(kernel_timers, &ut->t, ut->cid, tinit, absolute, interval, init_closure(&ut->info.timerfd.timer_expire, timerfd_timer_expire, ut)); out: spin_unlock(&ut->lock); fdesc_put(&ut->f); return rv; } sysreturn timerfd_gettime(int fd, struct itimerspec *curr_value) { if (!validate_user_memory(curr_value, sizeof(struct itimerspec), true)) return -EFAULT; sysreturn rv = 0; unix_timer ut = resolve_fd(current->p, fd); /* macro, may return EBADF */ spin_lock(&ut->lock); if (ut->f.type != FDESC_TYPE_TIMERFD) rv = -EINVAL; else itimerspec_from_timer(ut, curr_value); spin_unlock(&ut->lock); fdesc_put(&ut->f); return rv; } closure_function(5, 1, sysreturn, timerfd_read_bh, unix_timer, ut, void *, dest, u64, length, thread, t, io_completion, completion, u64, flags) { unix_timer ut = bound(ut); thread t = bound(t); boolean blocked = (flags & BLOCKQ_ACTION_BLOCKED) != 0; sysreturn rv = sizeof(u64); timer_debug("ut %p, dest %p, length %ld, tid %d, flags 0x%lx\n", ut, bound(dest), bound(length), t->tid, flags); if (flags & BLOCKQ_ACTION_NULLIFY) { assert(blocked); rv = -ERESTARTSYS; goto out; } spin_lock(&ut->lock); if (ut->info.timerfd.canceled) { rv = -ECANCELED; goto out; } u64 overruns = ut->overruns; if (overruns == 0) { if (!blocked && (ut->f.flags & TFD_NONBLOCK)) { rv = -EAGAIN; goto out; } timer_debug(" -> block\n"); spin_unlock(&ut->lock); return blockq_block_required(t, flags); } *(u64*)bound(dest) = overruns; ut->overruns = 0; out: spin_unlock(&ut->lock); timer_debug(" -> returning %ld\n", rv); apply(bound(completion), t, rv); closure_finish(); return rv; } closure_function(1, 6, sysreturn, timerfd_read, unix_timer, ut, void *, dest, u64, length, u64, offset_arg, thread, t, boolean, bh, io_completion, completion) { if (length < sizeof(u64)) return io_complete(completion, t, -EINVAL); unix_timer ut = bound(ut); timer_debug("ut %p, dest %p, length %ld, tid %d, bh %d, completion %p\n", ut, dest, length, t->tid, bh, completion); blockq_action ba = contextual_closure(timerfd_read_bh, ut, dest, length, t, completion); return blockq_check(ut->info.timerfd.bq, t, ba, bh); } closure_function(1, 1, u32, timerfd_events, unix_timer, ut, thread, t /* ignored */) { return bound(ut)->overruns > 0 ? EPOLLIN : 0; } closure_function(1, 2, sysreturn, timerfd_close, unix_timer, ut, thread, t, io_completion, completion) { unix_timer ut = bound(ut); spin_lock(&ut->lock); remove_unix_timer(ut); deallocate_blockq(ut->info.timerfd.bq); deallocate_closure(ut->f.read); deallocate_closure(ut->f.events); deallocate_closure(ut->f.close); release_fdesc(&ut->f); spin_unlock(&ut->lock); release_unix_timer(ut); return io_complete(completion, t, 0); } sysreturn timerfd_create(int clockid, int flags) { if (clockid != CLOCK_REALTIME && clockid != CLOCK_MONOTONIC && clockid != CLOCK_BOOTTIME && clockid != CLOCK_REALTIME_ALARM && clockid != CLOCK_BOOTTIME_ALARM) return -EINVAL; if (flags & ~(TFD_NONBLOCK | TFD_CLOEXEC)) return -EINVAL; unix_timer ut = allocate_unix_timer(UNIX_TIMER_TYPE_TIMERFD, clockid); if (ut == INVALID_ADDRESS) return -ENOMEM; init_fdesc(unix_timer_heap, &ut->f, FDESC_TYPE_TIMERFD); ut->info.timerfd.bq = allocate_blockq(unix_timer_heap, "timerfd"); if (ut->info.timerfd.bq == INVALID_ADDRESS) goto err_mem_bq; ut->info.timerfd.cancel_on_set = false; ut->info.timerfd.canceled = false; ut->f.flags = flags; ut->f.read = closure(unix_timer_heap, timerfd_read, ut); ut->f.events = closure(unix_timer_heap, timerfd_events, ut); ut->f.close = closure(unix_timer_heap, timerfd_close, ut); u64 fd = allocate_fd(current->p, ut); if (fd == INVALID_PHYSICAL) { apply(ut->f.close, 0, io_completion_ignore); return -EMFILE; } timer_debug("unix_timer %p, fd %d\n", ut, fd); return fd; err_mem_bq: release_unix_timer(ut); return -ENOMEM; } static unix_timer posix_timer_from_timerid(u32 timerid) { process p = current->p; process_lock(p); unix_timer ut = vector_get(p->posix_timers, timerid); process_unlock(p); return ut ? ut : INVALID_ADDRESS; } static s32 timer_overruns_s32(unix_timer ut) { return (s32)MIN((u64)S32_MAX, ut->overruns); } static void sigev_update_siginfo(unix_timer ut) { struct siginfo *si = &ut->info.posix.si; si->sifields.timer.overrun = timer_overruns_s32(ut); ut->overruns = 0; } static void sigev_deliver(unix_timer ut) { struct sigevent *sevp = &ut->info.posix.sevp; switch (sevp->sigev_notify) { case SIGEV_NONE: break; case SIGEV_SIGNAL | SIGEV_THREAD_ID: /* flag or value? */ assert(ut->info.posix.recipient != INVALID_ADDRESS); sigev_update_siginfo(ut); deliver_signal_to_thread(ut->info.posix.recipient, &ut->info.posix.si); break; case SIGEV_SIGNAL: sigev_update_siginfo(ut); deliver_signal_to_process(ut->p, &ut->info.posix.si); break; default: /* SIGEV_THREAD is a glibc thing; we should never see it. */ halt("%s: invalid sigev_notify %d\n", __func__, sevp->sigev_notify); } } define_closure_function(1, 2, void, posix_timer_expire, unix_timer, ut, u64, expiry, u64, overruns) { unix_timer ut = bound(ut); if (overruns != timer_disabled) { assert(overruns > 0); spin_lock(&ut->lock); ut->overruns += overruns - 1; timer_debug("id %d, interval %ld, +%d -> %d\n", ut->info.posix.id, ut->t.interval, overruns, ut->overruns); sigev_deliver(ut); boolean interval = ut->interval; spin_unlock(&ut->lock); if (interval) return; } release_unix_timer(ut); } sysreturn timer_settime(u32 timerid, int flags, const struct itimerspec *new_value, struct itimerspec *old_value) { /* Linux doesn't validate flags? */ if (!validate_user_memory(new_value, sizeof(struct itimerspec), false)) return -EINVAL; /* usually EFAULT, but linux gives EINVAL */ if (old_value && !validate_user_memory(old_value, sizeof(struct itimerspec), true)) return -EFAULT; unix_timer ut = posix_timer_from_timerid(timerid); if (ut == INVALID_ADDRESS) return -EINVAL; spin_lock(&ut->lock); sysreturn rv; if (old_value) { itimerspec_from_timer(ut, old_value); } remove_unix_timer(ut); ut->overruns = 0; if (new_value->it_value.tv_sec == 0 && new_value->it_value.tv_nsec == 0) { rv = 0; goto out; } timestamp tinit = time_from_timespec(&new_value->it_value); timestamp interval = time_from_timespec(&new_value->it_interval); boolean absolute = (flags & TFD_TIMER_ABSTIME) != 0; timer_debug("register timer: cid %d, init value %T, absolute %d, interval %T\n", ut->cid, tinit, absolute, interval); if (interval != 0) ut->interval = true; reserve_unix_timer(ut); register_timer(kernel_timers, &ut->t, ut->cid, tinit, absolute, interval, init_closure(&ut->info.posix.timer_expire, posix_timer_expire, ut)); rv = 0; out: spin_unlock(&ut->lock); return rv; } sysreturn timer_gettime(u32 timerid, struct itimerspec *curr_value) { if (!validate_user_memory(curr_value, sizeof(struct itimerspec), true)) return -EFAULT; unix_timer ut = posix_timer_from_timerid(timerid); if (ut == INVALID_ADDRESS) return -EINVAL; spin_lock(&ut->lock); itimerspec_from_timer(ut, curr_value); spin_unlock(&ut->lock); return 0; } sysreturn timer_getoverrun(u32 timerid) { unix_timer ut = posix_timer_from_timerid(timerid); if (ut == INVALID_ADDRESS) return -EINVAL; spin_lock(&ut->lock); sysreturn rv = timer_overruns_s32(ut); ut->overruns = 0; spin_unlock(&ut->lock); return rv; } sysreturn timer_delete(u32 timerid) { unix_timer ut = posix_timer_from_timerid(timerid); if (ut == INVALID_ADDRESS) return -EINVAL; spin_lock(&ut->lock); if (ut->info.posix.recipient != INVALID_ADDRESS) thread_release(ut->info.posix.recipient); process p = current->p; remove_unix_timer(ut); int id = ut->info.posix.id; spin_unlock(&ut->lock); process_lock(p); deallocate_u64((heap)p->posix_timer_ids, id, 1); assert(vector_set(p->posix_timers, id, 0)); process_unlock(p); release_unix_timer(ut); return 0; } sysreturn timer_create(int clockid, struct sigevent *sevp, u32 *timerid) { if (clockid == CLOCK_PROCESS_CPUTIME_ID || clockid == CLOCK_THREAD_CPUTIME_ID) { msg_err("%s: clockid %d not implemented\n", __func__); return -EOPNOTSUPP; } if (clockid != CLOCK_REALTIME && clockid != CLOCK_MONOTONIC && clockid != CLOCK_BOOTTIME && clockid != CLOCK_REALTIME_ALARM && clockid != CLOCK_BOOTTIME_ALARM) return -EINVAL; if (!validate_user_memory(timerid, sizeof(u32), true)) return -EFAULT; process p = current->p; thread recipient = INVALID_ADDRESS; /* default to process */ if (sevp) { if (!validate_user_memory(sevp, sizeof(struct sigevent), false)) return -EFAULT; switch (sevp->sigev_notify) { case SIGEV_NONE: break; case SIGEV_SIGNAL | SIGEV_THREAD_ID: recipient = thread_from_tid(p, sevp->sigev_un.tid); if (recipient == INVALID_ADDRESS) return -EINVAL; /* fall through */ case SIGEV_SIGNAL: if (sevp->sigev_signo < 1 || sevp->sigev_signo > NSIG) return -EINVAL; break; case SIGEV_THREAD: /* should never see this, but bark if we do */ msg_err("%s: SIGEV_THREAD should be handled by libc / nptl\n", __func__); return -EINVAL; default: return -EINVAL; } } unix_timer ut = allocate_unix_timer(UNIX_TIMER_TYPE_POSIX, clockid); if (ut == INVALID_ADDRESS) goto err_nomem; spin_lock(&ut->lock); process_lock(p); u64 id = allocate_u64((heap)p->posix_timer_ids, 1); if ((id != INVALID_PHYSICAL) && (!vector_set(p->posix_timers, id, ut))) { deallocate_u64((heap)p->posix_timer_ids, id, 1); id = INVALID_PHYSICAL; } process_unlock(p); if (id == INVALID_PHYSICAL) { spin_unlock(&ut->lock); release_unix_timer(ut); goto err_nomem; } struct sigevent default_sevp; if (!sevp) { default_sevp.sigev_notify = SIGEV_SIGNAL; default_sevp.sigev_signo = SIGALRM; zero(&default_sevp.sigev_value, sizeof(sigval_t)); default_sevp.sigev_value.sival_int = id; sevp = &default_sevp; } ut->info.posix.id = id; *timerid = id; ut->info.posix.sevp = *sevp; ut->info.posix.recipient = recipient; struct siginfo *si = &ut->info.posix.si; zero(si, sizeof(struct siginfo)); si->si_signo = sevp->sigev_signo; si->si_code = SI_TIMER; si->sifields.timer.tid = ut->info.posix.id; si->sifields.timer.sigval = ut->info.posix.sevp.sigev_value; spin_unlock(&ut->lock); return 0; err_nomem: if (recipient != INVALID_ADDRESS) thread_release(recipient); return -ENOMEM; } sysreturn getitimer(int which, struct itimerval *curr_value) { if (which == ITIMER_VIRTUAL || which == ITIMER_PROF) { msg_err("timer type %d not yet supported\n"); return -EOPNOTSUPP; } else if (which != ITIMER_REAL) { return -EINVAL; } if (!validate_user_memory(curr_value, sizeof(struct itimerval), true)) return -EFAULT; unix_timer ut = vector_get(current->p->itimers, which); if (ut) { spin_lock(&ut->lock); itimerval_from_timer(ut, curr_value); spin_unlock(&ut->lock); } else { curr_value->it_value.tv_sec = curr_value->it_interval.tv_sec = 0; curr_value->it_value.tv_usec = curr_value->it_interval.tv_usec = 0; } return 0; } define_closure_function(1, 2, void, itimer_expire, unix_timer, ut, u64, expiry, u64, overruns) { unix_timer ut = bound(ut); if (overruns != timer_disabled) { spin_lock(&ut->lock); /* Ignore overruns. Only one itimer signal may be queued. */ timer_debug("which %d, interval %ld, overruns (ignored) %d\n", ut->info.itimer.which, ut->t.interval, overruns); deliver_signal_to_process(ut->p, &ut->info.itimer.si); boolean interval = ut->interval; spin_unlock(&ut->lock); if (interval) return; } release_unix_timer(ut); } #define USEC_LIMIT 999999 static sysreturn setitimer_internal(unix_timer ut, int clockid, const struct itimerval *new_value, struct itimerval *old_value) { spin_lock(&ut->lock); if (old_value) itimerval_from_timer(ut, old_value); remove_unix_timer(ut); sysreturn rv; if (!new_value || (new_value->it_value.tv_sec == 0 && new_value->it_value.tv_usec == 0)) { rv = 0; goto out; } timestamp tinit = time_from_timeval(&new_value->it_value); timestamp interval = time_from_timeval(&new_value->it_interval); timer_debug("register timer: clockid %d, init value %T, interval %T\n", clockid, tinit, interval); if (interval != 0) ut->interval = true; reserve_unix_timer(ut); register_timer(kernel_timers, &ut->t, clockid, tinit, false, interval, init_closure(&ut->info.itimer.timer_expire, itimer_expire, ut)); rv = 0; out: spin_unlock(&ut->lock); return rv; } static unix_timer unix_timer_from_itimer_index(process p, int which, clock_id clockid) { unix_timer ut = vector_get(p->itimers, which); if (!ut) { ut = allocate_unix_timer(UNIX_TIMER_TYPE_ITIMER, clockid); if (ut == INVALID_ADDRESS) return ut; ut->info.itimer.which = which; struct siginfo *si = &ut->info.itimer.si; zero(si, sizeof(struct siginfo)); switch (which) { case ITIMER_REAL: si->si_signo = SIGALRM; break; case ITIMER_VIRTUAL: si->si_signo = SIGVTALRM; break; case ITIMER_PROF: si->si_signo = SIGPROF; break; } si->si_code = SI_KERNEL; assert(vector_set(p->itimers, which, ut)); } return ut; } sysreturn setitimer(int which, const struct itimerval *new_value, struct itimerval *old_value) { /* Since we are a unikernel, and ITIMER_REAL accounts for both user and system time, we'll just treat it like an ITIMER_REAL. This isn't entirely accurate because it accounts for system time that isn't on behalf of running threads. A more accurate method might be to create a timer heap per clock domain (in this case timer heaps attached to the process itself). We are presently limited by all timers mapping to monotonic system time. */ clock_id clockid; if (which == ITIMER_VIRTUAL) { msg_err("timer type %d not yet supported\n", which); if (new_value) { msg_err(" (it_value %T, it_interval %T)\n", time_from_timeval(&new_value->it_value), time_from_timeval(&new_value->it_interval)); } return -EOPNOTSUPP; } else if (which == ITIMER_REAL) { clockid = CLOCK_ID_REALTIME; } else if (which == ITIMER_PROF) { clockid = CLOCK_ID_MONOTONIC; } else { return -EINVAL; } if (new_value && (new_value->it_value.tv_usec > USEC_LIMIT || new_value->it_interval.tv_usec > USEC_LIMIT)) return -EINVAL; if (old_value && !validate_user_memory(old_value, sizeof(struct itimerval), true)) return -EFAULT; process p = current->p; sysreturn ret; process_lock(p); unix_timer ut = unix_timer_from_itimer_index(p, which, clockid); if (ut == INVALID_ADDRESS) ret = -ENOMEM; else ret = setitimer_internal(ut, clockid, new_value, old_value); process_unlock(p); return ret; } #ifdef __x86_64__ sysreturn alarm(unsigned int seconds) { struct itimerval new, old; new.it_value.tv_sec = seconds; new.it_value.tv_usec = 0; new.it_interval.tv_sec = 0; new.it_interval.tv_usec = 0; process p = current->p; boolean error = false; process_lock(p); unix_timer ut = unix_timer_from_itimer_index(p, ITIMER_REAL, CLOCK_ID_MONOTONIC); if ((ut == INVALID_ADDRESS) || (setitimer_internal(ut, CLOCK_ID_REALTIME, &new, &old) < 0)) error = true; process_unlock(p); if (error) return 0; /* no errno here (uint retval), so default to 0? */ if (old.it_value.tv_sec == 0 && old.it_value.tv_usec != 0) return 1; /* 0 for disarmed timer only, so round up */ return old.it_value.tv_sec; } #endif void register_timer_syscalls(struct syscall *map) { #ifdef __x86_64__ register_syscall(map, alarm, alarm, 0); #endif register_syscall(map, timerfd_create, timerfd_create, SYSCALL_F_SET_DESC); register_syscall(map, timerfd_gettime, timerfd_gettime, SYSCALL_F_SET_DESC); register_syscall(map, timerfd_settime, timerfd_settime, SYSCALL_F_SET_DESC); register_syscall(map, timer_create, timer_create, 0); register_syscall(map, timer_settime, timer_settime, 0); register_syscall(map, timer_gettime, timer_gettime, 0); register_syscall(map, timer_getoverrun, timer_getoverrun, 0); register_syscall(map, timer_delete, timer_delete, 0); register_syscall(map, getitimer, getitimer, 0); register_syscall(map, setitimer, setitimer, 0); } boolean unix_timers_init(unix_heaps uh) { unix_timer_heap = heap_locked((kernel_heaps)uh); return true; }
Paradise for who? Segmenting visitors' satisfaction with cognitive image and predicting behavioural loyalty The purpose of this research is to assess the influence of socio-demographic characteristics on destination image and loyalty, thereby offering a segmentation perspective of visitors to the island of Mauritius. A self-administered survey of hotel guests was undertaken and resulted in a sample of 705 respondents. Using a k-means clustering algorithm and discriminant analysis, three clusters of visitors were identified. Different image attributes predict visitors' revisit and recommendation intentions. These findings allow destination marketers to adapt the marketing mix elements to different segments while enabling a destination to emphasize the relevant attributes in promotion and positioning efforts. Copyright © 2011 John Wiley & Sons, Ltd.
#!/usr/bin/env python # Copyright 2014-2020 The PySCF Developers. 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 unittest from functools import reduce import numpy from pyscf import gto from pyscf import scf from pyscf import ao2mo from pyscf import mcscf from pyscf import fci from pyscf.mrpt import nevpt2 def nevpt2_dms(mc): mo_cas = mf.mo_coeff[:,mc.ncore:mc.ncore+mc.ncas] h1e = mc.h1e_for_cas()[0] h2e = ao2mo.incore.full(mf._eri, mo_cas) h2e = ao2mo.restore(1, h2e, norb).transpose(0,2,1,3) dm1, dm2, dm3, dm4 = fci.rdm.make_dm1234('FCI4pdm_kern_sf', mc.ci, mc.ci, norb, nelec) # Test integral transformation incore algorithm eris = nevpt2._ERIS(mc, mc.mo_coeff, method='incore') # Test integral transformation outcore algorithm eris = nevpt2._ERIS(mc, mc.mo_coeff, method='outcore') dms = {'1': dm1, '2': dm2, '3': dm3, '4': dm4} return eris, dms def setUpModule(): global mol, mf, mc, eris, dms, norb, nelec mol = gto.Mole() mol.verbose = 5 mol.output = '/dev/null' #None mol.atom = [ ['H', ( 0., 0. , 0. )], ['H', ( 0., 0. , 0.8 )], ['H', ( 0., 0. , 2. )], ['H', ( 0., 0. , 2.8 )], ['H', ( 0., 0. , 4. )], ['H', ( 0., 0. , 4.8 )], ['H', ( 0., 0. , 6. )], ['H', ( 0., 0. , 6.8 )], ['H', ( 0., 0. , 8. )], ['H', ( 0., 0. , 8.8 )], ['H', ( 0., 0. , 10. )], ['H', ( 0., 0. , 10.8 )], ['H', ( 0., 0. , 12 )], ['H', ( 0., 0. , 12.8 )], ] mol.basis = 'sto3g' mol.build() mf = scf.RHF(mol) mf.conv_tol = 1e-16 mf.kernel() norb = 6 nelec = 8 mc = mcscf.CASCI(mf, norb, nelec) mc.fcisolver.conv_tol = 1e-15 mc.kernel() mc.canonicalize_() eris, dms = nevpt2_dms(mc) def tearDownModule(): global mol, mf, mc, eris, dms mol.stdout.close() del mol, mf, mc, eris, dms class KnownValues(unittest.TestCase): # energy values for H14 from Dalton def test_Sr(self): norm, e = nevpt2.Sr(mc, mc.ci, dms, eris) self.assertAlmostEqual(e, -0.0202461540, delta=1.0e-6) self.assertAlmostEqual(norm, 0.039479583324952064, delta=1.0e-7) def test_Si(self): norm, e = nevpt2.Si(mc, mc.ci, dms, eris) self.assertAlmostEqual(e, -0.0021282083, delta=1.0e-6) self.assertAlmostEqual(norm, 0.0037402334190064367, delta=1.0e-7) def test_Sijrs(self): norm, e = nevpt2.Sijrs(mc, eris) self.assertAlmostEqual(e, -0.0071505004, delta=1.0e-6) self.assertAlmostEqual(norm, 0.023107592349719219, delta=1.0e-7) def test_Sijr(self): norm, e = nevpt2.Sijr(mc, dms, eris) self.assertAlmostEqual(e, -0.0050346117, delta=1.0e-6) self.assertAlmostEqual(norm, 0.012664066951786257, delta=1.0e-7) def test_Srsi(self): norm, e = nevpt2.Srsi(mc, dms, eris) self.assertAlmostEqual(e, -0.0136954715, delta=1.0e-6) self.assertAlmostEqual(norm, 0.040695892654346914, delta=1.0e-7) def test_Srs(self): norm, e = nevpt2.Srs(mc, dms, eris) self.assertAlmostEqual(e, -0.0175312323, delta=1.0e-6) self.assertAlmostEqual(norm, 0.056323606234166601, delta=1.0e-7) def test_Sir(self): norm, e = nevpt2.Sir(mc, dms, eris) self.assertAlmostEqual(e, -0.0338666048, delta=1.0e-6) self.assertAlmostEqual(norm, 0.074269050656629421, delta=1.0e-7) def test_energy(self): e = nevpt2.NEVPT(mc).kernel() self.assertAlmostEqual(e, -0.1031529251, delta=1.0e-6) def test_energy1(self): o2 = gto.M( verbose = 0, atom = ''' O 0 0 0 O 0 0 1.207''', basis = '6-31g', spin = 2) mf_o2 = scf.RHF(o2).run() mc = mcscf.CASCI(mf_o2, 6, 8) mc.fcisolver.conv_tol = 1e-16 mc.kernel() e = nevpt2.NEVPT(mc).kernel() self.assertAlmostEqual(e, -0.16978532268234559, 6) def test_reset(self): mol1 = gto.M(atom='C') pt = nevpt2.NEVPT(mc) pt.reset(mol1) self.assertTrue(pt.mol is mol1) self.assertTrue(pt._mc.mol is mol1) def test_for_occ2(self): mol = gto.Mole( verbose=0, atom = ''' O -3.3006173 2.2577663 0.0000000 H -4.0301066 2.8983985 0.0000000 H -2.5046061 2.8136052 0.0000000 ''') mf = mol.UHF().run() mc = mcscf.CASSCF(mf, 3, 6) caslist = [4, 5, 3] mc.kernel(mc.sort_mo(caslist)) e = nevpt2.NEVPT(mc).kernel() self.assertAlmostEqual(e, -0.031179434919517, 6) mc = mcscf.CASSCF(mf, 3, 6) caslist = [4, 5, 1] mc.kernel(mc.sort_mo(caslist)) e = nevpt2.NEVPT(mc).kernel() self.assertAlmostEqual(e, -0.031179434919517, 6) def test_multistate(self): # See issue #1081 mol = gto.M(atom=''' O 0.0000000000 0.0000000000 -0.1302052882 H 1.4891244004 0.0000000000 1.0332262019 H -1.4891244004 0.0000000000 1.0332262019 ''', basis = '631g', symmetry = False) mf = scf.RHF(mol).run() mc = mcscf.CASSCF(mf, 6, [4,4]) mc.fcisolver=fci.solver(mol,singlet=True) mc.fcisolver.nroots=2 mc = mcscf.state_average_(mc, [0.5,0.5]) mc.kernel() orbital = mc.mo_coeff.copy() mc = mcscf.CASCI(mf, 6, 8) mc.fcisolver=fci.solver(mol,singlet=True) mc.fcisolver.nroots=2 mc.kernel(orbital) # Ground State mp0 = nevpt2.NEVPT(mc, root=0) mp0.kernel() e0 = mc.e_tot[0] + mp0.e_corr self.assertAlmostEqual(e0, -75.867171, 4) # From ORCA (4.2.1) # First Excited State mp1 = nevpt2.NEVPT(mc, root=1) mp1.kernel() e1 = mc.e_tot[1] + mp1.e_corr self.assertAlmostEqual(e1, -75.828469, 4) # From ORCA (4.2.1) if __name__ == "__main__": print("Full Tests for nevpt2") unittest.main()
<filename>website/urls.py from django.conf.urls import include, url from . import views from . import autocomplete import backend urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^tos/$', views.tos, name='tos'), url(r'^map/$', views.map, name='map'), url(r'^dashboard/', include([ url(r'^$', views.dashboard, name='dashboard'), url(r'^add/$', views.kit_add, name='kit_add'), url(r'^(?P<kit_id>[0-9]+)/', include([ url(r'^$', views.kit, name='kit'), url(r'^download/$', views.kit_download, name='kit_download'), url(r'^configure/', include([ url(r'^profile/$', views.kit_configure_profile, name='kit_configure_profile'), url(r'^members/$', views.kit_configure_members, name='kit_configure_members'), url(r'^location/$', views.kit_configure_location, name='kit_configure_location'), url(r'^peripherals/$', views.kit_configure_peripherals, name='kit_configure_peripherals'), url(r'^peripherals/add/$', views.kit_configure_peripherals_add, name='kit_configure_peripherals_add'), url(r'^peripherals/add/(?P<peripheral_definition_id>[0-9]+)/$', views.kit_configure_peripherals_add_step2, name='kit_configure_peripherals_add_step2'), url(r'^access/$', views.kit_configure_access, name='kit_configure_access'), url(r'^danger/$', views.kit_configure_danger_zone, name='kit_configure_danger_zone'), ])), ])), ])), url(r'^peripherals/', include([ url(r'^$', views.peripheral_definition_list, name='peripheral_definition_list'), url(r'^add/$', views.peripheral_definition_add, name='peripheral_definition_add'), url(r'^(?P<peripheral_definition_id>[0-9]+)/', include([ url(r'^configure/$', views.peripheral_definition_configure, name='peripheral_definition_configure'), ])), ])), url(r'^autocomplete/', include([ url(r'^users/$', autocomplete.PersonUserAutocomplete.as_view(), name='autocomplete-users'), ])), ]
package org.aksw.jena_sparql_api.concept_cache.core; import java.util.Map; import org.apache.jena.graph.Node; import org.apache.jena.sparql.algebra.Op; public class RewriteResult2 { protected Op op; protected Map<Node, StorageEntry> idToStorageEntry; protected int rewriteLevel; // 0 = no rewrite, 1 = partial rewrite, 2 = full rewrite public RewriteResult2(Op op, Map<Node, StorageEntry> idToStorageEntry, int rewriteLevel) { super(); this.op = op; this.idToStorageEntry = idToStorageEntry; this.rewriteLevel = rewriteLevel; } public Op getOp() { return op; } public Map<Node, StorageEntry> getIdToStorageEntry() { return idToStorageEntry; } public int getRewriteLevel() { return rewriteLevel; } }
#pragma once #define FUSE_USE_VERSION 29 #include <fuse.h> void g2f_clear_ops(fuse_operations* ops); void g2f_init_ops(fuse_operations* ops);
/** * @author motb * @date 2021/4/9 16:13 * @description //TODO importCompanyDo **/ @Data public class ImportCompanyDo { @Excel(name = "编号") private String id; @Excel(name = "分组") private String group; @Excel(name = "搜索词 1") private String context; @Excel(name = "属性") private String attr; @Excel(name = "法人") private String leader; @Excel(name = "名称1") private String name1; @Excel(name = "黑名单") private String black; @Excel(name = "业务角色") private String role; @Excel(name = "税号") private String creditCode; @Override public int hashCode() { if (id == null) { return 1; } return id.hashCode(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ImportCompanyDo companyDo = (ImportCompanyDo) o; return Objects.equals(id, companyDo.id); } }
Defend Pop Punk Army in Way Over Their Heads in Syria RAQQA, Syria — Members of the popular “Defend Pop Punk Army” Facebook group allegedly got more than they bargained for on a recent mission to the war-ravaged country of Syria, according to transmissions from the front lines. “We heard there was almost no pop punk in all of Syria, and frankly, we were outraged — these people may never see four guys jumping on stage in unison. It’s a travesty,” said founder Bob Bucciano from a temporary shelter in a former market district. “In hindsight, a lack of palm-muted riffs in four-chord punk songs are the least of their problems.” Bucciano founded the group in 2010, when pop punk, mall emo, and Syrian governmental stability were all on the decline. His search for like-minded music fans was a success, with over 55,000 Facebook users comprising the group. Similarly, Syrian opposition forces have grown to an estimated 50,000 to 200,000 members in the same timeframe. “None of us really understood what’s going on here in Syria,” admitted group moderator Marla Jensen. “I asked our translator if the conflict was analogous to the Taking Back Sunday vs. Brand New feud of the early 2000s, but he wasn’t much help.” Bucciano reported a highly upvoted post in the group led to the mission trip. “The plan was to come here for recon — hand out some Rise Records samplers, price out real estate for an Alternative Press foreign bureau … maybe investigate founding a festival,” said Bucciano, now taking shelter between two bombed-out houses. “The New Found Glory show in Ciudad Juárez was such a hit. We didn’t think we could fail.” Related: Members of Defend Pop Punk Army tried a variety of tactics to subdue their enemies, including playing genre-defining releases from the past 25 years. Unfortunately, none were successful. “Once that first RPG hit our base’s neighboring building, I realized that ’90s-era Blink-182 probably can’t help this city right now,” said Jensen. “We want to apologize to Pete Wentz and Fueled by Ramen for their generous donations, because I just don’t see us making much headway.” Sadly, as the conflict continues, many in the Army are losing faith in the mission. “It’s a real bummer,” said longtime member Cynthia Powers. “This Facebook group has been the only good thing in my life since I lost my job as Gary Johnson’s campaign manager.” Photo by Shelby Kettrick @ShelbyShootsStuff.
/* Copyright 2018 The Knative 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 v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "github.com/knative/pkg/apis" "github.com/knative/pkg/kmeta" ) // +genclient // +genclient:noStatus // +genclient:nonNamespaced // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // ClusterBuildTemplate is a template that can used to easily create Builds. type ClusterBuildTemplate struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec BuildTemplateSpec `json:"spec"` } // Check that our resource implements several interfaces. var _ kmeta.OwnerRefable = (*ClusterBuildTemplate)(nil) var _ Template = (*ClusterBuildTemplate)(nil) var _ BuildTemplateInterface = (*ClusterBuildTemplate)(nil) // Check that ClusterBuildTemplate may be validated and defaulted. var _ apis.Validatable = (*ClusterBuildTemplate)(nil) var _ apis.Defaultable = (*ClusterBuildTemplate)(nil) // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // ClusterBuildTemplateList is a list of BuildTemplate resources. type ClusterBuildTemplateList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata"` Items []ClusterBuildTemplate `json:"items"` } // TemplateSpec returnes the Spec used by the template func (bt *ClusterBuildTemplate) TemplateSpec() BuildTemplateSpec { return bt.Spec } // Copy performes a deep copy func (bt *ClusterBuildTemplate) Copy() BuildTemplateInterface { return bt.DeepCopy() } func (bt *ClusterBuildTemplate) GetGroupVersionKind() schema.GroupVersionKind { return SchemeGroupVersion.WithKind("ClusterBuildTemplate") } // SetDefaults func (b *ClusterBuildTemplate) SetDefaults() {}
<filename>dist/native-common/FrontLayerViewManager.d.ts /** * FrontLayerViewManager.ts * * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. * * Manages stackable modals and popup views that are posted and dismissed * by the Types showModal/dismissModal/showPopup/dismissPopup methods. */ import * as React from 'react'; import SubscribableEvent from 'subscribableevent'; import { Types } from '../common/Interfaces'; export declare class FrontLayerViewManager { private _overlayStack; private _cachedPopups; event_changed: SubscribableEvent<() => void>; showModal(modal: React.ReactElement<Types.ViewProps>, modalId: string, options?: Types.ModalOptions): void; isModalDisplayed(modalId?: string): boolean; dismissModal(modalId: string): void; dismissAllmodals(): void; showPopup(popupOptions: Types.PopupOptions, popupId: string, delay?: number): boolean; dismissPopup(popupId: string): void; dismissAllPopups(): void; getModalLayerView(rootViewId?: string | null): React.ReactElement<any> | null; getActivePopupId(): string | null; releaseCachedPopups(): void; private _modalOptionsMatchesRootViewId; private _renderPopup; private _getOverlayContext; isPopupActiveFor(rootViewId?: string | null): boolean; getPopupLayerView(rootViewId?: string | null): JSX.Element | null; private _onBackgroundPressed; private _dismissActivePopup; private _findIndexOfModal; private _findIndexOfPopup; private _getActiveOverlay; isPopupDisplayed(popupId?: string): boolean; } declare const _default: FrontLayerViewManager; export default _default;
import classnames from 'classnames' import FeatherIcon from 'feather-icons-react' import React, { useState } from 'react' /* import DiscordLogo from '../../assets/Socials/discord-logo.svg' import GovForumIcon from '../../assets/Socials/gov-forum.svg' import KnowledgeBaseIcon from '../../assets/Socials/knowledge-base.svg' import { BottomVoteIcon } from '../../components/Navigation/BottomNavLink' */ import DocsIcon from '../../assets/Socials/docs.svg' import MediumLogo from '../../assets/Socials/medium-logo.svg' import TelegramLogo from '../../assets/Socials/telegram-logo.svg' import TreasuryIcon from '../../assets/Socials/treasury.svg' import TwitterLogo from '../../assets/Socials/twitter-logo.svg' import { Accordion } from '../Accordion' const sharedClasses = 'relative leading-none w-full flex justify-start items-center py-2 px-0 mb-1 ml-0 trans outline-none focus:outline-none active:outline-none h-10' const headerClasses = 'text-xs font-bold hover:text-highlight-2' const childClasses = 'text-xs opacity-70 hover:text-highlight-2' const socialsLinkData = [ { langKey: 'ecosystem', headerLabel: 'ecosystem', childLinks: [ /* { href: '#', langKey: 'vote', label: 'Vote', icon: ( <div className='opacity-60 pt-1'> <BottomVoteIcon /> </div> ) }, */ { href: 'https://docs.dtribe.gg', langKey: 'documentation', label: 'Documentation', icon: <img src={DocsIcon} className='w-3 opacity-70 mx-auto' /> }, /* { href: 'https://gov.pooltogether.com/', langKey: 'governanceForum', label: 'Governance forum', icon: <img src={GovForumIcon} className='w-4 opacity-70 mx-auto' /> }, */ { href: 'https://info.savewings.dtribe.gg', langKey: 'treasury', label: 'Treasury', icon: <img src={TreasuryIcon} className='w-4 opacity-70 mx-auto' /> } ] }, { langKey: 'socials', headerLabel: 'socials', childLinks: [ { href: 'https://twitter.com/dtribe_gg', label: 'Twitter', icon: <img src={TwitterLogo} className='w-4 opacity-70 mx-auto' /> }, { href: 'https://t.me/dtribe_gg', label: 'Telegram', icon: <img src={TelegramLogo} className='w-4 opacity-70 mx-auto hover:opacity-100 trans' /> }, { href: 'https://dtribe-gg.medium.com', label: 'Medium', icon: <img src={MediumLogo} className='w-4 opacity-70 mx-auto hover:opacity-100 trans' /> } ] } ] export const SocialLinks = (props) => { const { t } = props if (!t) { console.error('<SocialLinks /> requires the prop t (i18n trans method)') } const [expanded, setExpanded] = useState() return ( <> {socialsLinkData.map((linkData, index) => { return ( <SocialLinkSet t={t} key={`social-link-set-${index}`} index={index} linkData={linkData} expanded={expanded} setExpanded={setExpanded} /> ) })} </> ) } const SocialLinkSet = (props) => { const { linkData } = props const content = linkData.childLinks.map((childLink, index) => { return <SocialLinkChild {...props} key={`social-link-child-${index}`} childLink={childLink} /> }) return <SocialLinkHeader {...props}>{content}</SocialLinkHeader> } const SocialLinkHeader = (props) => { const { t } = props return ( <Accordion openUpwards key={`social-link-${props.index}`} i={props.index} expanded={props.expanded} setExpanded={props.setExpanded} content={props.children} header={ <a className={classnames(sharedClasses, headerClasses)}> <FeatherIcon icon='chevron-up' strokeWidth='0.25rem' className={classnames('w-4 h-4 stroke-current trans', { 'rotate-180': props.expanded === props.index })} /> <span className='pl-3 capitalize'> {t(props.linkData.langKey, props.linkData.headerLabel)} </span> </a> } /> ) } const SocialLinkChild = (props) => { const { t, childLink } = props const { langKey, label, icon, href, target } = childLink return ( <div> <a href={href} target={target} className={classnames(sharedClasses, childClasses)}> <span className='w-4'>{icon}</span> <span className='pl-3 capitalize'>{langKey ? t(langKey, label) : label}</span> </a> </div> ) } SocialLinkChild.defaultProps = { target: '_blank' }
/** * <pre> * label fields, normally only one field is used. * For multiple target models such as MMOE * multiple label_fields will be set. * </pre> * * <code>repeated string label_fields = 4;</code> */ public Builder addLabelFieldsBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensureLabelFieldsIsMutable(); labelFields_.add(value); onChanged(); return this; }
Now playing: Watch this: The Robomow Diaries: Robot lawnmower powers through soggy... (This is the first installment in a weekly series documenting our tests with the Robomow RS612.) Thursday, July 7, 2016 We should've known better. I've had the Robomow RS612 docked and charging at the edge of my front yard for two weeks. The length of the grass has just passed the embarrassing level and is heading into code violation territory. Sure, it's been raining off and on for five days in Louisville, KY., where CNET Appliances is based. But the rain had stopped when I woke up this morning, and I was on a deadline to test this robot lawnmower. It was natural that CNET Appliances would eventually make our way to reviewing and testing robot lawnmowers, a relatively new and expensive category of smart lawn care. And, robot lawnmowers are the outdoor cousin of robot vacuums, a category we've tested in our lab. We're starting with a mower from Robomow, an Israel-based company founded in 1995. The company has five battery-powered robot vacuums from $999 to $2,099 that designed to tackle different-sized lawns. We're using the $1,599 RS612 model, a mower designed for yards that are a fourth of an acre or less. Enlarge Image Chris Monroe/CNET My front yard has become the Robomow testing grounds. First, I had to cut the yard with a traditional lawnmower per instructions from Robomow so I could more easily install the perimeter wire (I had to cut my grass before I could cut my grass, which felt pretty weird). That wire is what tells the Robomow where the boundaries of my yard are so it knows the area it needs to cut. Then, one of our technical editors, Steve Conaway, spent a hot afternoon installing that wire around the front yard. He found a place at the edge of my yard for the base charging station, connected the station to a bright green perimeter wire, laid the wire around the edges of the yard, and secured the wire with plastic stakes (Robomow says you can bury the wire if you wish, but it blends in surprisingly well). I let the grass grow for about two weeks during which rainy days and deadlines kept pushing back the Robomow's start date. Some patches of grass had grown to more than a foot tall. Today had to be the day for Robomow's first run. Fortunately, the rain held back, but the grass was still wet from yesterday. Like traditional push lawnmowers, the Robomow can cut wet grass, but the company doesn't recommend it -- it makes for a wet, sticky mess. Freshly cut grass began to fill the treads of the Robomow's two back wheels as soon as it exited the base station, which serves as the starting point for the mower. I was convinced I'd have to stop the mower manually and clear out the wheels mid-mow. But the lawnmower pushed through the soggy lawn at a pretty vigorous clip. The Robomow did make two stops during its 40-minute run when it became overheated, more than likely a result of its trudge through wet grass. The screen on the mower's body said it was cooling down, which only took about five minutes. By the end of today's cutting session, though, the underside of the Robomow and its two blades were covered in a blanket of soggy grass clippings. The weirdest thing about watching the Robomow work was its seemingly random path around my yard. I selected the mowing option in which the Robomow would first edge the yard before moving into the interior. After it mowed around the perimeter, it took off diagonally across the lawn, then proceeded to cut strips of grass at random. It was kind of like the perceived aimless path of the iRobot Roomba, except there's a big difference between crumbs on the floor and strips of cut grass criss-crossing my yard. Robomow's user manual says that your grass might be uneven for the first few mows. That was an understatement. After 40 minutes of cutting, the blades stopped whirring, and the Robomow rolled around the perimeter until it docked itself on the base. Maybe it had a low charge. Maybe the blades were just too clogged with wet grass. But it looks like a bored pre-teen cut an asterisk into my front yard. We're giving the Robomow a month's worth of testing to really see how well it fits into a lawn care routine. That means I'll send the robot lawnmower again to hopefully conquer my haphazard front yard. But I just checked the weather forecast. It looks like rain.
// RTTResolver returns a Sliver from a Site with lowest RTT given a client's IP. func RTTResolver(c appengine.Context, toolID string, ip net.IP) (net.IP, error) { cgIP := rtt.GetClientGroup(ip).IP rttKey := datastore.NewKey(c, "string", "rtt", 0, nil) key := datastore.NewKey(c, "ClientGroup", cgIP.String(), 0, rttKey) var cg rtt.ClientGroup err := data.GetData(c, MCKey_ClientGroup(cgIP), key, &cg) if err != nil { if err == datastore.ErrNoSuchEntity { return nil, ErrNotEnoughData } return nil, err } var siteID string var sliverTool *data.SliverTool for _, sr := range cg.SiteRTTs { siteID = sr.SiteID sliverTool, err = data.GetRandomSliverFromSite(c, toolID, siteID) if err == nil { return net.ParseIP(sliverTool.SliverIPv4), nil } } return nil, ErrNotEnoughData }
/** * @ Created on: 2020/1/9 * @Author: LEGION XiaoLuo * @ Description: */ public class HomePageView extends FrameLayout implements IHomePageView { Context mContext; public FrameLayout mBgView; public ImageView mExitParentModeView; public ImageView mParentSetView; public FrameLayout mFirstSeeView; public FrameLayout mSecondListenView; public FrameLayout mThreeTalkView; public FrameLayout mFourLearnView; public ImageView mStoreView; public ImageView mMyAppView; public ArrayList<Animator> mAnimatorList; private AnimatorSet mSet; public HomePageView(Context context) { super(context); mContext = context; mAnimatorList = new ArrayList<>(); initView(); } private void initView() { mBgView = new BgView(mContext, mAnimatorList); addView(mBgView); mExitParentModeView = new ImageView(mContext); LayoutParams exitParams = new LayoutParams(UiUtil.div(468), UiUtil.div(213)); exitParams.leftMargin = UiUtil.div(30); exitParams.topMargin = UiUtil.div(0); mExitParentModeView.setBackgroundResource(R.drawable.home_bg_exit); addView(mExitParentModeView, exitParams); mParentSetView = new ImageView(mContext); LayoutParams setParams = new LayoutParams(UiUtil.div(406), UiUtil.div(213)); setParams.leftMargin = UiUtil.div(498); setParams.topMargin = UiUtil.div(0); mParentSetView.setBackgroundResource(R.drawable.home_bg_set); addView(mParentSetView, setParams); mFirstSeeView = new FirstSeeAnimationView(mContext, mAnimatorList); LayoutParams seeParams = new LayoutParams(UiUtil.div(515), UiUtil.div(533)); seeParams.leftMargin = UiUtil.div(147); seeParams.topMargin = UiUtil.div(290); addView(mFirstSeeView, seeParams); mThreeTalkView = new ThirdTellStory(mContext, mAnimatorList); LayoutParams talkParams = new LayoutParams(UiUtil.div(485), UiUtil.div(502)); talkParams.leftMargin = UiUtil.div(898); talkParams.topMargin = UiUtil.div(225); addView(mThreeTalkView, talkParams); mSecondListenView = new SecondListenSongView(mContext, mAnimatorList); LayoutParams listenParams = new LayoutParams(UiUtil.div(607), UiUtil.div(627)); listenParams.leftMargin = UiUtil.div(603); listenParams.topMargin = UiUtil.div(462); addView(mSecondListenView, listenParams); mFourLearnView = new FourLearnKnowView(mContext, mAnimatorList); LayoutParams learnParams = new LayoutParams(UiUtil.div(539), UiUtil.div(500)); learnParams.leftMargin = UiUtil.div(1244); learnParams.topMargin = UiUtil.div(506); addView(mFourLearnView, learnParams); ImageView tabView = new ImageView(mContext); LayoutParams tabParams = new LayoutParams(UiUtil.div(509), UiUtil.div(156)); tabParams.topMargin = UiUtil.div(1043); tabParams.leftMargin = UiUtil.div(1411); tabView.setBackgroundResource(R.drawable.home_bg_bottom_tab); addView(tabView, tabParams); mStoreView = new ImageView(mContext); LayoutParams storeParams = new LayoutParams(UiUtil.div(171), UiUtil.div(153)); storeParams.leftMargin = UiUtil.div(1518); storeParams.topMargin = UiUtil.div(1043); mStoreView.setBackgroundResource(R.drawable.home_bg_store); addView(mStoreView, storeParams); mMyAppView = new ImageView(mContext); LayoutParams myAppParams = new LayoutParams(UiUtil.div(171), UiUtil.div(153)); myAppParams.leftMargin = UiUtil.div(1721); myAppParams.topMargin = UiUtil.div(1043); mMyAppView.setBackgroundResource(R.drawable.home_bg_myapp); addView(mMyAppView, myAppParams); mSet = new AnimatorSet(); mSet.playTogether(mAnimatorList); mSet.start(); } @Override public View getView() { return this; } @Override public void destroy() { mSet.cancel(); } @TargetApi(Build.VERSION_CODES.KITKAT) @Override public void onResume() { if (mSet.isPaused()) { mSet.resume(); } } @TargetApi(Build.VERSION_CODES.KITKAT) @Override public void onStop() { if (mSet.isRunning()) { mSet.pause(); } } }
// Copyright 2021 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cpuprofile import ( "context" "errors" "fmt" "io" "net/http" "strconv" "sync" "time" "github.com/google/pprof/profile" goutil "github.com/pingcap/tidb/util" "github.com/pingcap/tidb/util/logutil" "go.uber.org/zap" ) // ProfileHTTPHandler is same as pprof.Profile. // The difference is ProfileHTTPHandler uses cpuprofile.GetCPUProfile to fetch profile data. func ProfileHTTPHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Content-Type-Options", "nosniff") sec, err := strconv.ParseInt(r.FormValue("seconds"), 10, 64) if sec <= 0 || err != nil { sec = 30 } if durationExceedsWriteTimeout(r, float64(sec)) { serveError(w, http.StatusBadRequest, "profile duration exceeds server's WriteTimeout") return } // Set Content Type assuming StartCPUProfile will work, // because if it does it starts writing. w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Content-Disposition", `attachment; filename="profile"`) pc := NewCollector() err = pc.StartCPUProfile(w) if err != nil { serveError(w, http.StatusInternalServerError, "Could not enable CPU profiling: "+err.Error()) return } time.Sleep(time.Second * time.Duration(sec)) err = pc.StopCPUProfile() if err != nil { serveError(w, http.StatusInternalServerError, "Could not enable CPU profiling: "+err.Error()) } } // Collector is a cpu profile collector, it collect cpu profile data from globalCPUProfiler. type Collector struct { ctx context.Context cancel context.CancelFunc started bool firstRead chan struct{} wg sync.WaitGroup dataCh ProfileConsumer writer io.Writer // Following fields uses to store the result data of collected. result *profile.Profile err error } // NewCollector returns a new NewCollector. func NewCollector() *Collector { ctx, cancel := context.WithCancel(context.Background()) return &Collector{ ctx: ctx, cancel: cancel, firstRead: make(chan struct{}), dataCh: make(ProfileConsumer, 1), } } // StartCPUProfile is a substitute for the `pprof.StartCPUProfile` function. // You should use this function instead of `pprof.StartCPUProfile`. // Otherwise you may fail, or affect the TopSQL feature and pprof profile HTTP API . // WARN: this function is not thread-safe. func (pc *Collector) StartCPUProfile(w io.Writer) error { if pc.started { return errors.New("Collector already started") } pc.started = true pc.writer = w pc.wg.Add(1) go goutil.WithRecovery(pc.readProfileData, nil) return nil } // StopCPUProfile is a substitute for the `pprof.StopCPUProfile` function. // WARN: this function is not thread-safe. func (pc *Collector) StopCPUProfile() error { if !pc.started { return nil } // wait for reading least 1 profile data. select { case <-pc.firstRead: case <-time.After(DefProfileDuration * 2): } pc.cancel() pc.wg.Wait() data, err := pc.buildProfileData() if err != nil || data == nil { return err } return data.Write(pc.writer) } // WaitProfilingFinish waits for collecting `seconds` profile data finished. func (pc *Collector) readProfileData() { // register cpu profile consumer. Register(pc.dataCh) defer func() { Unregister(pc.dataCh) pc.wg.Done() }() pc.result, pc.err = nil, nil firstRead := true for { select { case <-pc.ctx.Done(): return case data := <-pc.dataCh: pc.err = pc.handleProfileData(data) if pc.err != nil { return } if firstRead { firstRead = false close(pc.firstRead) } } } } func (pc *Collector) handleProfileData(data *ProfileData) error { if data.Error != nil { return data.Error } pd, err := profile.ParseData(data.Data.Bytes()) if err != nil { return err } if pc.result == nil { pc.result = pd return nil } pc.result, err = profile.Merge([]*profile.Profile{pc.result, pd}) return err } func (pc *Collector) buildProfileData() (*profile.Profile, error) { if pc.err != nil || pc.result == nil { return nil, pc.err } pc.removeLabel(pc.result) return pc.result, nil } const labelSQL = "sql" // removeLabel uses to remove the sql_digest and plan_digest labels for pprof cpu profile data. // Since TopSQL will set the sql_digest and plan_digest label, they are strange for other users. func (pc *Collector) removeLabel(profileData *profile.Profile) { for _, s := range profileData.Sample { for k := range s.Label { if k != labelSQL { delete(s.Label, k) } } } } func durationExceedsWriteTimeout(r *http.Request, seconds float64) bool { srv, ok := r.Context().Value(http.ServerContextKey).(*http.Server) return ok && srv.WriteTimeout != 0 && seconds >= srv.WriteTimeout.Seconds() } func serveError(w http.ResponseWriter, status int, txt string) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Header().Set("X-Go-Pprof", "1") w.Header().Del("Content-Disposition") w.WriteHeader(status) _, err := fmt.Fprintln(w, txt) if err != nil { logutil.BgLogger().Info("write http response error", zap.Error(err)) } }
<filename>trunks/mock_authorization_delegate.h // Copyright 2014 The Chromium OS 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 TRUNKS_MOCK_AUTHORIZATION_DELEGATE_H_ #define TRUNKS_MOCK_AUTHORIZATION_DELEGATE_H_ #include <string> #include <base/macros.h> #include <gmock/gmock.h> #include "trunks/authorization_delegate.h" namespace trunks { class MockAuthorizationDelegate : public AuthorizationDelegate { public: MockAuthorizationDelegate(); MockAuthorizationDelegate(const MockAuthorizationDelegate&) = delete; MockAuthorizationDelegate& operator=(const MockAuthorizationDelegate&) = delete; ~MockAuthorizationDelegate() override; MOCK_METHOD4(GetCommandAuthorization, bool(const std::string&, bool, bool, std::string*)); MOCK_METHOD2(CheckResponseAuthorization, bool(const std::string&, const std::string&)); MOCK_METHOD1(EncryptCommandParameter, bool(std::string*)); MOCK_METHOD1(DecryptResponseParameter, bool(std::string*)); MOCK_METHOD1(GetTpmNonce, bool(std::string*)); }; } // namespace trunks #endif // TRUNKS_MOCK_AUTHORIZATION_DELEGATE_H_
//-------------------------------------------------------------------------------------- // Name: CombiJointFilter() // Desc: A filter for the positional data. This filter uses a combination of velocity // position history to filter the joint positions. //-------------------------------------------------------------------------------------- void FilterCombination::Update( const SKinSkeletonRawData& pSkeletonData, const float fDeltaTime ) { for ( uint32 nJoint = 0; nJoint < KIN_SKELETON_POSITION_COUNT; ++nJoint ) { m_History[ nJoint ].m_vWantedPos = pSkeletonData.vSkeletonPositions[ nJoint ]; Vec4 vDelta; vDelta = m_History[ nJoint ].m_vWantedPos - m_History[ nJoint ].m_vLastWantedPos; { Vec4 vBlended; vBlended = Vec4(0,0,0,0); for( uint32 k = 0; k < m_nUseTaps; ++k) { vBlended = vBlended + m_History[ nJoint ].m_vPrevDeltas[k]; } vBlended = vBlended / ((float)m_nUseTaps); vBlended.w = 0.0f; vDelta.w = 0.0f; float fDeltaLength = vDelta.GetLength(); float fBlendedLength = vBlended.GetLength(); m_History[ nJoint ].m_fWantedLocalBlendRate = m_fDefaultApplyRate; m_History[ nJoint ].m_bActive[0] = false; m_History[ nJoint ].m_bActive[1] = false; m_History[ nJoint ].m_bActive[2] = false; if( fDeltaLength >= m_fDeltaLengthThreshold && fBlendedLength >= m_fBlendedLengthThreshold ) { float fDotProd; float fConfidence; if( m_bDotProdNormalize ) { Vec4 vDeltaOne = vDelta; vDeltaOne.Normalize(); Vec4 vBlendedOne = vBlended; vBlendedOne.Normalize(); fDotProd = vDeltaOne.Dot( vBlendedOne ); } else { fDotProd = vDelta.Dot(vBlended); } if( fDotProd >= m_fDotProdThreshold ) { fConfidence = fDotProd; m_History[ nJoint ].m_fWantedLocalBlendRate = min( fConfidence, 1.0f ); m_History[ nJoint ].m_bActive[0] = true; } } assert( m_History[ nJoint ].m_fWantedLocalBlendRate <= 1.0f ); } for( int j = m_nUseTaps-2; j >= 0; --j ) { m_History[ nJoint ].m_vPrevDeltas[j+1] = m_History[ nJoint ].m_vPrevDeltas[j]; } m_History[ nJoint ].m_vPrevDeltas[0] = vDelta; m_History[ nJoint ].m_vLastWantedPos = m_History[ nJoint ].m_vWantedPos; } for ( uint32 pass = 0; pass < 2; ++pass ) { for ( uint32 bone = 0; bone < g_numBones; ++bone ) { float fRate1; float fRate2; fRate1 = m_History[ g_Bones[bone].startJoint ].m_fWantedLocalBlendRate; fRate2 = m_History[ g_Bones[bone].endJoint ].m_fWantedLocalBlendRate; if( (fRate1 * m_fDownBlendRate) > fRate2) { m_History[ g_Bones[bone].endJoint ].m_fWantedLocalBlendRate = ( fRate1 * m_fDownBlendRate ); m_History[ g_Bones[bone].endJoint ].m_bActive[pass+1] = true; } if( ( fRate2 * m_fDownBlendRate ) > fRate1) { m_History[ g_Bones[bone].startJoint ].m_fWantedLocalBlendRate = ( fRate2 * m_fDownBlendRate ); m_History[ g_Bones[bone].startJoint ].m_bActive[pass+1] = true; } } } for ( uint32 joint = 0; joint < KIN_SKELETON_POSITION_COUNT; ++joint ) { m_History[ joint ].m_fActualLocalBlendRate = Lerp(m_History[ joint ].m_fActualLocalBlendRate, m_History[ joint ].m_fWantedLocalBlendRate, m_fBlendBlendRate); m_History[ joint ].m_vPos = Lerp(m_History[ joint ].m_vPos, m_History[ joint ].m_vWantedPos, m_History[ joint ].m_fActualLocalBlendRate); m_FilteredJoints[ joint ] = m_History[ joint ].m_vPos; } }
/** * * @author Bob Tarling */ public class Token { String text; TokenType type; int length; /** Creates a new instance of Token */ Token(String text, TokenType type) { this.text = text; this.type = type; this.length = text.length(); } /** Creates a new instance of Token */ Token(int length, TokenType type) { this.type = type; this.length = length; } public String toString() { return text; } public TokenType getType() { return type; } public boolean equals(Object o) { if (!(o instanceof Token)) return false; Token other = (Token) o; if (this == o) return true; if (type != other.type) return false; if (this.text == null && other.text == null) { return ((length == other.length)); } return (text.equals(other.text)); } public boolean hasText(String text) { return this.text.equals(text); } public int getLength() { return length; } public int hashCode() { if (text != null) { return text.hashCode(); } return length; } public Token append(Token token) { if (text != null) { return new Token(text + token.toString(), type); } else { return new Token(length + token.getLength(), type); } } }
/*! @file LowMCEnc.h * @brief Header file for LowMcEnc.c, the C implementation of LowMC. * * This file is part of the reference implementation of the Picnic and Fish * signature schemes, described in the paper: * * Post-Quantum Zero-Knowledge and Signatures from Symmetric-Key Primitives * <NAME> and <NAME> and <NAME> and <NAME> and * <NAME> and <NAME> and <NAME> and Greg * Zaverucha * Cryptology ePrint Archive: Report 2017/279 * http://eprint.iacr.org/2017/279 * * The code is provided under the MIT license, see LICENSE for * more details. * */ #ifndef LowMCEnc_h #define LowMCEnc_h #include <stdint.h> #include "LowMCConstants.h" /** Encrypt one block of data with the specified LowMC parameter set * * @param plaintext[in] The plaintext to encrypt, must have length STATE_SIZE_BYTES * @param ciphertext[in,out] The output ciphertext, must have length STATE_SIZE_BYTES * @param key[in] The key to use for encryption. Must have length STATE_SIZE_BYTES * @param parameters[in] The LowMC parameter set to be used * * @remark Before encryption, readLookupTables must be called, and afterwards * freeLookupTables should be called to free memory. */ void LowMCEnc(const uint32_t* plaintext, uint32_t* ciphertext, const uint32_t* key, lowmcparams_t* parameters); /** Read precomputed data required by LowMCEnc(). * If the path parameter is NULL, data is read from DEFAULT_DATA_PATH. If the path * parameter is provided, it must contain the trailing slash, i.e., "mypath/", not "mypath" */ int readLookupTables(lowmcparams_t* params, const char* path); /** Free memory allocated by readLookupTables */ void freeLookupTables(); #endif /* LowMcEnc_h */