hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
6c45f07b58df762a6ef96c8c13ac2b9ddf64d770
924
package com.fr.swift.cloud.query.builder.feture; import com.fr.swift.cloud.query.filter.info.SwiftDetailFilterInfo; import com.fr.swift.cloud.segment.Segment; /** * @author xiqiu * @date 2021/1/27 * @description 查询加速特征,父类定义结构,子类做具体值的实现 * @since swift-1.2.0 */ public abstract class BaseFeature<T> { private boolean init = false; protected T t; protected Segment segment; protected SwiftDetailFilterInfo detailFilterInfo; public BaseFeature(Segment segment, SwiftDetailFilterInfo detailFilterInfo) { this.segment = segment; this.detailFilterInfo = detailFilterInfo; } public T getValue() { if (!init) { setValue(); } return t; } public void setValue() { init = true; doSetValue(); } /** * 设计成这种模式是为了延迟加载,特征都准备好,有些操作是比较耗时的,但是没有用到的话就不会去真正计算,而且进行了封装 */ public abstract void doSetValue(); }
22.536585
81
0.658009
82917838bf90dbb95c378f0b4290648e44319091
8,069
package org.sj.verbs.activity; import static org.sj.verbs.utilities.ArabicLiterals.LALIF; import static org.sj.verbs.utilities.Constants.QURAN_VERB_ROOT; import static org.sj.verbs.utilities.Constants.QURAN_VERB_WAZAN; import static org.sj.verbs.utilities.Constants.VERBCASE; import static org.sj.verbs.utilities.Constants.VERBTYPE; import android.content.SharedPreferences; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.lifecycle.Lifecycle; import androidx.preference.PreferenceManager; import androidx.viewpager2.adapter.FragmentStateAdapter; import androidx.viewpager2.widget.ViewPager2; import com.google.android.material.tabs.TabLayout; import com.google.android.material.tabs.TabLayoutMediator; import org.sj.verbs.R; import org.sj.verbs.VerbConjugaorApp; import org.sj.verbs.fragments.Dictionary_frag; import org.sj.verbs.fragments.FragmentIsmIsmAla; import org.sj.verbs.fragments.FragmentIsmZarf; import org.sj.verbs.fragments.FragmentIsmfaelIsmMafools; import org.sj.verbs.fragments.FragmentVerb; import org.sj.verbs.fragments.TabSagheerFragmentVerb; import ru.dimorinny.floatingtextbutton.FloatingTextButton; public class NewTabsActivity extends BaseActivity { private static final int NUM_PAGES_THULATHI = 7; private static final int NUM_PAGES_MAZEED = 5; private boolean ismujarrad; Bundle dataBundle; // Arrey of strings FOR TABS TITLES private final String[] thulathientitles = new String[]{"Hans Weir", "Lane Lexicon", "Sarf-e-Sagheer ", "Verb Conjugaton", "Active/Passive Pcpl", "N.Of Instrument", "N.Place/Time"}; private final String[] thulathiartitles = new String[]{"قاموس هانز" , "لين معجم", "صرف صغير", "تصريف الأفعال ", "لاسم الفاعل/الاسم المفعول", "الاسم الآلة", "الاسم الظرف"}; private final String[] mazeedentitles = new String[]{"Hans Weir", "Lane Lexicon", "Sarf-e-Sagheer ", "Verb Conjugaton", "Active/Passive Participle"}; private final String[] mazeedartitles = new String[]{"قاموس هانز","لين معجم", "صرف صغير", "تصريف الأفعال ", "لاسم الفاعل/الاسم المفعول"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_newtabs); FloatingTextButton callButton = findViewById(R.id.action_button); SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(VerbConjugaorApp.getContext()); String language = shared.getString("lang", "en"); callButton.setOnClickListener(view -> { // viewPager.adapters=null; finish(); // Snackbar.make(viewById, "Call button clicked", Snackbar.LENGTH_SHORT).show(); }); FragmentManager fm = getSupportFragmentManager(); ViewStateAdapter sa = new ViewStateAdapter(fm, getLifecycle()); final ViewPager2 viewPager = findViewById(R.id.pager); viewPager.setAdapter(sa); final TabLayout tabLayout = findViewById(R.id.tabLayout); dataBundle = new Bundle(); Bundle bundle = getIntent().getExtras(); String root = bundle.getString(QURAN_VERB_ROOT); final String ss = root.replaceAll("[\\[\\]]", ""); String verbroot = ss.replaceAll("[,;\\s]", ""); int starts = verbroot.indexOf(LALIF); if (starts != -1) { verbroot = verbroot.replace(LALIF, "ء"); } String verbform = null; String verbmood = null; String verbtype = null; if(null!=bundle) { verbform = bundle.getString(QURAN_VERB_WAZAN); verbmood = bundle.getString(VERBCASE); verbtype=bundle.getString(VERBTYPE); } ismujarrad = verbtype.equals("mujarrad"); dataBundle.putSerializable(QURAN_VERB_ROOT, verbroot); dataBundle.putString(QURAN_VERB_WAZAN, verbform); dataBundle.putString(VERBCASE, verbmood); dataBundle.putString(VERBTYPE, verbtype); // Up to here, we have working scrollable pages if (ismujarrad) { if (language.equals("en")) { new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText(thulathientitles[position])).attach(); } else { new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText(thulathiartitles[position])).attach(); } } else { if (language.equals("en")) { new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText(mazeedentitles[position])).attach(); } else { new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText(mazeedartitles[position])).attach(); } } // Now we have tabs, NOTE: I am hardcoding the order, you'll want to do something smarter tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() { @Override public void onPageSelected(int position) { tabLayout.selectTab(tabLayout.getTabAt(position)); } }); // And now we have tabs that, when clicked, navigate to the correct page } private class ViewStateAdapter extends FragmentStateAdapter { public ViewStateAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) { super(fragmentManager, lifecycle); } @NonNull @Override public Fragment createFragment(int position) { // Hardcoded in this order, you'll want to use lists and make sure the titles match if (position == 0) { Dictionary_frag fragv = new Dictionary_frag(NewTabsActivity.this, "hans"); fragv.setArguments(dataBundle); return fragv.newInstance(); } else if (position == 1) { Dictionary_frag fragv = new Dictionary_frag(NewTabsActivity.this, "lanes"); fragv.setArguments(dataBundle); return fragv.newInstance(); } else if (position == 2) { TabSagheerFragmentVerb fragv = new TabSagheerFragmentVerb(NewTabsActivity.this); fragv.setArguments(dataBundle); return fragv.newInstance(); } else if (position == 3) { FragmentVerb fragv = new FragmentVerb(); fragv.setArguments(dataBundle); return fragv.newInstance(); } else if (position == 4) { FragmentIsmfaelIsmMafools fragvs = new FragmentIsmfaelIsmMafools(); fragvs.setArguments(dataBundle); return fragvs.newInstance(); } else if (position == 5) { FragmentIsmIsmAla fragvsi = new FragmentIsmIsmAla(); fragvsi.setArguments(dataBundle); return fragvsi.newInstance(); } else if (position == 6) { FragmentIsmZarf fragvsi = new FragmentIsmZarf(); fragvsi.setArguments(dataBundle); return fragvsi.newInstance(); } FragmentVerb fragv = new FragmentVerb(); fragv.setArguments(dataBundle); return fragv.newInstance(); } @Override public int getItemCount() { if (ismujarrad) { return NUM_PAGES_THULATHI; } else { return NUM_PAGES_MAZEED; } } } }
36.183857
184
0.639113
286ab228e59413dd7314380af9dd0c129553e32b
835
package com.antsoft.yecai.controller; import com.antsoft.yecai.service.RedPacketService; import org.springframework.beans.factory.annotation.Autowired; 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.RestController; /** * Created by ant on 2016/2/9. */ @RestController @RequestMapping("/v1/redPacket") public class RedPacketController { @Autowired private RedPacketService redPacketService; @RequestMapping(value = "/obtainDailyRedPacket", method = RequestMethod.POST) public void obtainDailyRedPacket(@RequestParam("userId") String userId) { redPacketService.obtainDailyRedPacket(userId); } }
34.791667
82
0.777246
d3921c82a34d883e681c64cddc6cafa8a10fd4e0
11,216
package com.spingular.cms.domain; import java.io.Serializable; import javax.persistence.*; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; /** * A ConfigVariables. */ @Entity @Table(name = "config_variables") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class ConfigVariables implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") @SequenceGenerator(name = "sequenceGenerator") private Long id; @Column(name = "config_var_long_1") private Long configVarLong1; @Column(name = "config_var_long_2") private Long configVarLong2; @Column(name = "config_var_long_3") private Long configVarLong3; @Column(name = "config_var_long_4") private Long configVarLong4; @Column(name = "config_var_long_5") private Long configVarLong5; @Column(name = "config_var_long_6") private Long configVarLong6; @Column(name = "config_var_long_7") private Long configVarLong7; @Column(name = "config_var_long_8") private Long configVarLong8; @Column(name = "config_var_long_9") private Long configVarLong9; @Column(name = "config_var_long_10") private Long configVarLong10; @Column(name = "config_var_long_11") private Long configVarLong11; @Column(name = "config_var_long_12") private Long configVarLong12; @Column(name = "config_var_long_13") private Long configVarLong13; @Column(name = "config_var_long_14") private Long configVarLong14; @Column(name = "config_var_long_15") private Long configVarLong15; @Column(name = "config_var_boolean_16") private Boolean configVarBoolean16; @Column(name = "config_var_boolean_17") private Boolean configVarBoolean17; @Column(name = "config_var_boolean_18") private Boolean configVarBoolean18; @Column(name = "config_var_string_19") private String configVarString19; @Column(name = "config_var_string_20") private String configVarString20; // jhipster-needle-entity-add-field - JHipster will add fields here public Long getId() { return id; } public void setId(Long id) { this.id = id; } public ConfigVariables id(Long id) { this.id = id; return this; } public Long getConfigVarLong1() { return this.configVarLong1; } public ConfigVariables configVarLong1(Long configVarLong1) { this.configVarLong1 = configVarLong1; return this; } public void setConfigVarLong1(Long configVarLong1) { this.configVarLong1 = configVarLong1; } public Long getConfigVarLong2() { return this.configVarLong2; } public ConfigVariables configVarLong2(Long configVarLong2) { this.configVarLong2 = configVarLong2; return this; } public void setConfigVarLong2(Long configVarLong2) { this.configVarLong2 = configVarLong2; } public Long getConfigVarLong3() { return this.configVarLong3; } public ConfigVariables configVarLong3(Long configVarLong3) { this.configVarLong3 = configVarLong3; return this; } public void setConfigVarLong3(Long configVarLong3) { this.configVarLong3 = configVarLong3; } public Long getConfigVarLong4() { return this.configVarLong4; } public ConfigVariables configVarLong4(Long configVarLong4) { this.configVarLong4 = configVarLong4; return this; } public void setConfigVarLong4(Long configVarLong4) { this.configVarLong4 = configVarLong4; } public Long getConfigVarLong5() { return this.configVarLong5; } public ConfigVariables configVarLong5(Long configVarLong5) { this.configVarLong5 = configVarLong5; return this; } public void setConfigVarLong5(Long configVarLong5) { this.configVarLong5 = configVarLong5; } public Long getConfigVarLong6() { return this.configVarLong6; } public ConfigVariables configVarLong6(Long configVarLong6) { this.configVarLong6 = configVarLong6; return this; } public void setConfigVarLong6(Long configVarLong6) { this.configVarLong6 = configVarLong6; } public Long getConfigVarLong7() { return this.configVarLong7; } public ConfigVariables configVarLong7(Long configVarLong7) { this.configVarLong7 = configVarLong7; return this; } public void setConfigVarLong7(Long configVarLong7) { this.configVarLong7 = configVarLong7; } public Long getConfigVarLong8() { return this.configVarLong8; } public ConfigVariables configVarLong8(Long configVarLong8) { this.configVarLong8 = configVarLong8; return this; } public void setConfigVarLong8(Long configVarLong8) { this.configVarLong8 = configVarLong8; } public Long getConfigVarLong9() { return this.configVarLong9; } public ConfigVariables configVarLong9(Long configVarLong9) { this.configVarLong9 = configVarLong9; return this; } public void setConfigVarLong9(Long configVarLong9) { this.configVarLong9 = configVarLong9; } public Long getConfigVarLong10() { return this.configVarLong10; } public ConfigVariables configVarLong10(Long configVarLong10) { this.configVarLong10 = configVarLong10; return this; } public void setConfigVarLong10(Long configVarLong10) { this.configVarLong10 = configVarLong10; } public Long getConfigVarLong11() { return this.configVarLong11; } public ConfigVariables configVarLong11(Long configVarLong11) { this.configVarLong11 = configVarLong11; return this; } public void setConfigVarLong11(Long configVarLong11) { this.configVarLong11 = configVarLong11; } public Long getConfigVarLong12() { return this.configVarLong12; } public ConfigVariables configVarLong12(Long configVarLong12) { this.configVarLong12 = configVarLong12; return this; } public void setConfigVarLong12(Long configVarLong12) { this.configVarLong12 = configVarLong12; } public Long getConfigVarLong13() { return this.configVarLong13; } public ConfigVariables configVarLong13(Long configVarLong13) { this.configVarLong13 = configVarLong13; return this; } public void setConfigVarLong13(Long configVarLong13) { this.configVarLong13 = configVarLong13; } public Long getConfigVarLong14() { return this.configVarLong14; } public ConfigVariables configVarLong14(Long configVarLong14) { this.configVarLong14 = configVarLong14; return this; } public void setConfigVarLong14(Long configVarLong14) { this.configVarLong14 = configVarLong14; } public Long getConfigVarLong15() { return this.configVarLong15; } public ConfigVariables configVarLong15(Long configVarLong15) { this.configVarLong15 = configVarLong15; return this; } public void setConfigVarLong15(Long configVarLong15) { this.configVarLong15 = configVarLong15; } public Boolean getConfigVarBoolean16() { return this.configVarBoolean16; } public ConfigVariables configVarBoolean16(Boolean configVarBoolean16) { this.configVarBoolean16 = configVarBoolean16; return this; } public void setConfigVarBoolean16(Boolean configVarBoolean16) { this.configVarBoolean16 = configVarBoolean16; } public Boolean getConfigVarBoolean17() { return this.configVarBoolean17; } public ConfigVariables configVarBoolean17(Boolean configVarBoolean17) { this.configVarBoolean17 = configVarBoolean17; return this; } public void setConfigVarBoolean17(Boolean configVarBoolean17) { this.configVarBoolean17 = configVarBoolean17; } public Boolean getConfigVarBoolean18() { return this.configVarBoolean18; } public ConfigVariables configVarBoolean18(Boolean configVarBoolean18) { this.configVarBoolean18 = configVarBoolean18; return this; } public void setConfigVarBoolean18(Boolean configVarBoolean18) { this.configVarBoolean18 = configVarBoolean18; } public String getConfigVarString19() { return this.configVarString19; } public ConfigVariables configVarString19(String configVarString19) { this.configVarString19 = configVarString19; return this; } public void setConfigVarString19(String configVarString19) { this.configVarString19 = configVarString19; } public String getConfigVarString20() { return this.configVarString20; } public ConfigVariables configVarString20(String configVarString20) { this.configVarString20 = configVarString20; return this; } public void setConfigVarString20(String configVarString20) { this.configVarString20 = configVarString20; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ConfigVariables)) { return false; } return id != null && id.equals(((ConfigVariables) o).id); } @Override public int hashCode() { // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ return getClass().hashCode(); } // prettier-ignore @Override public String toString() { return "ConfigVariables{" + "id=" + getId() + ", configVarLong1=" + getConfigVarLong1() + ", configVarLong2=" + getConfigVarLong2() + ", configVarLong3=" + getConfigVarLong3() + ", configVarLong4=" + getConfigVarLong4() + ", configVarLong5=" + getConfigVarLong5() + ", configVarLong6=" + getConfigVarLong6() + ", configVarLong7=" + getConfigVarLong7() + ", configVarLong8=" + getConfigVarLong8() + ", configVarLong9=" + getConfigVarLong9() + ", configVarLong10=" + getConfigVarLong10() + ", configVarLong11=" + getConfigVarLong11() + ", configVarLong12=" + getConfigVarLong12() + ", configVarLong13=" + getConfigVarLong13() + ", configVarLong14=" + getConfigVarLong14() + ", configVarLong15=" + getConfigVarLong15() + ", configVarBoolean16='" + getConfigVarBoolean16() + "'" + ", configVarBoolean17='" + getConfigVarBoolean17() + "'" + ", configVarBoolean18='" + getConfigVarBoolean18() + "'" + ", configVarString19='" + getConfigVarString19() + "'" + ", configVarString20='" + getConfigVarString20() + "'" + "}"; } }
27.762376
109
0.670649
54554974ff2c722078f00b53088cafc6f60b076e
279
package com.example.shejimoshi.decorator; /** * Created by Android-mwb on 2018/8/10. */ public abstract class Beverage { String description = "Unknown Beverage"; public String getDescription() { return description; } public abstract double cost(); }
18.6
44
0.681004
14794941b60a60385ee426bc7377a38799464d1e
5,528
package com.github.vitrocket.mybatis.dao; import com.github.vitrocket.mybatis.entity.*; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mybatis.spring.boot.test.autoconfigure.MybatisTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringRunner; import java.math.BigDecimal; import java.time.LocalDate; import java.util.List; import static org.junit.Assert.*; /** * @author Vit Rocket on 18.11.2017. * @version 1.0 * @since on 18.11.2017 */ @Slf4j @RunWith(SpringRunner.class) @MybatisTest public class SessionMapperTest { @Autowired private SessionMapper sessionMapper; @Autowired private UserMapper userMapper; @Autowired private CountryMapper countryMapper; @Autowired private LocationMapper locationMapper; @Autowired private UserGroupMapper userGroupMapper; private Country beforeCountry; private Location beforeLocation; private UserGroup beforeUserGroup; private User beforeUser; private Session beforeSession; @Test public void contextLoads() throws Exception { assertNotNull(sessionMapper); assertNotNull(userMapper); assertNotNull(beforeCountry); assertNotNull(beforeLocation); assertNotNull(beforeUserGroup); } @Before public void setUp() throws Exception { beforeCountry = new Country("Test Country", "Test Language"); countryMapper.insert(beforeCountry); assertNotNull(beforeCountry.getId()); log.info(beforeCountry.toString()); beforeLocation = new Location("My Location", BigDecimal.valueOf(50.111), BigDecimal.valueOf(50.111)); beforeLocation.setCountry(beforeCountry); locationMapper.insert(beforeLocation); assertNotNull(beforeLocation.getId()); log.info(beforeLocation.toString()); beforeUserGroup = new UserGroup("Test User Group"); userGroupMapper.insert(beforeUserGroup); assertNotNull(beforeUserGroup.getId()); log.info(beforeUserGroup.toString()); beforeUser = new User(1345678936, beforeLocation, beforeUserGroup); userMapper.insert(beforeUser); assertNotNull(beforeUser.getId()); log.info(beforeUser.toString()); beforeSession = Session.builder() .user(beforeUser) .dateOpened(LocalDate.of(2017, 12, 1)) .dateClosed(LocalDate.of(2017, 12, 10)) .build(); sessionMapper.insert(beforeSession); assertNotNull(beforeSession.getId()); log.info(beforeSession.toString()); } @Test public void testInsert() throws Exception { Session session = Session.builder() .user(new User()) .dateOpened(LocalDate.of(2017, 12, 1)) .dateClosed(LocalDate.of(2017, 12, 10)) .build(); sessionMapper.insert(session); assertNotNull(session.getId()); log.info(session.toString()); } @Test public void testFindSessionByDateOpened() throws Exception { Session session = Session.builder() .user(new User()) .dateOpened(LocalDate.of(2017, 12, 10)) .dateClosed(LocalDate.of(2017, 12, 15)) .build(); sessionMapper.insert(session); assertNotNull(session.getId()); log.info(session.toString()); List<Session> sessions = sessionMapper.findSessionByDateOpened(LocalDate.of(2017, 12, 1)); assertNotNull(sessions); assertTrue(sessions.size() > 0); assertFalse(sessions.contains(session)); log.info(sessions.toString()); } @Test public void testFindSessionByDateOpenedWithUser() throws Exception { Session session = Session.builder() .user(new User()) .dateOpened(LocalDate.of(2017, 12, 10)) .dateClosed(LocalDate.of(2017, 12, 15)) .build(); sessionMapper.insert(session); assertNotNull(session.getId()); log.info(session.toString()); List<Session> sessions = sessionMapper.findSessionByDateOpenedWithUser(LocalDate.of(2017, 12, 1)); assertNotNull(sessions); assertTrue(sessions.size() > 0); assertFalse(sessions.contains(session)); log.info(sessions.toString()); } @Test public void testFindSessionByDateOpenedWithUserWithLocation() throws Exception { Session session = Session.builder() .user(new User()) .dateOpened(LocalDate.of(2017, 12, 10)) .dateClosed(LocalDate.of(2017, 12, 15)) .build(); sessionMapper.insert(session); assertNotNull(session.getId()); log.info(session.toString()); List<Session> sessions = sessionMapper.findSessionByDateOpenedWithUserWithLocation(LocalDate.of(2017, 12, 1)); assertNotNull(sessions); assertTrue(sessions.size() > 0); assertFalse(sessions.contains(session)); log.info(sessions.toString()); } }
35.896104
118
0.612699
f4accb739a06357a46f5d1c55d69064fe0709bfe
1,504
package org.fiolino.indexer.sinks; import org.apache.solr.common.SolrInputDocument; import org.fiolino.common.container.Container; import org.fiolino.common.container.Selector; import org.fiolino.common.processing.sink.CloneableSink; import org.fiolino.common.processing.sink.ModifyingSink; import org.fiolino.common.processing.sink.Sink; /** * Created by kuli on 04.01.16. */ public final class TimestampSetter extends ModifyingSink<SolrInputDocument> implements CloneableSink<SolrInputDocument, TimestampSetter> { public static final String TIMESTAMP_FIELD = "timestamp"; private final Selector<Long> timestampSelector; public TimestampSetter(Sink<? super SolrInputDocument> target, Selector<Long> timestampSelector) { super(target); this.timestampSelector = timestampSelector; } @Override protected void touch(SolrInputDocument doc, Container metadata) { Long timestamp = metadata.get(timestampSelector); if (timestamp == null) { throw new IllegalStateException("No timestamp given!"); } doc.addField(TIMESTAMP_FIELD, timestamp); } @Override public TimestampSetter createClone() { return new TimestampSetter(targetForCloning(), timestampSelector); } @Override public void partialCommit(Container metadata) throws Exception { if (getTarget() instanceof CloneableSink) { ((CloneableSink<?, ?>) getTarget()).partialCommit(metadata); } } }
33.422222
102
0.722739
26670978dda8dbf508fbe26d55fd96ce9c2bddf1
2,316
/* * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.integrationtests; import io.crate.action.sql.SQLActionException; import io.crate.breaker.CrateCircuitBreakerService; import io.crate.breaker.RamAccountingContext; import org.elasticsearch.common.settings.Settings; import org.junit.Before; import org.junit.Test; public class GroupByAggregateBreakerTest extends SQLTransportIntegrationTest { @Override protected Settings nodeSettings(int nodeOrdinal) { RamAccountingContext.FLUSH_BUFFER_SIZE = 24; return Settings.builder() .put(super.nodeSettings(nodeOrdinal)) .put(CrateCircuitBreakerService.QUERY_CIRCUIT_BREAKER_LIMIT_SETTING.getKey(), "256b") .build(); } @Before public void initTestData() { Setup setup = new Setup(sqlExecutor); setup.setUpEmployees(); } @Test public void selectGroupByWithBreaking() throws Exception { expectedException.expect(SQLActionException.class); expectedException.expectMessage("CircuitBreakingException: [query] Data too large, data for "); // query takes 252 bytes of memory // 252b * 1.09 = 275b => should break with limit 256b execute("select name, department, max(income), min(age) from employees group by name, department order by 3"); } }
40.631579
118
0.737478
b91e705cc8bba088231e30e7242665e6baf14f38
647
package br.unicamp.ic.mc302.documento; class ExemploDocumento{ static public void main(String args[ ]){ Documento d1, d2; // Aloca d1 d1 = new Documento(); // Cria d1 d1.criarDocumento("Camila",181101); // Imprime informações sobre d1 d1.imprimir(); // Edita d1 (método não implementado) d1.editar(); // Aloca d2 d2 = new Documento(); // Cria d2 d2.criarDocumento("Surita", 139095); // Imprime informações sobre d2 d2.imprimir(); } }
21.566667
46
0.482226
38a23b83cdfbe72d090887d0812eb871b5dda857
502
package com.example.songr; import com.example.songr.entity.Album; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class SongrApplicationTests { @Test void contextLoads() { } @Test void testConstructorAlbum(){ Album alboum = new Album("Prince and the Revolution","Purple Rain",5,1,"https://pbs.twimg.com/media/Eihki4LWoAAcvjk?format=png&name=small"); assertNotNull(alboum); } private void assertNotNull(Album alboum) { } }
22.818182
142
0.76494
1a965ca7f044d6bcf2e0df1e603bbd2b37b17c60
3,323
/* * Copyright (c) 2011 Gary Belvin * * 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. */ package edu.jhu.privtext.util.encoders; import java.nio.ByteBuffer; import android.telephony.SmsMessage; /** * The plain text message format "The cipher text itself contains a padding * format: First a one octet value denoting the length of the plaintext, the * plaintext, optionally followed a null padding to expand the payload to the * full 140 octet envelope". * @author Gary Belvin * @version 0.1 */ public class SSMS_PTPayload { /** * A flag that turns on plain-text padding Security implication: by making all * messages equal length, an adversary will not be able to learn anything from * the ciphertext length. */ private static final boolean PlaintextPadding = true; public static byte[] parse(final byte[] thePayload) { // The first byte should be the length final ByteBuffer bb = ByteBuffer.wrap(thePayload); final byte ptlen = bb.get(); final byte[] pt = new byte[ptlen]; bb.get(pt); return pt; } /** * Wraps a plain text message with the appropriate header and padding. * @param theMaxPayloadSize The size of the desired resulting package. This is * determined by the size of MAC used in the SSMS_UserData layer * @param thePlaintext * @return A message of the format [bytes of plaintext][the plaintext][null * padding] */ public static byte[] wrapPlainText(final int theMaxPayloadSize, final byte[] thePlaintext) { assert theMaxPayloadSize > 1 && theMaxPayloadSize < SmsMessage.MAX_USER_DATA_SEPTETS_WITH_HEADER; assert (thePlaintext.length + 1) <= theMaxPayloadSize; int outputlen; if (PlaintextPadding) { outputlen = theMaxPayloadSize; } else { // Reserve one byte for the payload length outputlen = (byte) (thePlaintext.length + 1); } final ByteBuffer ud = ByteBuffer.allocate(outputlen); ud.put((byte) thePlaintext.length); ud.put(thePlaintext); // The if statement is probably unnecessary but adds clarity. if (PlaintextPadding) { final int paddinglen = outputlen - 1 - thePlaintext.length; final byte[] padding = new byte[paddinglen]; ud.put(padding); } return ud.array(); } }
36.516484
94
0.71622
7682951662260e5c7249ec1c988d4e0f21d61a9a
197
package com.works.bulutvet.entities; public interface StockJoinDepo { Integer getSId(); Integer getDepo(); Integer getAmount(); Integer getProduct(); String getDepo_name(); }
17.909091
36
0.695431
2e9a73eb55fb1b32842b18213fb95bc884674979
7,898
/******************************************************************************* * Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands * * This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer). * * ASAPRealizer is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License (LGPL) as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ASAPRealizer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with ASAPRealizer. If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package hmi.math; import com.google.common.primitives.Floats; /** * A collection of methods for vectors of arbitrary length * represented by float arrays. * @author Herwin van Welbergen, Job Zwiers */ public final class Vecf { /** */ private Vecf() { } /** * Returns a new float[] array with zero components */ public static float[] getVecf(int len) { return new float[len]; } /** * Rturns a new float[3] array with initialized components */ public static float[] getVecf(float[] vecf) { float[] result = new float[vecf.length]; System.arraycopy(vecf, 0, result, 0, vecf.length); return result; } /** * Tests for equality of two vectors */ public static boolean equals(float[] a, float[] b) { if (a == null && b == null) return true; if (a == null || b == null || a.length != b.length) return false; for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } return true; } /** * Tests for equality of vector components within epsilon. */ public static boolean epsilonEquals(float[] a, float[] b, float epsilon) { if (a == null && b == null) return true; if (a == null || b == null || a.length != b.length) return false; for (int i = 0; i < a.length; i++) { float diff = a[i] - b[i]; if (Float.isNaN(diff)) return false; if ((diff < 0 ? -diff : diff) > epsilon) return false; } return true; } /** * Returns a String of the form (v[0], v[1], ....) * */ public static String toString(float[] config) { StringBuilder buf = new StringBuilder(); buf.append('('); if (config == null) { buf.append("null"); } else { int len = config.length; if (len > 0) buf.append(config[0]); for (int i = 1; i < len; i++) { buf.append(", "); buf.append(config[i]); } } buf.append(')'); return buf.toString(); } /** * Copies vector src to vector dst. */ public static void set(float[] dst, float[] src) { for (int i = 0; i < dst.length; i++) dst[i] = src[i]; } /** * Adds vector a and b, puts result in dest. */ public static void add(float[] dst, float[] a, float[] b) { for (int i = 0; i < dst.length; i++) dst[i] = a[i] + b[i]; } /** * First scales vector a, then and a to dst * dst = dst + s*a */ public static void scaleAdd(float[] dst, float scale, float[] a) { for (int i = 0; i < dst.length; i++) { dst[i] += a[i] * scale; } } /** * Adds vector b to vector a. */ public static void add(float[] dst, float[] a) { for (int i = 0; i < dst.length; i++) dst[i] += a[i]; } /** * Adds vector a and b, puts result in dest. */ public static void sub(float[] dst, float[] a, float[] b) { for (int i = 0; i < dst.length; i++) dst[i] = a[i] - b[i]; } /** * Adds vector b to vector a. */ public static void sub(float[] dst, float[] a) { for (int i = 0; i < dst.length; i++) dst[i] -= a[i]; } /** * Scales a vector */ public static void scale(float scale, float[] dst) { for (int i = 0; i < dst.length; i++) dst[i] *= scale; } /** * Scales a vector */ public static void scale(float scale, float[] dst, float[] src) { for (int i = 0; i < dst.length; i++) dst[i] = scale * src[i]; } /** * Scales a vector */ public static void pmul(float[] dst, float[] a, float[] b) { for (int i = 0; i < dst.length; i++) dst[i] = a[i] * b[i]; } /** * Sets vector dst to the negated version of vector src */ public static void negate(float[] dst, float[] src) { for (int i = 0; i < dst.length; i++) dst[i] = -src[i]; } /** * Negates a vector */ public static void negate(float[] dst) { for (int i = 0; i < dst.length; i++) dst[i] = -dst[i]; } /** * Calculates the dot product for two vectors of length 3 */ public static float dot(float[] a, float[] b) { float d = 0.0f; for (int i = 0; i < a.length; i++) d += a[i] * b[i]; return d; } /** * returns the square of the vector length */ public static float lengthSq(float[] a) { return dot(a, a); } /** * returns the vector length */ public static float length(float[] a) { return (float) Math.sqrt(dot(a, a)); } /** * Linear interpolates between vector a and b, and puts the result in vector dst: * dst = (1-alpha)*a + alpha*b */ public static void interpolate(float[] dst, float[] a, float[] b, float alpha) { for (int i = 0; i < a.length; i++) dst[i] = (1 - alpha) * a[i] + alpha * b[i]; } /** * Normalizes a, that is, dst = a/|a| * @param a vector to be normalized * @param dst vector to receive the result */ public static void normalize(float[] dst, float[] a) { float linv = 1.0f / length(a); scale(linv, dst, a); } /** * Normalizes a, that is, a = a/|a| * @param a vector to be normalized */ public static void normalize(float[] a) { float linv = 1.0f / length(a); scale(linv, a); } public static void setZero(float[] dst) { for (int i = 0; i < dst.length; i++) { dst[i] = 0; } } public static double sum(float[] a) { double sum = 0; for (float f : a) { sum += f; } return sum; } public static double average(float[] a) { return sum(a) / a.length; } public static double max(float a[]) { return Floats.max(a); } public static double min(float a[]) { return Floats.min(a); } /** * Normalize the elements of a so that they are all between -1 and 1 and the biggest 'peak' is either -1 or 1<br> * a = a.-avg(a) * a./= max(abs(max(a)), abs(min(a))) */ public static void normalizeElements(float a[]) { double avg = average(a); for (int i = 0; i < a.length; i++) { a[i] -= avg; } Vecf.scale(1f / (float) Math.max(Math.abs(max(a)), Math.abs(min(a))), a); } }
24.836478
117
0.494429
1fe9b791be9a2b6340be169830f7546ef0c5d4a1
1,189
package com.prowidesoftware.swift.model.mx.dic; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ProtectTransactionType2Code. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="ProtectTransactionType2Code"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="PROT"/&gt; * &lt;enumeration value="COVP"/&gt; * &lt;enumeration value="COVR"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "ProtectTransactionType2Code") @XmlEnum public enum ProtectTransactionType2Code { /** * Reorganisation is a protect transaction type. * */ PROT, /** * Reorganisation is a cover on behalf of another participant transaction type. * */ COVP, /** * Reorganisation is a cover protect transaction type. * */ COVR; public String value() { return name(); } public static ProtectTransactionType2Code fromValue(String v) { return valueOf(v); } }
21.232143
95
0.646762
2ca26d1b19014b7ac9c72d2da0d7d0fee86b3253
1,114
package com.github.drakepork.opme.Utils; import com.google.inject.Inject; import com.github.drakepork.opme.Main; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import java.io.File; import java.io.IOException; public class LangCreator { private Main plugin; @Inject public LangCreator(Main plugin) { this.plugin = plugin; } public void init() { File lang = new File(this.plugin.getDataFolder() + File.separator + "lang" + File.separator + plugin.getConfig().getString("lang-file")); try { FileConfiguration langConf = YamlConfiguration.loadConfiguration(lang); langConf.addDefault("plugin-prefix", "&f[&cOpme&f] "); langConf.addDefault("opme-message", ""); langConf.addDefault("deopme-message", ""); langConf.addDefault("op-message", ""); langConf.addDefault("deop-message", ""); langConf.addDefault("no-perm", "&4Error: &cYou do not have permission to execute this command..."); langConf.options().copyDefaults(true); langConf.save(lang); } catch (IOException e) { e.printStackTrace(); } } }
28.564103
102
0.721724
5f5c64a564e8a721a9b7769c47cac02dc1f55f30
391
package com.baekgol.reactnativealarmmanager.db; import androidx.room.TypeConverter; import java.sql.Time; public class RoomTypeConverter { @TypeConverter public static Time fromTime(Long value){ return value==null ? null : new Time(value); } @TypeConverter public static Long toTime(Time time){ return time==null ? null : time.getTime(); } }
20.578947
52
0.682864
37b87c79deeadedda47649b47a5134dcbb7d89c9
86
package ann; public @interface Ann_1 { N[] value(); public @interface N {} }
12.285714
26
0.604651
247e8e794430b1b6eae2f72dc4afe16f210581b8
100
package com.xatu.ba01; public interface SomeService { void doSome(String name, Integer age); }
16.666667
42
0.74
948c964f7d170b13a72f5965ab75f5bb1cbe084a
759
package org.hisp.dhis.request.orgunit; import java.util.ArrayList; import java.util.List; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import com.fasterxml.jackson.annotation.JsonProperty; @Getter @Setter @Accessors( chain = true ) public class OrgUnitMergeRequest { @JsonProperty private List<String> sources = new ArrayList<>(); @JsonProperty private String target; @JsonProperty private DataMergeStrategy dataValueMergeStrategy; @JsonProperty private DataMergeStrategy dataApprovalMergeStrategy; @JsonProperty private Boolean deleteSources; public OrgUnitMergeRequest addSource( String source ) { this.sources.add( source ); return this; } }
19.973684
57
0.740448
5d87fd45d01f17fdd17017a5d65d41da6ace14ed
1,036
package org.minnie.utility.module.sohu; import java.util.ArrayList; import java.util.List; /** * @author neiplzer@gmail.com * @version 2014-3-11 * 双色球实体类 */ public class DoubleColor implements Comparable { private Integer phase; private List<String> red = new ArrayList<String>(6); private String blue; private Integer year; public Integer getPhase() { return phase; } public void setPhase(Integer phase) { this.phase = phase; } public List<String> getRed() { return red; } public void setRed(List<String> red) { this.red = red; } public String getBlue() { return blue; } public void setBlue(String blue) { this.blue = blue; } public Integer getYear() { return year; } public void setYear(Integer year) { this.year = year; } @Override public int compareTo(Object o) { return this.phase - ((DoubleColor) o).getPhase(); } @Override public String toString() { return "DoubleColor [phase=" + phase + ", red=" + red + ", blue=" + blue + ", year=" + year + "]"; } }
16.983607
67
0.656371
11227e773f8245dfe65e7ecda477b88f4c664433
11,464
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.xml.multiview.ui; import javax.swing.JPanel; import java.awt.*; import java.util.Enumeration; import java.util.Hashtable; import org.openide.nodes.Node; import org.netbeans.modules.xml.multiview.cookies.SectionFocusCookie; /** * This class acts as a container for <code>NodeSectionPanel</code>s. Generally * used with {@link org.netbeans.modules.xml.multiview.ui.SectionPanel}. * * @author mkuchtiak */ public class SectionView extends PanelView implements SectionFocusCookie, ContainerPanel { private JPanel scrollPanel, filler; javax.swing.JScrollPane scrollPane; private Hashtable<Node, NodeSectionPanel> map; private int sectionCount=0; private NodeSectionPanel activePanel; private InnerPanelFactory factory = null; boolean sectionSelected; /** * Constructs a new SectionView. * @param factory the factory for creating inner panels. */ public SectionView(InnerPanelFactory factory) { super(); this.factory=factory; } /** * Constructs a new SectionView. */ public SectionView() { super(); } public void initComponents() { super.initComponents(); map = new Hashtable<>(); setLayout(new java.awt.BorderLayout()); scrollPanel = new JPanel(); scrollPanel.setLayout(new java.awt.GridBagLayout()); scrollPane = new javax.swing.JScrollPane(); scrollPane.setViewportView(scrollPanel); scrollPane.getVerticalScrollBar().setUnitIncrement(15); filler = new JPanel(); // issue 233048: the background color issues with dark metal L&F // filler.setBackground(SectionVisualTheme.getDocumentBackgroundColor()); add(scrollPane, BorderLayout.CENTER); } /** * Opens and activates the given <code>panel</code>. */ public boolean focusSection(NodeSectionPanel panel) { panel.open(); openParents((JPanel)panel); panel.scroll(); setActivePanel(panel); panel.setActive(true); return true; } protected void openSection(Node node){ NodeSectionPanel panel = map.get(node); if (panel != null) { focusSection(panel); } } private void openParents(JPanel panel){ javax.swing.JScrollPane scrollP = null; NodeSectionPanel parentSection=null; java.awt.Container ancestor = panel.getParent(); while (ancestor !=null && scrollP == null){ if (ancestor instanceof javax.swing.JScrollPane){ scrollP = (javax.swing.JScrollPane) ancestor; } if (ancestor instanceof NodeSectionPanel){ parentSection = (NodeSectionPanel) ancestor; parentSection.open(); } ancestor = ancestor.getParent(); } } void mapSection(Node key, NodeSectionPanel panel){ map.put(key,panel); } void deleteSection(Node key){ map.remove(key); } /** * Gets the corresponding <code>NodeSectionPanel</code> for the * given <code>key</code>. * @return the corresponding panel or null. */ public NodeSectionPanel getSection(Node key){ return map.get(key); } /** * Adds a section for this. * @param section the section to be added. * @param open indicates whether given <code>section</code> * should be opened. */ public void addSection(NodeSectionPanel section, boolean open) { addSection(section); if (open) { section.open(); section.scroll(); section.setActive(true); } } /** * Adds a section for this. * @param section the section to be added. */ public void addSection(NodeSectionPanel section) { scrollPanel.remove(filler); java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = sectionCount; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; //gridBagConstraints.insets = new java.awt.Insets(6, 0, 0, 6); scrollPanel.add((JPanel)section,gridBagConstraints); section.setIndex(sectionCount); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = sectionCount+1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weighty = 2.0; //gridBagConstraints.insets = new java.awt.Insets(6, 2, 0, 6); scrollPanel.add(filler,gridBagConstraints); mapSection(section.getNode(), section); sectionCount++; } /** * Removes given <code>node</code> and its corresponding * section. */ public void removeSection(Node node) { NodeSectionPanel section = getSection(node); if (section!=null) { // looking for enclosing container java.awt.Container cont = ((java.awt.Component)section).getParent(); while (cont!=null && !(cont instanceof ContainerPanel)) { cont = cont.getParent(); } if ( cont!= null) { // removing last active component ContainerPanel contPanel = (ContainerPanel)cont; if (section instanceof SectionPanel) { Object key = ((SectionPanel)section).getKey(); if (key!=null && key==getLastActive()) { setLastActive(null); } } // removing section contPanel.removeSection(section); // removing node contPanel.getRoot().getChildren().remove(new Node[]{node}); } } } /** * Removes given <code>panel</code> and moves up remaining panels. */ public void removeSection(NodeSectionPanel panel){ int panelIndex = panel.getIndex(); scrollPanel.remove((JPanel)panel); // the rest components have to be moved up java.awt.Component[] components = scrollPanel.getComponents(); java.util.List<NodeSectionPanel> removedPanels = new java.util.ArrayList<>(); for (int i=0;i<components.length;i++) { if (components[i] instanceof NodeSectionPanel) { NodeSectionPanel pan = (NodeSectionPanel)components[i]; int index = pan.getIndex(); if (index>panelIndex) { scrollPanel.remove((JPanel)pan); pan.setIndex(index-1); removedPanels.add(pan); } } } for (int i=0;i<removedPanels.size();i++) { NodeSectionPanel pan = removedPanels.get(i); java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = pan.getIndex(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; //gridBagConstraints.insets = new java.awt.Insets(6, 0, 0, 6); scrollPanel.add((JPanel)pan,gridBagConstraints); } deleteSection(panel.getNode()); sectionCount--; } /** * Sets given <code>activePanel</code> as the currently active panel. */ public void setActivePanel(NodeSectionPanel activePanel) { if (this.activePanel!=null && this.activePanel!=activePanel) { this.activePanel.setActive(false); } this.activePanel = activePanel; if (activePanel instanceof SectionPanel) { setLastActive(((SectionPanel)activePanel).getKey()); } } public NodeSectionPanel getActivePanel() { return activePanel; } public void selectNode(Node node) { setManagerSelection(new Node[]{node}); } /** * Opens the panels that are associated with the given * <code>nodes</code>. */ public void showSelection(org.openide.nodes.Node[] nodes) { if (sectionSelected) { sectionSelected=false; return; } if (nodes!=null && nodes.length>0) { openSection(nodes[0]); } } void sectionSelected(boolean sectionSelected) { this.sectionSelected=sectionSelected; } protected org.netbeans.modules.xml.multiview.Error validateView() { return null; } /** * @return panel with the given <code>key</code> or null * if no matching panel was found. */ public SectionPanel findSectionPanel(Object key) { Enumeration<Node> en = map.keys(); while (en.hasMoreElements()) { NodeSectionPanel pan = map.get(en.nextElement()); if (pan instanceof SectionPanel) { SectionPanel p = (SectionPanel)pan; if (key==p.getKey()) { return p; } } } return null; } InnerPanelFactory getInnerPanelFactory() { return factory; } public void setInnerPanelFactory(InnerPanelFactory factory) { this.factory=factory; } /** * Opens the panel identified by given <code>key</code>. */ public void openPanel(Object key) { if (key!=null) { SectionPanel panel = findSectionPanel(key); if (panel!=null) { if (panel.getInnerPanel()==null) panel.open(); openParents((JPanel)panel); panel.scroll(); panel.setActive(true); } } } private Object getLastActive() { ToolBarDesignEditor toolBarDesignEditor = getToolBarDesignEditor(); return toolBarDesignEditor == null ? null : toolBarDesignEditor.getLastActive(); } private void setLastActive(Object key) { ToolBarDesignEditor toolBarDesignEditor = getToolBarDesignEditor(); if(toolBarDesignEditor != null) { toolBarDesignEditor.setLastActive(key); } } protected ToolBarDesignEditor getToolBarDesignEditor() { Container parent = getParent(); return parent == null ? null : (ToolBarDesignEditor) parent.getParent(); } }
34.119048
95
0.608252
166f8fa48cb94d27aab31a2ce8d9b0174db44a51
3,319
/* * 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 com.alipay.sofa.registry.server.data.change; import com.alipay.sofa.registry.common.model.dataserver.Datum; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; /** * changed data * * @author qian.lqlq * @version $Id: ChangeData.java, v 0.1 2017-12-08 16:23 qian.lqlq Exp $ */ public class ChangeData implements Delayed { /** data changed */ private Datum datum; /** change time */ private Long gmtCreate; /** timeout */ private long timeout; private DataSourceTypeEnum sourceType; private DataChangeTypeEnum changeType; /** * constructor * @param datum * @param timeout * @param sourceType * @param changeType */ public ChangeData(Datum datum, long timeout, DataSourceTypeEnum sourceType, DataChangeTypeEnum changeType) { this.datum = datum; this.gmtCreate = System.currentTimeMillis(); this.timeout = timeout; this.sourceType = sourceType; this.changeType = changeType; } /** * Getter method for property <tt>datum</tt>. * * @return property value of datum */ public Datum getDatum() { return datum; } /** * Setter method for property <tt>datum</tt>. * * @param datum value to be assigned to property datum */ public void setDatum(Datum datum) { this.datum = datum; } /** * Getter method for property <tt>sourceType</tt>. * * @return property value of sourceType */ public DataSourceTypeEnum getSourceType() { return sourceType; } /** * Getter method for property <tt>changeType</tt>. * * @return property value of changeType */ public DataChangeTypeEnum getChangeType() { return changeType; } @Override public long getDelay(TimeUnit unit) { return unit .convert(gmtCreate + timeout - System.currentTimeMillis(), TimeUnit.MILLISECONDS); } @Override public int compareTo(Delayed o) { if (o == this) { return 0; } if (o instanceof ChangeData) { ChangeData other = (ChangeData) o; if (this.gmtCreate < other.gmtCreate) { return -1; } else if (this.gmtCreate > other.gmtCreate) { return 1; } else { return 0; } } return -1; } }
27.658333
94
0.619162
e677e803792e7307716f73f8c5053fd3b69baa14
597
package de.adorsys.datasafe.rest.impl.security; import lombok.experimental.UtilityClass; @UtilityClass public class SecurityConstants { public static final String AUTH_LOGIN_URL = "/api/authenticate"; public static final String TOKEN_HEADER = "token"; public static final String TOKEN_PREFIX = "Bearer "; public static final String TOKEN_TYPE = "JWT"; public static final String TOKEN_ISSUER = "secure-api"; public static final String TOKEN_AUDIENCE = "secure-app"; public static final String ROLES_NAME = "rol"; public static final String TYPE_NAME = "typ"; }
33.166667
68
0.747069
42a395e310ced68c5ac9ec07ace3c7c2e71e7c6b
5,232
import org.bukkit.Material; import java.util.ArrayList; import java.util.List; import static java.lang.Math.abs; import static java.lang.Math.max; class Wire extends Renderer { static final Material BLUE = Material.BLUE_WOOL; static final Material YELLOW = Material.YELLOW_WOOL; static final Material PINK = Material.PINK_WOOL; static final Material LIGHT_BLUE = Material.LIGHT_BLUE_WOOL; static final Material LIGHT_GREEN = Material.LIME_WOOL; static final Material GREEN = Material.GREEN_WOOL; static final Material RED = Material.RED_WOOL; static final Material ORANGE = Material.ORANGE_WOOL; static final Material PURPLE = Material.PURPLE_WOOL; static final Material BROWN = Material.BROWN_WOOL; private Location from, to; private String id; private Material material; private String deferredMessage = ""; // Locations where repeaters need to be added due to intersecting wires. private List<Location> repeaters = new ArrayList<>(); // Locations which need to be left out due to an intersecting wire. private List<Location> holes = new ArrayList<>(); // Locations where slabs need to be added due to an intersection. private List<Location> slabs = new ArrayList<>(); // Locations which need to be raised due to an intersection. private List<Location> raised = new ArrayList<>(); // Wire connecting from and to, inclusive both. Wire(Location from, Location to, String id, Material material) { super(from, new Coordinates(from.to(to), from.to(to).rotate())); this.from = from; this.to = to; this.id = id; this.material = material; } @Override public void render(RenderTarget target) { if (!deferredMessage.isEmpty()) { target.message(id + deferredMessage); } int dx = to.getX() - from.getX(); int dz = to.getZ() - from.getZ(); if (dx * dz != 0) { target.message(id + ": dx = " + dx + " dz = " + dz); } if (to.getY() != from.getY()) { target.message(id + ": " + from + " -> " + to); } int len = max(abs(dx), abs(dz)); int sx = Integer.compare(dx, 0); int sz = Integer.compare(dz, 0); int strength = 0; for (int i = 0; i <= len; ++i) { Location location = new Location(from.getX() + sx * i, from.getY(), from.getZ() + sz * i); if (holes.contains(location)) { strength = 0; continue; } Location put = location; if (raised.contains(location)) { put = location.above(1); } // When crossing over two wires with one block gap, intermediate slabs block transferring the signal in // the crossed wire. if (slabs.contains(location) && !raised.contains(location)) { target.setTopSlab(put); } else { target.setBlock(put, material); } if (repeaters.contains(location)) { strength = 0; } if (strength == 0) { target.setRepeater(put.above(1), Utils.facingXZ(dx, dz)); strength = 15; } else { target.setWire(put.above(1)); --strength; } } } int getY() { return from.getY(); } // The other wire must pass orthogonal to this one, at the same y coordinate. This function causes holes, repeaters, // slabs and raised blocks adde as necessary to both wires. void intersectWith(Wire other) { if (other.getY() != getY()) { deferredMessage += " intersection: other (" + other.getId() + ") y = " + other.getY() + " this y = " + getY(); } if (from.getX() == to.getX()) { Location intersection = new Location(from.getX(), getY(), other.from.getZ()); raised.add(intersection.shifted(new Vector(0, 0, -1))); raised.add(intersection.shifted(new Vector(0, 0, 0))); raised.add(intersection.shifted(new Vector(0, 0, 1))); slabs.add(intersection.shifted(new Vector(0, 0, -2))); slabs.add(intersection.shifted(new Vector(0, 0, 2))); repeaters.add(intersection); other.holes.add(intersection); other.repeaters.add(intersection.shifted(new Vector(Integer.compare(other.to.getX(), intersection.getX()), 0, 0))); } else { Location intersection = new Location(other.from.getX(), getY(), from.getZ()); raised.add(intersection.shifted(new Vector(-1, 0, 0))); raised.add(intersection.shifted(new Vector(0, 0, 0))); raised.add(intersection.shifted(new Vector(1, 0, 0))); slabs.add(intersection.shifted(new Vector(-2, 0, 0))); slabs.add(intersection.shifted(new Vector(2, 0, 0))); repeaters.add(intersection); other.holes.add(intersection); other.repeaters.add(intersection.shifted(new Vector(0, 0, Integer.compare(other.to.getZ(), intersection.getZ())))); } } String getId() { return id; } }
39.636364
127
0.582951
000a702e37121c8fb6a0c4698db0f9e743bb22c0
22,742
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.resources.commerce.orders; import com.mozu.api.ApiContext; import java.util.List; import java.util.ArrayList; import com.mozu.api.MozuClient; import com.mozu.api.MozuUrl; import com.mozu.api.Headers; import com.mozu.api.security.AuthTicket; import org.apache.commons.lang3.StringUtils; /** <summary> * Use this subresource to retrieve details about items in an active order. * </summary> */ public class OrderItemResource { /// /// <see cref="Mozu.Api.ApiContext"/> /// private ApiContext _apiContext; public OrderItemResource(ApiContext apiContext) { _apiContext = apiContext; } /** * Retrieves the details of a single order item. * <p><pre><code> * OrderItem orderitem = new OrderItem(); * OrderItem orderItem = orderitem.getOrderItem( orderId, orderItemId); * </code></pre></p> * @param orderId Unique identifier of the order item to retrieve. * @param orderItemId Unique identifier of the order item details to retrieve. * @return com.mozu.api.contracts.commerceruntime.orders.OrderItem * @see com.mozu.api.contracts.commerceruntime.orders.OrderItem */ public com.mozu.api.contracts.commerceruntime.orders.OrderItem getOrderItem(String orderId, String orderItemId) throws Exception { return getOrderItem( orderId, orderItemId, null, null); } /** * Retrieves the details of a single order item. * <p><pre><code> * OrderItem orderitem = new OrderItem(); * OrderItem orderItem = orderitem.getOrderItem( orderId, orderItemId, draft, responseFields); * </code></pre></p> * @param draft If true, retrieve the draft version of this order item, which might include uncommitted changes to the order item, the order, or other order components. * @param orderId Unique identifier of the order item to retrieve. * @param orderItemId Unique identifier of the order item details to retrieve. * @param responseFields Use this field to include those fields which are not included by default. * @return com.mozu.api.contracts.commerceruntime.orders.OrderItem * @see com.mozu.api.contracts.commerceruntime.orders.OrderItem */ public com.mozu.api.contracts.commerceruntime.orders.OrderItem getOrderItem(String orderId, String orderItemId, Boolean draft, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.commerceruntime.orders.OrderItem> client = com.mozu.api.clients.commerce.orders.OrderItemClient.getOrderItemClient( orderId, orderItemId, draft, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * Retrieves the details of all items in an order. * <p><pre><code> * OrderItem orderitem = new OrderItem(); * OrderItemCollection orderItemCollection = orderitem.getOrderItems( orderId); * </code></pre></p> * @param orderId Unique identifier of the order items to retrieve. * @return com.mozu.api.contracts.commerceruntime.orders.OrderItemCollection * @see com.mozu.api.contracts.commerceruntime.orders.OrderItemCollection */ public com.mozu.api.contracts.commerceruntime.orders.OrderItemCollection getOrderItems(String orderId) throws Exception { return getOrderItems( orderId, null, null); } /** * Retrieves the details of all items in an order. * <p><pre><code> * OrderItem orderitem = new OrderItem(); * OrderItemCollection orderItemCollection = orderitem.getOrderItems( orderId, draft, responseFields); * </code></pre></p> * @param draft If true, retrieve the draft version of the order's items, which might include uncommitted changes to one or more order items, the order itself, or other order components. * @param orderId Unique identifier of the order items to retrieve. * @param responseFields Use this field to include those fields which are not included by default. * @return com.mozu.api.contracts.commerceruntime.orders.OrderItemCollection * @see com.mozu.api.contracts.commerceruntime.orders.OrderItemCollection */ public com.mozu.api.contracts.commerceruntime.orders.OrderItemCollection getOrderItems(String orderId, Boolean draft, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.commerceruntime.orders.OrderItemCollection> client = com.mozu.api.clients.commerce.orders.OrderItemClient.getOrderItemsClient( orderId, draft, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * Adds a new item to a defined order. * <p><pre><code> * OrderItem orderitem = new OrderItem(); * Order order = orderitem.createOrderItem( orderItem, orderId); * </code></pre></p> * @param orderId Unique identifier of the order for which to add the item. * @param orderItem The properties of the item to create in the existing order. * @return com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.OrderItem */ public com.mozu.api.contracts.commerceruntime.orders.Order createOrderItem(com.mozu.api.contracts.commerceruntime.orders.OrderItem orderItem, String orderId) throws Exception { return createOrderItem( orderItem, orderId, null, null, null, null); } /** * Adds a new item to a defined order. * <p><pre><code> * OrderItem orderitem = new OrderItem(); * Order order = orderitem.createOrderItem( orderItem, orderId, updateMode, version, skipInventoryCheck, responseFields); * </code></pre></p> * @param orderId Unique identifier of the order for which to add the item. * @param responseFields Use this field to include those fields which are not included by default. * @param skipInventoryCheck If true, do not validate the product inventory when adding this item to the order. * @param updateMode Specifies whether to add the item by updating the original order, updating the order in draft mode, or updating the order in draft mode and then committing the changes to the original. Draft mode enables users to make incremental order changes before committing the changes to the original order. Valid values are "ApplyToOriginal," "ApplyToDraft," or "ApplyAndCommit." * @param version System-supplied integer that represents the current version of the order, which prevents users from unintentionally overriding changes to the order. When a user performs an operation for a defined order, the system validates that the version of the updated order matches the version of the order on the server. After the operation completes successfully, the system increments the version number by one. * @param orderItem The properties of the item to create in the existing order. * @return com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.OrderItem */ public com.mozu.api.contracts.commerceruntime.orders.Order createOrderItem(com.mozu.api.contracts.commerceruntime.orders.OrderItem orderItem, String orderId, String updateMode, String version, Boolean skipInventoryCheck, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> client = com.mozu.api.clients.commerce.orders.OrderItemClient.createOrderItemClient( orderItem, orderId, updateMode, version, skipInventoryCheck, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * Update the discount applied to an item in an order. * <p><pre><code> * OrderItem orderitem = new OrderItem(); * Order order = orderitem.updateOrderItemDiscount( discount, orderId, orderItemId, discountId); * </code></pre></p> * @param discountId Unique identifier of the discount. System-supplied and read only. * @param orderId Unique identifier of the order associated with the item discount. * @param orderItemId Unique identifier of the item in the order. * @param discount Properties of the discount to modify for the order item. * @return com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.discounts.AppliedDiscount */ public com.mozu.api.contracts.commerceruntime.orders.Order updateOrderItemDiscount(com.mozu.api.contracts.commerceruntime.discounts.AppliedDiscount discount, String orderId, String orderItemId, Integer discountId) throws Exception { return updateOrderItemDiscount( discount, orderId, orderItemId, discountId, null, null, null); } /** * Update the discount applied to an item in an order. * <p><pre><code> * OrderItem orderitem = new OrderItem(); * Order order = orderitem.updateOrderItemDiscount( discount, orderId, orderItemId, discountId, updateMode, version, responseFields); * </code></pre></p> * @param discountId Unique identifier of the discount. System-supplied and read only. * @param orderId Unique identifier of the order associated with the item discount. * @param orderItemId Unique identifier of the item in the order. * @param responseFields Use this field to include those fields which are not included by default. * @param updateMode Specifies whether to change the item discount by updating the original order, updating the order in draft mode, or updating the order in draft mode and then committing the changes to the original. Draft mode enables users to make incremental order changes before committing the changes to the original order. Valid values are "ApplyToOriginal," "ApplyToDraft," or "ApplyAndCommit." * @param version System-supplied integer that represents the current version of the order, which prevents users from unintentionally overriding changes to the order. When a user performs an operation for a defined order, the system validates that the version of the updated order matches the version of the order on the server. After the operation completes successfully, the system increments the version number by one. * @param discount Properties of the discount to modify for the order item. * @return com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.discounts.AppliedDiscount */ public com.mozu.api.contracts.commerceruntime.orders.Order updateOrderItemDiscount(com.mozu.api.contracts.commerceruntime.discounts.AppliedDiscount discount, String orderId, String orderItemId, Integer discountId, String updateMode, String version, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> client = com.mozu.api.clients.commerce.orders.OrderItemClient.updateOrderItemDiscountClient( discount, orderId, orderItemId, discountId, updateMode, version, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * Updates the item fulfillment information for the order specified in the request. * <p><pre><code> * OrderItem orderitem = new OrderItem(); * Order order = orderitem.updateItemFulfillment( orderItem, orderId, orderItemId); * </code></pre></p> * @param orderId Unique identifier of the order. * @param orderItemId Unique identifier of the item in the order. * @param orderItem Properties of the order item to update for fulfillment. * @return com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.OrderItem */ public com.mozu.api.contracts.commerceruntime.orders.Order updateItemFulfillment(com.mozu.api.contracts.commerceruntime.orders.OrderItem orderItem, String orderId, String orderItemId) throws Exception { return updateItemFulfillment( orderItem, orderId, orderItemId, null, null, null); } /** * Updates the item fulfillment information for the order specified in the request. * <p><pre><code> * OrderItem orderitem = new OrderItem(); * Order order = orderitem.updateItemFulfillment( orderItem, orderId, orderItemId, updateMode, version, responseFields); * </code></pre></p> * @param orderId Unique identifier of the order. * @param orderItemId Unique identifier of the item in the order. * @param responseFields Use this field to include those fields which are not included by default. * @param updateMode Specifies whether to apply the coupon by updating the original order, updating the order in draft mode, or updating the order in draft mode and then commit the changes to the original. Draft mode enables users to make incremental order changes before committing the changes to the original order. Valid values are "ApplyToOriginal," "ApplyToDraft," or "ApplyAndCommit." * @param version System-supplied integer that represents the current version of the order, which prevents users from unintentionally overriding changes to the order. When a user performs an operation for a defined order, the system validates that the version of the updated order matches the version of the order on the server. After the operation completes successfully, the system increments the version number by one. * @param orderItem Properties of the order item to update for fulfillment. * @return com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.OrderItem */ public com.mozu.api.contracts.commerceruntime.orders.Order updateItemFulfillment(com.mozu.api.contracts.commerceruntime.orders.OrderItem orderItem, String orderId, String orderItemId, String updateMode, String version, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> client = com.mozu.api.clients.commerce.orders.OrderItemClient.updateItemFulfillmentClient( orderItem, orderId, orderItemId, updateMode, version, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * Override the price of an individual product on a line item in the specified order. * <p><pre><code> * OrderItem orderitem = new OrderItem(); * Order order = orderitem.updateItemProductPrice( orderId, orderItemId, price); * </code></pre></p> * @param orderId Unique identifier of the order containing the item to price override. * @param orderItemId Unique identifier of the item in the order to price override. * @param price The override price to specify for this item in the specified order. * @return com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.Order */ public com.mozu.api.contracts.commerceruntime.orders.Order updateItemProductPrice(String orderId, String orderItemId, Double price) throws Exception { return updateItemProductPrice( orderId, orderItemId, price, null, null, null); } /** * Override the price of an individual product on a line item in the specified order. * <p><pre><code> * OrderItem orderitem = new OrderItem(); * Order order = orderitem.updateItemProductPrice( orderId, orderItemId, price, updateMode, version, responseFields); * </code></pre></p> * @param orderId Unique identifier of the order containing the item to price override. * @param orderItemId Unique identifier of the item in the order to price override. * @param price The override price to specify for this item in the specified order. * @param responseFields Use this field to include those fields which are not included by default. * @param updateMode Specifies whether to change the product price by updating the original order, updating the order in draft mode, or updating the order in draft mode and then committing the changes to the original. Draft mode enables users to make incremental order changes before committing the changes to the original order. Valid values are "ApplyToOriginal," "ApplyToDraft," or "ApplyAndCommit." * @param version System-supplied integer that represents the current version of the order, which prevents users from unintentionally overriding changes to the order. When a user performs an operation for a defined order, the system validates that the version of the updated order matches the version of the order on the server. After the operation completes successfully, the system increments the version number by one. * @return com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.Order */ public com.mozu.api.contracts.commerceruntime.orders.Order updateItemProductPrice(String orderId, String orderItemId, Double price, String updateMode, String version, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> client = com.mozu.api.clients.commerce.orders.OrderItemClient.updateItemProductPriceClient( orderId, orderItemId, price, updateMode, version, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * Update the quantity of an item in an order. * <p><pre><code> * OrderItem orderitem = new OrderItem(); * Order order = orderitem.updateItemQuantity( orderId, orderItemId, quantity); * </code></pre></p> * @param orderId Unique identifier of the order containing the item to update quantity. * @param orderItemId Unique identifier of the item in the order to update quantity. * @param quantity The quantity of the item in the order to update. * @return com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.Order */ public com.mozu.api.contracts.commerceruntime.orders.Order updateItemQuantity(String orderId, String orderItemId, Integer quantity) throws Exception { return updateItemQuantity( orderId, orderItemId, quantity, null, null, null); } /** * Update the quantity of an item in an order. * <p><pre><code> * OrderItem orderitem = new OrderItem(); * Order order = orderitem.updateItemQuantity( orderId, orderItemId, quantity, updateMode, version, responseFields); * </code></pre></p> * @param orderId Unique identifier of the order containing the item to update quantity. * @param orderItemId Unique identifier of the item in the order to update quantity. * @param quantity The quantity of the item in the order to update. * @param responseFields Use this field to include those fields which are not included by default. * @param updateMode Specifies whether to change the item quantity by updating the original order, updating the order in draft mode, or updating the order in draft mode and then committing the changes to the original. Draft mode enables users to make incremental order changes before committing the changes to the original order. Valid values are "ApplyToOriginal," "ApplyToDraft," or "ApplyAndCommit." * @param version System-supplied integer that represents the current version of the order, which prevents users from unintentionally overriding changes to the order. When a user performs an operation for a defined order, the system validates that the version of the updated order matches the version of the order on the server. After the operation completes successfully, the system increments the version number by one. * @return com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.Order */ public com.mozu.api.contracts.commerceruntime.orders.Order updateItemQuantity(String orderId, String orderItemId, Integer quantity, String updateMode, String version, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> client = com.mozu.api.clients.commerce.orders.OrderItemClient.updateItemQuantityClient( orderId, orderItemId, quantity, updateMode, version, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * Removes a previously added item from a defined order. * <p><pre><code> * OrderItem orderitem = new OrderItem(); * Order order = orderitem.deleteOrderItem( orderId, orderItemId); * </code></pre></p> * @param orderId Unique identifier of the order with the item to remove. * @param orderItemId Unique identifier of the item to remove from the order. * @return com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.Order */ public com.mozu.api.contracts.commerceruntime.orders.Order deleteOrderItem(String orderId, String orderItemId) throws Exception { return deleteOrderItem( orderId, orderItemId, null, null); } /** * Removes a previously added item from a defined order. * <p><pre><code> * OrderItem orderitem = new OrderItem(); * Order order = orderitem.deleteOrderItem( orderId, orderItemId, updateMode, version); * </code></pre></p> * @param orderId Unique identifier of the order with the item to remove. * @param orderItemId Unique identifier of the item to remove from the order. * @param updateMode Specifies whether to remove the item by updating the original order, updating the order in draft mode, or updating the order in draft mode and then committing the changes to the original. Draft mode enables users to make incremental order changes before committing the changes to the original order. Valid values are "ApplyToOriginal," "ApplyToDraft," or "ApplyAndCommit." * @param version System-supplied integer that represents the current version of the order, which prevents users from unintentionally overriding changes to the order. When a user performs an operation for a defined order, the system validates that the version of the updated order matches the version of the order on the server. After the operation completes successfully, the system increments the version number by one. * @return com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.Order */ public com.mozu.api.contracts.commerceruntime.orders.Order deleteOrderItem(String orderId, String orderItemId, String updateMode, String version) throws Exception { MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> client = com.mozu.api.clients.commerce.orders.OrderItemClient.deleteOrderItemClient( orderId, orderItemId, updateMode, version); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } }
62.823204
422
0.773899
e2f7e360b223ad5e8fef2ed7faaa5d40f1968eb0
7,576
package au.edu.unimelb.csse.join; import java.io.IOException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.search.DocIdSetIterator; import au.edu.unimelb.csse.join.AbstractJoin.PostingsAndFreq; public class AbstractJoinTest extends HolisticJoinTestCase { private class AbstractJoinTestStub extends AbstractJoin { public AbstractJoinTestStub(String[] labels) { super(labels, new int[] { -1, 0, 1 }, getDescOp(3)); } public int getCurrentContextPos() { return currentContextPos; } public int getAtomicContextsCount() { return atomicContextsCount; } public PostingsAndFreq[] getPostingsAndFreqs() { return postingsFreqs; } @Override public void setupPerAtomicContext() { // do nothing } @Override public void setupPerDoc() throws IOException { // do nothing } } public void testSetupInitsVariables() throws Exception { AbstractJoinTestStub aj = new AbstractJoinTestStub(new String[] { "AA", "BB", "DD" }); IndexWriter w = setupIndex(); w.addDocument(getDoc("(AA(AA DD)(AA BB)(AA DD))")); w.addDocument(getDoc("(AA(AA BB)(AA BB))")); w.addDocument(getDoc("(AA(AA DD))")); w.addDocument(getDoc("(AA(AA DD)(AA DD)(AA DD))")); w.addDocument(getDoc("(AA(AA JJ)(AA KK)(AA LL))")); IndexReader r = commitIndexAndOpenReader(w); boolean setupSuccess = aj.setup(r); assertTrue(setupSuccess); assertEquals(0, aj.getCurrentContextPos()); assertEquals(1, aj.getAtomicContextsCount()); PostingsAndFreq[] postingsFreqs = aj.getPostingsAndFreqs(); assertEquals(3, postingsFreqs.length); // postingsFreqs should be ordered by doc freq assertEquals("BB", postingsFreqs[0].term.text()); assertEquals("DD", postingsFreqs[1].term.text()); assertEquals("AA", postingsFreqs[2].term.text()); } public void testDocFreqTiePostingsAndFreqSorting() throws Exception { AbstractJoinTestStub aj = new AbstractJoinTestStub(new String[] { "AA", "BB", "DD" }); IndexWriter w = setupIndex(); w.addDocument(getDoc("(AA(AA DD)(AA BB)(AA DD))")); w.addDocument(getDoc("(AA(AA BB)(AA BB))")); w.addDocument(getDoc("(AA(AA DD)(AA DD)(AA DD))")); IndexReader r = commitIndexAndOpenReader(w); boolean setupSuccess = aj.setup(r); assertTrue(setupSuccess); PostingsAndFreq[] postingsFreqs = aj.getPostingsAndFreqs(); assertEquals(3, postingsFreqs.length); assertEquals("BB", postingsFreqs[0].term.text()); assertEquals("DD", postingsFreqs[1].term.text()); assertEquals("AA", postingsFreqs[2].term.text()); aj = new AbstractJoinTestStub(new String[] { "DD", "AA", "BB" }); setupSuccess = aj.setup(r); assertTrue(setupSuccess); postingsFreqs = aj.getPostingsAndFreqs(); assertEquals(3, postingsFreqs.length); assertEquals("DD", postingsFreqs[0].term.text()); assertEquals("BB", postingsFreqs[1].term.text()); assertEquals("AA", postingsFreqs[2].term.text()); } public void testNextDocAtomicContext() throws Exception { AbstractJoin aj = new AbstractJoinTestStub(new String[] { "AA", "BB", "DD" }); IndexWriter w = setupIndex(); w.addDocument(getDoc("(AA(AA DD)(AA DD)(AA DD))")); // doc 0; some terms // in query w.addDocument(getDoc("(AA(AA BB)(AA BB)(AA BB))")); // doc 1; some terms // in query w.addDocument(getDoc("(BB(BB DD)(KK DD)(BB DD))")); // doc 2; some terms // in query w.addDocument(getDoc("(KK(KK PP)(FF JJ))")); // doc 3; no term in query w.addDocument(getDoc("(AA(AA DD)(AA BB)(AA DD))")); // doc 4; all terms // in query w.addDocument(getDoc("(KK(KK QQ)(FF JJ))")); // doc 5; no term in query w.addDocument(getDoc("(AA(AA BB)(AA BB)(AA DD))")); // doc 6; all terms w.addDocument(getDoc("(KK(KK MM)(NN JJ))")); // doc 7; no term in query IndexReader r = commitIndexAndOpenReader(w); boolean setupSuccess = aj.setup(r); assertTrue(setupSuccess); int doc = aj.nextDocAtomicContext(); assertEquals(4, doc); doc = aj.nextDocAtomicContext(); assertEquals(6, doc); doc = aj.nextDocAtomicContext(); assertEquals(DocIdSetIterator.NO_MORE_DOCS, doc); } public void testNextDocAtomicContextWhenFirstDocMatches() throws Exception { AbstractJoin aj = new AbstractJoinTestStub(new String[] { "AA", "BB", "DD" }); IndexWriter w = setupIndex(); w.addDocument(getDoc("(AA(AA DD)(AA BB)(AA DD))")); // all terms IndexReader r = commitIndexAndOpenReader(w); boolean setupSuccess = aj.setup(r); assertTrue(setupSuccess); int doc = aj.nextDocAtomicContext(); assertEquals(0, doc); doc = aj.nextDocAtomicContext(); assertEquals(DocIdSetIterator.NO_MORE_DOCS, doc); } public void testMaxReached() throws Exception { AbstractJoin aj = new AbstractJoinTestStub(new String[] { "AA", "BB", "DD" }); IndexWriter w = setupIndex(); w.addDocument(getDoc("(AA(AA DD)(AA BB)(AA DD))")); // all terms IndexReader r = commitIndexAndOpenReader(w); boolean setupSuccess = aj.setup(r); assertTrue(setupSuccess); int doc = aj.nextDocAtomicContext(); assertEquals(0, doc); doc = aj.nextDocAtomicContext(); assertEquals(DocIdSetIterator.NO_MORE_DOCS, doc); assertTrue(aj.isAtLastContext()); } public void testIteratesOverMultipleAtomicContexts() throws Exception { AbstractJoin aj = new AbstractJoinTestStub(new String[] { "AA", "BB", "DD" }); IndexWriter w = setupIndex(); for (int i = 0; i < 250000; i++) { w.addDocument(getDoc("(AA(BB DD))")); w.addDocument(getDoc("(KK(LL MM)(NN OO)(PP QQ))")); w.addDocument(getDoc("(RR(SS TT)(ZZ(UU VV))(WW YY))")); } IndexReader r = commitIndexAndOpenReader(w); assertTrue(r.getContext().leaves().size() > 1); aj.setup(r); int expectedAtomicContextNum = 0; int doc; for (int i = 0; i < 250000; i++) { doc = aj.nextDocAtomicContext(); if (doc == DocIdSetIterator.NO_MORE_DOCS) { aj.initAtomicContextPositionsFreqs(); i--; expectedAtomicContextNum++; continue; } assertEquals("expected i " + (i + 1), expectedAtomicContextNum, aj.currentContextPos); } doc = aj.nextDocAtomicContext(); assertEquals(DocIdSetIterator.NO_MORE_DOCS, doc); } public void testNextDocSeamlesslyIteratesOverMultipleAtomicContexts() throws Exception { AbstractJoin aj = new AbstractJoinTestStub(new String[] { "AA", "BB", "DD" }); IndexWriter w = setupIndex(); for (int i = 0; i < 250000; i++) { w.addDocument(getDoc("(AA(BB DD))")); w.addDocument(getDoc("(KK(LL MM)(NN OO)(PP QQ))")); w.addDocument(getDoc("(RR(SS TT)(ZZ(UU VV))(WW YY))")); } IndexReader r = commitIndexAndOpenReader(w); assertTrue(r.getContext().leaves().size() > 1); aj.setup(r); assertFalse("Should not be at last context on start", aj.isAtLastContext()); int doc; for (int i = 0; i < 250000; i++) { doc = aj.nextDoc(); assertTrue("Expected 250000 docs with reqd terms but found " + (i + 1), doc != DocIdSetIterator.NO_MORE_DOCS); } doc = aj.nextDocAtomicContext(); assertEquals(DocIdSetIterator.NO_MORE_DOCS, doc); } public void testGetQueryRoot() throws Exception { AbstractJoin ts = new TwigStackJoin(new String[] { "A", "B", "C", "D", "E" }, new int[] { -1, 0, 1, 0, 4 }, getDescOp(5), lrdp); IndexWriter w = setupIndex(); w.addDocument(getDoc("(A(A(E J)(B D))(A(B(C E)(E D)))(A(D(B(A(C J)))(E(D E)))))")); // doc 0 IndexReader r = commitIndexAndOpenReader(w); ts.setup(r); // call to setup or nextDoc is required to find the queryRoot PostingsAndFreq queryRoot = ts.root; assertEquals("A", queryRoot.term.text()); } }
34.126126
113
0.677534
4dd8f43922fbe6fcc84ec8f97c34eb1388b26f56
7,095
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.embedding.engine; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import io.flutter.FlutterInjector; import io.flutter.embedding.engine.dart.DartExecutor.DartEntrypoint; import io.flutter.embedding.engine.loader.FlutterLoader; import java.util.ArrayList; import java.util.List; /** * Represents a collection of {@link io.flutter.embedding.engine.FlutterEngine}s who share resources * to allow them to be created faster and with less memory than calling the {@link * io.flutter.embedding.engine.FlutterEngine}'s constructor multiple times. * * <p>When creating or recreating the first {@link io.flutter.embedding.engine.FlutterEngine} in the * FlutterEngineGroup, the behavior is the same as creating a {@link * io.flutter.embedding.engine.FlutterEngine} via its constructor. When subsequent {@link * io.flutter.embedding.engine.FlutterEngine}s are created, resources from an existing living {@link * io.flutter.embedding.engine.FlutterEngine} is re-used. * * <p>The shared resources are kept until the last surviving {@link * io.flutter.embedding.engine.FlutterEngine} is destroyed. * * <p>Deleting a FlutterEngineGroup doesn't invalidate its existing {@link * io.flutter.embedding.engine.FlutterEngine}s, but it eliminates the possibility to create more * {@link io.flutter.embedding.engine.FlutterEngine}s in that group. */ public class FlutterEngineGroup { /* package */ @VisibleForTesting final List<FlutterEngine> activeEngines = new ArrayList<>(); /** * Create a FlutterEngineGroup whose child engines will share resources. * * <p>Since the FlutterEngineGroup is likely to have a longer lifecycle than any individual * Android component, it's more semantically correct to pass in an application context rather than * the individual Android component's context to minimize the chances of leaks. */ public FlutterEngineGroup(@NonNull Context context) { this(context, null); } /** * Create a FlutterEngineGroup whose child engines will share resources. Use {@code dartVmArgs} to * pass flags to the Dart VM during initialization. * * <p>Since the FlutterEngineGroup is likely to have a longer lifecycle than any individual * Android component, it's more semantically correct to pass in an application context rather than * the individual Android component's context to minimize the chances of leaks. */ public FlutterEngineGroup(@NonNull Context context, @Nullable String[] dartVmArgs) { FlutterLoader loader = FlutterInjector.instance().flutterLoader(); if (!loader.initialized()) { loader.startInitialization(context.getApplicationContext()); loader.ensureInitializationComplete(context.getApplicationContext(), dartVmArgs); } } /** * Creates a {@link io.flutter.embedding.engine.FlutterEngine} in this group and run its {@link * io.flutter.embedding.engine.dart.DartExecutor} with a default entrypoint of the "main" function * in the "lib/main.dart" file. * * <p>If no prior {@link io.flutter.embedding.engine.FlutterEngine} were created in this group, * the initialization cost will be slightly higher than subsequent engines. The very first {@link * io.flutter.embedding.engine.FlutterEngine} created per program, regardless of * FlutterEngineGroup, also incurs the Dart VM creation time. * * <p>Subsequent engine creations will share resources with existing engines. However, if all * existing engines were {@link io.flutter.embedding.engine.FlutterEngine#destroy()}ed, the next * engine created will recreate its dependencies. */ public FlutterEngine createAndRunDefaultEngine(@NonNull Context context) { return createAndRunEngine(context, null); } /** * Creates a {@link io.flutter.embedding.engine.FlutterEngine} in this group and run its {@link * io.flutter.embedding.engine.dart.DartExecutor} with the specified {@link DartEntrypoint}. * * <p>If no prior {@link io.flutter.embedding.engine.FlutterEngine} were created in this group, * the initialization cost will be slightly higher than subsequent engines. The very first {@link * io.flutter.embedding.engine.FlutterEngine} created per program, regardless of * FlutterEngineGroup, also incurs the Dart VM creation time. * * <p>Subsequent engine creations will share resources with existing engines. However, if all * existing engines were {@link io.flutter.embedding.engine.FlutterEngine#destroy()}ed, the next * engine created will recreate its dependencies. */ public FlutterEngine createAndRunEngine( @NonNull Context context, @Nullable DartEntrypoint dartEntrypoint) { return createAndRunEngine(context, dartEntrypoint, null); } /** * Creates a {@link io.flutter.embedding.engine.FlutterEngine} in this group and run its {@link * io.flutter.embedding.engine.dart.DartExecutor} with the specified {@link DartEntrypoint} and * the specified {@code initialRoute}. * * <p>If no prior {@link io.flutter.embedding.engine.FlutterEngine} were created in this group, * the initialization cost will be slightly higher than subsequent engines. The very first {@link * io.flutter.embedding.engine.FlutterEngine} created per program, regardless of * FlutterEngineGroup, also incurs the Dart VM creation time. * * <p>Subsequent engine creations will share resources with existing engines. However, if all * existing engines were {@link io.flutter.embedding.engine.FlutterEngine#destroy()}ed, the next * engine created will recreate its dependencies. */ public FlutterEngine createAndRunEngine( @NonNull Context context, @Nullable DartEntrypoint dartEntrypoint, @Nullable String initialRoute) { FlutterEngine engine = null; if (dartEntrypoint == null) { dartEntrypoint = DartEntrypoint.createDefault(); } if (activeEngines.size() == 0) { engine = createEngine(context); if (initialRoute != null) { engine.getNavigationChannel().setInitialRoute(initialRoute); } engine.getDartExecutor().executeDartEntrypoint(dartEntrypoint); } else { engine = activeEngines.get(0).spawn(context, dartEntrypoint, initialRoute); } activeEngines.add(engine); final FlutterEngine engineToCleanUpOnDestroy = engine; engine.addEngineLifecycleListener( new FlutterEngine.EngineLifecycleListener() { @Override public void onPreEngineRestart() { // No-op. Not interested. } @Override public void onEngineWillDestroy() { activeEngines.remove(engineToCleanUpOnDestroy); } }); return engine; } @VisibleForTesting /* package */ FlutterEngine createEngine(Context context) { return new FlutterEngine(context); } }
44.34375
100
0.742213
93b564776d5f554e6f0fb4dc9f51534fef0d6e00
1,433
package com.example; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; /** * * session * 作用 * 解决相同用户发送不同请求时的数据共享问题 * 特点: * 1. 服务器端存储共享数据的技术 * 2. session需要依赖cookie技术 * 3. 每个用户对应一个独立的session对象 * 4. 每个session对象的默认有效时长是30min * 5. 每次关闭浏览器的时候,重新请求都会开启一个session对象,因为返回的JSESSIONID保存在浏览器的内存中 * 是临时cookie,所以关闭之后自然消失 */ public class SessionServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置请求响应的编码格式 request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("gbk"); System.out.println("接受到请求 get"); // 获取session对象 HttpSession session = request.getSession(); // 设置session的有效时长,单位是s session.setMaxInactiveInterval(5); // 拿到JSESSIONID System.out.println(session.getId()); // 向session中设置参数 session.invalidate(); // 设置session强制失效 session.setAttribute("111", "zhangsan"); response.getWriter().write("学习session"); } }
29.244898
122
0.708304
91942f1cb5c3f4ac853a92e2fde728ab7eb40d61
2,683
package jkind.smv.visitors; import static java.util.stream.Collectors.toList; import java.util.List; import java.util.function.Function; import jkind.smv.SMVArrayAccessExpr; import jkind.smv.SMVArrayExpr; import jkind.smv.SMVArrayUpdateExpr; import jkind.smv.SMVBinaryExpr; import jkind.smv.SMVBoolExpr; import jkind.smv.SMVCaseExpr; import jkind.smv.SMVCastExpr; import jkind.smv.SMVExpr; import jkind.smv.SMVFunctionCallExpr; import jkind.smv.SMVIdExpr; import jkind.smv.SMVIntExpr; import jkind.smv.SMVModuleCallExpr; import jkind.smv.SMVRealExpr; import jkind.smv.SMVUnaryExpr; public class SMVExprMapVisitor implements SMVExprVisitor<SMVExpr> { @Override public SMVExpr visit(SMVArrayAccessExpr e) { return new SMVArrayAccessExpr(e.array.accept(this), e.index.accept(this)); } @Override public SMVExpr visit(SMVArrayExpr e) { return new SMVArrayExpr(visitSMVExprs(e.elements)); } @Override public SMVExpr visit(SMVArrayUpdateExpr e) { return new SMVArrayUpdateExpr(e.array.accept(this), e.index.accept(this), e.value.accept(this)); } @Override public SMVExpr visit(SMVBinaryExpr e) { SMVExpr left = e.left.accept(this); SMVExpr right = e.right.accept(this); if (e.left == left && e.right == right) { return e; } return new SMVBinaryExpr(left, e.op, right); } @Override public SMVExpr visit(SMVBoolExpr e) { return e; } @Override public SMVExpr visit(SMVCastExpr e) { return new SMVCastExpr(e.type, e.expr.accept(this)); } @Override public SMVExpr visit(SMVFunctionCallExpr e) { return new SMVFunctionCallExpr(e.function, visitSMVExprs(e.args)); } @Override public SMVExpr visit(SMVModuleCallExpr e) { return new SMVModuleCallExpr(e.module, visitSMVExprs(e.args)); } @Override public SMVExpr visit(SMVIdExpr e) { return e; } @Override public SMVExpr visit(SMVCaseExpr e) { SMVExpr cond = e.cond.accept(this); SMVExpr thenExpr = e.thenExpr.accept(this); SMVExpr elseExpr = e.elseExpr.accept(this); if (e.cond == cond && e.thenExpr == thenExpr && e.elseExpr == elseExpr) { return e; } return new SMVCaseExpr(e.cond, e.elseExpr, e.thenExpr); } @Override public SMVExpr visit(SMVIntExpr e) { return e; } @Override public SMVExpr visit(SMVRealExpr e) { return e; } @Override public SMVExpr visit(SMVUnaryExpr e) { SMVExpr expr = e.expr.accept(this); if (e.expr == expr) { return e; } return new SMVUnaryExpr(e.op, expr); } protected List<SMVExpr> visitSMVExprs(List<? extends SMVExpr> es) { return map(e -> e.accept(this), es); } protected <A, B> List<B> map(Function<? super A, ? extends B> f, List<A> xs) { return xs.stream().map(f).collect(toList()); } }
23.535088
98
0.728662
c371f48ad1a96f4aa64a00a7abbca81e828ecf8a
2,465
package com.example.zoomwroom; import com.example.zoomwroom.Entities.ContactInformation; import com.example.zoomwroom.Entities.User; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; public class ContactinformationUnitTest { public ContactInformation MockContactinformation(){ return new ContactInformation("7808852269","test@gmail.ca"); } @Test void testsetphonenumber(){ ContactInformation contactInformation = MockContactinformation(); assertEquals("7808852269",contactInformation.getPhoneNumber()); assertNotEquals("7808852268",contactInformation.getPhoneNumber()); contactInformation.setPhoneNumber("7808852268"); assertEquals("7808852268",contactInformation.getPhoneNumber()); assertNotEquals("7808852269",contactInformation.getPhoneNumber()); } @Test void testsetemail(){ ContactInformation contactInformation = MockContactinformation(); assertEquals("test@gmail.ca",contactInformation.getEmail()); assertNotEquals("test@gmail1.ca",contactInformation.getEmail()); contactInformation.setEmail("test1@gmail.ca"); assertEquals("test1@gmail.ca",contactInformation.getEmail()); assertNotEquals("test1@gmail1.ca",contactInformation.getEmail()); } @Test void testgetphonenumber(){ ContactInformation contactInformation = MockContactinformation(); assertEquals("7808852269",contactInformation.getPhoneNumber()); assertNotEquals("7808852268",contactInformation.getPhoneNumber()); contactInformation.setPhoneNumber("7808852268"); assertEquals("7808852268",contactInformation.getPhoneNumber()); assertNotEquals("7808852269",contactInformation.getPhoneNumber()); } @Test void testgetemail(){ ContactInformation contactInformation = MockContactinformation(); assertEquals("test@gmail.ca",contactInformation.getEmail()); assertNotEquals("test@gmail1.ca",contactInformation.getEmail()); contactInformation.setEmail("test1@gmail.ca"); assertEquals("test1@gmail.ca",contactInformation.getEmail()); assertNotEquals("test1@gmail1.ca",contactInformation.getEmail()); } }
34.236111
74
0.738742
9b3c8c6043d9d987c0f28c6331945abdc6e8cbd6
482
package concurrent.phase2; public class UseGate extends Thread{ private final Gate gate; private final String name; private final String address; public UseGate(String name, String address, Gate gate) { this.name = name; this.address = address; this.gate = gate; } @Override public void run() { System.out.println(name + " begin"); while (true) { this.gate.pass(name, address); } } }
19.28
60
0.591286
13095ce0f5f871fc0cd099cf9d577de466150af3
552
package io.virtdata.docinfo; import io.virtdata.annotations.Service; import io.virtdata.docsys.api.Docs; import io.virtdata.docsys.api.DocsInfo; import io.virtdata.docsys.api.DocsysDynamicManifest; @Service(DocsysDynamicManifest.class) public class VirtdataMarkdownManifest implements DocsysDynamicManifest { public DocsInfo getDocs() { return new Docs().namespace("virtdata-docs").addFirstFoundPath( "virtdata-userlibs/src/main/resources/docs-for-virtdata/", "docs-for-virtdata/").asDocsInfo(); } }
30.666667
74
0.740942
471b966d5eabe2c4432286b4fe5f0619f9c54b40
743
package com.softicar.platform.db.sql.type; import com.softicar.platform.db.core.DbResultSet; import com.softicar.platform.db.sql.utils.SqlComparisons; /** * Implementation of {@link ISqlValueType} for enumerations. * * @author Oliver Richers */ final class SqlEnumValueType<E extends Enum<E>> extends PrimitiveSqlValueType<E> { private final Class<E> enumClass; public SqlEnumValueType(Class<E> enumClass) { this.enumClass = enumClass; } @Override public E getValue(DbResultSet resultSet, int index) { return resultSet.getEnum(enumClass, index); } @Override public Class<E> getValueClass() { return enumClass; } @Override public int compare(E left, E right) { return SqlComparisons.compare(left, right); } }
19.552632
82
0.74428
b097c97f113c7ad5bc59695aade595f07308a1d0
250
package com.intel.fib; public class FibLib { public static long fibJ(long n) { if( n==0 ) return 0; if( n==1 ) return 1; return fibJ(n-1) + fibJ(n-2); } static { System.loadLibrary("Fib"); } public static native long fibN(long n); }
15.625
40
0.628
ae3dd30ac17466ff319435b3efe6f6871a461d8e
736
package cn.huanzi.qch.springboottimer; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableScheduling; @EnableScheduling //启用定时器 @SpringBootApplication public class SpringbootTimerApplication { public static void main(String[] args) { SpringApplication.run(SpringbootTimerApplication.class, args); } /** * 启动成功 */ @Bean public ApplicationRunner applicationRunner() { return applicationArguments -> { System.out.println("启动成功!"); }; } }
27.259259
70
0.744565
79b4e088b840642276850894b013ee77d9006e57
917
package com.example.android.viewpager; public class loc { private String address; private String name; private int imgid; private String phone; private String disctription; public loc(String address, String name, String phone, int imgid, String disctription) { this.address = address; this.name = name; this.imgid = imgid; this.phone = phone; this.disctription = disctription; } public loc(String address, String name, String phone) { this.address = address; this.name = name; this.phone = phone; } public String getName() { return name; } public String getAddress() { return address; } public String getPhone() { return phone; } public int getImgid() { return imgid; } public String getDisctription() { return disctription; } }
20.840909
91
0.601963
9612dfd688c1f9bc5ac5b79d90a53ffc98c5aab9
1,146
/* * Copyright (c) 1998-2020 John Caron and University Corporation for Atmospheric Research/Unidata * See LICENSE for license information. */ package ucar.nc2.internal.util.xml; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Formatter; import org.junit.Test; /** Test {@link ucar.nc2.internal.util.xml.RuntimeConfigParser} */ public class TestRuntimeConfigParser { private final String config = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<runtimeConfig>\n" + " <ioServiceProvider class='edu.univ.ny.stuff.FooFiles'/>\n" + " <coordSystemFactory convention='foo' class='test.Foo'/>\n" + " <coordTransBuilder name='atmos_ln_sigma_coordinates' type='vertical' class='my.stuff.atmosSigmaLog'/>\n" + " <typedDatasetFactory datatype='Point' class='gov.noaa.obscure.file.Flabulate'/>\n" + "</runtimeConfig>"; @Test public void testRead() throws IOException { Formatter errlog = new Formatter(); ByteArrayInputStream stringIS = new ByteArrayInputStream(config.getBytes()); RuntimeConfigParser.read(stringIS, errlog); System.out.printf("%s%n", errlog); } }
38.2
115
0.719895
c0a6e0f4eed35a48bdae5b74b8aba6d04019ec2f
844
package org.naddeo.graphql.types; import com.google.common.collect.ImmutableSet; import lombok.Builder; import lombok.Data; import lombok.Singular; import org.naddeo.graphql.types.container.VariableArgumentContainer; import java.util.stream.Stream; @Data @Builder public class VariableArguments implements VariableArgumentContainer { public static final VariableArguments EMPTY_VARIABLE_ARGUMENTS = new VariableArguments(null); @Singular private final ImmutableSet<VariableArgument> variableArguments; public VariableArguments(ImmutableSet<VariableArgument> variableArguments) { this.variableArguments = variableArguments == null ? ImmutableSet.of() : variableArguments; } @Override public Stream<VariableArgument> variableArgumentStream() { return this.variableArguments.stream(); } }
29.103448
99
0.785545
d6a23d3a1d7531345b66fff7eb68d2598ce372a9
1,018
import consoleio.C; /** * Copyright (c) 2017 Arjun Nair */ /** * Tree node for wait statement. * @author Arjun Nair */ public class ASTWaitStatement extends SimpleNode { public ASTWaitStatement(int id) { super(id); } public ASTWaitStatement(ParfA p, int id) { super(p, id); } public void interpret() { try { jjtGetChild(0).interpret(); Thread.sleep(1000 * (int) ((Double) ParfANode.stack[ParfANode.p--]).doubleValue()); } catch(ClassCastException e) { C.io.println("Runtime error at line: " + jjtGetLastToken().endLine + ", column: " + jjtGetLastToken().endColumn + ", wait time must be a numeric expression."); throw new IllegalStateException(); } catch(InterruptedException e) { C.io.println("A fatal exception occurred when processing line: " + jjtGetLastToken().endLine + ", column: " + jjtGetLastToken().endColumn + ", try running the program again."); throw new IllegalStateException(); } } }
24.829268
180
0.63556
7bae28294393d439cd6ebecffc993c1df275054c
1,280
package servlet; import bean.Order; import bean.OrderItem; import bean.User; import dao.OrderDao; import dao.OrderItemDao; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * @Author : garyhu * @Since : 2017/10/19 * @Decription : */ @WebServlet(name = "CreateOrderServlet") public class CreateOrderServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { User u = (User) req.getSession().getAttribute("user"); if(u==null){ resp.sendRedirect("/login.jsp"); return; } Order o = new Order(); o.setUser(u); new OrderDao().insert(o); List<OrderItem> items = (List<OrderItem>) req.getSession().getAttribute("items"); for(OrderItem item : items){ item.setOrder(o); new OrderItemDao().insert(item); } items.clear(); resp.setContentType("text/html; charset=UTF-8"); resp.getWriter().println("订单创建成功"); } }
26.122449
115
0.667969
1793481c5aebf411a7d38afe30ca387856682e71
1,938
/** Copyright 2021 DDRTools Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * */ package com.mx.ddrtools.components.datepicker; import android.widget.NumberPicker; import java.text.DecimalFormatSymbols; import java.util.Locale; public class TwoDigitFormatter implements NumberPicker.Formatter { final StringBuilder mBuilder = new StringBuilder(); char mZeroDigit; java.util.Formatter mFmt; final Object[] mArgs = new Object[1]; public TwoDigitFormatter() { final Locale locale = Locale.getDefault(); init(locale); } private void init(Locale locale) { mFmt = createFormatter(locale); mZeroDigit = getZeroDigit(locale); } public String format(int value) { final Locale currentLocale = Locale.getDefault(); if (mZeroDigit != getZeroDigit(currentLocale)) { init(currentLocale); } mArgs[0] = value; mBuilder.delete(0, mBuilder.length()); mFmt.format("%02d", mArgs); return mFmt.toString(); } private static char getZeroDigit(Locale locale) { // The original TwoDigitFormatter directly referenced LocaleData's value. Instead, // we need to use the public DecimalFormatSymbols API. return DecimalFormatSymbols.getInstance(locale).getZeroDigit(); } private java.util.Formatter createFormatter(Locale locale) { return new java.util.Formatter(mBuilder, locale); } }
31.258065
90
0.704334
a36a3a28e58651d34f3eadc2ae4ce746e0ac1bc5
1,256
/*####################################################### * * Maintained by Gregor Santner, 2017- * https://gsantner.net/ * * License: Apache 2.0 * https://github.com/gsantner/opoc/#licensing * https://www.apache.org/licenses/LICENSE-2.0 * #########################################################*/ package net.gsantner.opoc.util; import java.util.regex.Pattern; @SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue", "SpellCheckingInspection", "deprecation"}) public class GeneralUtils { public static String toTitleCase(final String string) { return toTitleCase(string, Pattern.compile("\\s")); } public static String toTitleCase(final String string, final Pattern separator) { if (string == null) return null; final StringBuilder result = new StringBuilder(); boolean nextTitleCase = true; for (char c : string.toCharArray()) { if (separator.matcher(String.valueOf(c)).matches()) { nextTitleCase = true; } else if (nextTitleCase) { c = Character.toTitleCase(c); nextTitleCase = false; } result.append(c); } return result.toString(); } }
29.904762
109
0.557325
8389e1ef36b6cf02819e01e858472b4e745f9881
1,506
package uk.gov.dhsc.htbhf.claimant.service; import lombok.Builder; import lombok.Data; import uk.gov.dhsc.htbhf.claimant.entitlement.VoucherEntitlement; import uk.gov.dhsc.htbhf.claimant.entity.Claim; import uk.gov.dhsc.htbhf.claimant.model.VerificationResult; import java.util.Optional; @Data @Builder public class ClaimResult { private Claim claim; private Optional<VoucherEntitlement> voucherEntitlement; private VerificationResult verificationResult; public static ClaimResult withNoEntitlement(Claim claim) { return ClaimResult.builder() .claim(claim) .voucherEntitlement(Optional.empty()) .build(); } public static ClaimResult withNoEntitlement(Claim claim, VerificationResult verificationResult) { return ClaimResult.builder() .claim(claim) .voucherEntitlement(Optional.empty()) .verificationResult(verificationResult) .build(); } public static ClaimResult withEntitlement(Claim claim, VoucherEntitlement voucherEntitlement, VerificationResult verificationResult) { return ClaimResult.builder() .claim(claim) .voucherEntitlement(Optional.of(voucherEntitlement)) .verificationResult(verificationResult) .build(); } }
33.466667
88
0.622178
780c8c48f552c0095e4d585cea5054ab58907733
7,798
package me.aki.tactical.dex.textifier; import me.aki.tactical.core.Method; import me.aki.tactical.core.textify.BodyTextifier; import me.aki.tactical.core.textify.Printer; import me.aki.tactical.core.textify.TextUtil; import me.aki.tactical.core.textify.TypeTextifier; import me.aki.tactical.core.type.Type; import me.aki.tactical.dex.DexBody; import me.aki.tactical.dex.Register; import me.aki.tactical.dex.TryCatchBlock; import me.aki.tactical.dex.insn.BranchInstruction; import me.aki.tactical.dex.insn.Instruction; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class DexBodyTextifier implements BodyTextifier { @Override public void textifyParameters(Printer printer, Method method) { int parameterIndex = 0; int parameterCount = method.getParameterTypes().size(); Iterator<Type> paramTypeIterator = method.getParameterTypes().iterator(); while (paramTypeIterator.hasNext()) { TypeTextifier.getInstance().textify(printer, paramTypeIterator.next()); printer.addText(" "); printer.addLiteral(getParameterRegisterName(parameterIndex++, parameterCount)); if (paramTypeIterator.hasNext()) { printer.addText(", "); } } } private String getParameterRegisterName(int parameter, int parameterCount) { return "param" + TextUtil.paddedNumber(parameter, parameterCount); } private Map<Register, String> buildRegisterMap(DexBody dexBody) { Map<Register, String> nameMap = new HashMap<>(); nameThisRegister(dexBody, nameMap); nameParameterRegisters(dexBody, nameMap); nameRemainingRegisters(dexBody, nameMap); return nameMap; } private void nameThisRegister(DexBody dexBody, Map<Register, String> nameMap) { dexBody.getThisRegister().ifPresent(thisRegister -> nameMap.put(thisRegister, "this")); } private void nameParameterRegisters(DexBody dexBody, Map<Register, String> nameMap) { int parameterIndex = 0; int parameterCount = dexBody.getParameterRegisters().size(); for (Register paramRegister : dexBody.getParameterRegisters()) { String registerName = getParameterRegisterName(parameterIndex++, parameterCount); nameMap.put(paramRegister, registerName); } } private void nameRemainingRegisters(DexBody dexBody, Map<Register, String> nameMap) { Set<Register> unnamedRegisters = new HashSet<>(dexBody.getRegisters()); unnamedRegisters.removeAll(nameMap.keySet()); int registerIndex = 0; for (Register unnamedRegister : unnamedRegisters) { String registerName = "register" + TextUtil.paddedNumber(registerIndex++, unnamedRegisters.size()); nameMap.put(unnamedRegister, registerName); } } private Map<Instruction, String> buildLabelMap(DexBody body) { Set<Instruction> referencedInsns = getReferencedInstructions(body); Map<Instruction, String> labels = new HashMap<>(); int labelIndex = 0; for (Instruction instruction : body.getInstructions()) { if (referencedInsns.contains(instruction)) { String labelName = "label" + TextUtil.paddedNumber(labelIndex++, referencedInsns.size()); labels.put(instruction, labelName); } } return labels; } private Set<Instruction> getReferencedInstructions(DexBody body) { Stream<Instruction> insnsReferencedByBranchInsn = body.getInstructions().stream() .flatMap(insn -> insn instanceof BranchInstruction ? Stream.of((BranchInstruction) insn) : Stream.of()) .flatMap(branchInsn -> branchInsn.getBranchTargets().stream()); Stream<Instruction> insnsReferencedByTryCatchBlocks = body.getTryCatchBlocks().stream() .flatMap(block -> Stream.concat( Stream.of(block.getStart(), block.getEnd()), block.getHandlers().stream().map(TryCatchBlock.Handler::getHandler) )); return Stream.concat(insnsReferencedByBranchInsn, insnsReferencedByTryCatchBlocks).collect(Collectors.toSet()); } @Override public void textify(Printer printer, Method value) { DexBody body = (DexBody) value.getBody().get(); TextifyCtx ctx = new TextifyCtx(buildRegisterMap(body), buildLabelMap(body)); textifyRegisters(printer, ctx, body); textifyInstructions(printer, ctx, body); textifyTryCatchBlocks(printer, ctx, body); } private void textifyRegisters(Printer printer, TextifyCtx ctx, DexBody body) { Set<Register> syntheticRegisters = new HashSet<>(); body.getThisRegister().ifPresent(syntheticRegisters::add); syntheticRegisters.addAll(body.getParameterRegisters()); List<Register> unnamedRegisters = body.getRegisters().stream() .filter(register -> !syntheticRegisters.contains(register)) .collect(Collectors.toList()); for (Register register : unnamedRegisters) { printer.addText("register "); if (register.getType() == null) { // Registers should always have a type. It's only absent during conversions from other intermediations. printer.addText("<null>"); } else { TypeTextifier.getInstance().textify(printer, register.getType()); } printer.addText(" "); printer.addLiteral(ctx.getRegisterName(register)); printer.addText(";"); printer.newLine(); } if (!unnamedRegisters.isEmpty()) { printer.newLine(); } } private void textifyInstructions(Printer printer, TextifyCtx ctx, DexBody body) { for (Instruction instruction : body.getInstructions()) { ctx.getLabelOpt(instruction).ifPresent(label -> { printer.decreaseIndent(); printer.addLiteral(label); printer.addText(":"); printer.newLine(); printer.increaseIndent(); }); InstructionTextifier.getInstance().textify(printer, ctx, instruction); printer.newLine(); } } private void textifyTryCatchBlocks(Printer printer, TextifyCtx ctx, DexBody body) { for (TryCatchBlock tryCatchBlock : body.getTryCatchBlocks()) { printer.addText("try "); printer.addLiteral(ctx.getLabel(tryCatchBlock.getStart())); printer.addText(" -> "); printer.addLiteral(ctx.getLabel(tryCatchBlock.getEnd())); printer.addText(" catch {"); if (tryCatchBlock.getHandlers().size() == 1) { printer.addText(" "); printHandler(printer, ctx, tryCatchBlock.getHandlers().get(0)); printer.addText(" "); } else { printer.newLine(); for (TryCatchBlock.Handler handler : tryCatchBlock.getHandlers()) { printHandler(printer, ctx, handler); printer.newLine(); } } printer.addText("}"); printer.newLine(); } } private void printHandler(Printer printer, TextifyCtx ctx, TryCatchBlock.Handler handler) { handler.getException().ifPresentOrElse(exception -> { printer.addText("case "); printer.addPath(exception); printer.addText(": "); }, () -> { printer.addText("default: "); }); printer.addLiteral(ctx.getLabel(handler.getHandler())); printer.addText(";"); } }
39.583756
119
0.633111
59fdc6f222f104754c5e850f1943b05531e97df9
5,994
package test.extract; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import code.ponfee.commons.extract.DataExtractor; import code.ponfee.commons.extract.DataExtractorBuilder; /** * 性能:Path > File > Input * @author Ponfee */ public class ExcelExtractorTest { @Test public void testXLS1() throws FileNotFoundException, IOException { DataExtractor et = DataExtractorBuilder.newBuilder("e:\\writeTest2.xls") .streaming(true) .headers(new String[] { "a", "b", "c", "d", "e", "f" }).build(); et.extract((n, d) -> { System.out.println(Arrays.toString((String[])d)); }); } @Test public void testXLS2() throws FileNotFoundException, IOException { DataExtractor et = DataExtractorBuilder.newBuilder("e:\\writeTest2.xls") .streaming(false) .headers(new String[] { "a", "b", "c", "d", "e", "f" }).build(); et.extract((n, d) -> { System.out.println(Arrays.toString((String[])d)); }); } @Test public void testXLSX1() throws FileNotFoundException, IOException { DataExtractor et = DataExtractorBuilder.newBuilder("e:\\mergeTest.xlsx") .streaming(false) .headers(new String[] { "a", "b", "c", "d", "e", "f" }).build(); et.extract((n, d) -> { System.out.println(Arrays.toString((String[])d)); }); } @Test public void testXLSX2() throws FileNotFoundException, IOException { DataExtractor et = DataExtractorBuilder.newBuilder("e:\\mergeTest.xlsx") .streaming(true) .headers(new String[] { "a", "b", "c", "d", "e", "f" }).build(); et.extract((n, d) -> { System.out.println(Arrays.toString((String[])d)); }); } @Test public void testFile() throws FileNotFoundException, IOException { DataExtractor et = DataExtractorBuilder.newBuilder(new File("D:\\test\\test_excel_14.xlsx")) /*.headers(new String[] { "a", "b", "c", "d", "e" })*/.build(); et.extract((n, d) -> { System.out.println(Arrays.toString((String[])d)); }); } @Test public void testInput() throws FileNotFoundException, IOException { DataExtractor et = DataExtractorBuilder.newBuilder(new FileInputStream("D:\\test\\test_excel_14.xlsx"), "test_excel_16.xlsx", null) .headers(new String[] { "a", "b", "c", "d", "e" }).build(); et.extract((n, d) -> { if (n == 0) { System.out.println(Arrays.toString((String[])d)); } if (n == 1) { System.out.println(Arrays.toString((String[])d)); } System.out.println(Arrays.toString((String[])d)); }); } @Test public void test1() throws FileNotFoundException, IOException { DataExtractor et = DataExtractorBuilder.newBuilder("e:\\data_expert_temp.xls") .headers(new String[] { "a", "b", "c", "d", "e" }).build(); et.extract((n, d) -> { System.out.println(Arrays.toString((String[])d)); }); } @Test public void test2() throws FileNotFoundException, IOException { DataExtractor et = DataExtractorBuilder.newBuilder("E:\\test.xlsx") .headers(new String[] { "a", "b", "c", "d", "e" }).build(); et.extract((n, d) -> { System.out.println(String.join("|",(String[])d)); }); } @Test public void test3() throws FileNotFoundException, IOException { DataExtractor et = DataExtractorBuilder.newBuilder("src/test/java/test/extract/advices_export.xls") .headers(new String[] { "a", "b", "c", "d"}).build(); et.extract((n, d) -> { System.out.println(String.join("|",(String[])d)); }); } @Test public void testCsvPath() throws FileNotFoundException, IOException { DataExtractor et = DataExtractorBuilder.newBuilder("E:\\test.csv") .headers(new String[] { "a", "b", "c", "d", "e" }).build(); et.extract((n, d) -> { if (n < 10) System.out.println(Arrays.toString((String[])d)); }); } @Test public void testCsv1() throws FileNotFoundException, IOException { DataExtractor et = DataExtractorBuilder.newBuilder("E:\\test.csv") .headers(new String[] { "a", "b", "c", "d", "e" }).build(); et.extract((n, d) -> { System.out.println(Arrays.toString((String[])d)); }); } @Test public void testCsv2() throws FileNotFoundException, IOException { DataExtractor et = DataExtractorBuilder.newBuilder("E:\\test.csv") .headers(new String[] { "a", "b", "c", "d", "e" }).build(); et.extract(1).forEach(x -> { System.out.println(Arrays.toString((String[])x)); }); } // ------------------------------------------------------ @Test public void test6() throws FileNotFoundException, IOException { //test("E:\\test20.xlsx", false); // 9.1 s //test("E:\\test100.xlsx", true); // 7.8 //test("E:\\writeTest.xls", false); // 2.6 test("E:\\writeTest.xls", true); // 2.0 } private void test(String filename, boolean streaming) throws FileNotFoundException, IOException { DataExtractor et = DataExtractorBuilder.newBuilder(filename) .streaming(streaming).headers(new String[] { "a", "b", "c", "d", "e" }).build(); AtomicInteger count = new AtomicInteger(); et.extract((n, d) -> { if (n < 10) { System.out.println(Arrays.toString((String[])d)); } count.incrementAndGet(); }); System.out.println(count.get()); } }
36.773006
139
0.556056
4b9523125c49b2bba177de123f97c3a0cb11d664
3,108
/* * Copyright (C) 2021-2021 Huawei Technologies Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.huawei.flowcontrol.console.util; /** * 枚举类定义常量 * * @author XiaoLong Wang * @since 2020-12-21 */ public enum DataType { /** * 流控规则 */ FLOW("/flow"), /** * redis存储流控规则前缀 */ FLOW_RULE_KEY("sentinel_flow_rule_"), /** * 热点规则 */ PARAMFLOW("/paramFlow"), /** * redis存储热点规则前缀 */ PARAMFLOW_RULE_KEY("sentinel_paramFlow_rule_"), /** * 降级规则 */ DEGRADE("/degrade"), /** * redis存储降级规则前缀 */ DEGRADE_RULE_KEY("sentinel_degrade_rule_"), /** * 授权规则 */ AUTHORITY("/authority"), /** * redis存储授权规则前缀 */ AUTHORITY_RULE_KEY("sentinel_authority_rule_"), /** * 系统规则 */ SYSTEM("/system"), /** * redis存储系统规则前缀 */ SYSTEM_RULE_KEY("sentinel_system_rule_"), /** * zk保存前缀 */ RULE_ROOT_PATH("/sentinel_rule_config"), /** * redis存储应用名 */ APPNAMES("appnames"), /** * 心跳数据 */ HEARTBEAT_DATA("heartbeat"), /** * 监控数据存储redis后缀 */ REDISMETRICE("metric"), /** * CAS加载顺序 */ ORDER_ONE("1"), /** * CAS加载顺序 */ ORDER_TWO("2"), /** * swagger 在线接口文档扫描路径 */ SWAGGER_SCAN_BASE_PACKAGE("com.huawei.flowcontrol.controller"), /** * 流控规则controllerWrapper后缀 */ FLOW_RULE_SUFFIX("-flowRule"), /** * 降级规则controllerWrapper后缀 */ DEGRADE_RULE_SUFFIX("-degradeRule"), /** * 系统规则controllerWrapper后缀 */ SYSTEM_RULE_SUFFIX("-systemRule"), /** * 热点参数规则controllerWrapper后缀 */ PARAMFLOW_RULE_SUFFIX("-paramFlowRule"), /** * 操作成功 */ OPERATION_SUCCESS("SUCCESS"), /** * 操作失败 */ OPERATION_FAIL("FAIL"), /** * cas/mo存储session name */ CONST_CAS_ASSERTION("_const_cas_assertion_"), /** * 连接符 */ SEPARATOR_HYPHEN("-"), /** * 下划线 */ SEPARATOR_UNDERLINE("_"), /** * 分隔符 */ SEPARATOR_COLON(":"), /** * 存储告警规则yaml命名空间 */ YAML_ROOT_PATH("/default"), /** * yaml */ YAML("/alarm.default.alarm-settings"); private String value; /** * 构造函数 * * @param value 设置值 */ DataType(String value) { this.value = value; } /** * 获取数据 * * @return 枚举值 */ public String getDataType() { return value; } }
16.272251
77
0.548263
c6120b31fe9578a9e10029f7e9794c7255d500f0
1,155
package com.github.seratch.jslack.api.methods.request.dnd; import com.github.seratch.jslack.api.methods.SlackApiRequest; public class DndEndSnoozeRequest implements SlackApiRequest { /** * Authentication token. Requires scope: `dnd:write` */ private String token; DndEndSnoozeRequest(String token) { this.token = token; } public static DndEndSnoozeRequestBuilder builder() { return new DndEndSnoozeRequestBuilder(); } public String getToken() { return this.token; } public void setToken(String token) { this.token = token; } public static class DndEndSnoozeRequestBuilder { private String token; DndEndSnoozeRequestBuilder() { } public DndEndSnoozeRequest.DndEndSnoozeRequestBuilder token(String token) { this.token = token; return this; } public DndEndSnoozeRequest build() { return new DndEndSnoozeRequest(token); } public String toString() { return "DndEndSnoozeRequest.DndEndSnoozeRequestBuilder(token=" + this.token + ")"; } } }
24.574468
94
0.64329
6fc864a2f9a37c106894c3636f36cdc2f5b9f558
870
package com.pepper.framework.aspectj.lang.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 数据权限过滤注解 * * @author pepper */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DataScope { /** * 部门表的别名 */ public String deptAlias() default ""; /** * 用户表的别名 */ public String userAlias() default ""; String hospitalAlias() default ""; String appointmentAlias() default ""; String medicalProjectAlias() default ""; String areaAlias() default ""; String communityAlias() default ""; String propertyAlias() default ""; String boardAlias() default ""; String videoAlias() default ""; }
19.772727
53
0.690805
0972ad6606afafc7cfd279ef8956e214f85393cd
665
package net.sourceforge.barbecue.output; public class CenteredLabelLayout extends LabelLayout { /** Pixel gap between the barcode bars and the top of the data text underneath */ public static final int BARS_TEXT_VGAP = 5; public CenteredLabelLayout(int x, int y, int width) { super(x, y, width, BARS_TEXT_VGAP); } protected void calculate() { textX = (float) ((((width - x) - textLayout.getBounds().getWidth()) / 2) + x); textY = (float) (y + textLayout.getBounds().getHeight() + BARS_TEXT_VGAP); int height = (int) (textLayout.getBounds().getHeight() + BARS_TEXT_VGAP + 1); bgX = x; bgY = y; bgWidth = width - x; bgHeight = height; } }
31.666667
82
0.685714
6a768c03146e3322f8e94f79344a4c7cef8a017d
741
package com.kaushikam.jpa.entity.inheritance.table_per_class; import javax.persistence.Entity; import java.math.BigDecimal; @Entity public class FullTimeTeacher extends Teacher { private BigDecimal salary; public FullTimeTeacher() {} public FullTimeTeacher(String name, BigDecimal salary) { super(name); this.salary = salary; } public BigDecimal getSalary() { return salary; } public void setSalary(BigDecimal salary) { this.salary = salary; } @Override public String toString() { return "FullTimeEmployee{" + "id=" + getId() + ", name=" + getName() + ", salary=" + salary + '}'; } }
21.171429
61
0.588394
c74fde749f6bccfbc433fb37e9290be568877038
3,088
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.dialect.lock; import java.io.Serializable; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.engine.spi.EntityEntry; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.Lockable; /** * A pessimistic locking strategy that increments the version immediately (obtaining an exclusive write lock). * <p/> * This strategy is valid for LockMode.PESSIMISTIC_FORCE_INCREMENT * * @author Scott Marlow * @since 3.5 */ public class PessimisticForceIncrementLockingStrategy implements LockingStrategy { private final Lockable lockable; private final LockMode lockMode; /** * Construct locking strategy. * * @param lockable The metadata for the entity to be locked. * @param lockMode Indicates the type of lock to be acquired. */ public PessimisticForceIncrementLockingStrategy(Lockable lockable, LockMode lockMode) { this.lockable = lockable; this.lockMode = lockMode; // ForceIncrement can be used for PESSIMISTIC_READ, PESSIMISTIC_WRITE or PESSIMISTIC_FORCE_INCREMENT if ( lockMode.lessThan( LockMode.PESSIMISTIC_READ ) ) { throw new HibernateException( "[" + lockMode + "] not valid for [" + lockable.getEntityName() + "]" ); } } @Override public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session) { if ( !lockable.isVersioned() ) { throw new HibernateException( "[" + lockMode + "] not supported for non-versioned entities [" + lockable.getEntityName() + "]" ); } EntityEntry entry = session.getPersistenceContext().getEntry( object ); final EntityPersister persister = entry.getPersister(); Object nextVersion = persister.forceVersionIncrement( entry.getId(), entry.getVersion(), session ); entry.forceLocked( object, nextVersion ); } /** * Retrieve the specific lock mode defined. * * @return The specific lock mode. */ protected LockMode getLockMode() { return lockMode; } }
38.123457
132
0.757448
ba6cffc70a8744ad6847fff032b9b7500e770742
66
package com.yz.tc.async; public class asynchronousBlockQueue { }
13.2
37
0.787879
390efe3f9caabf643239ef6211992d68e13a56ff
2,009
package com.ywy.learn.command.user; import com.ywy.learn.command.user.api.command.AuthRemoveCommand; import com.ywy.learn.command.user.api.event.AuthRemovedEvent; import com.ywy.learn.command.user.api.event.UserRemovedEvent; import com.ywy.learn.common.api.gateway.MetaDataGateway; import org.axonframework.eventhandling.saga.EndSaga; import org.axonframework.eventhandling.saga.SagaEventHandler; import org.axonframework.eventhandling.saga.SagaLifecycle; import org.axonframework.eventhandling.saga.StartSaga; import org.axonframework.messaging.MetaData; import org.axonframework.spring.stereotype.Saga; import org.springframework.beans.factory.annotation.Autowired; import java.io.Serializable; /** * 用户被删除saga,实现用户删除后的其他业务,比如用户注销之后,需要删除授权中心(另一个聚合根)相关授权 * * @author ve * @date 2019/8/25 2:46 */ @Saga public class UserRemovedSaga implements Serializable { static { // todo 项目重启时应当检查saga是否完成 } @Autowired transient MetaDataGateway metaDataGateway; /** * saga事务的第一个节点,需要以@StartSaga标识事务开始 * * @param event * @param metaData */ @StartSaga @SagaEventHandler(associationProperty = "id") public void handle(UserRemovedEvent event, MetaData metaData) { // 1.创建授权中心删除指定cert命令 AuthRemoveCommand command = new AuthRemoveCommand(); command.setUserId(event.getId()); // 2.为此saga设置关联,用于匹配第二节点与后续事件 SagaLifecycle.associateWith("userId", event.getId()); // 3.发送此命令,进入下一节点 metaDataGateway.send(command, metaData); } /** * saga事务的第二个节点,若是最后一个事件,以注解@EndSaga标识事务结束,否则需要显性指定事务结束SagaLifecycle.end(); * * @param event * @param metaData */ @EndSaga @SagaEventHandler(associationProperty = "id", keyName = "userId") // 此处keyName与上面的"userId"相同,associationProperty则是userId(即找到event.getUserId()进行匹配关联saga事务第一节点) public void handle(AuthRemovedEvent event, MetaData metaData) { // ok, do nothing. event.getId(); metaData.get("aa"); } }
30.439394
96
0.724739
b5b347db2e2856e4c0d78f39fd12c724a9755af5
4,041
package com.inicu.models; public class RdsReportJSON { private Integer rds_onset; private Integer rds_duration; private String rds_cause; private Integer max_downes; private Boolean resp_support; private Integer duration_lowflow = 0; private Integer duration_highflow = 0; private Integer duration_cpap = 0; private Integer duration_mv = 0; private Integer duration_hfo = 0; private Boolean rds_surfactant; private Integer age_at_surfactant; private String surfactant_type; private Integer surfactant_dose; private Integer no_antibiotics; private Integer antibiotics_duration; public RdsReportJSON() { super(); this.resp_support = false; this.rds_surfactant = false; } public Integer getRds_onset() { return rds_onset; } public void setRds_onset(Integer rds_onset) { this.rds_onset = rds_onset; } public Integer getRds_duration() { return rds_duration; } public void setRds_duration(Integer rds_duration) { this.rds_duration = rds_duration; } public String getRds_cause() { return rds_cause; } public void setRds_cause(String rds_cause) { this.rds_cause = rds_cause; } public Integer getMax_downes() { return max_downes; } public void setMax_downes(Integer max_downes) { this.max_downes = max_downes; } public Boolean getResp_support() { return resp_support; } public void setResp_support(Boolean resp_support) { this.resp_support = resp_support; } public Integer getDuration_lowflow() { return duration_lowflow; } public void setDuration_lowflow(Integer duration_lowflow) { this.duration_lowflow = duration_lowflow; } public Integer getDuration_highflow() { return duration_highflow; } public void setDuration_highflow(Integer duration_highflow) { this.duration_highflow = duration_highflow; } public Integer getDuration_cpap() { return duration_cpap; } public void setDuration_cpap(Integer duration_cpap) { this.duration_cpap = duration_cpap; } public Integer getDuration_mv() { return duration_mv; } public void setDuration_mv(Integer duration_mv) { this.duration_mv = duration_mv; } public Integer getDuration_hfo() { return duration_hfo; } public void setDuration_hfo(Integer duration_hfo) { this.duration_hfo = duration_hfo; } public Boolean getRds_surfactant() { return rds_surfactant; } public void setRds_surfactant(Boolean rds_surfactant) { this.rds_surfactant = rds_surfactant; } public Integer getAge_at_surfactant() { return age_at_surfactant; } public void setAge_at_surfactant(Integer age_at_surfactant) { this.age_at_surfactant = age_at_surfactant; } public String getSurfactant_type() { return surfactant_type; } public void setSurfactant_type(String surfactant_type) { this.surfactant_type = surfactant_type; } public Integer getSurfactant_dose() { return surfactant_dose; } public void setSurfactant_dose(Integer surfactant_dose) { this.surfactant_dose = surfactant_dose; } public Integer getNo_antibiotics() { return no_antibiotics; } public void setNo_antibiotics(Integer no_antibiotics) { this.no_antibiotics = no_antibiotics; } public Integer getAntibiotics_duration() { return antibiotics_duration; } public void setAntibiotics_duration(Integer antibiotics_duration) { this.antibiotics_duration = antibiotics_duration; } @Override public String toString() { return "RdsReportJSON [rds_onset=" + rds_onset + ", rds_duration=" + rds_duration + ", rds_cause=" + rds_cause + ", max_downes=" + max_downes + ", resp_support=" + resp_support + ", duration_lowflow=" + duration_lowflow + ", duration_highflow=" + duration_highflow + ", duration_cpap=" + duration_cpap + ", duration_mv=" + duration_mv + ", duration_hfo=" + duration_hfo + ", rds_surfactant=" + rds_surfactant + ", age_at_surfactant=" + age_at_surfactant + ", surfactant_type=" + surfactant_type + ", surfactant_dose=" + surfactant_dose + ", no_antibiotics=" + no_antibiotics + ", antibiotics_duration=" + antibiotics_duration + "]"; } }
23.494186
112
0.757981
95db4b5d2da801398ae2faee5dcab0c4686f41e7
1,929
package com.example.module.project.model; import lombok.Data; import org.apache.commons.lang3.StringUtils; import org.springframework.data.mongodb.core.mapping.Document; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Data @Document("project_bid") public class ProjectBid { private String bidId = UUID.randomUUID().toString().replace("-",""); private String projectId = StringUtils.EMPTY; private String status = StringUtils.EMPTY; //招投标状态 private String step = StringUtils.EMPTY;//招投标进度 private String isEnroll = StringUtils.EMPTY;//是否报名成功 private String enrollWay = StringUtils.EMPTY;//报名方式 private String enrollCost = StringUtils.EMPTY;//报名费用 private String enrollUserId = StringUtils.EMPTY;//实际报名人id private String enrollUserName = StringUtils.EMPTY;//实际报名人 private String annualFee = StringUtils.EMPTY;//年费金额 private String realityEnrollTime = StringUtils.EMPTY;//实际报名时间 private String createBy = StringUtils.EMPTY; private String createTime = StringUtils.EMPTY; private String updateBy = StringUtils.EMPTY; private String updateTime = StringUtils.EMPTY; private String delFlag = StringUtils.EMPTY; private MapDeposit deposit = new MapDeposit(); private MapBidDocument bidDocument = new MapBidDocument(); private MapProjectQualificationAudit projectQualificationAudit = new MapProjectQualificationAudit(); private MapProjectSkillAudit projectSkillAudit = new MapProjectSkillAudit(); private MapProjectBusinessAudit projectBusinessAudit = new MapProjectBusinessAudit(); private MapMakeBidDocument makeBidDocument = new MapMakeBidDocument(); private MapCloseBidDocument closeBidDocument = new MapCloseBidDocument(); private MapWinBidResultAnalyse winBidResultAnalyse = new MapWinBidResultAnalyse(); private List<MapBidList> bidList = new ArrayList<>(); private String dataSource = "EPMS"; }
45.928571
104
0.777605
8628437816173d6d0bf0c8b2aa666d0518ca5a31
2,708
/* * Copyright (c) 2015 Spotify AB. * * 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 com.spotify.heroic.profile; import com.google.common.collect.ImmutableList; import com.spotify.heroic.HeroicConfig; import com.spotify.heroic.ExtraParameters; import com.spotify.heroic.aggregationcache.AggregationCacheModule; import com.spotify.heroic.aggregationcache.InMemoryAggregationCacheBackendConfig; import com.spotify.heroic.cluster.ClusterManagerModule; import com.spotify.heroic.metadata.MetadataManagerModule; import com.spotify.heroic.metric.MetricManagerModule; import com.spotify.heroic.metric.MetricModule; import com.spotify.heroic.metric.generated.GeneratedMetricModule; import com.spotify.heroic.metric.generated.generator.SineGeneratorModule; public class GeneratedProfile extends HeroicProfileBase { @Override public HeroicConfig.Builder build(final ExtraParameters params) throws Exception { // @formatter:off // final SuggestManagerModule suggest = SuggestManagerModule.create(suggestModules, null); return HeroicConfig.builder() .cluster( ClusterManagerModule.builder() ) .metric( MetricManagerModule.builder() .backends(ImmutableList.<MetricModule>of( GeneratedMetricModule.builder() .generatorModule(SineGeneratorModule.builder().build()) .build() )) ) .metadata( MetadataManagerModule.builder() ) .cache( AggregationCacheModule.builder() .backend(InMemoryAggregationCacheBackendConfig.builder().build()) ); // @formatter:on } @Override public String description() { return "Configures a metric backend containing generated data (does not support writes)"; } }
39.823529
98
0.694609
646ce4cfb92804b560e8e507ce0e8923f18232d3
927
package org.clafer.ir; import org.clafer.domain.Domain; import org.clafer.common.Check; /** * * @author jimmy */ public class IrLength extends IrAbstractInt { private final IrStringExpr string; IrLength(IrStringExpr string, Domain domain) { super(domain); this.string = Check.notNull(string); } public IrStringExpr getString() { return string; } @Override public <A, B> B accept(IrIntExprVisitor<A, B> visitor, A a) { return visitor.visit(this, a); } @Override public boolean equals(Object obj) { if (obj instanceof IrLength) { IrLength other = (IrLength) obj; return string.equals(other.string) ; } return false; } @Override public int hashCode() { return 41 * string.hashCode(); } @Override public String toString() { return "|" + string + "|"; } }
19.723404
65
0.593312
d2864a7e1f1394750ab9f572f3ad88d7981f920c
6,631
/*- * Copyright (C) 2011, 2018 Oracle and/or its affiliates. All rights reserved. * * This file was distributed by Oracle as part of a version of Oracle NoSQL * Database made available at: * * http://www.oracle.com/technetwork/database/database-technologies/nosqldb/downloads/index.html * * Please see the LICENSE file included in the top-level directory of the * appropriate version of Oracle NoSQL Database for a copy of the license and * additional information. */ package oracle.kv.impl.async.dialog.netty; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import oracle.kv.impl.async.AbstractEndpointGroup; import oracle.kv.impl.async.AbstractListener; import oracle.kv.impl.async.DialogHandlerFactory; import oracle.kv.impl.async.EndpointConfig; import oracle.kv.impl.async.ListenerConfig; import oracle.kv.impl.async.NetworkAddress; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.util.internal.logging.InternalLoggerFactory; import io.netty.util.internal.logging.JdkLoggerFactory; public class NettyEndpointGroup extends AbstractEndpointGroup { private static boolean logHandlerEnabled = false; /* Use the jdk logging. */ static { InternalLoggerFactory.setDefaultFactory(JdkLoggerFactory.INSTANCE); } private final EventLoopGroup eventLoopGroup; public NettyEndpointGroup(Logger logger, int nthreads) throws Exception { super(logger); eventLoopGroup = new NioEventLoopGroup(nthreads); } /** * Enables the netty log handler for debugging. * * This will add a log handler to the pipeline. */ public static void enableLogHandler() { logHandlerEnabled = true; } /** * Disables the netty log handler. */ public static void disableLogHandler() { logHandlerEnabled = false; } /** * Returns {@code true} if log handler is enabled. */ public static boolean logHandlerEnabled() { return logHandlerEnabled; } @Override public ScheduledExecutorService getSchedExecService() { return eventLoopGroup; } @Override protected NettyCreatorEndpoint newCreatorEndpoint(NetworkAddress address, EndpointConfig endpointConfig) { return new NettyCreatorEndpoint( this, eventLoopGroup, address, endpointConfig); } @Override protected NettyListener newListener(AbstractEndpointGroup endpointGroup, ListenerConfig listenerConfig, Map<Integer, DialogHandlerFactory> dialogHandlerFactories) { return new NettyListener( endpointGroup, listenerConfig, dialogHandlerFactories); } @Override protected void shutdownInternal(boolean force) { if (force) { eventLoopGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS); } else { eventLoopGroup.shutdownGracefully(); } } class NettyListener extends AbstractListener { private Channel listeningChannel = null; NettyListener(AbstractEndpointGroup endpointGroup, ListenerConfig listenerConfig, Map<Integer, DialogHandlerFactory> dialogHandlerFactories) { super(endpointGroup, listenerConfig, dialogHandlerFactories); } /** * Creates the listening channel if not existing yet. * * The method is called inside a synchronization block of the parent * endpoint group. */ @Override protected void createChannel() throws IOException { if (listeningChannel == null) { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(eventLoopGroup) .channel(NioServerSocketChannel.class) .handler(new ChannelErrorHandler()) .childHandler(new Initializer()); listeningChannel = NettyUtil.listen(serverBootstrap, listenerConfig); } } /** * Close the created listening channel. * * The method is called inside a synchronization block of the parent * endpoint group. */ @Override protected void closeChannel() { if (listeningChannel == null) { return; } listeningChannel.close(); listeningChannel = null; } @Override protected NetworkAddress getLocalAddress() { if (listeningChannel == null) { return null; } return NettyUtil.getLocalAddress(listeningChannel); } private class Initializer extends ChannelInitializer<SocketChannel> { @Override public void initChannel(SocketChannel channel) { InetSocketAddress addr = channel.remoteAddress(); NetworkAddress remoteAddress = new NetworkAddress(addr.getHostName(), addr.getPort()); NettyResponderEndpoint endpoint = new NettyResponderEndpoint( NettyEndpointGroup.this, remoteAddress, listenerConfig, NettyListener.this, endpointConfig); acceptedEndpoints.add(endpoint); addResponderEndpoint(endpoint); ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast(endpoint.getHandler()); } } private class ChannelErrorHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { onChannelError(cause, !ctx.channel().isOpen()); } } } }
32.665025
96
0.636706
b91a0c3fb189dc5f717b4dbde049a3c2a93aa944
2,150
package one.jodi.base.model.types.impl; import one.jodi.base.model.types.DataStoreKey; import one.jodi.base.service.metadata.Key; import java.io.Serializable; import java.util.Collections; import java.util.List; class DataStoreKeyImpl implements DataStoreKey, Serializable { private static final long serialVersionUID = 3251914312836598528L; private final String name; private final KeyType type; private final List<String> columns; private final boolean inDatabase; private final boolean enabledInDatabase; protected DataStoreKeyImpl(Key key) { super(); this.name = key.getName(); this.type = mapKeyType(key.getType()); this.columns = Collections.unmodifiableList(key.getColumns()); this.inDatabase = key.existsInDatabase(); this.enabledInDatabase = key.isEnabledInDatabase(); } private DataStoreKey.KeyType mapKeyType(Key.KeyType type) { DataStoreKey.KeyType result; switch (type) { case PRIMARY: result = DataStoreKey.KeyType.PRIMARY; break; case ALTERNATE: result = DataStoreKey.KeyType.ALTERNATE; break; default: result = DataStoreKey.KeyType.INDEX; } return result; } @Override public String getName() { return name; } @Override public KeyType getType() { return type; } @Override public List<String> getColumns() { return columns; } @Override public boolean existsInDatabase() { return inDatabase; } @Override public boolean isEnabledInDatabase() { return enabledInDatabase; } @Override public String toString() { String sep = ""; StringBuilder sb = new StringBuilder(); sb.append(name); sb.append(" : "); sb.append(type); sb.append(" ("); for (String column : columns) { sb.append(sep); sb.append(column); sep = ", "; } sb.append(")"); return sb.toString(); } }
24.157303
70
0.59907
7264bc3040b5f7991c73358d95066a68333fa526
134
package com.accela.CommandExecutionCenter.shared; public interface IConstants { public static long SERIAL_VERSION_UID=1L; }
16.75
50
0.783582
d77cf6a8eec2bb6d996adc798300cd56c98a6623
4,960
package b01.l3.drivers.roches.cobas.u601; import b01.foc.util.ASCII; import b01.l3.data.L3Test; import b01.l3.data.L3TestDesc; import b01.l3.drivers.astm.AstmDriver; import b01.l3.drivers.astm.ResultLineReader; public class CobasU601_ResultLineReader extends ResultLineReader { private int posForTestCode = 0; private String machineTestCode = null; public CobasU601_ResultLineReader(AstmDriver driver, int posForTestCode) { super(driver); this.posForTestCode = posForTestCode; } public String getMachineTestCode() { return machineTestCode; } public void setMachineTestCode(String machineTestCode) { this.machineTestCode = machineTestCode; } public void readToken(String token, int fieldPos, int compPos) { /* fieldPos:1 compPos:0 token:4 fieldPos:2 compPos:0 token:4 fieldPos:2 compPos:1 token:KET fieldPos:3 compPos:0 token:+++ fieldPos:3 compPos:1 token:50 mg/dL fieldPos:3 compPos:2 token:+++ mmol/L fieldPos:5 compPos:0 token:St. Georges Hospital fieldPos:8 compPos:0 token:F fieldPos:10 compPos:0 token:parasito fieldPos:13 compPos:0 token:u60 20:44:55:621 : fieldPos:2 compPos:0 token:1 20:44:55:621 : fieldPos:2 compPos:1 token:ERY 20:44:55:621 : fieldPos:3 compPos:0 token:++++ 20:44:55:622 : fieldPos:3 compPos:1 token:150 /uL 20:44:55:622 : fieldPos:3 compPos:2 token:>250 /uL 20:44:55:622 : fieldPos:5 compPos:0 token:St. Georges Hospital 20:44:55:622 : fieldPos:8 compPos:0 token:F 20:44:55:622 : fieldPos:10 compPos:0 token:parasito 20:44:55:622 : fieldPos:13 compPos:0 token:u60 */ b01.foc.Globals.logDetail(" fieldPos:"+fieldPos+" compPos:"+compPos+" token:"+token); if(fieldPos == 2 && compPos == posForTestCode){ setMachineTestCode(token); String lisCode = getDriver().testMaps_getLisCode(token); setDoRead(lisCode != null); if(isDoRead()){ if(!getDriver().getAstmParams().isCheckResultFrameTestCodeWithOrderFrameTestCode()){ String testLabelToFind = lisCode.trim(); L3Test test = getSample().findTest(testLabelToFind); if(test == null){ test = getSample().addTest(); } test.setLabel(lisCode.trim()); setTest(test); }else{ setDoRead(lisCode.trim().compareTo(getTest().getLabel()) == 0); } } }else if(fieldPos == FLD_DATA_VALUE){ if(isDoRead()){ if(compPos == 0){ //If both columns are equal we only need to put the column 1 //We will try to see if is a numerical value //---------------------------------------------------------- Double dbl = null; try{ dbl = Double.valueOf(token); getTest().setValue(dbl.doubleValue()); getTest().setResultOk(true); }catch(Exception e){ getTest().setValue(L3TestDesc.VALUE_NULL); getTest().setValueNotes(token); getTest().setResultOk(true); } //---------------------------------------------------------- }else if(compPos == 2){ String unit = ""; int spaceIndex = token.indexOf(' '); if(spaceIndex > 0){ unit = token.substring(spaceIndex+1, token.length()); token = token.substring(0, spaceIndex)+" "; if(unit.contains("uL")){ String mm3 = "mm"+ASCII.CUBE; unit = unit.replace("uL", mm3); } } //If the Unit is empty we need to set it hard coded // if(unit == null || unit.trim().compareTo("") == 0){ String machineCode = getMachineTestCode(); if(machineCode != null) { if(machineCode.equals("1") && (unit == null || unit.trim().compareTo("") == 0)){//1-ERY unit = " /mm"+ASCII.CUBE; }else if(machineCode.equals("2") && (unit == null || unit.trim().compareTo("") == 0)){//2-LEU unit = " /mm"+ASCII.CUBE; }else if( machineCode.equals("3")//3-NIT || machineCode.equals("4")//4-KET || machineCode.equals("5")//5-GLU || machineCode.equals("6")//6-PRO || machineCode.equals("7")//7-UBG || machineCode.equals("8"))//8-BIL { unit = ""; // }else if(machineCode.equals("4")){//KET // //unit = "mmol/L"; // unit = ""; // }else if(machineCode.equals("5")){//GLU // //unit = "mmol/L"; // unit = ""; // }else if(machineCode.equals("6")){//PRO // //unit = "g/L"; // unit = ""; // }else if(machineCode.equals("7")){//UBG // //unit = "umol/L"; // unit = ""; // }else if(machineCode.equals("8")){//BIL // //unit = "umol/L"; // unit = ""; } } // } //------------------------------------------------- getTest().setUnitLabel(unit); if(unit!=null && !unit.isEmpty() && getTest().getValueNotes() != null && !getTest().getValueNotes().isEmpty() && !getTest().getValueNotes().contains(token)){ getTest().setValueNotes(getTest().getValueNotes()+" ("+token+unit+")");//The token has the last space getTest().setResultOk(true); } } } } } }
33.972603
162
0.592137
531416ba855d6e4b909d6b457b5df10ee1aa4f24
618
package com.koma.mediacategory; import com.koma.mediacategory.util.LogUtils; /** * Created by koma on 2017/1/14. */ public class MainPresenter implements MainContract.Presenter { private static final String TAG = MainPagerAdapter.class.getSimpleName(); private MainContract.View mView; public MainPresenter(MainContract.View view) { mView = view; } @Override public void subscribe() { LogUtils.i(TAG, "subscribe"); } @Override public void unSubscribe() { LogUtils.i(TAG, "unSubscribe"); } @Override public void initAdapter() { } }
18.727273
77
0.660194
0ffb9a912d1dce8c9e3f9a82179ac2dfa712d525
1,609
package demo; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import static demo.TheFoo.checkRedAlert; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mockStatic; @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") class TheFooTest { @Test void shouldKnowTheFoo() { final var theFoo = "I am the Foo!"; final var didTheFoo = new TheFoo(theFoo); assertThat(didTheFoo.getLabel()).isEqualTo(theFoo); } @SuppressWarnings("ConstantConditions") @Test void shouldComplainWhenInvalid() { assertThatThrownBy(() -> new TheFoo(null)) .isInstanceOf(NullPointerException.class); } @Test void shouldRedAlert() { assertThat(new TheFoo("We are the Borg.").isRedAlert()) .isTrue(); } @Test void shouldNotRedAlert() { assertThat(new TheFoo("My debt is repaid.").isRedAlert()) .isFalse(); } @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE") @Test void shouldRedAlertAsStaticMock() { final var label = "Some label, *mumble, mumble*. <IRRELEVANT>"; try (MockedStatic<TheFoo> mockFoo = mockStatic(TheFoo.class)) { mockFoo.when(() -> checkRedAlert(eq(label))).thenReturn(true); assertThat(new TheFoo(label).isRedAlert()) .isTrue(); } } }
29.254545
74
0.666252
8fc9576773531ee65a9ac587e3728ee89474d98e
327
/* * Copyright (c) 2000-2005 by JetBrains s.r.o. All Rights Reserved. * Use is subject to license terms. */ package com.intellij.aop.psi; /** * @author peter */ public class AopPointcutDesignatorTokenType extends AopElementType { public AopPointcutDesignatorTokenType(final String typeName) { super(typeName); } }
21.8
68
0.733945
5f6e4a95b8627bc411ae17c718145de559c3c1db
1,775
/** * Copyright (c) 2011, Cloudera, Inc. All Rights Reserved. * * Cloudera, Inc. 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 * * This software 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.cloudera.crunch.type; import java.util.List; import org.apache.hadoop.fs.Path; import com.cloudera.crunch.MapFn; import com.cloudera.crunch.SourceTarget; /** * A {@code PType} defines a mapping between a data type that is used in a * Crunch pipeline and a serialization and storage format that is used to * read/write data from/to HDFS. Every {@link PCollection} has an associated * {@code PType} that tells Crunch how to read/write data from that * {@code PCollection}. * */ public interface PType<T> { /** * Returns the Java type represented by this {@code PType}. */ Class<T> getTypeClass(); /** * Returns the {@code PTypeFamily} that this {@code PType} belongs to. */ PTypeFamily getFamily(); MapFn<Object, T> getInputMapFn(); MapFn<T, Object> getOutputMapFn(); Converter getConverter(); /** * Returns a {@code SourceTarget} that is able to read/write data using the * serialization format specified by this {@code PType}. */ SourceTarget<T> getDefaultFileSource(Path path); /** * Returns the sub-types that make up this PType if it is a composite instance, * such as a tuple. */ List<PType> getSubTypes(); }
28.629032
81
0.700845
9c44a4c18e5e24540a3ffe71d1cb3a0ebcbf4b0d
10,228
package es.upm.oeg.librairy.service.modeler.clients; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.google.common.cache.*; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.ObjectMapper; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.json.JSONArray; import org.json.JSONObject; import org.librairy.service.nlp.facade.AvroClient; import org.librairy.service.nlp.facade.model.Form; import org.librairy.service.nlp.facade.model.Group; import org.librairy.service.nlp.facade.model.PoS; import org.librairy.service.nlp.facade.rest.model.GroupsRequest; import org.librairy.service.nlp.facade.rest.model.TokensRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import org.thymeleaf.util.StringUtils; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es> */ @Component public class LibrairyNlpClient { private static final Logger LOG = LoggerFactory.getLogger(LibrairyNlpClient.class); static{ Unirest.setDefaultHeader("Accept", MediaType.APPLICATION_JSON_VALUE); Unirest.setDefaultHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE); com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); // jacksonObjectMapper.enable(SerializationFeature.INDENT_OUTPUT); jacksonObjectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); Unirest.setObjectMapper(new ObjectMapper() { public <T> T readValue(String value, Class<T> valueType) { try { return jacksonObjectMapper.readValue(value, valueType); } catch (IOException e) { throw new RuntimeException(e); } } public String writeValue(Object value) { try { return jacksonObjectMapper.writeValueAsString(value); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }); try { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); Unirest.setHttpClient(httpclient); } catch (Exception e) { LOG.error("HTTP Error",e); } } @Value("#{environment['NLP_ENDPOINT']?:'${nlp.endpoint}'}") String nlpEndpoint; LoadingCache<String, AvroClient> clients; public void setNlpEndpoint(String nlpEndpoint) { this.nlpEndpoint = nlpEndpoint; } @PostConstruct public void setup(){ clients = CacheBuilder.newBuilder() .maximumSize(100) .removalListener(new RemovalListener<String, AvroClient>() { @Override public void onRemoval(RemovalNotification<String, AvroClient> removalNotification) { removalNotification.getValue().close(); LOG.info("AVRO connection closed: " + removalNotification.getKey()); } }) .build( new CacheLoader<String, AvroClient>() { public AvroClient load(String key) throws IOException { AvroClient client = new AvroClient(); String language = StringUtils.substringAfter(key,"-lang:"); Integer port = 65111; String url = nlpEndpoint; if (nlpEndpoint.contains(":")){ port = Integer.valueOf(org.apache.commons.lang3.StringUtils.substringAfterLast(nlpEndpoint,":")); url = org.apache.commons.lang3.StringUtils.substringBefore(nlpEndpoint,":"); } String nlpServiceEndpoint = url.replace("%%", language); try { LOG.info("Creating a new AVRO connection to: " + nlpServiceEndpoint); client.open(nlpServiceEndpoint,port); return client; } catch (Exception e) { LOG.error("Error connecting to nlp service: " + nlpServiceEndpoint, e); throw e; } } }); } @PreDestroy public void shutdown(){ clients.cleanUp(); } public String lemmatize(String text, String language, List<PoS> poSList, Boolean entities){ String key = "Thread-"+ Thread.currentThread().getId()+"-lang:"+language; if (nlpEndpoint.startsWith("http")) return lemmatizeByHttp(text,language,poSList, key, entities); else return lemmatizeByAVRO(text,language,poSList, key, entities); } private String lemmatizeByAVRO(String text, String language, List<PoS> poSList, String key, Boolean entities){ try { AvroClient client = clients.get(key); return client.tokens(text,poSList, Form.LEMMA, entities, language); } catch (Exception e) { LOG.error("Error retrieving lemmas from nlp service: " + nlpEndpoint.replace("%%", language), e); } return ""; } private String lemmatizeByHttp(String text, String language, List<PoS> poSList, String key, Boolean multigrams){ try { TokensRequest request = new TokensRequest(); request.setFilter(poSList); request.setForm(Form.LEMMA); request.setLang(language); request.setText(text); request.setMultigrams(multigrams); HttpResponse<JsonNode> response = Unirest.post(nlpEndpoint + "/tokens"). body(request). asJson(); if (response.getStatus() == 200) { return response.getBody().getObject().getString("processedText"); }else{ LOG.warn("Response error from nlp-service: " + response.getStatus() + ": " + response.getStatusText()); } } catch (UnirestException e) { LOG.warn("Error getting lemma from NLP service",e); } return ""; } public List<Group> bow(String text, String language, List<PoS> poSList, Boolean entities){ String key = "Thread-"+ Thread.currentThread().getId()+"-lang:"+language; if (nlpEndpoint.startsWith("http")) return bowByHttp(text,language,poSList, key, entities); else return bowByAVRO(text,language,poSList, key, entities); } private List<Group> bowByAVRO(String text, String language, List<PoS> poSList, String key, Boolean multigrams){ try { AvroClient client = clients.get(key); return client.groups(text,poSList, Form.LEMMA, multigrams, false, false, language); } catch (Exception e) { LOG.error("Error retrieving bow from nlp service: " + nlpEndpoint.replace("%%", language), e); } return Collections.emptyList(); } private List<Group> bowByHttp(String text, String language, List<PoS> poSList, String key, Boolean multigrams){ List<Group> tokens = new ArrayList<>(); try { GroupsRequest request = new GroupsRequest(); request.setFilter(poSList); request.setText(text); request.setMultigrams(multigrams); request.setLang(language); HttpResponse<JsonNode> response = Unirest.post(nlpEndpoint + "/groups"). body(request). asJson(); if (response.getStatus() == 200){ JSONArray tokenList = response.getBody().getObject().getJSONArray("groups"); for(int i=0;i<tokenList.length();i++){ JSONObject json = tokenList.getJSONObject(i); Group token = Group.newBuilder().setToken(json.getString("token")).setFreq(json.getInt("freq")).setPos(PoS.valueOf(json.getString("pos").toUpperCase())).build(); tokens.add(token); } }else{ LOG.warn("Response error from nlp-service: " + response.getStatus() + ": " + response.getStatusText()); } } catch (UnirestException e) { LOG.warn("Error getting lemma from NLP service",e); } return tokens; } }
40.912
181
0.608428
d7e2c7fd8eea57c7768217e8a3ee194517a58443
304
package com.flycms.core.exception; import lombok.Getter; /** * @author 郑杰 * @date 2018/09/18 11:27:40 * 通用异常处理类 */ @Getter public class FlycmsException extends RuntimeException{ private int id; public FlycmsException(int id, String msg){ super(msg); this.id = id; } }
15.2
54
0.651316
af510125a97d1cf5975c8915af8c2aee3f3e22c3
1,340
package LeetCode; import java.util.Stack; public class ValidParenthes { // pass both public boolean isValid(String s) { // Start typing your Java solution below // DO NOT write main() function Stack<Character> stack = new Stack<Character>(); if (s == null || s.isEmpty()) return true; for (int i = 0; i < s.length(); i++) { char cur = s.charAt(i); if (cur == '{' || cur == '[' || cur == '(') stack.push(cur); else { if (stack.isEmpty()) return false; if (cur == '}') { if (stack.peek() != '{') return false; stack.pop(); } else if (cur == ')') { if (stack.peek() != '(') return false; stack.pop(); } else if (cur == ']') { if (stack.peek() != '[') return false; stack.pop(); } } } if (stack.isEmpty()) return true; else return false; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
26.8
56
0.381343
a34dc182271e72c7a74d6d862105b511a359129c
10,690
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. * */ package com.azure.cosmos; import com.azure.cosmos.implementation.CosmosItemProperties; import com.azure.cosmos.models.CosmosItemRequestOptions; import com.azure.cosmos.models.CosmosItemResponse; import com.azure.cosmos.models.FeedOptions; import com.azure.cosmos.models.FeedResponse; import com.azure.cosmos.models.ModelBridgeInternal; import com.azure.cosmos.models.PartitionKey; import com.azure.cosmos.models.SqlQuerySpec; import com.azure.cosmos.rx.TestSuiteBase; import com.azure.cosmos.implementation.HttpConstants; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; public class CosmosItemTest extends TestSuiteBase { private CosmosClient client; private CosmosContainer container; @Factory(dataProvider = "clientBuilders") public CosmosItemTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosItemTest() { assertThat(this.client).isNull(); this.client = clientBuilder().buildClient(); CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); container = client.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { assertThat(this.client).isNotNull(); this.client.close(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void createItem() throws Exception { CosmosItemProperties properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<CosmosItemProperties> itemResponse = container.createItem(properties); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); validateItemResponse(properties, itemResponse); properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<CosmosItemProperties> itemResponse1 = container.createItem(properties, new CosmosItemRequestOptions()); validateItemResponse(properties, itemResponse1); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_alreadyExists() throws Exception { CosmosItemProperties properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<CosmosItemProperties> itemResponse = container.createItem(properties); validateItemResponse(properties, itemResponse); properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<CosmosItemProperties> itemResponse1 = container.createItem(properties, new CosmosItemRequestOptions()); validateItemResponse(properties, itemResponse1); // Test for conflict try { container.createItem(properties, new CosmosItemRequestOptions()); } catch (Exception e) { assertThat(e).isInstanceOf(CosmosClientException.class); assertThat(((CosmosClientException) e).getStatusCode()).isEqualTo(HttpConstants.StatusCodes.CONFLICT); } } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readItem() throws Exception { CosmosItemProperties properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<CosmosItemProperties> itemResponse = container.createItem(properties); CosmosItemResponse<CosmosItemProperties> readResponse1 = container.readItem(properties.getId(), new PartitionKey(properties.get("mypk")), new CosmosItemRequestOptions(), CosmosItemProperties.class); validateItemResponse(properties, readResponse1); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void replaceItem() throws Exception{ CosmosItemProperties properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<CosmosItemProperties> itemResponse = container.createItem(properties); validateItemResponse(properties, itemResponse); String newPropValue = UUID.randomUUID().toString(); BridgeInternal.setProperty(properties, "newProp", newPropValue); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(options, new PartitionKey(properties.get("mypk"))); // replace document CosmosItemResponse<CosmosItemProperties> replace = container.replaceItem(properties, properties.getId(), new PartitionKey(properties.get("mypk")), options); assertThat(BridgeInternal.getProperties(replace).get("newProp")).isEqualTo(newPropValue); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void deleteItem() throws Exception { CosmosItemProperties properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<CosmosItemProperties> itemResponse = container.createItem(properties); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); CosmosItemResponse<?> deleteResponse = container.deleteItem(properties.getId(), new PartitionKey(properties.get("mypk")), options); assertThat(deleteResponse.getStatusCode()).isEqualTo(204); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readAllItems() throws Exception{ CosmosItemProperties properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<CosmosItemProperties> itemResponse = container.createItem(properties); FeedOptions feedOptions = new FeedOptions(); CosmosPagedIterable<CosmosItemProperties> feedResponseIterator3 = container.readAllItems(feedOptions, CosmosItemProperties.class); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryItems() throws Exception{ CosmosItemProperties properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<CosmosItemProperties> itemResponse = container.createItem(properties); String query = String.format("SELECT * from c where c.id = '%s'", properties.getId()); FeedOptions feedOptions = new FeedOptions(); CosmosPagedIterable<CosmosItemProperties> feedResponseIterator1 = container.queryItems(query, feedOptions, CosmosItemProperties.class); // Very basic validation assertThat(feedResponseIterator1.iterator().hasNext()).isTrue(); SqlQuerySpec querySpec = new SqlQuerySpec(query); CosmosPagedIterable<CosmosItemProperties> feedResponseIterator3 = container.queryItems(querySpec, feedOptions, CosmosItemProperties.class); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryItemsWithContinuationTokenAndPageSize() throws Exception{ List<String> actualIds = new ArrayList<>(); CosmosItemProperties properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); actualIds.add(properties.getId()); properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); actualIds.add(properties.getId()); properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); actualIds.add(properties.getId()); String query = String.format("SELECT * from c where c.id in ('%s', '%s', '%s')", actualIds.get(0), actualIds.get(1), actualIds.get(2)); FeedOptions feedOptions = new FeedOptions(); String continuationToken = null; int pageSize = 1; int initialDocumentCount = 3; int finalDocumentCount = 0; CosmosPagedIterable<CosmosItemProperties> feedResponseIterator1 = container.queryItems(query, feedOptions, CosmosItemProperties.class); do { Iterable<FeedResponse<CosmosItemProperties>> feedResponseIterable = feedResponseIterator1.iterableByPage(continuationToken, pageSize); for (FeedResponse<CosmosItemProperties> fr : feedResponseIterable) { int resultSize = fr.getResults().size(); assertThat(resultSize).isEqualTo(pageSize); finalDocumentCount += fr.getResults().size(); continuationToken = fr.getContinuationToken(); } } while(continuationToken != null); assertThat(finalDocumentCount).isEqualTo(initialDocumentCount); } private CosmosItemProperties getDocumentDefinition(String documentId) { final String uuid = UUID.randomUUID().toString(); final CosmosItemProperties properties = new CosmosItemProperties(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , documentId, uuid)); return properties; } private void validateItemResponse(CosmosItemProperties containerProperties, CosmosItemResponse<CosmosItemProperties> createResponse) { // Basic validation assertThat(BridgeInternal.getProperties(createResponse).getId()).isNotNull(); assertThat(BridgeInternal.getProperties(createResponse).getId()) .as("check Resource Id") .isEqualTo(containerProperties.getId()); } }
47.511111
143
0.662114
db797bc109172a79f9ea5475d930fc165a612427
137
package mypackage; class Program { public static void main() { System.out.print("Connect to database"); } }
15.222222
49
0.576642
c6865100c2c747656598259448bb30ba1e805def
817
package com.sct.service.core.web.controller.file; import com.sct.commons.file.location.FileLocation; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel(value = "下载文件描述") public class DownloadFile { //下载文件生成的文件名 @ApiModelProperty(value = "下载生成的文件名(不带文件类型后缀,后缀依据服务存放的文件类型生成)") private String downFileName; @ApiModelProperty(value = "服务端文件定位信息") private FileLocation fileLocation; public String getDownFileName() { return downFileName; } public void setDownFileName(String downFileName) { this.downFileName = downFileName; } public FileLocation getFileLocation() { return fileLocation; } public void setFileLocation(FileLocation fileLocation) { this.fileLocation = fileLocation; } }
26.354839
67
0.72705
fa97b9e3b663be7cb5200a658c5012e8db7838c9
209
// My very first CSC1006S program to display Hello World // Batandwa Mgutsi // MGTBAT001 // 08/08/2020 class HelloWorld { public static void main(String[] args){ System.out.println("Hello World"); } }
20.9
56
0.703349
111bc54ece23dd099054c15990488ba25930b16c
581
package dao; import java.util.List; import entity.Organization; public interface OrganizationDAOI { /** * 해당 카테고리 조직의 모든 조직 불러오기 * * @param organizationClass 불러올 조직의 클래스 * @return */ public List<Organization> getAllOrganization(Class<? extends Organization> organizationClass); /** * 해당 조직의 하위 조직 불러오기 * * @param organization 기준이 될 조직 * @return 기준 조직의 바로 아래 조직 */ public List<Organization> getChildrenOf(Organization deptDiv, Organization govofcDiv, Organization hgdeptDiv, Organization dept); }
22.346154
113
0.659208
4f2d2db4f26ee09dde3fbbb3e3998c30ceaf2a4e
1,632
package net.cubespace.yamler.converter; import net.cubespace.yamler.ConfigSection; import net.cubespace.yamler.InternalConverter; import java.lang.reflect.ParameterizedType; import java.util.Map; /** * @author geNAZt (fabian.fassbender42@googlemail.com) */ public class Config implements Converter { public Config(InternalConverter internalConverter) { } @Override public Object toConfig(Class<?> type, Object obj, ParameterizedType parameterizedType) throws Exception { return (obj instanceof Map) ? obj : ((net.cubespace.yamler.YamlerConfig) obj).saveToMap(); } @Override public Object fromConfig(Class<?> type, Object section, ParameterizedType genericType) throws Exception { if (section == null) { return null; } net.cubespace.yamler.YamlerConfig obj = (net.cubespace.yamler.YamlerConfig) newInstance(type); obj.loadFromMap((section instanceof Map) ? (Map<?, ?>) section : ((ConfigSection) section).getRawMap()); return obj; } // recursively handles enclosed classes public Object newInstance(Class<?> type) throws Exception { // Class<?> enclosingClass = type.getEnclosingClass(); // if (enclosingClass != null) { // Object instanceOfEnclosingClass = newInstance(enclosingClass); // return type.getConstructor(enclosingClass).newInstance(instanceOfEnclosingClass); // } else { return type.newInstance(); // } } @Override public boolean supports(Class<?> type) { return net.cubespace.yamler.YamlerConfig.class.isAssignableFrom(type); } }
33.306122
112
0.688725
2a71a63c6a2125aa4a38a024afaea4a289935cc9
1,778
/* * Copyright (c) 2008-2016 Computer Network Information Center (CNIC), Chinese Academy of Sciences. * * This file is part of Duckling project. * * 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 net.duckling.vmt.exception; import java.util.HashMap; import java.util.Map; /** * @author lvly * @since 2013-5-3 */ public final class DBErrorCode { private DBErrorCode(){ } /** * 路径不存在 * */ public static final int DN_NOT_EXISTS = 1; /** * 实体已存在 * */ public static final int NODE_EXISTS = 2; /** * 路径已存在 * */ public static final int DN_EXISTS=3; private static final Map<Integer, String> DIC = new HashMap<Integer, String>(); static { DIC.put(DN_NOT_EXISTS, "DN_NOT_EXISTS:this[{0}] dn not Exists"); DIC.put(NODE_EXISTS, "NODE IS EXISTS:the node {0} is Exists"); } /** * 根据errorCode获得描述 * @param errorCode 请看DBErrorCode.xxx * @param var 要替换的值 * @return 描述 */ public static String getDesc(int errorCode, String... var) { String desc = DIC.get(errorCode); if (desc == null) { return "unkown"; } if (var != null) { for (int i = 0; i < var.length; i++){ desc = desc.replaceAll("\\{" + i + "\\}", var[i]); } } return desc; } }
25.042254
99
0.646232
0d72261ea1799078fef7caebe34fadee51665d66
3,881
package net.sourceforge.transparent.actions; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.InputException; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.vcs.VcsConfiguration; import com.intellij.openapi.vcs.ui.Refreshable; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ScrollPaneFactory; import com.intellij.util.ui.OptionsDialog; import net.sourceforge.transparent.TransparentVcs; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.Collection; public class CheckoutDialog extends OptionsDialog implements Refreshable { @NonNls private final static String TITLE = "Checkout Comment"; @NonNls private final static String FILES_SUFFIX = " files"; private final String myLabel; private final JTextArea myCommentArea = new JTextArea(); private final VcsConfiguration myConfiguration; protected Collection<Refreshable> myAdditionalComponents = new ArrayList<>(); public CheckoutDialog( Project project, VirtualFile fileToCheckout ) { super( project ); myConfiguration = VcsConfiguration.getInstance( myProject ); myLabel = fileToCheckout.getPresentableUrl(); setTitle( TITLE ); init(); } public CheckoutDialog( Project project, VirtualFile[] filesToCheckout ) { super( project ); myConfiguration = VcsConfiguration.getInstance( myProject ); myLabel = filesToCheckout.length + FILES_SUFFIX; setTitle( TITLE ); init(); } protected boolean isToBeShown() { return TransparentVcs.getInstance( myProject ).getCheckoutOptions().getValue(); } protected void setToBeShown( boolean value, boolean onOk ) { TransparentVcs.getInstance( myProject ).getCheckoutOptions().setValue( value ); } protected JComponent createCenterPanel() { JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); JPanel commentArea = new JPanel(new BorderLayout()); commentArea.add(new JLabel(myLabel), BorderLayout.NORTH); commentArea.add(ScrollPaneFactory.createScrollPane(getCommentArea()), BorderLayout.CENTER); panel.add(commentArea, BorderLayout.CENTER); return panel; } @Nullable public JComponent getPreferredFocusedComponent() { return myCommentArea; } public String getComment() { return myCommentArea.getText().trim(); } protected void doOKAction() { if( myConfiguration.FORCE_NON_EMPTY_COMMENT && getComment().length() == 0 ) { int requestForCheckin = Messages.showYesNoDialog("Check out with empty comment?", "Comment Is Empty", Messages.getWarningIcon()); if( requestForCheckin != Messages.YES ) return; } myConfiguration.LAST_COMMIT_MESSAGE = getComment(); try { saveState(); super.doOKAction(); } catch (InputException ex) { ex.show(); } } protected JTextArea getCommentArea() { initCommentArea(); return myCommentArea; } protected boolean shouldSaveOptionsOnCancel() { return false; } protected void initCommentArea() { myCommentArea.setRows(3); myCommentArea.setWrapStyleWord(true); myCommentArea.setLineWrap(true); myCommentArea.setSelectionStart(0); myCommentArea.setSelectionEnd(myCommentArea.getText().length()); } public void refresh() { for (Refreshable component : myAdditionalComponents) component.refresh(); } public void saveState() { for (Refreshable component : myAdditionalComponents) component.saveState(); } public void restoreState() { for (Refreshable component : myAdditionalComponents) component.restoreState(); } public void show() { refresh(); super.show(); } }
30.085271
107
0.714249
244118ffadcef5f8013444bc64f144f474792ef7
1,756
package com.company; import java.util.Scanner; public class ex13_PointInTheFigure { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int h = Integer.parseInt(scanner.nextLine()); int x = Integer.parseInt(scanner.nextLine()); int y = Integer.parseInt(scanner.nextLine()); // figura 1 int x1Rec01 = 0; int y1Rec01 = 0; int x2Rec01 = h * 3; int y2Rec01 = h; //figura 2 int x1Rec02 = h; int y1Rec02 = h; int x2Rec02 = h * 2; int y2Rec02 = h * 4; // proverki boolean inRectangle01 = x > x1Rec01 && x < x2Rec01 && y > y1Rec01 && y < y2Rec01; boolean inRectangle02 = x > x1Rec02 && x < x2Rec02 && y > y1Rec02 && y < y2Rec02; boolean onInsideBorder = y == y1Rec02 && x > x1Rec02 && x < x2Rec02; boolean leftRec01 = x == x1Rec01 && y >= y1Rec01 && y <= y2Rec01; boolean rightRec01 = x == x2Rec01 && y >= y1Rec01 && y <= y2Rec01; boolean topRec01 = y == y2Rec01 && x >= x1Rec01 && x <= x2Rec01; boolean bottomRec01 = y == y1Rec01 && x >= x1Rec01 && x <= x2Rec01; boolean leftRec02 = x == x1Rec02 && y >= y1Rec02 && y <= y2Rec02; boolean rightRec02 = x == x2Rec02 && y >= y1Rec02 && y <= y2Rec02; boolean topRec02 = y == y2Rec02 && x >= x1Rec02 && x <= x2Rec02; if (inRectangle01 || inRectangle02 || onInsideBorder) { System.out.println("inside"); } else if (leftRec01 || rightRec01 || topRec01 || bottomRec01 || leftRec02 || rightRec02 || topRec02) { System.out.println("border"); } else { System.out.println("outside"); } } }
33.132075
89
0.547836
3993f15f0e78a302ce25351b93bba50a49e25918
1,273
package com.blazemeter.jmeter.debugger.elements; import org.apache.jmeter.gui.util.MenuFactory; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.threads.gui.AbstractThreadGroupGui; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.Collection; public class DebuggingThreadGroupGui extends AbstractThreadGroupGui { public DebuggingThreadGroupGui() { super(); removeAll(); setLayout(new BorderLayout(0, 5)); setBorder(makeBorder()); Box box = Box.createVerticalBox(); box.add(makeTitlePanel()); add(box, BorderLayout.NORTH); } @Override public String getLabelResource() { return getClass().getCanonicalName(); } @Override public String getStaticLabel() { return "Debugging Thread Group"; } @Override public TestElement createTestElement() { return new DebuggingThreadGroup(); } @Override public void modifyTestElement(TestElement element) { } @Override public JPopupMenu createPopupMenu() { return MenuFactory.getDefaultMenu(); } @Override public Collection<String> getMenuCategories() { return new ArrayList<>(); } }
23.145455
69
0.673998
fc76cbc003a9772b04b1cd6d93b2a762f9a1bc68
11,573
/* * Copyright 2010-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.code.pathlet.web.ognl.impl; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import ognl.DefaultClassResolver; import ognl.NullHandler; import ognl.Ognl; import ognl.OgnlException; import ognl.OgnlRuntime; import ognl.TypeConverter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Utility class that provides common access to the Ognl APIs for * setting and getting properties from objects (usually Actions). * * @author Charlie Zhang */ public class OgnlUtil { private static final Log log = LogFactory.getLog(OgnlUtil.class); private ConcurrentHashMap<String, Object> expressions = new ConcurrentHashMap<String, Object>(); private TypeConverter defaultConverter; private DefaultClassResolver defaultClassResolver; private ReflectionProvider reflectionProvider; private boolean enableExpressionCache = true; private boolean enableDev = false; public OgnlUtil(TypeConverter defaultConverter, DefaultClassResolver defaultClassResolver) { NullHandler nh = new InstantiatingNullHandler(); OgnlRuntime.setNullHandler(Object.class, nh); OgnlRuntime.setNullHandler(byte[].class, nh); OgnlRuntime.setNullHandler(short[].class, nh); OgnlRuntime.setNullHandler(char[].class, nh); OgnlRuntime.setNullHandler(int[].class, nh); OgnlRuntime.setNullHandler(long[].class, nh); OgnlRuntime.setNullHandler(float[].class, nh); OgnlRuntime.setNullHandler(double[].class, nh); OgnlRuntime.setNullHandler(Object[].class, nh); this.reflectionProvider = new ReflectionProvider(); this.defaultConverter = defaultConverter; this.defaultClassResolver = defaultClassResolver; } /** * Sets the properties on the object using the default context, defaulting to not throwing * exceptions for problems setting the properties. * * @param properties * @param o */ public void setProperties(Map<String, ?> properties, Object o) throws OgnlException { setProperties(properties, o, false); } /** * Sets the object's properties using the default type converter. * * @param props the properties being set * @param o the object * @param context the action context * @param throwPropertyExceptions boolean which tells whether it should throw exceptions for * problems setting the properties */ public void setProperties(Map<String, ?> props, Object o, Map<String, Object> context, boolean throwPropertyExceptions) throws OgnlException { if (props == null) { return; } Object oldRoot = Ognl.getRoot(context); Ognl.setRoot(context, o); for (Map.Entry<String, ?> entry : props.entrySet()) { String expression = entry.getKey(); internalSetProperty(expression, entry.getValue(), o, context, throwPropertyExceptions); } Ognl.setRoot(context, oldRoot); } /** * Sets the properties on the object using the default context. * * @param properties the property map to set on the object * @param o the object to set the properties into * @param throwPropertyExceptions boolean which tells whether it should throw exceptions for * problems setting the properties */ public void setProperties(Map<String, ?> properties, Object o, boolean throwPropertyExceptions) throws OgnlException { Map context = Ognl.createDefaultContext(o, this.defaultClassResolver, this.defaultConverter); setProperties(properties, o, context, throwPropertyExceptions); } /** * Sets the named property to the supplied value on the Object, defaults to not throwing * property exceptions. * * @param name the name of the property to be set * @param value the value to set into the named property * @param o the object upon which to set the property * @param context the context which may include the TypeConverter */ public void setProperty(String name, Object value, Object o, Map<String, Object> context) throws OgnlException { setProperty(name, value, o, context, false); } /** * Sets the named property to the supplied value on the Object. * * @param name the name of the property to be set * @param value the value to set into the named property * @param o the object upon which to set the property * @param context the context which may include the TypeConverter * @param throwPropertyExceptions boolean which tells whether it should throw exceptions for * problems setting the property */ public void setProperty(String name, Object value, Object o, Map<String, Object> context, boolean throwPropertyExceptions) throws OgnlException { Object oldRoot = Ognl.getRoot(context); Ognl.setRoot(context, o); internalSetProperty(name, value, o, context, throwPropertyExceptions); Ognl.setRoot(context, oldRoot); } /** * Wrapper around Ognl.setValue() to handle type conversion for collection elements. * Ideally, this should be handled by OGNL directly. */ public void setValue(String name, Map<String, Object> context, Object root, Object value) throws OgnlException { Ognl.setValue(compile(name), context, root, value); } public Object getValue(String name, Map<String, Object> context, Object root) throws OgnlException { return Ognl.getValue(compile(name), context, root); } public Object getValue(String name, Map<String, Object> context, Object root, Class resultType) throws OgnlException { return Ognl.getValue(compile(name), context, root, resultType); } public Object compile(String expression) throws OgnlException { if (enableExpressionCache) { Object o = expressions.get(expression); if (o == null) { o = Ognl.parseExpression(expression); expressions.put(expression, o); } return o; } else return Ognl.parseExpression(expression); } /** * Copies the properties in the object "from" and sets them in the object "to" * using specified type converter, or {@link com.opensymphony.xwork2.conversion.impl.XWorkConverter} if none * is specified. * * @param from the source object * @param to the target object * @param context the action context we're running under * @param exclusions collection of method names to excluded from copying ( can be null) * @param inclusions collection of method names to included copying (can be null) * note if exclusions AND inclusions are supplied and not null nothing will get copied. */ public void copy(Object from, Object to, Map<String, Object> context, Collection<String> exclusions, Collection<String> inclusions) { if (from == null || to == null) { log.warn("Attempting to copy from or to a null source. This is illegal and is bein skipped. This may be due to an error in an OGNL expression, action chaining, or some other event."); return; } TypeConverter conv = defaultConverter; Map contextFrom = Ognl.createDefaultContext(from); Ognl.setTypeConverter(contextFrom, conv); Map contextTo = Ognl.createDefaultContext(to); Ognl.setTypeConverter(contextTo, conv); PropertyDescriptor[] fromPds; PropertyDescriptor[] toPds; try { fromPds = this.reflectionProvider.getPropertyDescriptors(from); toPds = this.reflectionProvider.getPropertyDescriptors(to); } catch (IntrospectionException e) { log.error("An error occured", e); return; } Map<String, PropertyDescriptor> toPdHash = new HashMap<String, PropertyDescriptor>(); for (PropertyDescriptor toPd : toPds) { toPdHash.put(toPd.getName(), toPd); } for (PropertyDescriptor fromPd : fromPds) { if (fromPd.getReadMethod() != null) { boolean copy = true; if (exclusions != null && exclusions.contains(fromPd.getName())) { copy = false; } else if (inclusions != null && !inclusions.contains(fromPd.getName())) { copy = false; } if (copy == true) { PropertyDescriptor toPd = toPdHash.get(fromPd.getName()); if ((toPd != null) && (toPd.getWriteMethod() != null)) { try { Object expr = compile(fromPd.getName()); Object value = Ognl.getValue(expr, contextFrom, from); Ognl.setValue(expr, contextTo, to, value); } catch (OgnlException e) { // ignore, this is OK } } } } } } /** * Copies the properties in the object "from" and sets them in the object "to" * using specified type converter, or {@link com.opensymphony.xwork2.conversion.impl.XWorkConverter} if none * is specified. * * @param from the source object * @param to the target object * @param context the action context we're running under */ public void copy(Object from, Object to, Map<String, Object> context) { copy(from, to, context, null, null); } private void internalSetProperty(String name, Object value, Object o, Map<String, Object> context, boolean throwPropertyExceptions) throws OgnlException{ try { setValue(name, context, o, value); } catch (OgnlException e) { Throwable reason = e.getReason(); String msg = "Caught OgnlException while setting property '" + name + "' on type '" + o.getClass().getName() + "'."; Throwable exception = (reason == null) ? e : reason; if (throwPropertyExceptions) { throw new OgnlException(msg, exception); } else { if(enableDev == true) { log.warn(msg, exception); System.out.println(msg); exception.printStackTrace(); } } } } }
38.321192
195
0.637691
c2e1a17abde800f4365871324bcf8b83d797c9ac
1,328
package io.qameta.allure.bamboo; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoRule; import java.nio.file.Paths; import static org.apache.commons.io.FileUtils.deleteQuietly; import static org.apache.commons.io.FileUtils.getTempDirectoryPath; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import static org.mockito.junit.MockitoJUnit.rule; public class AllureDownloaderTest { @Rule public MockitoRule mockitoRule = rule(); @Mock AllureSettingsManager settingsManager; AllureGlobalConfig settings; @InjectMocks AllureDownloader downloader; private String homeDir; @Before public void setUp() { homeDir = Paths.get(getTempDirectoryPath(), "allure-home").toString(); settings = new AllureGlobalConfig(); when(settingsManager.getSettings()).thenReturn(settings); } @Test public void itShouldDownloadAndExtractAllureRelease() { downloader.downloadAndExtractAllureTo(homeDir, "2.17.2"); assertTrue(Paths.get(homeDir, "bin", "allure").toFile().exists()); } @After public void tearDown() { deleteQuietly(Paths.get(homeDir).toFile()); } }
27.666667
78
0.730422
9f3dcb3d6084534875ab071acc694264a070e972
6,944
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.scaling.distsql.parser.core; import org.apache.shardingsphere.distsql.parser.autogen.ScalingStatementBaseVisitor; import org.apache.shardingsphere.distsql.parser.autogen.ScalingStatementParser; import org.apache.shardingsphere.distsql.parser.autogen.ScalingStatementParser.AlgorithmDefinitionContext; import org.apache.shardingsphere.distsql.parser.autogen.ScalingStatementParser.CheckScalingContext; import org.apache.shardingsphere.distsql.parser.autogen.ScalingStatementParser.CheckoutScalingContext; import org.apache.shardingsphere.distsql.parser.autogen.ScalingStatementParser.CreateShardingScalingContext; import org.apache.shardingsphere.distsql.parser.autogen.ScalingStatementParser.DropScalingContext; import org.apache.shardingsphere.distsql.parser.autogen.ScalingStatementParser.DropShardingScalingContext; import org.apache.shardingsphere.distsql.parser.autogen.ScalingStatementParser.ResetScalingContext; import org.apache.shardingsphere.distsql.parser.autogen.ScalingStatementParser.ShowScalingCheckAlgorithmsContext; import org.apache.shardingsphere.distsql.parser.autogen.ScalingStatementParser.ShowScalingListContext; import org.apache.shardingsphere.distsql.parser.autogen.ScalingStatementParser.ShowScalingStatusContext; import org.apache.shardingsphere.distsql.parser.autogen.ScalingStatementParser.StartScalingContext; import org.apache.shardingsphere.distsql.parser.autogen.ScalingStatementParser.StopScalingContext; import org.apache.shardingsphere.distsql.parser.autogen.ScalingStatementParser.StopScalingSourceWritingContext; import org.apache.shardingsphere.distsql.parser.segment.AlgorithmSegment; import org.apache.shardingsphere.scaling.distsql.statement.CheckScalingStatement; import org.apache.shardingsphere.scaling.distsql.statement.CheckoutScalingStatement; import org.apache.shardingsphere.scaling.distsql.statement.CreateShardingScalingStatement; import org.apache.shardingsphere.scaling.distsql.statement.DropScalingStatement; import org.apache.shardingsphere.scaling.distsql.statement.DropShardingScalingStatement; import org.apache.shardingsphere.scaling.distsql.statement.ResetScalingStatement; import org.apache.shardingsphere.scaling.distsql.statement.ShowScalingCheckAlgorithmsStatement; import org.apache.shardingsphere.scaling.distsql.statement.ShowScalingListStatement; import org.apache.shardingsphere.scaling.distsql.statement.ShowScalingStatusStatement; import org.apache.shardingsphere.scaling.distsql.statement.StartScalingStatement; import org.apache.shardingsphere.scaling.distsql.statement.StopScalingSourceWritingStatement; import org.apache.shardingsphere.scaling.distsql.statement.StopScalingStatement; import org.apache.shardingsphere.sql.parser.api.visitor.ASTNode; import org.apache.shardingsphere.sql.parser.api.visitor.SQLVisitor; import org.apache.shardingsphere.sql.parser.sql.common.value.identifier.IdentifierValue; import java.util.Properties; /** * SQL statement visitor for scaling. */ public final class ScalingSQLStatementVisitor extends ScalingStatementBaseVisitor<ASTNode> implements SQLVisitor { @Override public ASTNode visitShowScalingList(final ShowScalingListContext ctx) { return new ShowScalingListStatement(); } @Override public ASTNode visitShowScalingStatus(final ShowScalingStatusContext ctx) { return new ShowScalingStatusStatement(ctx.jobId().getText()); } @Override public ASTNode visitStartScaling(final StartScalingContext ctx) { return new StartScalingStatement(ctx.jobId().getText()); } @Override public ASTNode visitStopScaling(final StopScalingContext ctx) { return new StopScalingStatement(ctx.jobId().getText()); } @Override public ASTNode visitDropScaling(final DropScalingContext ctx) { return new DropScalingStatement(ctx.jobId().getText()); } @Override public ASTNode visitResetScaling(final ResetScalingContext ctx) { return new ResetScalingStatement(ctx.jobId().getText()); } @Override public ASTNode visitCheckScaling(final CheckScalingContext ctx) { AlgorithmSegment typeStrategy = null; if (null != ctx.algorithmDefinition()) { typeStrategy = (AlgorithmSegment) visit(ctx.algorithmDefinition()); } return new CheckScalingStatement(ctx.jobId().getText(), typeStrategy); } @Override public ASTNode visitShowScalingCheckAlgorithms(final ShowScalingCheckAlgorithmsContext ctx) { return new ShowScalingCheckAlgorithmsStatement(); } @Override public ASTNode visitStopScalingSourceWriting(final StopScalingSourceWritingContext ctx) { return new StopScalingSourceWritingStatement(ctx.jobId().getText()); } @Override public ASTNode visitCheckoutScaling(final CheckoutScalingContext ctx) { return new CheckoutScalingStatement(ctx.jobId().getText()); } @Override public ASTNode visitAlgorithmDefinition(final AlgorithmDefinitionContext ctx) { return new AlgorithmSegment(ctx.algorithmName().getText(), getAlgorithmProperties(ctx)); } @Override public ASTNode visitCreateShardingScaling(final CreateShardingScalingContext ctx) { return new CreateShardingScalingStatement(new IdentifierValue(ctx.scalingName().getText()).getValue()); } @Override public ASTNode visitDropShardingScaling(final DropShardingScalingContext ctx) { return new DropShardingScalingStatement(new IdentifierValue(ctx.scalingName().getText()).getValue()); } private Properties getAlgorithmProperties(final AlgorithmDefinitionContext ctx) { Properties result = new Properties(); if (null == ctx.algorithmProperties()) { return result; } for (ScalingStatementParser.AlgorithmPropertyContext each : ctx.algorithmProperties().algorithmProperty()) { result.setProperty(new IdentifierValue(each.key.getText()).getValue(), new IdentifierValue(each.value.getText()).getValue()); } return result; } }
49.956835
137
0.792771
3c794c2edc0247fbd2b4373c8db8801724e942d9
1,886
/* * The MIT License * * Copyright 2015 Otwarta Platforma Wyborcza. * * 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. */ package pl.otwartapw.opw.pre.management.handler; import java.io.Serializable; import javax.enterprise.context.SessionScoped; import javax.inject.Named; import pl.otwartapw.opw.pre.commons.Version; /** * * @author Adam Kowalewski */ @Named @SessionScoped public class VersionHandler implements Serializable { private static final long serialVersionUID = 1L; private String versionFull; public VersionHandler() { String uri = "/META-INF/maven/pl.otwartapw.opw-pre/opw-pre-management-jsf/pom.properties"; versionFull = new Version(uri).getVersionFull(); } public String getVersionFull() { return versionFull; } public void setVersionFull(String versionFull) { this.versionFull = versionFull; } }
33.087719
94
0.757158
54ea1cd9020f5b125158f35c526abe489fdea0a4
4,465
package com.restteam.ong.services; import com.amazonaws.AmazonClientException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.PutObjectRequest; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.annotation.PostConstruct; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; @Service public class AmazonS3ClientService { private AmazonS3 s3Client; @Value("${aws_access_key_id}") private String accessKey; @Value("${aws_secret_access_key}") private String secretKey; @Value("${aws_bucket_name}") private String bucketName; @Value("${aws_bucket_region}") private String region; @Value("${aws_endpoint_url}") private String endpointUrl; @PostConstruct private void initializeAmazon() { AWSCredentials awsCredentials = new BasicAWSCredentials(this.accessKey, this.secretKey); this.s3Client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(awsCredentials)).withRegion(region).build(); } //En la request el archivo viene de tipo MultiPart, tengo que convertirlo a File private File convertMultiPartToFile(MultipartFile file) throws IOException { try { File convFile = new File(file.getOriginalFilename()); FileOutputStream fos = new FileOutputStream(convFile); fos.write(file.getBytes()); fos.close(); return convFile; } catch (FileNotFoundException e) { throw new FileNotFoundException(e.getMessage()); } catch (IOException e) { throw new IOException(e.getMessage()); } } //Genero el nombre del archivo con el horario actual y el nombre del archivo private String generateFileName(MultipartFile multiPart) { return new Date().getTime() + "-" + multiPart.getOriginalFilename().replace(" ", "_"); } //Este metodo sube el archivo al bucket en amazon s3, tambien lo setea como publico //es decir, cualquier usuario solo con la url puede obtenerlo en la web private void uploadFileTos3bucket(String fileName, File file) { s3Client.putObject(new PutObjectRequest(bucketName, fileName, file) .withCannedAcl(CannedAccessControlList.PublicRead)); } //Esta funcion es la que llama el service, se encarga de convertir a tipo File, generar nombre //generar la url del archivo, y subirlo. public String uploadFile(MultipartFile multipartFile) throws Exception { String fileUrl = ""; try { File file = convertMultiPartToFile(multipartFile); String fileName = generateFileName(multipartFile); fileUrl = endpointUrl + "/" + bucketName + "/" + fileName; uploadFileTos3bucket(fileName, file); file.delete(); } catch (FileNotFoundException e) { throw new FileNotFoundException(e.getMessage()); } catch (IOException e) { throw new IOException(e.getMessage()); } catch (Exception e) { throw new Exception(e.getMessage()); } return fileUrl; } //Esta funcion elimina un archivo del bucket solo con su url public String deleteFileFromS3Bucket(String fileUrl) throws Exception { try { String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1); if(s3Client.doesObjectExist(bucketName, fileName)){ s3Client.deleteObject(bucketName,fileName); return "Successfully deleted"; } throw new FileNotFoundException("File url dont matches with any object in the bucket"); } catch (SdkClientException e) { throw new SdkClientException(e.getMessage()); } catch (AmazonClientException e) { throw new AmazonClientException(e.getMessage()); } catch (Exception e) { throw new Exception(e.getMessage()); } } }
40.225225
150
0.691377
a4a989e3d81cdabf0002670b490c12e949d5cee5
200
package dk.schau.SchemingMind.SchemingMindActivity; public interface ISchemingMindClient { public void setUsername(String username); public void setPassword(String password); public void run(); }
25
51
0.815
6f33b8ccf862d1940e28c916094e489c6c8db7c5
1,723
/*- * #%L * Yet Another Plugin Framework * %% * Copyright (C) 2017 Fabian Damken * %% * 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. * #L% */ package com.dmken.oss.yapf.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.dmken.oss.yapf.util.Environment; /** * Spring auto-configuration for YAPF. * * <p> * This creates all beans for plugin loading and plugin management, populates * the {@link SpringContextHolder} as a bean and prepares YAPF to work seamless * with Spring. * </p> * * <p> * <b> NOTE: Do not access this class without checking for a valid Spring * environment using {@link Environment#isSpring()} first! </b> * </p> */ @SuppressWarnings("javadoc") @Configuration public class YapfAutoConfiguration { @Bean public SpringContextHolder springContextHolder(final ApplicationContext applicationContext, final ApplicationEventPublisher applicationEventPublisher) { return new SpringContextHolder(applicationContext, applicationEventPublisher); } }
33.134615
95
0.748114
f32652415fa35298054c7859be0f08ea9d634a5a
3,317
package de.codingair.warpsystem.commands; import de.codingair.codingapi.server.Sound; import de.codingair.codingapi.server.commands.BaseComponent; import de.codingair.codingapi.server.commands.CommandBuilder; import de.codingair.codingapi.server.commands.CommandComponent; import de.codingair.codingapi.server.commands.MultiCommandComponent; import de.codingair.warpsystem.WarpSystem; import de.codingair.warpsystem.gui.affiliations.Category; import de.codingair.warpsystem.gui.guis.GWarps; import de.codingair.warpsystem.language.Example; import de.codingair.warpsystem.language.Lang; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.io.IOException; import java.util.List; public class CWarps extends CommandBuilder { public CWarps() { super("Warps", new BaseComponent() { @Override public void noPermission(CommandSender sender, String label, CommandComponent child) { } @Override public void onlyFor(boolean player, CommandSender sender, String label, CommandComponent child) { sender.sendMessage(Lang.getPrefix() + Lang.get("Only_For_Players", new Example("ENG", "This action is only for players!"), new Example("GER", "Diese Aktion ist nur für Spieler!"))); } @Override public void unknownSubCommand(CommandSender sender, String label, String[] args) { run(sender, null); } @Override public boolean runCommand(CommandSender sender, String label, String[] args) { run(sender, null); return false; } }.setOnlyPlayers(true), true); try { setHighestPriority(WarpSystem.getInstance().getFileManager().getFile("Config").getConfig().getBoolean("WarpSystem.Dominate_In_Commands.Highest_Priority.Warps", true)); } catch(Exception e) { e.printStackTrace(); } getBaseComponent().addChild(new MultiCommandComponent() { @Override public void addArguments(CommandSender sender, List<String> suggestions) { for(Category c : WarpSystem.getInstance().getIconManager().getCategories()) { suggestions.add(c.getNameWithoutColor()); } } @Override public boolean runCommand(CommandSender sender, String label, String argument, String[] args) { run(sender, WarpSystem.getInstance().getIconManager().getCategory(argument)); return false; } }); } static void run(CommandSender sender, Category category) { Player p = (Player) sender; if(!WarpSystem.activated) return; if(WarpSystem.maintenance && !p.hasPermission(WarpSystem.PERMISSION_ByPass_Maintenance)) { p.sendMessage(Lang.getPrefix() + Lang.get("Warning_Maintenance", new Example("ENG", "&cThe WarpSystem is currently in maintenance mode, please try it later again."), new Example("GER", "&cDas WarpSystem ist momentan im Wartungs-Modus, bitte versuche es später erneut."))); return; } new GWarps(p, category, false).open(); Sound.LEVEL_UP.playSound(p); } }
40.45122
197
0.653904
76fd4c71c6de0893a0e8fbf5c25c0597767bb8b6
396
package com.siimkinks.sqlitemagic.intellij.plugin.provider; import com.intellij.codeInspection.InspectionToolProvider; import com.siimkinks.sqlitemagic.intellij.plugin.inspection.SqliteMagicInspection; public class SqliteMagicInspectionProvider implements InspectionToolProvider { @Override public Class[] getInspectionClasses() { return new Class[]{SqliteMagicInspection.class}; } }
33
82
0.833333
f349a366c786c0712d1ce62809f98379352ae048
407
package monster.entity; import java.io.Serializable; public class RankItem implements Serializable { private int score; private User user; public void setScore(int score) { this.score = score; } public void setUser(User user) { this.user = user; } public int getScore() { return score; } public User getUser() { return user; } }
16.28
47
0.60688
ed97f8584df2a75d08834cb42e8330d72bb02885
3,388
package structures.results; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import structures.MetricResultNotifier; import structures.metrics.NamespaceMetric; public class NamespaceMetricResult implements MetricResultNotifier<NamespaceMetric> { private Map<String, NamespaceMetric> namespaceMetrics; private double typesPerNamespace[]; private int number = 0; public NamespaceMetricResult() { namespaceMetrics = new LinkedHashMap<>(); } @Override public void setTop(int number) { this.number = number; } @Override public void add(NamespaceMetric metric) { if (!namespaceMetrics.containsKey(metric.getName())) namespaceMetrics.put(metric.getName(), metric); else { NamespaceMetric nmm = namespaceMetrics.get(metric.getName()); nmm.addNumOfTypes(); namespaceMetrics.replace(metric.getName(), nmm); } } public Map<String, NamespaceMetric> getNamespaceMetrics() { return namespaceMetrics; } public LinkedHashMap<String, NamespaceMetric> getSortedNamespaceMetrics() { return namespaceMetrics.entrySet().stream().sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); } public Set<String> getNamespacesName() { return namespaceMetrics.keySet(); } public NamespaceMetric getNamespace(String name) { return namespaceMetrics.get(name); } public int getTotalNumberOfTypes() { int totalTypes = 0; for (String name : this.getNamespacesName()) { NamespaceMetric namespace = this.getNamespace(name); totalTypes += namespace.getNumOfTypes(); } return totalTypes; } public int getTotalNumberOfNamespaces() { return this.getNamespacesName().size() > 0? this.getNamespacesName().size() : 1; } public Set<String> getNamesResult() { Set<String> names = (number > 0) ? getSortedNamespaceMetricsWithLimit() : getSortedNamespaceMetrics().keySet(); return names; } private Set<String> getSortedNamespaceMetricsWithLimit() { List<String> namespaceList = new ArrayList<>(getSortedNamespaceMetrics().keySet()); return new LinkedHashSet<>( namespaceList.subList(0, number > namespaceList.size() ? namespaceList.size() : number)); } public int getTotalNumberOfAbstractTypes() { int totalAbstractTypes = 0; for (String name : this.getNamespacesName()) { NamespaceMetric namespace = this.getNamespace(name); totalAbstractTypes += namespace.getNumOfAbstractTypes(); } return totalAbstractTypes; } public double getInstability(double ca, double ce) { return (ca + ce > 0) ? ce / (ca + ce) : 0; } public double getAbstractness(double nac, double noc) { return nac / noc; } public double getDistance(double abstractness, double instability) { double distance = abstractness + instability - 1; return distance >= 0 ? distance : distance * (-1); } public void defineNumberOfTypesPerNamespace() { typesPerNamespace = new double[getTotalNumberOfNamespaces()]; int position = 0; for (String name : this.getNamespacesName()) { NamespaceMetric namespace = this.getNamespace(name); typesPerNamespace[position++] = namespace.getNumOfTypes(); } } public double[] getTypesPerNamespace() { return typesPerNamespace; } }
29.46087
113
0.743211
4ffee583ca4806211c0b5a42609ab5ae62c20c4a
1,826
package eap.web.filter; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import eap.util.StringUtil; import eap.util.UrlUtil; /** * <p> Title: </p> * <p> Description: </p> * @作者 chiknin@gmail.com * @创建时间 * @版本 1.00 * @修改记录 * @see org.springframework.web.filter.CharacterEncodingFilter * <pre> * 版本 修改人 修改时间 修改内容描述 * ---------------------------------------- * * ---------------------------------------- * </pre> */ public class CharacterEncodingFilter extends EnhanceFilter { private String encoding; private boolean forceEncoding = false; private String onceCharsetParamName = "_charset"; @Override protected void doFilterCleaned(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String charset = UrlUtil.getUrlQueryStringAsMap(request.getQueryString()).get(onceCharsetParamName); if (StringUtil.isBlank(charset)) { charset = encoding; } if (charset != null && (this.forceEncoding || request.getCharacterEncoding() == null)) { request.setCharacterEncoding(charset); if (this.forceEncoding) { response.setCharacterEncoding(charset); } } filterChain.doFilter(request, response); } public void setEncoding(String encoding) { this.encoding = encoding; } public void setForceEncoding(boolean forceEncoding) { this.forceEncoding = forceEncoding; } public String getOnceCharsetParamName() { return onceCharsetParamName; } public void setOnceCharsetParamName(String onceCharsetParamName) { this.onceCharsetParamName = onceCharsetParamName; } }
27.666667
115
0.684009
a504830cb5e5e3eb8ff176f5b7a1324f15e8b425
2,910
/** * Steven Ward * RoomCarpet.java | Carpet Calculator Project * * This file contains the definition of the RoomCarpet class, which is described below. * * Due Date: October 09, 2016 * */ /** * RoomCarpet class to "wrap" the general process of determining the cost to carpet a room. * The 'RoomCarpet' class serves as a sort of "model" component for this (Carpet Calculator) * program. It stores user input in its two member fields: 1) 'size', which stores length and width * values retrieved from the user and calculates the corresponding area, and 2) 'carpetCost' to hold * the price per square foot of carpet provided by the user. With those above fields containing * acceptable values, the total cost to carpet a room can be calculated by the 'getTotalCost()' * member function and presented to the user, along with the data, with th 'toString()' member * function. * */ public class RoomCarpet { private final RoomDimension size; // dimensions of the room, given as RoomDimension object private final double carpetCost; // unit cost of the carpet, in dollars per square foot /** * Sole constructor. * Creates an instance of the RoomCarpet class from two parameters, which are used to initialize * the corresponding member fields for the instance. * * @param dim RoomDimension object containing the length and width of the room * @param cost double value representing the carpet's unit cost in dollars per square foot * * @see #size * @see #carpetCost * @see RoomDimension#length * @see RoomDimension#width * @see RoomDimension#RoomDimension(double,double) * */ public RoomCarpet(RoomDimension dim, double cost) { this.size = dim; this.carpetCost = cost; } /** * Calculates the total cost of carpeting a room. * Uses the getArea() function of the instance's size member, and the value of its carpetCost * member to determine the total cost of carpeting the room represented by its RoomCarpet * instance. * * @return double value representing the total cost of carpeting * * @see #size * @see #carpetCost * @see RoomDimension#getArea() * */ public double getTotalCost() { return this.size.getArea() * this.carpetCost; } /** * Translates the instance's data into a String object. * Generates a String which expresses the data contained in the instance's size member (through * the object's own toString() member function) and carpetCost member. * * @return String containing the relevant data corresponding to the instance * * @see #size * @see #carpetCost * @see RoomDimension#toString() * */ public String toString() { return ( this.size.toString() + ", which at $" + this.carpetCost + " per sq ft, will cost a total of $" + this.getTotalCost() ); } }
35.487805
132
0.685911
44da09b19c4555e62c1a918464c6257fe924d926
1,060
package br.com.zupacademy.mario.proposta.domain.Cartao; import java.time.Instant; import java.time.LocalDate; import java.util.UUID; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity(name = "aviso_viagem") public class AvisoViagem { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private LocalDate validoAte; private String destino; private UUID uuid = UUID.randomUUID(); private String ipDaSolicitacao; private String userAgentDaSolicitacao; private Instant instante = Instant.now(); @ManyToOne private Cartao cartao; @Deprecated public AvisoViagem() {} public AvisoViagem(LocalDate validoAte, String destino, Cartao cartao, String ipDaSolicitacao, String userAgentDaSolicitacao) { this.validoAte = validoAte; this.destino = destino; this.cartao = cartao; this.ipDaSolicitacao = ipDaSolicitacao; this.userAgentDaSolicitacao = userAgentDaSolicitacao; } }
23.555556
95
0.790566
379d997e34568719fbc3a07bf1c37a80259c3acb
1,719
package ir.component.core.engine; import ir.component.core.dao.model.Car; import org.springframework.stereotype.Repository; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; import javax.annotation.Resource; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; /** * @author Mohammad Yasin Kaji */ @Repository @Transactional public class CarDao { @PersistenceContext(name = "securityPersistentContext") private EntityManager entityManager; @Resource private TransactionTemplate transactionTemplate; @Transactional public void persist(final Car car) { // EntityTransaction transaction = entityManager.getTransaction(); // transaction.begin(); // entityManager.persist(user); // transaction.commit(); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) { entityManager.persist(car); } }); } @Transactional public List<Car> allCars() { return transactionTemplate.execute(new TransactionCallback<List<Car>>() { public List<Car> doInTransaction(TransactionStatus transactionStatus) { return (List<Car>) entityManager.createQuery("from Car").getResultList(); } }); } }
31.833333
94
0.733566
e9c2b293619bdf0f043caac759c34a10fee59177
773
package com.byznass.tiolktrack.kernel.crypto; import com.byznass.tiolktrack.kernel.TiolkTrackException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class TokenEncrypter { private static final Logger LOGGER = LoggerFactory.getLogger(TokenEncrypter.class); public byte[] computeHash(String token, byte[] passSalt) { try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(passSalt); return messageDigest.digest(token.getBytes()); } catch (NoSuchAlgorithmException e) { LOGGER.error("No algorithm for chosen hash type", e); throw new TiolkTrackException("No algorithm for chosen hash type", e); } } }
26.655172
84
0.776197
cb56345bf37248875dd7df79a4f23e7376a83df6
811
package zhibi.learn.controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import zhibi.learn.query.I18nQuery; import javax.validation.Valid; /** * @author 执笔 * @date 2018/12/2 19:16 */ @RestController public class I18nController { /** * i18n请求 * * @param i18nQuery * @param result * @return */ @RequestMapping("i18n") public String i18n(@Valid I18nQuery i18nQuery, BindingResult result) { StringBuilder builder = new StringBuilder(); if (result.hasErrors()) { result.getAllErrors().forEach(error -> builder.append(error.getDefaultMessage())); } return builder.toString(); } }
23.852941
94
0.683107
b1d03148fa779d3b86af7a624e13061a35742a2a
813
module slideshowfx.server { exports com.twasyl.slideshowfx.server; exports com.twasyl.slideshowfx.server.service; exports com.twasyl.slideshowfx.server.bus; exports com.twasyl.slideshowfx.server.beans.quiz; exports com.twasyl.slideshowfx.server.beans.chat; opens com.twasyl.slideshowfx.server.webapp.css; opens com.twasyl.slideshowfx.server.webapp.html; opens com.twasyl.slideshowfx.server.webapp.images; opens com.twasyl.slideshowfx.server.webapp.js; requires freemarker; requires java.logging; requires java.xml; requires javafx.graphics; requires javafx.web; requires jdk.xml.dom; requires slideshowfx.global.configuration; requires slideshowfx.icons; requires slideshowfx.utils; requires io.vertx.core; requires io.vertx.web; }
33.875
54
0.750308
4204ebccf9ed07b3504c1b84350739a6de8be859
2,843
package dp; import java.util.Arrays; /** * The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess. * * The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. * * Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers). * * To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. * * Return the knight's minimum initial health so that he can rescue the princess. * * Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. * * * * Example 1: * * Input: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]] * Output: 7 * Explanation: The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN. */ public class DungeonGame { //这题思路就是从最后的位置倒推,救完公主后必须保证health point至少为1(任何时刻骑士的血槽必须大于0,否则立即挂掉) //因此在进入最后的位置的时候,必须保证骑士的minHP = 1 - dungeon[i][j];//dungeon[i][j]是最后公主的位置 //拓展到任意一点,dp[i][j] 表示在进入位置i,j之前必须保有的最少健康值,则有dp[i][j] = Math.min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j], 如果该值小于等于0,则让dp[i][j] = 1; //since we are using last row(i + 1)'s value, we can use 1d array, and need to scan backwards each row since we are using j+ 1 at current row //初始化的时候注意,每个cell先初始化为Integer.MAX_VALUE, 然后令dp[n - 1] = 1, 即骑士的血槽救完公主后至少为1. //怎样理解minHP = Math.min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]呢 //比如我们在到达i,j之前已经知道最少需要的能量 E, 为了能达到这个能量,在i,j minHP = E - dungeon[i][j] //minHP +消耗的dungeon[i][j]才能make up to E public int calculateMinimumHP(int[][] dungeon) { if(dungeon == null || dungeon.length == 0 || dungeon[0].length == 0) return 0; int m = dungeon.length; int n = dungeon[0].length; int[] dp = new int[n + 1]; Arrays.fill(dp, Integer.MAX_VALUE);;//since we are bottoming up, we are initializing the last row with integer.max 为什么用max呢,主要是为了方便计算,Math.min(dp[i + 1][j], dp[i][j + 1]); //initialization dp[n - 1] = 1;//初始化在救完公主后骑士血槽最少为1. for(int i = m - 1; i >= 0; i--) { for(int j = n - 1; j >= 0; j--) { dp[j] = Math.min(dp[j], dp[j + 1]) - dungeon[i][j]; if(dp[j] <= 0) dp[j] = 1;//任何时候骑士的血不能等于0,最少是1 } } return dp[0]; } }
53.641509
286
0.658811
361510762b6ecef6eab65db35c71a982fcc1bb5e
15,897
package csdev.couponstash.logic.parser; import static csdev.couponstash.commons.util.DateUtil.MONTH_YEAR_VALIDATION_REGEX; import static csdev.couponstash.model.coupon.RemindDate.DATE_FORMATTER; import static java.util.Objects.requireNonNull; import java.time.LocalDate; import java.time.YearMonth; import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import csdev.couponstash.commons.core.index.Index; import csdev.couponstash.commons.util.DateUtil; import csdev.couponstash.commons.util.StringUtil; import csdev.couponstash.logic.parser.exceptions.ParseException; import csdev.couponstash.model.coupon.Condition; import csdev.couponstash.model.coupon.ExpiryDate; import csdev.couponstash.model.coupon.Limit; import csdev.couponstash.model.coupon.Name; import csdev.couponstash.model.coupon.PromoCode; import csdev.couponstash.model.coupon.RemindDate; import csdev.couponstash.model.coupon.StartDate; import csdev.couponstash.model.coupon.Usage; import csdev.couponstash.model.coupon.savings.MonetaryAmount; import csdev.couponstash.model.coupon.savings.PercentageAmount; import csdev.couponstash.model.coupon.savings.Saveable; import csdev.couponstash.model.coupon.savings.Savings; import csdev.couponstash.model.tag.Tag; /** * Contains utility methods used for parsing strings in the various *Parser classes. */ public class ParserUtil { public static final String MESSAGE_INVALID_INDEX = "Your input index of \"%s\" is not " + "a non-zero unsigned integer."; public static final String MESSAGE_INDEX_OVERFLOW = String.format("Index is too large. Why do you need so many coupons? " + "Try something less than or equals to %d.", Integer.MAX_VALUE); // used to reject user input for text that is too long to be displayed properly by Coupon Stash public static final String MESSAGE_STRING_TOO_LONG = "\"%1$s\" is too long! Length of" + " %2$d exceeds the limit of %3$d characters."; public static final String MESSAGE_TOTAL_TAGS_TOO_LONG = "The combined length of all your tags is above the " + "limit of %d. Remove/reduce some tags!"; public static final String MESSAGE_TOO_MANY_TAGS = "There are too many tags! " + "You have %1$d tags, which exceeds the limit of %2$d."; /** * Parses {@code oneBasedIndex} into an {@code Index} and returns it. Leading and trailing whitespaces will be * trimmed. * @throws ParseException if the specified index is invalid (not non-zero unsigned integer). */ public static Index parseIndex(String oneBasedIndex) throws ParseException { String trimmedIndex = oneBasedIndex.trim(); if (StringUtil.isIntegerOverflow(trimmedIndex)) { throw new ParseException(MESSAGE_INDEX_OVERFLOW); } if (!StringUtil.isNonZeroUnsignedInteger(trimmedIndex)) { throw new ParseException(String.format(MESSAGE_INVALID_INDEX, trimmedIndex)); } return Index.fromOneBased(Integer.parseInt(trimmedIndex)); } /** * Parses a {@code String name} into a {@code Name}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code name} is invalid. */ public static Name parseName(String name) throws ParseException { requireNonNull(name); String trimmedName = checkStringLength(name.trim(), Name.STRING_LENGTH_LIMIT); if (!Name.isValidName(trimmedName)) { throw new ParseException(Name.MESSAGE_CONSTRAINTS); } return new Name(trimmedName); } /** * Parses a {@code String promoCode} into a {@code PromoCode}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code promoCode} is invalid. */ public static PromoCode parsePromoCode(String promoCode) throws ParseException { requireNonNull(promoCode); String trimmedPromoCode = checkStringLength(promoCode.trim(), PromoCode.STRING_LENGTH_LIMIT); return new PromoCode(trimmedPromoCode); } /** * Parses a {@code String savings} into a {@code Savings}. * Leading and trailing whitespaces will be trimmed. * * @param savings The Collection of Strings that each represent * certain savings entered by the user. * @param moneySymbol The symbol to be used for monetary amounts, * as specified in the UserPrefs. * @throws ParseException If the given {@code savings} is invalid. * (if no savings are given, or if both a monetary amount * and a percentage amount is given) */ public static Savings parseSavings(Collection<String> savings, String moneySymbol) throws ParseException { requireNonNull(savings); boolean hasMoney = false; boolean hasPercent = false; MonetaryAmount monetaryAmount = null; PercentageAmount percentageAmount = null; List<Saveable> saveables = new ArrayList<Saveable>(); for (String str : savings) { if (str.startsWith(moneySymbol)) { if (!hasMoney) { hasMoney = true; String trimmedMonetaryAmount = str.trim().substring(moneySymbol.length()); try { monetaryAmount = new MonetaryAmount(trimmedMonetaryAmount); } catch (NumberFormatException e) { throw new ParseException(Savings.MESSAGE_CONSTRAINTS); } catch (IllegalArgumentException e) { throw new ParseException(e.getMessage()); } } else { // if more than one monetary amount, throw error throw new ParseException(Savings.MULTIPLE_NUMBER_AMOUNTS); } } else if (str.endsWith(PercentageAmount.PERCENT_SUFFIX)) { if (!hasPercent) { hasPercent = true; String trimmedPercentage = str.trim(); String rawNumber = trimmedPercentage .substring(0, trimmedPercentage.length() - PercentageAmount.PERCENT_SUFFIX.length()); try { percentageAmount = new PercentageAmount(Double.parseDouble(rawNumber)); } catch (NumberFormatException e) { throw new ParseException(Savings.MESSAGE_CONSTRAINTS); } catch (IllegalArgumentException e) { throw new ParseException(e.getMessage()); } } else { // if more than one percentage amount, throw error throw new ParseException(Savings.MULTIPLE_NUMBER_AMOUNTS); } } else { String trimmedSaveable = checkStringLength(str.trim(), Saveable.STRING_LENGTH_LIMIT); // numbers might be a mistake by the user if (trimmedSaveable.matches(".*\\d.*")) { throw new ParseException( String.format(Savings.NUMBER_DETECTED_BUT_NOT_IN_FORMAT, moneySymbol)); } if (!trimmedSaveable.isBlank()) { // avoid adding blank Strings saveables.add(new Saveable(trimmedSaveable)); } } } if ((saveables.isEmpty() && !hasMoney && !hasPercent)) { // throw an exception if no savings throw new ParseException(Savings.MESSAGE_CONSTRAINTS); } else if (hasMoney && hasPercent) { // throw an exception if savings contains both // monetary amount and percentage amount throw new ParseException(Savings.MULTIPLE_NUMBER_AMOUNTS); } else if (saveables.isEmpty()) { if (hasMoney) { return new Savings(monetaryAmount); } else { // hasPercent return new Savings(percentageAmount); } } else if (hasMoney) { return new Savings(monetaryAmount, saveables); } else if (hasPercent) { return new Savings(percentageAmount, saveables); } else { return new Savings(saveables); } } /** * Parses a {@code String expiryDate} into an {@code ExpiryDate}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code expiryDate} is invalid. */ public static ExpiryDate parseExpiryDate(String expiryDate) throws ParseException { requireNonNull(expiryDate); String trimmedDate = expiryDate.trim(); if (!DateUtil.isValidDate(trimmedDate)) { throw new ParseException(ExpiryDate.MESSAGE_CONSTRAINTS); } return new ExpiryDate(trimmedDate); } /** * Parses a {@code String yearMonth} into an {@code YearMonth}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code yearMonth} is invalid. */ public static YearMonth parseYearMonth(String yearMonth) throws ParseException { requireNonNull(yearMonth); YearMonth ym; String trimmedDate = yearMonth.trim(); try { if (!trimmedDate.matches(MONTH_YEAR_VALIDATION_REGEX)) { throw new ParseException(DateUtil.MESSAGE_YEAR_MONTH_WRONG_FORMAT); } else { ym = YearMonth.parse(trimmedDate, DateUtil.YEAR_MONTH_FORMATTER); } } catch (ParseException | DateTimeParseException pe) { throw new ParseException(DateUtil.MESSAGE_YEAR_MONTH_WRONG_FORMAT); } return ym; } /** * Parses a {@code String startDate} into an {@code StartDate}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code startDate} is invalid. */ public static StartDate parseStartDate(String startDate) throws ParseException { requireNonNull(startDate); String trimmedDate = startDate.trim(); if (!DateUtil.isValidDate(trimmedDate)) { throw new ParseException(StartDate.MESSAGE_CONSTRAINTS); } return new StartDate(trimmedDate); } /** * Parses a {@code String usage} into a {@code Usage}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code usage} is invalid. */ public static Usage parseUsage(String usage) throws ParseException { requireNonNull(usage); String trimmedUsage = usage.trim(); if (!Usage.isValidUsage(trimmedUsage)) { throw new ParseException(Usage.MESSAGE_CONSTRAINTS); } return new Usage(trimmedUsage); } /** * Parses a {@code String limit} into a {@code Limit}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code limit} is invalid. */ public static Limit parseLimit(String limit) throws ParseException { requireNonNull(limit); String trimmedLimit = limit.trim(); if (!Limit.isValidLimit(trimmedLimit)) { throw new ParseException(Limit.MESSAGE_CONSTRAINTS); } if (StringUtil.isIntegerOverflow(trimmedLimit)) { throw new ParseException(MESSAGE_INDEX_OVERFLOW); } return new Limit(trimmedLimit); } /** * Parses a {@code String condition} into a {@code Condtion}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code condition} is invalid. */ public static Condition parseCondition(String condition) throws ParseException { requireNonNull(condition); String trimmedCondition = checkStringLength(condition.trim(), Condition.STRING_LENGTH_LIMIT); if (!Condition.isValidCondition(trimmedCondition)) { throw new ParseException(Condition.MESSAGE_CONSTRAINTS); } return new Condition(trimmedCondition); } /** * Parses a {@code String monetaryAmount} into a {@code MonetaryAmount}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code originalAmount} is invalid. */ public static MonetaryAmount parseMonetaryAmount(String monetaryAmount) throws ParseException { requireNonNull(monetaryAmount); String trimmedMonetaryAmount = monetaryAmount.trim(); try { MonetaryAmount convertedMonetaryAmount = new MonetaryAmount(trimmedMonetaryAmount); return convertedMonetaryAmount; } catch (IllegalArgumentException e) { throw new ParseException(MonetaryAmount.MESSAGE_CONSTRAINTS); } } /** * Parses a {@code String tag} into a {@code Tag}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code tag} is invalid. */ public static Tag parseTag(String tag) throws ParseException { requireNonNull(tag); String trimmedTag = checkStringLength(tag.trim(), Tag.STRING_LENGTH_LIMIT); if (!Tag.isValidTagName(trimmedTag)) { throw new ParseException(Tag.MESSAGE_CONSTRAINTS); } return new Tag(trimmedTag); } /** * Parses {@code Collection<String> tags} into a {@code Set<Tag>}. */ public static Set<Tag> parseTags(Collection<String> tags) throws ParseException { requireNonNull(tags); if (tags.size() > Tag.MAX_NUMBER_OF_TAGS) { throw new ParseException(String.format(MESSAGE_TOO_MANY_TAGS, tags.size(), Tag.MAX_NUMBER_OF_TAGS)); } final Set<Tag> tagSet = new HashSet<>(); int totalLength = 0; for (String tagName : tags) { Tag trimmedTag = parseTag(tagName); tagSet.add(trimmedTag); totalLength += trimmedTag.toString().length(); } if (totalLength > Tag.TOTAL_STRING_LENGTH_LIMIT) { throw new ParseException(String.format(MESSAGE_TOTAL_TAGS_TOO_LONG, Tag.TOTAL_STRING_LENGTH_LIMIT)); } return tagSet; } /** * Parses a {@code String remindDate} into a {@code RemindDate}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code remindDate} is invalid. */ public static RemindDate parseRemindDate(String remindDate) throws ParseException { requireNonNull(remindDate); String trimmedDate = remindDate.trim(); if (!DateUtil.isValidDate(trimmedDate)) { throw new ParseException(RemindDate.MESSAGE_CONSTRAINTS); } RemindDate remind = new RemindDate(); remind.setRemindDate(LocalDate.parse(trimmedDate, DATE_FORMATTER)); return remind; } /** * Checks if a String exceeds a given limit on the * number of characters, to avoid causing problems * with the rendering of text on the UI. * * @param s The String to be checked. * @param limit The int representing the character limit. * @return Returns the original String s if it is * determined to fit within the limit. * @throws ParseException If the String s exceeds the limit. */ private static String checkStringLength(String s, int limit) throws ParseException { int currentLength = s.length(); if (currentLength > limit) { throw new ParseException(String.format(MESSAGE_STRING_TOO_LONG, s, currentLength, limit)); } return s; } }
41.077519
114
0.644084
be234ae507d21bcb9b1bb14f6a19d2941fcd2a25
1,823
package view; import control.Controller; import control.Main; import javafx.application.Application; import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.SpinnerValueFactory; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class InitialJFX extends Application { private Stage stage; private Controller controller; @Override public void start(Stage primaryStage) { try { stage = primaryStage; FXMLLoader loader = new FXMLLoader(); loader.setLocation(InitialJFX.class.getResource("sample.fxml")); //BorderPane is root element dur to fxml file BorderPane root = loader.load(); Scene scene = new Scene(root,452,219); scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.setTitle("JATanks"); controller = loader.getController(); controller.mySpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(2, 14, 2)); controller.setInitInstance(this); primaryStage.show(); } catch(Exception e) { e.printStackTrace(); } } public void sendDataToParent(){ Main.setIsDatabaseSet(controller.isDatabaseSet); Main.setTankQuantity(controller.mySpinner.getValue()); Platform.runLater(new Runner()); stage.close(); } public static void startInitialJFX(String[] args) { launch(args); } } class Runner implements Runnable{ @Override public void run() { try { new JavaFXView().start(new Stage()); }catch (Exception e){e.printStackTrace();} } }
31.431034
111
0.657159
47fec103bc67ce6049e6cafcb7c2976930f75307
3,089
/** * Copyright 2016 Antony Holmes * * 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 edu.columbia.rdf.matcalc.toolbox.plot.heatmap.legacy; import java.util.List; import org.jebtk.core.Props; import org.jebtk.graphplot.figure.heatmap.legacy.CountGroups; import org.jebtk.graphplot.figure.series.XYSeriesGroup; import org.jebtk.graphplot.figure.series.XYSeriesModel; import org.jebtk.math.matrix.DataFrame; import org.jebtk.modern.window.ModernRibbonWindow; import edu.columbia.rdf.matcalc.figure.FormatPlotPane; /** * Merges designated segments together using the merge column. Consecutive rows * with the same merge id will be merged together. Coordinates and copy number * will be adjusted but genes, cytobands etc are not. * * @author Antony Holmes * */ public abstract class DifferentialExpressionPlotWindow extends HeatMapWindow { /** * The constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** The m comparison groups. */ private XYSeriesGroup mComparisonGroups; /** * Instantiates a new pattern discovery plot window. * * @param window the window * @param name the name * @param matrix the matrix * @param groups the all groups * @param comparisonGroups the comparison groups * @param rowGroups the row groups * @param countGroups the count groups * @param history the history * @param Props the properties */ public DifferentialExpressionPlotWindow(ModernRibbonWindow window, String name, DataFrame matrix, XYSeriesModel groups, XYSeriesGroup comparisonGroups, XYSeriesModel rowGroups, CountGroups countGroups, List<String> history, Props properties) { super(window, matrix, groups, rowGroups, countGroups, history, properties); mComparisonGroups = comparisonGroups; setFormatPane(); } /* * @Override public void setMatrix(DataFrame matrix) { super.setMatrix(matrix); * * setFormatPane(); } */ /** * Sets the format pane. */ public void setFormatPane() { setFormatPane(createFormatPane()); } /** * Creates the format pane. * * @return the format plot pane */ public FormatPlotPane createFormatPane() { return new DifferentialExpressionPanel(this, mMatrix, mGroups, mComparisonGroups, mRowGroups, mZoomModel, mColorMapModel, mColorModel, mScaleModel, tabsPane().tabs(), mCountGroups, mHistory, mProps); } }
33.215054
110
0.697637