repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
sathyavikram-ksu/sppam-api
src/main/java/com/group1/sppam/repository/EffortRepository.java
<reponame>sathyavikram-ksu/sppam-api<gh_stars>0 package com.group1.sppam.repository; import com.group1.sppam.models.Effort; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface EffortRepository extends CrudRepository<Effort, Long> { List<Effort> findAllByRequirement_IdOrderByCreatedAtDesc(Long id); }
mjorod/textram
tool/ca.mcgill.sel.ram/src/ca/mcgill/cs/sel/ram/impl/RLongImpl.java
/** */ package ca.mcgill.cs.sel.ram.impl; import ca.mcgill.cs.sel.ram.RLong; import ca.mcgill.cs.sel.ram.RamPackage; import java.lang.reflect.InvocationTargetException; import org.eclipse.emf.common.util.WrappedException; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EOperation; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>RLong</b></em>'. * <!-- end-user-doc --> * <p> * </p> * * @generated */ public class RLongImpl extends PrimitiveTypeImpl implements RLong { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected RLongImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return RamPackage.Literals.RLONG; } /** * The cached invocation delegate for the '{@link #getName() <em>Get Name</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected static final EOperation.Internal.InvocationDelegate GET_NAME__EINVOCATION_DELEGATE = ((EOperation.Internal)RamPackage.Literals.RLONG.getEOperations().get(0)).getInvocationDelegate(); /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { try { return (String)GET_NAME__EINVOCATION_DELEGATE.dynamicInvoke(this, null); } catch (InvocationTargetException ite) { throw new WrappedException(ite); } } /** * The cached invocation delegate for the '{@link #getInstanceClassName() <em>Get Instance Class Name</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getInstanceClassName() * @generated * @ordered */ protected static final EOperation.Internal.InvocationDelegate GET_INSTANCE_CLASS_NAME__EINVOCATION_DELEGATE = ((EOperation.Internal)RamPackage.Literals.RLONG.getEOperations().get(1)).getInvocationDelegate(); /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getInstanceClassName() { try { return (String)GET_INSTANCE_CLASS_NAME__EINVOCATION_DELEGATE.dynamicInvoke(this, null); } catch (InvocationTargetException ite) { throw new WrappedException(ite); } } } //RLongImpl
masrice/megamol
core/src/param/FilePathParam.cpp
<reponame>masrice/megamol<filename>core/src/param/FilePathParam.cpp /* * FilePathParam.cpp * * Copyright (C) 2008 by Universitaet Stuttgart (VIS). * Alle Rechte vorbehalten. */ #include "mmcore/param/FilePathParam.h" #include "mmcore/utility/FileUtils.h" #include "stdafx.h" using namespace megamol::core::param; FilePathParam::FilePathParam(const std::filesystem::path& initVal, Flags_t flags, const Extensions_t& exts) : AbstractParam() , flags(flags) , extensions(exts) , value() { this->InitPresentation(AbstractParamPresentation::ParamType::FILEPATH); this->SetValue(initVal); } FilePathParam::FilePathParam(const std::string& initVal, Flags_t flags, const Extensions_t& exts) : FilePathParam(std::filesystem::u8path(initVal), flags, exts){}; FilePathParam::FilePathParam(const char* initVal, Flags_t flags, const Extensions_t& exts) : FilePathParam(std::filesystem::u8path(initVal), flags, exts){}; std::string FilePathParam::Definition() const { return "MMFILA"; } bool FilePathParam::ParseValue(std::string const& v) { try { this->SetValue(v); return true; } catch (...) {} return false; } void FilePathParam::SetValue(const std::filesystem::path& v, bool setDirty) { try { auto new_value = v; if (this->value != new_value) { auto error_flags = FilePathParam::ValidatePath(new_value, this->extensions, this->flags); if (error_flags & Flag_File) { megamol::core::utility::log::Log::DefaultLog.WriteWarn( "[FilePathParam] Omitting value '%s'. Expected file but directory is given.", new_value.generic_u8string().c_str()); } if (error_flags & Flag_Directory) { megamol::core::utility::log::Log::DefaultLog.WriteWarn( "[FilePathParam] Omitting value '%s'. Expected directory but file is given.", new_value.generic_u8string().c_str()); } if (error_flags & Flag_NoExistenceCheck) { megamol::core::utility::log::Log::DefaultLog.WriteWarn( "[FilePathParam] Omitting value '%s'. File does not exist.", new_value.generic_u8string().c_str()); } if (error_flags & Flag_RestrictExtension) { std::string log_exts; for (auto& ext : this->extensions) { log_exts += "'." + ext + "' "; } megamol::core::utility::log::Log::DefaultLog.WriteWarn( "[FilePathParam] Omitting value '%s'. File does not have required extension: %s", new_value.generic_u8string().c_str(), log_exts.c_str()); } if (error_flags == 0) { this->value = new_value; this->indicateChange(); if (setDirty) this->setDirty(); } } } catch (std::filesystem::filesystem_error& e) { megamol::core::utility::log::Log::DefaultLog.WriteError( "Filesystem Error: %s [%s, %s, line %d]\n", e.what(), __FILE__, __FUNCTION__, __LINE__); } } void megamol::core::param::FilePathParam::SetValue(const std::string& v, bool setDirty) { this->SetValue(std::filesystem::u8path(v), setDirty); } void megamol::core::param::FilePathParam::SetValue(const char* v, bool setDirty) { this->SetValue(std::filesystem::u8path(v), setDirty); } FilePathParam::Flags_t FilePathParam::ValidatePath(const std::filesystem::path& p, const Extensions_t& e, Flags_t f) { try { FilePathParam::Flags_t retval = 0; if ((f & FilePathParam::Flag_File) && std::filesystem::is_directory(p)) { retval |= FilePathParam::Flag_File; } if ((f & FilePathParam::Flag_Directory) && std::filesystem::is_regular_file(p)) { retval |= FilePathParam::Flag_Directory; } if (!(f & Flag_NoExistenceCheck) && !std::filesystem::exists(p)) { retval |= FilePathParam::Flag_NoExistenceCheck; } if (f & FilePathParam::Flag_RestrictExtension) { bool valid_ext = false; for (auto& ext : e) { if (p.extension().generic_u8string() == std::string("." + ext)) { valid_ext = true; } } if (!valid_ext) { retval |= FilePathParam::Flag_RestrictExtension; } } return retval; } catch (std::filesystem::filesystem_error& e) { megamol::core::utility::log::Log::DefaultLog.WriteError( "Filesystem Error: %s [%s, %s, line %d]\n", e.what(), __FILE__, __FUNCTION__, __LINE__); return 0; } }
makkrnic/simutrans-extended
gui/halt_list_stats.cc
/* * This file is part of the Simutrans-Extended project under the Artistic License. * (see LICENSE.txt) */ #include "halt_list_stats.h" #include "../simhalt.h" #include "../simskin.h" #include "../simcolor.h" #include "../display/simgraph.h" #include "../display/viewport.h" #include "../player/simplay.h" #include "../simworld.h" #include "../display/simimg.h" #include "../dataobj/translator.h" #include "../descriptor/skin_desc.h" #include "../utils/cbuffer_t.h" #include "../utils/simstring.h" #include "gui_frame.h" /** * Events werden hiermit an die GUI-components * gemeldet * @author <NAME> */ bool halt_list_stats_t::infowin_event(const event_t *ev) { if(halt.is_bound()) { if(IS_LEFTRELEASE(ev)) { if (event_get_last_control_shift() != 2) { halt->show_info(); } return true; } if(IS_RIGHTRELEASE(ev)) { welt->get_viewport()->change_world_position(halt->get_basis_pos3d()); return true; } } return false; } /** * Draw the component * @author <NAME> */ void halt_list_stats_t::draw(scr_coord offset) { clip_dimension clip = display_get_clip_wh(); if( !( (pos.y+offset.y)>clip.yy || (pos.y+offset.y)<clip.y-32 ) && halt.is_bound()) { // status now in front display_fillbox_wh_clip(pos.x+offset.x+4, pos.y+offset.y+6, 26, D_INDICATOR_HEIGHT, halt->get_status_farbe(), true); // name int left = pos.x + offset.x + 32+2 + display_proportional_clip(pos.x + offset.x + 32+2, pos.y + offset.y + 2, translator::translate(halt->get_name()), ALIGN_LEFT, SYSCOL_TEXT, true); // what kind of stop haltestelle_t::stationtyp const halttype = halt->get_station_type(); int pos_y = pos.y+offset.y-41; if (halttype & haltestelle_t::railstation && skinverwaltung_t::zughaltsymbol) { display_color_img(skinverwaltung_t::zughaltsymbol->get_image_id(0), left, pos_y, 0, false, true); left += 23; } if (halttype & haltestelle_t::loadingbay && skinverwaltung_t::autohaltsymbol) { display_color_img(skinverwaltung_t::autohaltsymbol->get_image_id(0), left, pos_y, 0, false, true); left += 23; } if (halttype & haltestelle_t::busstop && skinverwaltung_t::bushaltsymbol) { display_color_img(skinverwaltung_t::bushaltsymbol->get_image_id(0), left, pos_y, 0, false, true); left += 23; } if (halttype & haltestelle_t::dock && skinverwaltung_t::schiffshaltsymbol) { display_color_img(skinverwaltung_t::schiffshaltsymbol->get_image_id(0), left, pos_y, 0, false, true); left += 23; } if (halttype & haltestelle_t::airstop && skinverwaltung_t::airhaltsymbol) { display_color_img(skinverwaltung_t::airhaltsymbol->get_image_id(0), pos.x+left, pos_y, 0, false, true); left += 23; } if (halttype & haltestelle_t::monorailstop && skinverwaltung_t::monorailhaltsymbol) { display_color_img(skinverwaltung_t::monorailhaltsymbol->get_image_id(0), pos.x+left, pos_y, 0, false, true); left += 23; } if (halttype & haltestelle_t::tramstop && skinverwaltung_t::tramhaltsymbol) { display_color_img(skinverwaltung_t::tramhaltsymbol->get_image_id(0), pos.x+left, pos_y, 0, false, true); left += 23; } if (halttype & haltestelle_t::maglevstop && skinverwaltung_t::maglevhaltsymbol) { display_color_img(skinverwaltung_t::maglevhaltsymbol->get_image_id(0), pos.x+left, pos_y, 0, false, true); left += 23; } if (halttype & haltestelle_t::narrowgaugestop && skinverwaltung_t::narrowgaugehaltsymbol) { display_color_img(skinverwaltung_t::narrowgaugehaltsymbol->get_image_id(0), pos.x+left, pos_y, 0, false, true); left += 23; } // now what do we accept here? pos_y = pos.y+offset.y+14; left = pos.x+offset.x+2; if (halt->get_pax_enabled()) { display_color_img(skinverwaltung_t::passengers->get_image_id(0), left, pos_y, 0, false, true); left += 10; } if (halt->get_mail_enabled()) { display_color_img(skinverwaltung_t::mail->get_image_id(0), left, pos_y, 0, false, true); left += 10; } if (halt->get_ware_enabled()) { display_color_img(skinverwaltung_t::goods->get_image_id(0), left, pos_y, 0, false, true); left += 10; } static cbuffer_t buf; buf.clear(); halt->get_short_freight_info(buf); display_proportional_clip(pos.x+offset.x+32+2, pos_y, buf, ALIGN_LEFT, SYSCOL_TEXT, true); } }
saydulk/parliamentary-questions
db/migrate/20150428133026_clean_stats_data.rb
class CleanStatsData < ActiveRecord::Migration def change ActiveRecord::Base.connection.execute( "UPDATE action_officers_pqs " + "SET updated_at = created_at " + "WHERE action_officer_id = 497;" ) ActiveRecord::Base.connection.execute( "UPDATE action_officers_pqs " + "SET created_at = pqs.created_at FROM pqs " + "WHERE action_officers_pqs.action_officer_id = 497 " + "AND action_officers_pqs.pq_id = pqs.id;" ) end end
GitHubYangZhiwen/arcgis-js-siteapp-3.x
widgets/BatchAttributeEditor/nls/nl/strings.js
<reponame>GitHubYangZhiwen/arcgis-js-siteapp-3.x<filename>widgets/BatchAttributeEditor/nls/nl/strings.js define({ "_widgetLabel": "Batch Attribute Editor", "widgetIntroSelectByArea": "Gebruik een van de tools hieronder om een selectie van objecten te maken om bij te werken. Als de rij is <font class='maxRecordInIntro'>gemarkeerd</font>, dan is het maximum aantal gegevens overschreden.", "widgetIntroSelectByFeature": "Gebruik de tool hieronder om een object te kiezen uit de <font class='layerInIntro'>${0}</font>-laag. Dit object wordt gebruikt om alle overeenkomende objecten te selecteren en bij te werken. Als de rij is <font class='maxRecordInIntro'>gemarkeerd</font>, dan is het maximum aantal gegevens overschreden.", "widgetIntroSelectByFeatureQuery": "Gebruik de tool hieronder om een object te kiezen uit <font class='layerInIntro'>${0}</font>. Het <font class='layerInIntro'>${1}</font>-attribuut van dit object wordt gebruikt om de lagen eronder te queryen en de resulterende objecten te updaten. Als de rij is <font class='maxRecordInIntro'>gemarkeerd</font>, dan is het maximum aantal gegevens overschreden.", "widgetIntroSelectByQuery": "Voer een waarde in om een geselecteerde set te creëren. Als de rij is <font class='maxRecordInIntro'>gemarkeerd</font>, dan is het maximum aantal gegevens overschreden.", "layerTable": { "colLabel": "Laagnaam", "numSelected": "#", "colSyncStatus": "" }, "noConfiguredLayers": "Geen bewerkbare lagen geconfigureerd", "editorPopupTitle": "Batch Attribute Editor", "editorPopupSaveBtn": "Opslaan", "editorPopupMultipleValues": "", "clear": "Wissen", "featuresUpdated": "${0} / ${1} object(en) geactualiseerd", "featuresSelected": "${0} object(en) geselecteerd", "featuresSkipped": "Omgeleid", "search": "Zoeken", "queryInput": "Voer querywaarde in", "noFilterTip": "Zonder filterexpressie zal deze querytaak alle functies in de opgegeven gegevensbron weergeven.", "setFilterTip": "Stel het filter correct in.", "filterPopup": "Filter laag", "filterAppend": "Als er een kaartfilter bestaat", "filterAppendOR": "Eén expressie toevoegen aan bestaande kaartfilter", "filterAppendAND": "Alle expressies toevoegen aan bestaande kaartfilter", "cancel": "Annuleren", "noValue": "Geen waarde", "emptyString": "Lege tekenreeks", "existingValue": "Bestaande waarde gebruiken", "newDate": "Nieuwe gegevens", "valueChooser": "Selecteer/type een waarde", "ok": "OK", "drawBox": { "point": "Punt", "line": "Lijn", "polyline": "Polylijn", "freehandPolyline": "Polylijn in vrije stijl", "extent": "Extent", "polygon": "Vlak", "freehandPolygon": "Veelhoek in vrije stijl", "clear": "Wissen", "addPointToolTip": "Klik om in dit gebied te selecteren", "addShapeToolTip": "Teken een vorm om objecten te selecteren", "freehandToolTip": "Houd ingedrukt om een vorm te tekenen om objecten te selecteren", "startToolTip": "Teken een vorm om objecten te selecteren" }, "errors": { "layerNotFound": "Laag ${0} met ID ${1} werd niet gevonden in de kaart, de kaart is mogelijk gewijzigd sinds de configuratie van de widget", "queryNullID": "Het object van ${0} gaf een ongeldige ID", "noSelectedLayers": "Geen geselecteerde lagen met te actualiseren records", "inputValueError": "Ongeldige waarde in de vorm", "saveError": "Kan ${0} objecten niet opslaan, details toegevoegd aan console", "requiredValue": "Vereiste waarde" } });
mosoft521/lemon
src/main/java/com/mossle/internal/sendmail/service/SendmailDataService.java
package com.mossle.internal.sendmail.service; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import java.util.List; import java.util.Map; import javax.annotation.Resource; import com.mossle.api.store.StoreDTO; import com.mossle.client.store.StoreClient; import com.mossle.core.mail.MailDTO; import com.mossle.core.mail.MailHelper; import com.mossle.core.mail.MailServerInfo; import com.mossle.core.mapper.BeanMapper; import com.mossle.core.mapper.JsonMapper; import com.mossle.core.store.DataSourceInputStreamSource; import com.mossle.core.template.TemplateService; import com.mossle.core.util.StringUtils; import com.mossle.internal.sendmail.persistence.domain.SendmailApp; import com.mossle.internal.sendmail.persistence.domain.SendmailAttachment; import com.mossle.internal.sendmail.persistence.domain.SendmailConfig; import com.mossle.internal.sendmail.persistence.domain.SendmailHistory; import com.mossle.internal.sendmail.persistence.domain.SendmailQueue; import com.mossle.internal.sendmail.persistence.domain.SendmailTemplate; import com.mossle.internal.sendmail.persistence.manager.SendmailConfigManager; import com.mossle.internal.sendmail.persistence.manager.SendmailHistoryManager; import com.mossle.internal.sendmail.persistence.manager.SendmailQueueManager; import com.mossle.internal.sendmail.persistence.manager.SendmailTemplateManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class SendmailDataService { private static Logger logger = LoggerFactory .getLogger(SendmailDataService.class); private SendmailConfigManager sendmailConfigManager; private SendmailQueueManager sendmailQueueManager; private SendmailHistoryManager sendmailHistoryManager; private SendmailTemplateManager sendmailTemplateManager; private StoreClient storeClient; private BeanMapper beanMapper = new BeanMapper(); private MailHelper mailHelper; private TemplateService templateService; private JsonMapper jsonMapper = new JsonMapper(); public void send(String to, String subject, String content, String configCode, String tenantId) { SendmailConfig sendmailConfig = sendmailConfigManager.findUnique( "from SendmailConfig where name=? and tenantId=?", configCode, tenantId); SendmailQueue sendmailQueue = new SendmailQueue(); sendmailQueue.setReceiver(to); sendmailQueue.setSubject(subject); sendmailQueue.setContent(content); sendmailQueue.setSendmailConfig(sendmailConfig); sendmailQueue.setTenantId(tenantId); sendmailQueueManager.save(sendmailQueue); } public void sendTemplate(String to, String data, String templateCode, String configCode, String tenantId) { SendmailConfig sendmailConfig = sendmailConfigManager.findUnique( "from SendmailConfig where name=? and tenantId=?", configCode, tenantId); SendmailTemplate sendmailTemplate = sendmailTemplateManager.findUnique( "from SendmailTemplate where name=? and tenantId=?", templateCode, tenantId); SendmailQueue sendmailQueue = new SendmailQueue(); sendmailQueue.setReceiver(to); sendmailQueue.setData(data); sendmailQueue.setSendmailTemplate(sendmailTemplate); sendmailQueue.setSendmailConfig(sendmailConfig); sendmailQueue.setTenantId(tenantId); sendmailQueueManager.save(sendmailQueue); } public void saveSendmailQueue(String from, String to, String subject, String content, long sendmailConfigId) { SendmailConfig sendmailConfig = sendmailConfigManager .get(sendmailConfigId); SendmailQueue sendmailQueue = new SendmailQueue(); sendmailQueue.setSender(from); sendmailQueue.setReceiver(to); sendmailQueue.setSubject(subject); sendmailQueue.setContent(content); sendmailQueue.setSendmailConfig(sendmailConfig); sendmailQueue.setTenantId(sendmailConfig.getTenantId()); sendmailQueueManager.save(sendmailQueue); } public void saveSendmailQueue(String from, String to, String subject, String content, String tenantId) { SendmailQueue sendmailQueue = new SendmailQueue(); sendmailQueue.setSender(from); sendmailQueue.setReceiver(to); sendmailQueue.setSubject(subject); sendmailQueue.setContent(content); sendmailQueue.setTenantId(tenantId); sendmailQueueManager.save(sendmailQueue); } public List<SendmailQueue> findTopSendmailQueues(int size, String tenantId) { return (List<SendmailQueue>) sendmailQueueManager.pagedQuery( "from SendmailQueue where tenantId=?", 1, size, tenantId) .getResult(); } public List<SendmailQueue> findTopSendmailQueues(SendmailApp sendmailApp) { int pageNo = 1; int pageSize = sendmailApp.getPriority(); String hql = "from SendmailQueue where sendmailApp=? and (catalog='' or catalog=null) order by id"; return (List<SendmailQueue>) sendmailQueueManager.pagedQuery(hql, pageNo, pageSize, sendmailApp).getResult(); } public List<SendmailQueue> findTopSendmailQueues( SendmailTemplate sendmailTemplate, int num) { int pageNo = 1; int pageSize = num; String hql = "from SendmailQueue where sendmailTemplate=? order by id"; return (List<SendmailQueue>) sendmailQueueManager.pagedQuery(hql, pageNo, pageSize, sendmailTemplate).getResult(); } public void processSendmailQueue(SendmailQueue sendmailQueue) throws Exception { MailDTO mailDto = new MailDTO(); MailDTO resultMailDto = null; if (sendmailQueue.getSendmailConfig() != null) { SendmailTemplate sendmailTemplate = sendmailQueue .getSendmailTemplate(); SendmailConfig sendmailConfig = sendmailQueue.getSendmailConfig(); MailServerInfo mailServerInfo = new MailServerInfo(); mailServerInfo.setHost(sendmailConfig.getHost()); mailServerInfo.setPort(sendmailConfig.getPort()); mailServerInfo.setSmtpAuth(sendmailConfig.getSmtpAuth() == 1); mailServerInfo .setSmtpStarttls(sendmailConfig.getSmtpStarttls() == 1); mailServerInfo.setSmtpSsl(sendmailConfig.getSmtpSsl() == 1); mailServerInfo.setUsername(sendmailConfig.getUsername()); mailServerInfo.setPassword(sendmailConfig.getPassword()); mailServerInfo.setDefaultFrom(sendmailConfig.getDefaultFrom()); mailServerInfo.setMode(sendmailConfig.getStatus()); mailServerInfo.setTestMail(sendmailConfig.getTestMail()); // config this.configSender(mailDto, sendmailQueue, sendmailTemplate); this.configReceiver(mailDto, sendmailQueue, sendmailTemplate); this.configCc(mailDto, sendmailQueue, sendmailTemplate); this.configBcc(mailDto, sendmailQueue, sendmailTemplate); if (StringUtils.isBlank(sendmailQueue.getSubject())) { if (StringUtils.isBlank(sendmailQueue.getData())) { mailDto.setSubject(sendmailTemplate.getSubject()); } else { Map<String, Object> map = jsonMapper.fromJson( sendmailQueue.getData(), Map.class); String subject = templateService.renderText( sendmailTemplate.getSubject(), map); mailDto.setSubject(subject); } } else { mailDto.setSubject(sendmailQueue.getSubject()); } if (StringUtils.isBlank(sendmailQueue.getContent())) { if (StringUtils.isBlank(sendmailQueue.getData())) { mailDto.setContent(sendmailTemplate.getContent()); } else { Map<String, Object> map = jsonMapper.fromJson( sendmailQueue.getData(), Map.class); String content = templateService.renderText( sendmailTemplate.getContent(), map); mailDto.setContent(content); } } else { mailDto.setContent(sendmailQueue.getContent()); } // mailDto.setFrom(mailTemplate.getSender()); // mailDto.setTo(mailTemplate.getReceiver()); // mailDto.setCc(mailTemplate.getCc()); // mailDto.setBcc(mailTemplate.getBcc()); // mailDto.setSubject(mailTemplate.getSubject()); // mailDto.setContent(mailTemplate.getContent()); if (sendmailTemplate != null) { for (SendmailAttachment sendmailAttachment : sendmailTemplate .getSendmailAttachments()) { StoreDTO storeDto = storeClient.getStore( "sendmailattachment", sendmailAttachment.getPath(), sendmailQueue.getTenantId()); mailDto.addAttachment( sendmailAttachment.getName(), new DataSourceInputStreamSource(storeDto .getDataSource())); } } resultMailDto = new MailHelper().send(mailDto, mailServerInfo); // model.addAttribute("mailDto", mailDto); if (!resultMailDto.isSuccess()) { StringWriter writer = new StringWriter(); resultMailDto.getException().printStackTrace( new PrintWriter(writer)); // model.addAttribute("exception", writer.toString()); } } else { mailDto.setFrom(sendmailQueue.getSender()); mailDto.setTo(sendmailQueue.getReceiver()); mailDto.setSubject(sendmailQueue.getSubject()); mailDto.setContent(sendmailQueue.getContent()); resultMailDto = mailHelper.send(mailDto); } if (resultMailDto == null) { logger.info("result mailDto is null"); return; } this.saveMailHistory(sendmailQueue, resultMailDto); } public void configSender(MailDTO mailDto, SendmailQueue sendmailQueue, SendmailTemplate sendmailTemplate) { if (StringUtils.isBlank(sendmailQueue.getSender())) { if ((sendmailTemplate != null) && (sendmailTemplate.getSender() != null)) { mailDto.setFrom(sendmailTemplate.getSender().trim()); } } else { mailDto.setFrom(sendmailQueue.getSender().trim()); } } public void configReceiver(MailDTO mailDto, SendmailQueue sendmailQueue, SendmailTemplate sendmailTemplate) { if (StringUtils.isBlank(sendmailQueue.getReceiver())) { if ((sendmailTemplate != null) && (sendmailTemplate.getReceiver() != null)) { mailDto.setTo(sendmailTemplate.getReceiver().trim()); } } else { mailDto.setTo(sendmailQueue.getReceiver().trim()); } } public void configCc(MailDTO mailDto, SendmailQueue sendmailQueue, SendmailTemplate sendmailTemplate) { if (StringUtils.isBlank(sendmailQueue.getCc())) { if ((sendmailTemplate != null) && (sendmailTemplate.getCc() != null)) { mailDto.setCc(sendmailTemplate.getCc().trim()); } } else { mailDto.setCc(sendmailQueue.getCc().trim()); } } public void configBcc(MailDTO mailDto, SendmailQueue sendmailQueue, SendmailTemplate sendmailTemplate) { if (StringUtils.isBlank(sendmailQueue.getBcc())) { if ((sendmailTemplate != null) && (sendmailTemplate.getBcc() != null)) { mailDto.setBcc(sendmailTemplate.getBcc().trim()); } } else { mailDto.setBcc(sendmailQueue.getBcc().trim()); } } public void saveMailHistory(SendmailQueue sendmailQueue, MailDTO mailDto) { if (mailDto == null) { logger.info("mailDto is null"); return; } SendmailHistory sendmailHistory = new SendmailHistory(); beanMapper.copy(mailDto, sendmailHistory); sendmailHistory.setSender(mailDto.getFrom()); sendmailHistory.setReceiver(mailDto.getTo()); sendmailHistory.setStatus(mailDto.isSuccess() ? "success" : "error"); sendmailHistory.setTenantId(sendmailQueue.getTenantId()); sendmailHistory.setCatalog(sendmailQueue.getCatalog()); sendmailHistory.setBatch(sendmailQueue.getBatch()); if (mailDto.getException() != null) { sendmailHistory.setInfo(mailDto.getException().getMessage()); } sendmailHistory .setSendmailTemplate(sendmailQueue.getSendmailTemplate()); sendmailHistory.setSendmailConfig(sendmailQueue.getSendmailConfig()); sendmailHistory.setSendmailApp(sendmailQueue.getSendmailApp()); sendmailHistory.setData(sendmailQueue.getData()); sendmailHistory.setCreateTime(new Date()); sendmailHistoryManager.save(sendmailHistory); sendmailQueueManager.remove(sendmailQueue); } public boolean checkConfigCodeExists(String configCode, String tenantId) { SendmailConfig sendmailConfig = sendmailConfigManager.findUnique( "from SendmailConfig where name=? and tenantId=?", configCode, tenantId); return sendmailConfig != null; } public boolean checkTemplateCodeExists(String templateCode, String tenantId) { SendmailTemplate sendmailTemplate = sendmailTemplateManager.findUnique( "from SendmailTemplate where name=? and tenantId=?", templateCode, tenantId); return sendmailTemplate != null; } @Resource public void setSendmailConfigManager( SendmailConfigManager sendmailConfigManager) { this.sendmailConfigManager = sendmailConfigManager; } @Resource public void setSendmailQueueManager( SendmailQueueManager sendmailQueueManager) { this.sendmailQueueManager = sendmailQueueManager; } @Resource public void setSendmailHistoryManager( SendmailHistoryManager sendmailHistoryManager) { this.sendmailHistoryManager = sendmailHistoryManager; } @Resource public void setSendmailTemplateManager( SendmailTemplateManager sendmailTemplateManager) { this.sendmailTemplateManager = sendmailTemplateManager; } @Resource public void setStoreClient(StoreClient storeClient) { this.storeClient = storeClient; } @Resource public void setMailHelper(MailHelper mailHelper) { this.mailHelper = mailHelper; } @Resource public void setTemplateService(TemplateService templateService) { this.templateService = templateService; } }
camallen/Panoptes
spec/workers/unfinish_workflow_worker_spec.rb
<reponame>camallen/Panoptes require 'spec_helper' RSpec.describe UnfinishWorkflowWorker do let(:worker) { described_class.new } let(:workflow) { create(:workflow) } describe "#perform" do it "should not do anything if the workflow is not finished" do expect { worker.perform(workflow.id) }.not_to change{ workflow.reload.finished_at } end context "with a finished workflow" do let(:workflow) { create(:workflow, finished_at: DateTime.now) } it "should remove the finished flag if the workflow is finished" do expect { worker.perform(workflow.id) }.to change{ workflow.reload.finished_at } end it "should touch the updated_at timestamp" do workflow.update(updated_at: Time.now - 1.hour) expect { worker.perform(workflow.id) }.to change{ workflow.reload.updated_at} end end end end
moikot/smartthings-go
client/deviceprofiles/get_device_profile_parameters.go
// Code generated by go-swagger; DO NOT EDIT. package deviceprofiles // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "net/http" "time" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" ) // NewGetDeviceProfileParams creates a new GetDeviceProfileParams object // with the default values initialized. func NewGetDeviceProfileParams() *GetDeviceProfileParams { var () return &GetDeviceProfileParams{ timeout: cr.DefaultTimeout, } } // NewGetDeviceProfileParamsWithTimeout creates a new GetDeviceProfileParams object // with the default values initialized, and the ability to set a timeout on a request func NewGetDeviceProfileParamsWithTimeout(timeout time.Duration) *GetDeviceProfileParams { var () return &GetDeviceProfileParams{ timeout: timeout, } } // NewGetDeviceProfileParamsWithContext creates a new GetDeviceProfileParams object // with the default values initialized, and the ability to set a context for a request func NewGetDeviceProfileParamsWithContext(ctx context.Context) *GetDeviceProfileParams { var () return &GetDeviceProfileParams{ Context: ctx, } } // NewGetDeviceProfileParamsWithHTTPClient creates a new GetDeviceProfileParams object // with the default values initialized, and the ability to set a custom HTTPClient for a request func NewGetDeviceProfileParamsWithHTTPClient(client *http.Client) *GetDeviceProfileParams { var () return &GetDeviceProfileParams{ HTTPClient: client, } } /*GetDeviceProfileParams contains all the parameters to send to the API endpoint for the get device profile operation typically these are written to a http.Request */ type GetDeviceProfileParams struct { /*AcceptLanguage Language header representing the client's preferred language. The format of the `Accept-Language` header follows what is defined in [RFC 7231, section 5.3.5](https://tools.ietf.org/html/rfc7231#section-5.3.5) */ AcceptLanguage *string /*Authorization OAuth token */ Authorization string /*DeviceProfileID the device profile ID */ DeviceProfileID string timeout time.Duration Context context.Context HTTPClient *http.Client } // WithTimeout adds the timeout to the get device profile params func (o *GetDeviceProfileParams) WithTimeout(timeout time.Duration) *GetDeviceProfileParams { o.SetTimeout(timeout) return o } // SetTimeout adds the timeout to the get device profile params func (o *GetDeviceProfileParams) SetTimeout(timeout time.Duration) { o.timeout = timeout } // WithContext adds the context to the get device profile params func (o *GetDeviceProfileParams) WithContext(ctx context.Context) *GetDeviceProfileParams { o.SetContext(ctx) return o } // SetContext adds the context to the get device profile params func (o *GetDeviceProfileParams) SetContext(ctx context.Context) { o.Context = ctx } // WithHTTPClient adds the HTTPClient to the get device profile params func (o *GetDeviceProfileParams) WithHTTPClient(client *http.Client) *GetDeviceProfileParams { o.SetHTTPClient(client) return o } // SetHTTPClient adds the HTTPClient to the get device profile params func (o *GetDeviceProfileParams) SetHTTPClient(client *http.Client) { o.HTTPClient = client } // WithAcceptLanguage adds the acceptLanguage to the get device profile params func (o *GetDeviceProfileParams) WithAcceptLanguage(acceptLanguage *string) *GetDeviceProfileParams { o.SetAcceptLanguage(acceptLanguage) return o } // SetAcceptLanguage adds the acceptLanguage to the get device profile params func (o *GetDeviceProfileParams) SetAcceptLanguage(acceptLanguage *string) { o.AcceptLanguage = acceptLanguage } // WithAuthorization adds the authorization to the get device profile params func (o *GetDeviceProfileParams) WithAuthorization(authorization string) *GetDeviceProfileParams { o.SetAuthorization(authorization) return o } // SetAuthorization adds the authorization to the get device profile params func (o *GetDeviceProfileParams) SetAuthorization(authorization string) { o.Authorization = authorization } // WithDeviceProfileID adds the deviceProfileID to the get device profile params func (o *GetDeviceProfileParams) WithDeviceProfileID(deviceProfileID string) *GetDeviceProfileParams { o.SetDeviceProfileID(deviceProfileID) return o } // SetDeviceProfileID adds the deviceProfileId to the get device profile params func (o *GetDeviceProfileParams) SetDeviceProfileID(deviceProfileID string) { o.DeviceProfileID = deviceProfileID } // WriteToRequest writes these params to a swagger request func (o *GetDeviceProfileParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { if err := r.SetTimeout(o.timeout); err != nil { return err } var res []error if o.AcceptLanguage != nil { // header param Accept-Language if err := r.SetHeaderParam("Accept-Language", *o.AcceptLanguage); err != nil { return err } } // header param Authorization if err := r.SetHeaderParam("Authorization", o.Authorization); err != nil { return err } // path param deviceProfileId if err := r.SetPathParam("deviceProfileId", o.DeviceProfileID); err != nil { return err } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
Tariqali13/JusGotPaidFrontend
components/layouts/marketing-template/marketing-template.js
// @flow import React from 'react'; import NProgress from 'nprogress'; import Router from 'next/router'; import { Header, Footer, TopHeader } from './components'; import MarketingHead from './marketing-head'; type Props = { children: any, showMenu?: boolean, }; const MarketingTemplate = (props: Props) => { const { children } = props; Router.onRouteChangeStart = () => { NProgress.start(); }; Router.onRouteChangeComplete = () => { NProgress.done(); }; Router.onRouteChangeError = () => { NProgress.done(); }; return ( <React.Fragment> <MarketingHead /> <Header {...props} /> {children} <Footer /> </React.Fragment> ); }; MarketingTemplate.defaultProps = { showMenu: true, }; export default MarketingTemplate;
nokia-wroclaw/nokia-book
02/MiNiK/src/store.hpp
<filename>02/MiNiK/src/store.hpp #pragma once #include <cassert> #include <string> #include <vector> #include <algorithm> #include <memory> const int WordSize = 4; struct FunctionDef { std::string name; std::string symName; std::size_t numberOfArgs; std::size_t frameSize; bool predefined; }; class StoreManager { struct Frame { FunctionDef func; int argsOffset; int varsOffset; std::vector<std::pair<std::string, int>> vars; Frame(FunctionDef func) : func(func) , argsOffset((func.numberOfArgs + 1) * WordSize) , varsOffset(- WordSize) { } }; std::unique_ptr<Frame> frame; public: StoreManager() : frame(nullptr) {} void newFunction(FunctionDef func) { frame.reset(new Frame(func)); } void pushLocalVariable(std::string id) { frame->vars.push_back({id, frame->varsOffset}); frame->varsOffset -= WordSize; assert(frame->varsOffset + WordSize <= static_cast<int>(frame->func.frameSize)); } void popLocalVariable(std::string id) { assert(not frame->vars.empty()); assert(frame->vars.back().first == id); frame->vars.pop_back(); frame->varsOffset += WordSize; } void addArgumentVariable(std::string id) { frame->vars.push_back({id, frame->argsOffset}); frame->argsOffset -= WordSize; } int getVariableOffset(std::string id) { auto currentVars = frame->vars; auto var = std::find_if( currentVars.cbegin(), currentVars.cend(), [id](decltype(currentVars)::value_type const &var) { return var.first == id; }); return var->second; } };
mcdeoliveira/NC
NCGB/Compile/src/Timing.cpp
<reponame>mcdeoliveira/NC // Timing.c #include "Timing.hpp" /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Instructions NOTE: This file is not to be used with Timing.h or Timing.inline.h - it is the C implementation of timing commands. To time a section of code, first allocate a long, assigning it to the return value of TimingStart(). long ts = TimingStart(); From then on, the elapsed time can be computed by passing this returned value to TimingCheck: long elapsedTime = TimingCheck(ts); * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ double TimingStart() { #ifdef USE_UNIX timeval tp; struct timezone tzp; gettimeofday(&tp, &tzp); return tp.tv_sec + tp.tv_usec / Timing::s_DividingFactor; #else return 0.0; #endif }; #ifdef USE_UNIX double TimingCheck(double t) { timeval tp; struct timezone tzp; gettimeofday(&tp, &tzp); return((tp.tv_sec + tp.tv_usec / Timing::s_DividingFactor) - t); }; #else double TimingCheck(double) { return 0.0; }; #endif //const int Timing::s_DividingFactor = 1000000; //const int Timing::s_DividingFactor = 1; const int Timing::s_DividingFactor = 1000;
suluner/tencentcloud-sdk-cpp
tdmq/include/tencentcloud/tdmq/v20200217/model/EnvironmentRole.h
<filename>tdmq/include/tencentcloud/tdmq/v20200217/model/EnvironmentRole.h<gh_stars>10-100 /* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_TDMQ_V20200217_MODEL_ENVIRONMENTROLE_H_ #define TENCENTCLOUD_TDMQ_V20200217_MODEL_ENVIRONMENTROLE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Tdmq { namespace V20200217 { namespace Model { /** * 环境角色集合 */ class EnvironmentRole : public AbstractModel { public: EnvironmentRole(); ~EnvironmentRole() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取环境(命名空间)。 * @return EnvironmentId 环境(命名空间)。 */ std::string GetEnvironmentId() const; /** * 设置环境(命名空间)。 * @param EnvironmentId 环境(命名空间)。 */ void SetEnvironmentId(const std::string& _environmentId); /** * 判断参数 EnvironmentId 是否已赋值 * @return EnvironmentId 是否已赋值 */ bool EnvironmentIdHasBeenSet() const; /** * 获取角色名称。 * @return RoleName 角色名称。 */ std::string GetRoleName() const; /** * 设置角色名称。 * @param RoleName 角色名称。 */ void SetRoleName(const std::string& _roleName); /** * 判断参数 RoleName 是否已赋值 * @return RoleName 是否已赋值 */ bool RoleNameHasBeenSet() const; /** * 获取授权项,最多只能包含produce、consume两项的非空字符串数组。 * @return Permissions 授权项,最多只能包含produce、consume两项的非空字符串数组。 */ std::vector<std::string> GetPermissions() const; /** * 设置授权项,最多只能包含produce、consume两项的非空字符串数组。 * @param Permissions 授权项,最多只能包含produce、consume两项的非空字符串数组。 */ void SetPermissions(const std::vector<std::string>& _permissions); /** * 判断参数 Permissions 是否已赋值 * @return Permissions 是否已赋值 */ bool PermissionsHasBeenSet() const; /** * 获取角色描述。 * @return RoleDescribe 角色描述。 */ std::string GetRoleDescribe() const; /** * 设置角色描述。 * @param RoleDescribe 角色描述。 */ void SetRoleDescribe(const std::string& _roleDescribe); /** * 判断参数 RoleDescribe 是否已赋值 * @return RoleDescribe 是否已赋值 */ bool RoleDescribeHasBeenSet() const; /** * 获取创建时间。 * @return CreateTime 创建时间。 */ std::string GetCreateTime() const; /** * 设置创建时间。 * @param CreateTime 创建时间。 */ void SetCreateTime(const std::string& _createTime); /** * 判断参数 CreateTime 是否已赋值 * @return CreateTime 是否已赋值 */ bool CreateTimeHasBeenSet() const; /** * 获取更新时间。 * @return UpdateTime 更新时间。 */ std::string GetUpdateTime() const; /** * 设置更新时间。 * @param UpdateTime 更新时间。 */ void SetUpdateTime(const std::string& _updateTime); /** * 判断参数 UpdateTime 是否已赋值 * @return UpdateTime 是否已赋值 */ bool UpdateTimeHasBeenSet() const; private: /** * 环境(命名空间)。 */ std::string m_environmentId; bool m_environmentIdHasBeenSet; /** * 角色名称。 */ std::string m_roleName; bool m_roleNameHasBeenSet; /** * 授权项,最多只能包含produce、consume两项的非空字符串数组。 */ std::vector<std::string> m_permissions; bool m_permissionsHasBeenSet; /** * 角色描述。 */ std::string m_roleDescribe; bool m_roleDescribeHasBeenSet; /** * 创建时间。 */ std::string m_createTime; bool m_createTimeHasBeenSet; /** * 更新时间。 */ std::string m_updateTime; bool m_updateTimeHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_TDMQ_V20200217_MODEL_ENVIRONMENTROLE_H_
swaron/fruit
web-helper/target/classes/META-INF/web-resources/libjs/src/form/field/VTypes.js
<filename>web-helper/target/classes/META-INF/web-resources/libjs/src/form/field/VTypes.js Ext.define("Lib.form.field.VTypes", { override : "Ext.form.field.VTypes", daterange : function(val, field) { var date = field.parseDate(val); var basicValidate = function(datefield) { var vtype = datefield.vtype; datefield.vtype = undefined; var isValid = datefield.isValid(); datefield.vtype = vtype; return isValid; }; if (field.startDateField) { var start = Ext.getCmp(field.startDateField) || field.up('container').down('#' + field.startDateField); if (!date) { if (start.hasActiveError() && basicValidate(start)) { start.clearInvalid(); // to clear form's invalid status Ext.defer(start.validate, 100, start); } return true; } var startDate = start.getValue(); if (!startDate) { return true; } if (startDate.getTime() > date.getTime()) { return false; } else { if (start.hasActiveError() && basicValidate(start)) { start.clearInvalid(); // to clear form's invalid status Ext.defer(start.validate, 100, start); } return true; } } else if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) { var end = Ext.getCmp(field.endDateField) || field.up('container').down('#' + field.endDateField); if (!date) { if (end.hasActiveError() && basicValidate(end)) { end.clearInvalid(); // to clear form's invalid status Ext.defer(end.validate, 100, end); } return true; } var endDate = end.getValue(); if (!endDate) { return true; } if (date.getTime() > endDate.getTime()) { return false; } else { if (end.hasActiveError() && basicValidate(end)) { end.clearInvalid(); // to clear form's invalid status Ext.defer(end.validate, 100, end); } return true; } } /* * Always return true since we're only using this vtype to set the min/max allowed values (these are tested for * after the vtype test) */ return true; }, daterangeText : '结束日期需要大于开始日期', numberrange : function(val, field) { if (field.startNumberField) { var start = Ext.getCmp(field.startNumberField) || field.up('container').down('#' + field.startNumberField); if (!val) { start.clearInvalid(); return true; } var startVal = start.getValue(); if (!startVal) { return true; } if (startVal > val) { return false; } else { start.clearInvalid(); return true; } } else if (field.endNumberField) { var end = Ext.getCmp(field.endNumberField) || field.up('container').down('#' + field.endNumberField); if (!val) { end.clearInvalid(); return true; } var endVal = end.getValue(); if (!endVal) { return true; } if (val > endVal) { return false; } else { end.clearInvalid(); return true; } } return true; }, numberrangeText: '结束数值需要大于开始数值' });
coiax/muhscreeps
prototype.source.js
<filename>prototype.source.js 'use strict';Source.prototype.is_harvestable = function(a) { return 0 === this.energy ? !1 : a && this.pos.isNearTo(a) ? !0 : this.pos.walkable_adjacent().length ? !0 : !1 };
korydraughn/jargon
jargon-core/src/main/java/org/irods/jargon/core/pub/PluggableApiCallResult.java
package org.irods.jargon.core.pub; public class PluggableApiCallResult { private String jsonResult = ""; private int intInfo = 0; private int errorInfo = 0; public String getJsonResult() { return jsonResult; } public void setJsonResult(String jsonResult) { this.jsonResult = jsonResult; } public int getIntInfo() { return intInfo; } public void setIntInfo(int intInfo) { this.intInfo = intInfo; } public int getErrorInfo() { return errorInfo; } public void setErrorInfo(int errorInfo) { this.errorInfo = errorInfo; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("PluggableApiCallResult ["); if (jsonResult != null) { builder.append("jsonResult=").append(jsonResult).append(", "); } builder.append("intInfo=").append(intInfo).append(", errorInfo=").append(errorInfo).append("]"); return builder.toString(); } }
zccdy/XBHEBProject
model/XBHImagePicker.h
<filename>model/XBHImagePicker.h // // XBHImagePicker.h // XBHEBProject // // Created by xubh-note on 15/4/20. // Copyright (c) 2015年 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> typedef NS_ENUM(NSUInteger, XBHImagePickerDataMode){ XBHImagePickerDataMode_ImageFromLibrary=0, XBHImagePickerDataMode_ImageByCamera, XBHImagePickerDataMode_Video }; @protocol XBHImagePickerDelegate <NSObject> @optional //图片 NSData 视屏 NSString -(void)XBHImagePickerDidPick:(NSString *)dataPath fileName:(NSString *)name fileSize:(long long)size PickMode:(XBHImagePickerDataMode)mode thumbImage:(UIImage *)thumb; @end @interface XBHImagePicker : NSObject @property (nonatomic,weak) id<XBHImagePickerDelegate> delegate; /** * 缩略图大小 */ @property (nonatomic,assign) CGSize thumbImageSize; // 判断设备是否有摄像头 +(BOOL) XBHImagePicker_isCameraAvailable; // 前面的摄像头是否可用 +(BOOL) XBHImagePicker_isFrontCameraAvailable; // 后面的摄像头是否可用 + (BOOL) XBHImagePicker_isRearCameraAvailable; // 检查摄像头是否支持录像 +(BOOL) XBHImagePicker_doesCameraSupportShootingVideos; // 检查摄像头是否支持拍照 +(BOOL) XBHImagePicker_doesCameraSupportTakingPhotos; // 相册是否可用 + (BOOL) XBHImagePicker_isPhotoLibraryAvailable; // 是否可以在相册中选择视频 + (BOOL)XBHImagePicker_canPickVideosFromPhotoLibrary; // 是否可以在相册中选择图片 +(BOOL)XBHImagePicker_canUserPickPhotosFromPhotoLibrary; -(void)pickImageWithController:(UIViewController *)controller; -(void)pickVideoWithController:(UIViewController *)controller; -(void)canmeraWithController:(UIViewController *)controller; @end
GirlsOfSteelRobotics/GirlsOfSteelFRC
old_robots/y2013/Eve2013/src/main/java/com/gos/ultimate_ascent/commands/TrackSideTarget.java
package com.gos.ultimate_ascent.commands; import edu.wpi.first.wpilibj.command.CommandGroup; import com.gos.ultimate_ascent.objects.ShooterCamera; import com.gos.ultimate_ascent.subsystems.Chassis; public class TrackSideTarget extends CommandGroup { public TrackSideTarget(Chassis chassis) { double turnTheta = ShooterCamera.getSideDiffAngle() + ShooterCamera.getLocationOffsetAngle(); if (ShooterCamera.foundSideTarget()) { addSequential(new Rotate(chassis, turnTheta, true)); } } }
wilfredwilly/springboot-learn-by-example
chapter-09/springboot-jpa-demo/src/main/java/com/sivalabs/demo/UserRepository.java
/** * */ package com.sivalabs.demo; import org.springframework.data.jpa.repository.JpaRepository; /** * @author Siva * */ public interface UserRepository extends JpaRepository<User, Integer> { }
sxxlearn2rock/AgileJavaStudy
src/cn/sxx/agilejava/report/ReportCardTest.java
<reponame>sxxlearn2rock/AgileJavaStudy package cn.sxx.agilejava.report; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.junit.Before; import org.junit.Test; import cn.sxx.agilejava.studentinfo.Student; public class ReportCardTest { private ReportCard card; @Before public void setUp() throws Exception { card = new ReportCard(); } @Test public void testMessage() { assertEquals(ReportCard.A_MESSAGE, card.getMessage(Student.Grade.A)); assertEquals(ReportCard.B_MESSAGE, card.getMessage(Student.Grade.B)); assertEquals(ReportCard.C_MESSAGE, card.getMessage(Student.Grade.C)); assertEquals(ReportCard.D_MESSAGE, card.getMessage(Student.Grade.D)); assertEquals(ReportCard.F_MESSAGE, card.getMessage(Student.Grade.F)); } @Test public void testKeys() { Set<Student.Grade> expectedGrades = new HashSet<Student.Grade>(); expectedGrades.add(Student.Grade.A); expectedGrades.add(Student.Grade.B); expectedGrades.add(Student.Grade.C); expectedGrades.add(Student.Grade.D); expectedGrades.add(Student.Grade.F); Set<Student.Grade> grades = new HashSet<Student.Grade>(); for (Student.Grade grade : card.getMessages().keySet()) { grades.add(grade); //System.out.println(grade); } assertEquals(expectedGrades, grades); } @Test public void testValue() { List<String> expectedMessages = new ArrayList<String>(); expectedMessages.add(ReportCard.A_MESSAGE); expectedMessages.add(ReportCard.B_MESSAGE); expectedMessages.add(ReportCard.C_MESSAGE); expectedMessages.add(ReportCard.D_MESSAGE); expectedMessages.add(ReportCard.F_MESSAGE); Collection<String> messages = card.getMessages().values(); for (String string : messages) { assertTrue(expectedMessages.contains(string)); } assertEquals(expectedMessages.size(), messages.size()); } @Test public void testString() { String a = "<NAME>"; String b = "<NAME>"; assertTrue(a.equals(b)); } }
Telecominfraproject/wlan-cloud-owprov-ui
src/pages/VenuePage/VenueChildrenCard/VenueLiveView/CirclePack/CircleComponent/DeviceCircle.js
<reponame>Telecominfraproject/wlan-cloud-owprov-ui import React, { useMemo } from 'react'; import PropTypes from 'prop-types'; import { animated } from '@react-spring/web'; import { IconButton, Popover, PopoverArrow, PopoverBody, PopoverCloseButton, PopoverContent, PopoverHeader, PopoverTrigger, Portal, Text, Tooltip, Table, Tbody, Td, Tr, Box, Flex, } from '@chakra-ui/react'; import { ArrowSquareOut, Tag } from 'phosphor-react'; import { useGetGatewayUi } from 'hooks/Network/Endpoints'; import FormattedDate from 'components/FormattedDate'; import { useTranslation } from 'react-i18next'; import { useCircleGraph } from 'contexts/CircleGraphProvider'; import { bytesString } from 'utils/stringHelper'; const propTypes = { node: PropTypes.instanceOf(Object).isRequired, handleClicks: PropTypes.shape({ onClick: PropTypes.func.isRequired, }).isRequired, style: PropTypes.instanceOf(Object).isRequired, }; const DeviceCircle = ({ node, style, handleClicks }) => { const { t } = useTranslation(); const { data: gwUi } = useGetGatewayUi(); const { popoverRef } = useCircleGraph(); const handleOpenInGateway = useMemo( () => () => window.open(`${gwUi}/#/devices/${node.data.details.deviceInfo.serialNumber}`, '_blank'), [gwUi], ); return ( <Popover isLazy trigger="hover" placement="auto"> <PopoverTrigger> <animated.circle key={node.id} cx={style.x} cy={style.y} r={style.radius} fill={node.data.details.color} stroke="black" strokeWidth="1px" cursor="pointer" opacity={style.opacity} onClick={handleClicks.onClick} /> </PopoverTrigger> <Portal containerRef={popoverRef}> <PopoverContent w="580px"> <PopoverArrow /> <PopoverCloseButton alignContent="center" mt={1} /> <PopoverHeader display="flex"> <Tag size={24} weight="fill" /> <Text ml={2}>{node?.data?.name.split('/')[0]}</Text> <Tooltip hasArrow label={t('common.view_in_gateway')} placement="top"> <IconButton ml={2} colorScheme="blue" icon={<ArrowSquareOut size={20} />} size="xs" onClick={handleOpenInGateway} /> </Tooltip> </PopoverHeader> <PopoverBody> <Box px={0} fontWeight="bold" w="100%"> <Table variant="simple" size="sm"> <Tbody> <Tr> <Td w="130px">{t('common.type')}</Td> <Td> {node.data.details.deviceInfo.deviceType === '' ? t('common.unknown') : node.data.details.deviceInfo.deviceType} </Td> <Td w="150px">TX {t('analytics.delta')}</Td> <Td>{bytesString(node.data.details.tx_bytes_delta)}</Td> </Tr> <Tr> <Td w="130px">{t('analytics.firmware')}</Td> <Td>{node.data.details.deviceInfo.lastFirmware?.split('/')[1] ?? t('common.unknown')}</Td> <Td w="150px">RX {t('analytics.delta')}</Td> <Td>{bytesString(node.data.details.rx_bytes_delta)}</Td> </Tr> <Tr> <Td w="130px">SSIDs</Td> <Td>{node.data.children.length}</Td> <Td w="150px">2G {t('analytics.associations')}</Td> <Td>{node.data.details.deviceInfo.associations_2g}</Td> </Tr> <Tr> <Td w="130px">{t('analytics.health')}</Td> <Td>{node.data.details.deviceInfo.health}%</Td> <Td w="150px">5G {t('analytics.associations')}</Td> <Td>{node.data.details.deviceInfo.associations_5g}</Td> </Tr> <Tr> <Td w="130px">{t('analytics.memory_used')}</Td> <Td>{Math.floor(node.data.details.deviceInfo.memory)}%</Td> <Td w="150px">6G {t('analytics.associations')}</Td> <Td>{node.data.details.deviceInfo.associations_6g}</Td> </Tr> </Tbody> </Table> {node.data.details.deviceInfo.lastDisconnection !== 0 && ( <Flex ml={4}> <Text mr={1}>{t('analytics.last_disconnection')}</Text> <Text> <FormattedDate date={node.data.details.deviceInfo.lastDisconnection} /> </Text> </Flex> )} </Box> </PopoverBody> </PopoverContent> </Portal> </Popover> ); }; DeviceCircle.propTypes = propTypes; export default React.memo(DeviceCircle);
YongChenSu/GoodJobShare
src/components/CompanyAndJobTitle/WorkExperiences/index.js
import React from 'react'; import PropTypes from 'prop-types'; import CompanyAndJobTitleWrapper from '../CompanyAndJobTitleWrapper'; import StatusRenderer from '../StatusRenderer'; import WorkExperiencesSection from './WorkExperiences'; import Helmet from './Helmet'; const WorkExperiences = ({ pageType, pageName, tabType, workExperiences, status, page, canView, }) => ( <CompanyAndJobTitleWrapper pageType={pageType} pageName={pageName} tabType={tabType} > <StatusRenderer status={status}> <Helmet pageType={pageType} pageName={pageName} workExperiences={workExperiences} page={page} /> <WorkExperiencesSection pageType={pageType} pageName={pageName} tabType={tabType} data={workExperiences} page={page} canView={canView} /> </StatusRenderer> </CompanyAndJobTitleWrapper> ); WorkExperiences.propTypes = { pageType: PropTypes.string, pageName: PropTypes.string, tabType: PropTypes.string, workExperiences: PropTypes.arrayOf(PropTypes.object), status: PropTypes.string.isRequired, page: PropTypes.number.isRequired, canView: PropTypes.bool.isRequired, }; export default WorkExperiences;
umts/st-pax
app/models/feedback.rb
<reponame>umts/st-pax<gh_stars>0 # frozen_string_literal: true require 'mock_github_client' class Feedback include ActiveModel::Model attr_accessor :title, :description, :category, :issue, :user CATEGORIES = %w[bug enhancement addition].freeze DEFAULT_CATEGORIES = %w[unconfirmed].freeze validates :title, presence: true validates :category, inclusion: { in: CATEGORIES } def self.repo Figaro.env.github_repo end def self.token Figaro.env.github_token end def submit! @issue = client.create_issue Feedback.repo, title, signed_description, labels: labels end def load(issue_number) @issue = client.issue Feedback.repo, issue_number self.title = @issue.title self.description = @issue.body self.category = (@issue.labels.map(&:name) & Feedback::CATEGORIES).first end def client @client ||= if Feedback.token.present? Octokit::Client.new(access_token: Feedback.token) else MockGithubClient.new end end private def labels categories = Feedback::DEFAULT_CATEGORIES + [category] categories.join(',') end def signed_description return description unless user.present? "#{description}\n\n[#{user.id}](#{user.url})" end end
byrne-greg/the-stool-diary
src/context/global/actions.js
<reponame>byrne-greg/the-stool-diary<filename>src/context/global/actions.js import { CHANGE_LANGUAGE, UPDATE_AUTH_USER, UPDATE_USER } from "./actionTypes" export const updateUser = (dispatch, value) => updateState(dispatch, UPDATE_USER, value) export const updateAuthUser = (dispatch, authUser) => { updateState(dispatch, UPDATE_AUTH_USER, authUser) } export const changeLanguage = (dispatch, value) => updateState(dispatch, CHANGE_LANGUAGE, value) const updateState = (dispatch, actionType, newValue) => dispatch({ type: actionType, value: newValue }) const updateSession = (key, value) => { sessionStorage.setItem(key, JSON.stringify(value)) }
SmartDataAnalytics/ckan-deploy
dcat-suite-app/src/main/java/org/aksw/dcat_suite/app/model/impl/UserSpaceImpl.java
<filename>dcat-suite-app/src/main/java/org/aksw/dcat_suite/app/model/impl/UserSpaceImpl.java package org.aksw.dcat_suite.app.model.impl; import java.nio.file.Path; import org.aksw.dcat_suite.app.model.api.UserProjectMgr; import org.aksw.dcat_suite.app.model.api.UserSpace; public class UserSpaceImpl extends LifeCycleEntityPathImpl implements UserSpace { protected UserProjectMgr projectMgr; public UserSpaceImpl(Path basePath, String entityId) { super(basePath, entityId); this.projectMgr = new UserProjectMgrImpl(super.getBasePath()); } @Override public UserProjectMgr getProjectMgr() { return projectMgr; } }
omunroe-com/nasaaccmars
src/js/components/terrain.js
<gh_stars>10-100 // Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { Scene, GridSize } from '../core/scene'; import { CommonTex } from '../core/common-tex'; import { C4DUtils } from '../c4d/c4d-utils'; import { C4DExportLoader } from '../c4d/c4d-export-loader'; import { JPEGWorker } from '../workers/jpeg-worker'; import { MathUtils } from '../utils/math-utils'; const TerrainShader = require( '../shaders/terrain-shader' ); const EdgeShader = require( '../shaders/edge-shader' ); const EDGE_VECTORS = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ]; const ZERO_VECTOR = new THREE.Vector3( 0, 0, 0 ); // Named texture sizes and their corresponding filename suffixes const TEXTURE_SIZES = [ 'small', 'base', 'large' ]; const TEXTURE_SUFFIXES = { xsmall: '_xsm', small: '_sm', base: '', large: '_lg' }; // On mobile platforms, only the four center tiles are allowed to load the medium // resolution texture, in order to save memory. The four center tile IDs are // specified here. const CENTER_TILE_IDS = [ '03333333', '12222222', '21111111', '30000000' ]; const TERRAIN_DIR = 'terrain/'; const LOAD_PROXY_GEO = new THREE.PlaneBufferGeometry( 0.01, 0.01 ); const ANIM_IN_DURATION = 1.0; if ( typeof AFRAME !== 'undefined' && AFRAME ) { AFRAME.registerComponent( 'terrain', { dependencies: [ 'visible' ], init: function() { this.tileMeshes = []; this.tileMeshesByID = {}; this.background = null; this.collision = null; this.animIn = 0; this.gridState = 1; this.isSimpleVisible = false; this.isTerrainVisible = false; this.el.sceneEl.addEventListener( 'terrain-intersected', this.onIntersected.bind( this ) ); this.el.sceneEl.addEventListener( 'terrain-intersected-cleared', this.onControllerMoved.bind( this ) ); document.addEventListener( 'mousemove', this.onMouseMoved.bind( this ) ); this.el.setAttribute( 'event-priority', 50 ); // Listen for stateremoved event for showing the collision or terrain meshes this.el.addEventListener( 'stateadded', event => { if ( event.detail.state === 'show-simple' ) { this.isSimpleVisible = true; if ( this.collision ) this.collision.setVisible( this.isSimpleVisible ); } if ( event.detail.state === 'show-terrain' ) { this.isTerrainVisible = true; this.setVisible( this.isTerrainVisible ); } }); // Listen for stateremoved event for hiding the collision or terrain meshes this.el.addEventListener( 'stateremoved', event => { if ( event.detail.state === 'show-simple' ) { this.isSimpleVisible = false; if ( this.collision ) this.collision.setVisible( this.isSimpleVisible ); } if ( event.detail.state === 'show-terrain' ) { this.isTerrainVisible = false; this.setVisible( this.isTerrainVisible ); } }); }, /** * Loads everything required to render the terrain: * common textures, scene file, and initial detail textures. * Returns a promise which resolves when the loading is complete. */ loadTerrain: function() { return new Promise( ( resolve, reject ) => { CommonTex.load() .then( () => this.loadMeshes() ) .then( () => this.loadInitialTextures() ) .then( () => resolve( this.tileMeshes ) ); }); }, /** * Loads the terrain mesh for the current site. * Returns a promise which resolves when the terrain meshes are loaded */ loadMeshes: function() { const rootPath = TERRAIN_DIR + Scene.baseFilename + '/' + Scene.baseFilename; const loader = new C4DExportLoader(); return new Promise( ( resolve, reject ) => { loader.load( TERRAIN_DIR + Scene.baseFilename + '/terrain.glb' ).then( response => { this.terrain = response.scene; this.terrain.scale.multiplyScalar( 100 ); this.el.setObject3D( 'mesh', this.terrain ); // Loop through each node in the scene and separate out the tiles // from the background and collision meshes. this.terrain.traverse( node => { if ( !node.metadata ) return; if ( node.metadata.type === 'SIMPLE' ) { this.collision = new SimpleTerrain( node ); this.collision.setVisible( this.isSimpleVisible ); return; } if ( node.metadata.type === 'BACKGROUND' ) { this.background = new BackgroundTerrain( node ); this.background.setVisible( this.isTerrainVisible ); return; } if ( node.metadata.type === 'TILE' ) { var mesh = new TileMesh( node ); this.tileMeshes.push( mesh ); this.tileMeshesByID[ mesh.id ] = mesh; } }); // Set up the simplified collision mesh this.el.appendChild( this.collision.el ); this.collision.setupMesh(); this.collision.bindEvents(); // Load the background terrain's texture, then resolve the promise this.background.loadTexture().then( () => resolve() ); }); }); }, /** * Loads each tile's initial textures. * Returns a promise which resolves when all initial textures are loaded */ loadInitialTextures: function() { return new Promise( ( resolve, reject ) => { if ( !this.tileMeshes.length ) return reject(); // Get array of promises for loading the initial set of textures const initialLoadPromises = this.tileMeshes.map( tilemesh => { return tilemesh.loadNextTextureSize(); }); // Execuse all promises and resolve when complete Promise.all( initialLoadPromises ).then( () => { resolve(); }); }); }, /** * Update the transition animation state */ tick: function( t, dt ) { // Adjust delta time so that it is 0..1 over ANIM_IN_DURATION seconds dt = ( dt / 1000 ) * ( 1 / ANIM_IN_DURATION ); // Roll the transition animation forward to 1 if the scene is visible and loaded, // otherwise roll it back to 0. if ( this.el.is( 'visible' ) && this.isTerrainVisible && this.el.sceneEl.is( 'intro-complete' ) ) { this.animIn += dt; } else { this.animIn -= dt; } this.animIn = MathUtils.clamp( this.animIn, 0, 1 ); // Update all tile meshes with new the animIn value this.tileMeshes.forEach( mesh => { mesh.updateMaterialAnimIn( this.animIn ); }); }, onIntersected: function( event ) { this.gridState = this.el.sceneEl.is( 'interactive' ) ? 2 : 0; this.updateGrid( event.detail.point ); }, onMouseMoved: function() { this.gridState--; this.updateGrid( ZERO_VECTOR ); }, onControllerMoved: function() { this.gridState = 0; this.updateGrid( ZERO_VECTOR ); }, /** * Update the grid overlay's position to match the cursor ray * position. Some extra math is required to compensate for * the variable size of the grid overlay. * * TODO: this could be optimized. Instead of every tile calculating the * scaled grid position, it should only be done once. */ updateGrid( point ) { const gridPosition = point.clone() .subScalar( GridSize / 2 ) .multiplyScalar( 1 / GridSize ); this.tileMeshes.forEach( mesh => { mesh.updateMaterialGrid( gridPosition, this.gridState ); }); }, setVisible: function( visible ) { this.background.setVisible( visible ); }, loadNextTextureSizeForID: function( id ) { return this.tileMeshesByID[ id ].loadNextTextureSize(); }, remove: function() { this.tileMeshes.forEach( mesh => mesh.destroy() ); this.collision.destroy(); this.background.destroy(); this.tileMeshes = []; this.tileMeshesByID = {}; this.el.removeObject3D( 'mesh' ); } }); } /** * TileMesh * * Class which contains a single terrain tile mesh, and handles loading and * initialization of its multi-size textures. */ class TileMesh { constructor( node ) { this.node = node; this.id = this.node.metadata.id; this.mesh = C4DUtils.getChildWithType( node, 'Mesh' ); this.animIn = 0; // Remove unused color geometry attribute this.mesh.geometry.removeAttribute( 'color' ); // Get the center coordinate of the tile by calculating the tile's bounding box. // The center coordinate is used to sort tiles by distance from the player so that // closer tiles load their higher-resolution textures first. this.box = new THREE.Box3(); this.box.setFromObject( this.mesh ); this.center = this.box.getCenter(); this.textureLoader = new THREE.TextureLoader(); this.texturesBySize = {}; this.textureSizePrefixes = []; this.currentTexture = undefined; this.currentSize = undefined; const isMobile = AFRAME.utils.device.isMobile(); const isCenterTile = CENTER_TILE_IDS.indexOf( this.id ) !== -1; this.hasMediumSize = this.node.metadata.hasMediumSize; // On mobile platforms, do not load the large size textures this.hasLargeSize = this.node.metadata.hasLargeSize && !isMobile; // On mobile platforms, only the four center tiles are allowed to load the medium // resolution texture, in order to save memory. if ( isMobile && !isCenterTile ) { this.hasMediumSize = false; } // Adjust texture size prefixes depending on what platform the user is on. // // Mobile platforms load only the xsmall and medium sizes. // Desktop platforms load the xsmall, then medium, then large sizes. if ( isMobile ) { this.textureSizePrefixes = [ this.node.metadata.xsmallPrefix, TEXTURE_SUFFIXES.base ]; } else { this.textureSizePrefixes = [ this.node.metadata.xsmallPrefix, TEXTURE_SUFFIXES.base, TEXTURE_SUFFIXES.large ]; } // The small texture size is a normal THREE.Texture object. It is displayed // normally and is the first texture the user will see when the terrain is // visible. Until this texture is loaded, the terrain will not be displayed // and a loading bar will be displayed to the user. this.texturesBySize.small = new THREE.Texture(); // The base size texture is a special ProgressiveTexture object which uses a // progressive loading technique to load JPEG data onto the GPU without causing // framerate stutters. // // This allows us to load the small texture size initially before the user sees anything, // and then as the user explores the environment, these higher resolution images will be // loaded in the background without disrupting the overall experience. // // This gives us a fast initial load, but also allows for the gradual loading of higher // resolution textures without interruption. if ( this.hasMediumSize ) { this.texturesBySize.base = new THREE.ProgressiveTexture( this.node.metadata.size ); } // Some tiles have a large size texture, which is 2x the base texture size. This texture // is also progressively loaded. if ( this.hasLargeSize && !isMobile ) { this.texturesBySize.large = new THREE.ProgressiveTexture( this.node.metadata.size * 2 ); } // Create a load proxy material. Because of the way the ProgressiveTexture loads // images, it will display garbage data until the loading is complete. We don't // want to show this garbage data, so the ProgressiveTexture is loaded into this // proxy material onto the proxy mesh, which is a small plane placed out of view. // Once the load is complete, the texture will be swapped onto the main tile mesh. // // The proxy material is set to use the base size texture, since that is the first // size which will be loaded using the progressive loader. if ( this.hasMediumSize ) { this.loadProxyMaterial = new THREE.MeshBasicMaterial(); this.loadProxyMaterial.map = this.texturesBySize.base; this.loadProxyMesh = new THREE.Mesh( LOAD_PROXY_GEO, this.loadProxyMaterial ); // Prevent the proxy mesh from being culled. Because the transfer of texture data // from the progressive JPEG loader to the GPU is done in the render thread, if // the proxy mesh is culled from the render queue, it will not update and // the progressive loading will stall. this.loadProxyMesh.frustumCulled = false; this.node.add( this.loadProxyMesh ); } // Create a standard terrain tile material. The texture map stored in loadProxyMaterial // will be swapped into this material once the progressive loading is complete. this.mesh.material = new THREE.ShaderMaterial({ uniforms: THREE.UniformsUtils.clone( TerrainShader.uniforms ), vertexShader: TerrainShader.vertexShader, fragmentShader: TerrainShader.fragmentShader }); // Enable wireframe mode if the scene flag is set this.mesh.material.wireframe = Scene.wireframe; // Set initial shader uniforms this.mesh.material.uniforms.gridTex.value = CommonTex.textures.grid; this.mesh.material.uniforms.triangleTex.value = CommonTex.textures.triangles; } /** * Loads the next texture size up in the texture size list. * Starts at size 0 if currentSize is undefined. * * Returns a promise which resolves when the texture is loaded. */ loadNextTextureSize() { return new Promise( ( resolve, reject ) => { // Set initial size to load or increment the current size if ( this.currentSize === undefined ) { this.currentSize = 0; } else { this.currentSize++; } // Requested a texture, but it doesn't exist; exit if ( this.currentSize > 2 ) return resolve( 'maximum size reached' ); if ( this.currentSize === 1 && !this.hasMediumSize ) return resolve( 'medium size doesn\'t exist' ); if ( this.currentSize === 2 && !this.hasLargeSize ) return resolve( 'large size doesn\'t exist' ); // Get the previous texture so it can be disposed of properly once the current // texture is loaded. if ( this.currentSize > 0 ) { this.previousTexture = this.texturesBySize[ TEXTURE_SIZES[ this.currentSize - 1 ] ]; } else { this.previousTexture = null; } // Grab the current texture object from the size list this.currentTexture = this.texturesBySize[ TEXTURE_SIZES[ this.currentSize ] ]; const url = Scene.rootDirectory + 'tiles/' + this.id + this.textureSizePrefixes[ this.currentSize ] + '.jpg'; // Only ProgressiveTextures need to be loaded with the JPEG worker. // Normal textures can be loaded with the standard TextureLoader. if ( this.currentTexture.isProgressiveTexture ) { // Texture doesn't exist, exit if ( !this.currentTexture ) return resolve( 'size doesn\'t exist' ); // Texture is already loaded, exit if ( this.currentTexture.displayed ) return resolve( 'texture is already loaded' ); // Set texture URL this.currentTexture.url = url; // Set jpeg worker host to the current texture JPEGWorker.host = this.currentTexture; // Release the jpeg worker host and update the material when // the current texture is displayed this.currentTexture.onDisplayComplete( () => { JPEGWorker.host = null; this.updateMaterialTexture(); this.destroyPreviousTexture(); return resolve( 'success: size = ' + TEXTURE_SIZES[ this.currentSize ] ); }); // Load using the static jpeg worker this.currentTexture.loadWithWorker( JPEGWorker.worker ); this.loadProxyMaterial.map = this.currentTexture; this.loadProxyMaterial.needsUpdate = true; } else { // Texture is already loaded, exit if ( this.currentTexture.image ) return resolve( 'texture is already loaded' ); // Load using the normal texture loader this.textureLoader.load( url, texture => { this.currentTexture = texture; this.updateMaterialTexture(); this.destroyPreviousTexture(); return resolve( 'success: size = ' + TEXTURE_SIZES[ this.currentSize ] ); }); } }); } /** * Updates the animIn value to a given number */ updateMaterialAnimIn( animIn ) { if ( !this.mesh ) return; if ( this.mesh.material.uniforms.animIn.value === animIn ) return; this.mesh.material.uniforms.animIn.value = animIn; } /** * Updates the terrain texture map to the current texture */ updateMaterialTexture() { if ( !this.mesh ) return; this.mesh.material.uniforms.terrainTex.value = this.currentTexture; this.mesh.material.needsUpdate = true; } /** * Updates the grid overlay's position and opacity state */ updateMaterialGrid( position, gridState ) { if ( !this.mesh ) return; this.mesh.material.uniforms.gridOpacity.value = gridState > 0 ? 1 : 0; this.mesh.material.uniforms.gridPosition.value = position.clone(); } /** * Dispose of the previously-loaded texture */ destroyPreviousTexture() { if ( !this.previousTexture ) return; this.previousTexture.dispose(); this.previousTexture = null; this.loadProxyMaterial.map = null; this.texturesBySize[ TEXTURE_SIZES[ this.currentSize - 1 ] ] = null; } /** * Attempts to dispose of (almost) every piece of memory this object references */ destroy() { if ( this.mesh ) { this.mesh.material.uniforms.terrainTex.value = null; this.mesh.material.dispose(); this.mesh.geometry.dispose(); this.mesh.geometry = null; } if ( this.loadProxyMaterial ) this.loadProxyMaterial.dispose(); if ( this.texturesBySize.base ) this.texturesBySize.base.dispose(); if ( this.texturesBySize.small ) this.texturesBySize.small.dispose(); if ( this.texturesBySize.large ) this.texturesBySize.large.dispose(); if ( this.currentTexture ) this.currentTexture.dispose(); if ( this.loadProxyMesh ) this.node.remove( this.loadProxyMesh ); this.texturesBySize = null; this.loadProxyMaterial = null; this.currentTexture = null; this.loadProxyMaterial = null; this.loadProxyMesh = null; this.mesh = null; this.node = null; } } /** * BackgroundTerrain * * Class which contains the low-res unwalkable background terrain mesh and loader * for the background mesh's texture. */ class BackgroundTerrain { constructor( node ) { this.node = node; this.mesh = C4DUtils.getChildWithType( this.node, 'Mesh' ); this.loader = new THREE.TextureLoader(); this.visible = false; // Remove unused color geometry attribute this.mesh.geometry.removeAttribute( 'color' ); } loadTexture() { return new Promise( ( resolve, reject ) => { const path = TERRAIN_DIR + Scene.baseFilename + '/background.jpg'; this.loader.load( path, texture => { this.uniforms = THREE.UniformsUtils.clone( TerrainShader.uniforms ); this.uniforms.terrainTex.value = texture; this.mesh.material = new THREE.ShaderMaterial({ uniforms: this.uniforms, fragmentShader: TerrainShader.fragmentShader, vertexShader: TerrainShader.vertexShader, visible: this.visible }); // Listen for initial-load-complete event from Scene, and show // the background terrain when it is thrown. Scene.on( 'initial-load-complete', event => { if ( !this.mesh ) return; this.mesh.material.uniforms.animIn.value = 1; this.mesh.material.needsUpdate = true; }); resolve(); }); }); } setVisible( visible ) { this.visible = visible; if ( this.mesh.material ) { this.mesh.material.visible = this.visible; } } destroy() { if ( this.mesh.material ) { this.mesh.material.uniforms.terrainTex.value = null; this.mesh.material.dispose(); } this.mesh.geometry.dispose(); this.mesh.geometry = null; this.mesh = null; this.node = null; } } /** * SimpleTerrain * * Class which contains the simplified terrain mesh, used for collision * detection and for displaying as a wireframe during scene loading. */ class SimpleTerrain { constructor( node ) { this.node = node; this.mesh = C4DUtils.getChildWithType( this.node, 'Mesh' ); this.visible = false; this.el = document.createElement( 'a-entity' ); this.el.classList.add( 'clickable' ); this.el.classList.add( 'ignoreBounds' ); this.el.setAttribute( 'consume-click', '' ); this.el.setObject3D( 'mesh', this.mesh ); this.el.id = 'collision'; this.cursorPosition = new THREE.Vector3(); this.cursorStart = new THREE.Vector3(); } setupMesh() { var terrainGeometry = this.mesh.geometry; // Convert the terrain's BufferGeometry to regular Geometry and back again. This // forces mergeVertices() to be called, which removes all duplicate vertices which // are left over from the mesh simplification process. terrainGeometry = new THREE.Geometry().fromBufferGeometry( terrainGeometry ); terrainGeometry = new THREE.BufferGeometry().fromGeometry( terrainGeometry ); // Generate barycentric coordinates for each triangle vertex. This is used by the edge-shader // to generate a wireframe effect. // // Based on http://codeflow.org/entries/2012/aug/02/easy-wireframe-display-with-barycentric-coordinates/ var position = terrainGeometry.attributes.position; var centers = new Float32Array( position.count * 3 ); for ( let i = 0, l = position.count; i < l; i++ ) { EDGE_VECTORS[ i % 3 ].toArray( centers, i * 3 ); } // Add the barycentric coordinate array to the terrain geometry as a vertex attribute terrainGeometry.addAttribute( 'center', new THREE.BufferAttribute( centers, 3 ) ); // Remove unused geometry attributes terrainGeometry.removeAttribute( 'uv' ); terrainGeometry.removeAttribute( 'color' ); this.material = new THREE.ShaderMaterial({ uniforms: EdgeShader.uniforms, vertexShader: EdgeShader.vertexShader, fragmentShader: EdgeShader.fragmentShader, visible: this.visible }); // Set uniforms this.material.uniforms.lineColor.value = new THREE.Color( 0x9b9087 ); this.material.uniforms.fillColor.value = new THREE.Color( 0x141312 ); this.material.uniforms.fogColor.value = new THREE.Color( 0x141312 ); this.material.extensions.derivatives = true; this.mesh = new THREE.Mesh( terrainGeometry, this.material ); this.el.setObject3D( 'mesh', this.mesh ); } setVisible( visible ) { this.visible = visible; if ( this.material ) { this.material.visible = this.visible; } } bindEvents() { this.el.addEventListener( 'raycaster-intersected', event => { if ( this.el.sceneEl.is( 'modal' ) ) return; this.cursorPosition.copy( event.detail.intersection.point ); this.el.sceneEl.emit( 'terrain-intersected', event.detail.intersection, false ); }); this.el.addEventListener( 'raycaster-intersected-cleared', event => { this.el.sceneEl.emit( 'terrain-intersected-cleared', null, false ); }); this.el.addEventListener( 'raycaster-cursor-down', event => { if ( this.el.sceneEl.is( 'modal' ) ) return; this.cursorStart.copy( this.cursorPosition ); this.el.sceneEl.emit( 'terrain-cursor-down', { point: this.cursorPosition }, false ); }); this.el.addEventListener( 'raycaster-cursor-up', event => { if ( this.el.sceneEl.is( 'modal' ) ) { this.el.sceneEl.emit( 'modal-up', null, false ); return; } this.cursorStart.sub( this.cursorPosition ); this.el.sceneEl.emit( 'terrain-cursor-up', { point: this.cursorPosition, buttonHoldTime: event.detail.buttonHoldTime, deltaSquared: this.cursorStart.lengthSq() }, false ); }); } destroy() { this.mesh.geometry.dispose(); this.mesh.geometry = null; this.mesh = null; this.node = null; } }
billwert/azure-sdk-for-java
sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/EnvironmentConfiguration.java
<filename>sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/EnvironmentConfiguration.java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.core.implementation.util; import com.azure.core.util.Configuration; import com.azure.core.util.ConfigurationSource; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Contains environment (system properties and environment variables) configuration information that is * used during construction of client libraries. */ public class EnvironmentConfiguration { /* * Configurations that are loaded into the global configuration store when the application starts. */ private static final Set<String> DEFAULT_CONFIGURATIONS = new HashSet<>(Arrays.asList( Configuration.PROPERTY_HTTP_PROXY, Configuration.PROPERTY_HTTPS_PROXY, Configuration.PROPERTY_IDENTITY_ENDPOINT, Configuration.PROPERTY_IDENTITY_HEADER, Configuration.PROPERTY_NO_PROXY, Configuration.PROPERTY_MSI_ENDPOINT, Configuration.PROPERTY_MSI_SECRET, Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID, Configuration.PROPERTY_AZURE_USERNAME, Configuration.PROPERTY_AZURE_PASSWORD, Configuration.PROPERTY_AZURE_CLIENT_ID, Configuration.PROPERTY_AZURE_CLIENT_SECRET, Configuration.PROPERTY_AZURE_TENANT_ID, Configuration.PROPERTY_AZURE_CLIENT_CERTIFICATE_PATH, Configuration.PROPERTY_AZURE_IDENTITY_DISABLE_CP1, Configuration.PROPERTY_AZURE_RESOURCE_GROUP, Configuration.PROPERTY_AZURE_CLOUD, Configuration.PROPERTY_AZURE_AUTHORITY_HOST, Configuration.PROPERTY_AZURE_TELEMETRY_DISABLED, Configuration.PROPERTY_AZURE_LOG_LEVEL, Configuration.PROPERTY_AZURE_HTTP_LOG_DETAIL_LEVEL, Configuration.PROPERTY_AZURE_TRACING_DISABLED, Configuration.PROPERTY_AZURE_POD_IDENTITY_TOKEN_URL, Configuration.PROPERTY_AZURE_REGIONAL_AUTHORITY_NAME, Configuration.PROPERTY_AZURE_REQUEST_RETRY_COUNT, Configuration.PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Configuration.PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Configuration.PROPERTY_AZURE_REQUEST_RESPONSE_TIMEOUT, Configuration.PROPERTY_AZURE_REQUEST_READ_TIMEOUT )); private static final EnvironmentConfiguration GLOBAL_CONFIGURATION = new EnvironmentConfiguration(); private final ConcurrentMap<String, String> explicitConfigurations; private final ConcurrentMap<String, Optional<String>> envConfigurations; private final ConcurrentMap<String, Optional<String>> sysPropertiesConfigurations; /** * Constructs a configuration containing the known Azure properties constants. */ private EnvironmentConfiguration() { this(EnvironmentVariablesConfigurationSource.GLOBAL_SOURCE, path -> Collections.emptyMap()); } /** * Clones original configuration. */ public EnvironmentConfiguration(EnvironmentConfiguration original) { this.explicitConfigurations = new ConcurrentHashMap<>(original.explicitConfigurations); this.envConfigurations = new ConcurrentHashMap<>(original.envConfigurations); this.sysPropertiesConfigurations = new ConcurrentHashMap<>(original.sysPropertiesConfigurations); } /** * Constructs a configuration containing mocked environment. Use this constructor for testing. */ public EnvironmentConfiguration(ConfigurationSource systemPropertiesConfigurationSource, ConfigurationSource environmentConfigurationSource) { this.explicitConfigurations = new ConcurrentHashMap<>(); if (environmentConfigurationSource == null) { environmentConfigurationSource = EnvironmentVariablesConfigurationSource.GLOBAL_SOURCE; } Map<String, String> fromEnvironment = environmentConfigurationSource.getProperties(null); Objects.requireNonNull(fromEnvironment, "'environmentConfigurationSource.getProperties(null)' can't be null"); this.envConfigurations = new ConcurrentHashMap<>(fromEnvironment.size()); for (Map.Entry<String, String> config : fromEnvironment.entrySet()) { this.envConfigurations.put(config.getKey(), Optional.ofNullable(config.getValue())); } if (systemPropertiesConfigurationSource == null) { this.sysPropertiesConfigurations = new ConcurrentHashMap<>(); } else { Map<String, String> fromSystemProperties = systemPropertiesConfigurationSource.getProperties(null); Objects.requireNonNull(fromSystemProperties, "'systemPropertiesConfigurationSource.getProperties(null)' can't be null"); this.sysPropertiesConfigurations = new ConcurrentHashMap<>(fromSystemProperties.size()); for (Map.Entry<String, String> config : fromSystemProperties.entrySet()) { this.sysPropertiesConfigurations.put(config.getKey(), Optional.ofNullable(config.getValue())); } } } public static EnvironmentConfiguration getGlobalConfiguration() { return GLOBAL_CONFIGURATION; } /** * Gets the value of the environment variable. * <p> * This method first checks the values previously loaded from the environment, if the configuration is found there * it will be returned. Otherwise, this will attempt to load the value from the environment. * * @param name Name of the configuration. * @return Value of the configuration if found, otherwise null. */ public String getEnvironmentVariable(String name) { return getOrLoad(name, envConfigurations, false); } /** * Gets the value of the system property. * <p> * This method first checks the values previously loaded from the environment, if the configuration is found there * it will be returned. Otherwise, this will attempt to load the value from the environment. * * @param name Name of the configuration. * @return Value of the configuration if found, otherwise null. */ public String getSystemProperty(String name) { return getOrLoad(name, sysPropertiesConfigurations, true); } /** * Gets the value of the configuration. * <p> * This method first checks the values previously loaded from the environment, if the configuration is found there * it will be returned. Otherwise, this will attempt to load the value from the environment. * * @param name Name of the configuration. * @return Value of the configuration if found, otherwise null. */ public String get(String name) { String value = explicitConfigurations.get(name); if (value != null) { return value; } value = getSystemProperty(name); if (value != null) { return value; } return getEnvironmentVariable(name); } /* * Attempts to get the value of the configuration from the configuration store, if the value isn't found then it * attempts to load it from the runtime parameters then the environment variables. * * If no configuration is found null is returned. * * @param name Configuration property name. * @return The configuration value from either the configuration store, runtime parameters, or environment * variable, in that order, if found, otherwise null. */ private String getOrLoad(String name, ConcurrentMap<String, Optional<String>> configurations, boolean loadFromSystemProperties) { Optional<String> value = configurations.get(name); if (value != null) { return value.orElse(null); } String envValue = loadFromSystemProperties ? loadFromProperties(name) : loadFromEnvironment(name); configurations.put(name, Optional.ofNullable(envValue)); return envValue; } /** * Adds a configuration with the given value. * <p> * This will overwrite the previous configuration value if it existed. * * @param name Name of the configuration. * @param value Value of the configuration. * @return The updated Configuration object. */ public EnvironmentConfiguration put(String name, String value) { explicitConfigurations.put(name, value); return this; } /** * Removes the configuration. * <p> * This returns the value of the configuration if it previously existed. * * @param name Name of the configuration. * @return The configuration if it previously existed, otherwise null. */ public String remove(String name) { return explicitConfigurations.remove(name); } private String loadFromEnvironment(String name) { return System.getenv(name); } private String loadFromProperties(String name) { return System.getProperty(name); } public static final class EnvironmentVariablesConfigurationSource implements ConfigurationSource { public static final ConfigurationSource GLOBAL_SOURCE = new EnvironmentVariablesConfigurationSource(); Map<String, String> configurations; private EnvironmentVariablesConfigurationSource() { configurations = new HashMap<>(); for (String config : DEFAULT_CONFIGURATIONS) { String value = System.getenv(config); if (value != null) { configurations.put(config, value); } } } @Override public Map<String, String> getProperties(String ignored) { return configurations; } } }
hephzaron/youth-interact
server/dist/helpers/GenerateTreeStructure.js
<gh_stars>0 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Node * @param { data } data * @returns { object } data */ function Node(data) { this.data = data; this.children = []; } /** * @class Tree */ var Tree = function () { /** * @constructor * @memberof Tree * @description Creates an instance of recipe review tree * @returns { object } reviews */ function Tree() { (0, _classCallCheck3.default)(this, Tree); this.root = null; } /** * Add children to parent node * @method add * @memberof Tree * @param { object } data * @param { object } toNodeData * @returns {object} node */ (0, _createClass3.default)(Tree, [{ key: 'add', value: function add(data, toNodeData) { var node = new Node(data); var parent = toNodeData ? this.findBFS(toNodeData) : null; if (parent) { parent.children.push(node); } else { if (!this.root) { this.root = node; } return 'Root node is already assigned'; } } /** * Finds node to to add data to using BFS * @param { object } data * @returns { object } node */ }, { key: 'findBFS', value: function findBFS(data) { var queue = [this.root]; while (queue.length) { var node = queue.shift(); if (_lodash2.default.isEqual(node.data, data)) { return node; } node.children.map(function (child) { return queue.push(child); }); } return null; } }]); return Tree; }(); exports.default = Tree;
jsaveta/SPIMBench
src/eu/ldbc/semanticpublishing/transformations/logical/CWSameAs.java
<filename>src/eu/ldbc/semanticpublishing/transformations/logical/CWSameAs.java package eu.ldbc.semanticpublishing.transformations.logical; import java.util.Random; import org.openrdf.model.Model; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.model.impl.LinkedHashModel; import eu.ldbc.semanticpublishing.generators.data.AbstractAsynchronousWorker; import eu.ldbc.semanticpublishing.generators.data.sesamemodelbuilders.SesameBuilder; import eu.ldbc.semanticpublishing.transformations.Transformation; import eu.ldbc.semanticpublishing.transformations.TransformationConfiguration; public class CWSameAs implements Transformation{ AbstractAsynchronousWorker worker; private static final String rdfTypeNamespace = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"; private static final String owlsameAs = "http://www.w3.org/2002/07/owl#sameAs"; private static final String thing = "http://www.bbc.co.uk/things"; private static final String cworkNamespace = "http://www.bbc.co.uk/ontologies/creativework/"; Random random = new Random(); public CWSameAs(AbstractAsynchronousWorker worker){ this.worker = worker; } @Override public Object execute(Object arg) { return null; } @Override public String print() { // TODO Auto-generated method stub return null; } @Override public Model executeStatement(Statement st) { Model model = new LinkedHashModel(); Model sameAsModel = new LinkedHashModel(); int randomIndexSameAs = 0; Value object = null; Value o11 = null; Resource subject_original_cw = null; URI predicate_original_cw = null; Resource subject_sameas = null; Boolean sameAsStatement = false; if(!worker.getsesameModelArrayList().isEmpty() && worker.getsesameModelArrayList().size() >= 2){ int times = 0; do{ while(randomIndexSameAs != 0){ randomIndexSameAs = random.nextInt(worker.getsesameModelArrayList().size()); } sameAsModel = worker.getsesameModel2ArrayList().get(randomIndexSameAs); Model s11 = worker.getsesameModelArrayList().get(randomIndexSameAs); for (Statement stat : sameAsModel){ object = stat.getObject(); subject_original_cw = stat.getSubject(); predicate_original_cw = stat.getPredicate(); for (Statement st1 : s11){ o11 = st1.getObject(); break; } break; } times++; //TODO check this while statement }while((times < worker.getsesameModelArrayList().size()) && !o11.toString().equals(object.toString()) && (!object.toString().contains("NewsItem")|| !object.toString().contains("Programme")|| !object.toString().contains("BlogPost")|| !subject_original_cw.toString().startsWith(thing)) && !predicate_original_cw.toString().equals(rdfTypeNamespace)); subject_sameas = SesameBuilder.sesameValueFactory.createURI(worker.getru().GenerateUniqueID(subject_original_cw.toString())); } if(subject_sameas != null){ for (Statement statement : sameAsModel){ if(!statement.getSubject().toString().equals(subject_original_cw.toString())){ if(!sameAsStatement){ worker.getSesameModel_2().add(subject_sameas , SesameBuilder.sesameValueFactory.createURI(owlsameAs),subject_original_cw,(Resource)null); sameAsStatement = true; } worker.getSesameModel_2().add((Resource)statement.getSubject(), (URI)statement.getPredicate(),(Value) statement.getObject(), (Resource)statement.getContext()); } else{ if(statement.getPredicate().toString().equals(cworkNamespace + "title")){ Model tempModel = TransformationConfiguration.aggregatePROPERTIES(worker).executeStatement(statement); if(!tempModel.isEmpty()){ for (Statement tempStatement : tempModel){ worker.getSesameModel_2().add((Resource)subject_sameas,(URI)tempStatement.getPredicate(),(Value)tempStatement.getObject(),(Resource)statement.getContext()); } } } // else if(statement.getPredicate().toString().equals(cworkNamespace + "dateCreated") || statement.getPredicate().toString().equals(cworkNamespace + "dateModified")){ // Object temp = (String) TransformationConfiguration.dateFORMAT("yyyy-MM-dd HH:mm:ss", DateFormat.SHORT).execute(statement.getObject().toString()).toString(); // if (temp instanceof Value){ // worker.getSesameModel_2().add(subject_sameas, (URI)statement.getPredicate(),(Value)temp, (Resource)statement.getContext()); // } // } else if (statement.getPredicate().toString().equals(rdfTypeNamespace)){ worker.getSesameModel_2().add(subject_sameas, (URI)statement.getPredicate(),(Value) statement.getObject(), (Resource)statement.getContext()); } else{ String temp = (String) TransformationConfiguration.deleteRANDOMCHARS(0.2).execute(statement.getObject().toString()).toString(); worker.getSesameModel_2().add(subject_sameas, (URI)statement.getPredicate(),SesameBuilder.sesameValueFactory.createLiteral(temp.replace("\"", "")), (Resource)statement.getContext()); } } } } if(subject_original_cw != null){ model.add(subject_original_cw,SesameBuilder.sesameValueFactory.createURI(owlsameAs),subject_sameas,(Resource)null); } return model; } }
evmorov/ruby-coffeescript
code/python/array_get_first_and_last.py
<reponame>evmorov/ruby-coffeescript arr = ['one', 'two'] print(arr[0]) print(arr[-1])
sudeshana/carbon-governance
components/governance/org.wso2.carbon.governance.list.ui/src/main/java/org/wso2/carbon/governance/list/ui/clients/ListMetadataServiceClient.java
/* * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 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 * * 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.wso2.carbon.governance.list.ui.clients; import org.apache.axis2.AxisFault; import org.apache.axis2.client.Options; import org.apache.axis2.client.ServiceClient; import org.apache.axis2.context.ConfigurationContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.governance.list.stub.ListMetadataServiceStub; import org.wso2.carbon.governance.list.stub.beans.xsd.PolicyBean; import org.wso2.carbon.governance.list.stub.beans.xsd.SchemaBean; import org.wso2.carbon.governance.list.stub.beans.xsd.ServiceBean; import org.wso2.carbon.governance.list.stub.beans.xsd.WSDLBean; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.ui.CarbonUIUtil; import org.wso2.carbon.utils.ServerConstants; import javax.servlet.ServletConfig; import javax.servlet.http.HttpSession; public class ListMetadataServiceClient { private static final Log log = LogFactory.getLog(ListMetadataServiceClient.class); private ListMetadataServiceStub stub; private String epr; public ListMetadataServiceClient( String cookie, String backendServerURL, ConfigurationContext configContext) throws RegistryException { epr = backendServerURL + "ListMetadataService"; try { stub = new ListMetadataServiceStub(configContext, epr); ServiceClient client = stub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); } catch (AxisFault axisFault) { String msg = "Failed to initiate ListMetadataServices service client. " + axisFault.getMessage(); log.error(msg, axisFault); throw new RegistryException(msg, axisFault); } } public ListMetadataServiceClient(ServletConfig config, HttpSession session) throws RegistryException { String cookie = (String)session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); ConfigurationContext configContext = (ConfigurationContext) config. getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); epr = backendServerURL + "ListMetadataService"; try { stub = new ListMetadataServiceStub(configContext, epr); ServiceClient client = stub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); } catch (AxisFault axisFault) { String msg = "Failed to initiate Add Services service client. " + axisFault.getMessage(); log.error(msg, axisFault); throw new RegistryException(msg, axisFault); } } public ServiceBean listservices(String criteria) throws Exception{ return stub.listservices(criteria); } public WSDLBean listwsdls() throws Exception{ return stub.listwsdls(); } public WSDLBean listWsdlsByName(String wsdlName) throws Exception{ return stub.listWsdlsByName(wsdlName); } public PolicyBean listpolicies() throws Exception{ return stub.listpolicies(); } public PolicyBean listPoliciesByName(String policyName) throws Exception{ return stub.listPoliciesByNames(policyName); } public SchemaBean listschemas() throws Exception{ return stub.listschema(); } public SchemaBean listSchemasByName(String name) throws Exception{ return stub.listSchemaByName(name); } }
annabranco/zombie-mix
src/setup/zombies.js
import Walker from '../assets/images/zombies/walker.jpg'; import WalkerSmall from '../assets/images/zombies/walker-small.jpg'; import Runner from '../assets/images/zombies/runner.jpg'; import RunnerSmall from '../assets/images/zombies/runner-small.jpg'; import Fatty from '../assets/images/zombies/fatty.jpg'; import FattySmall from '../assets/images/zombies/fatty-small.jpg'; import Abomination from '../assets/images/zombies/abomination.jpg'; import AbominationSmall from '../assets/images/zombies/abomination-small.jpg'; import Horde from '../assets/images/zombies/horde.jpg'; import HordeSmall from '../assets/images/zombies/horde-small.jpg'; import Dogz from '../assets/images/zombies/dogz.jpg'; import DogzSmall from '../assets/images/zombies/dogz-small.jpg'; import DogzIntro from '../assets/images/zombies/Dogz.png'; import WalkerIntro from '../assets/images/zombies/Walker.png'; import RunnerIntro from '../assets/images/zombies/Runner.png'; import FattyIntro from '../assets/images/zombies/Fatty.png'; import AbominationIntro from '../assets/images/zombies/Abomination.png'; import { ZOMBIE } from '../constants'; export const ZOMBIES_S1 = { Walker: { img: Walker, imgSmall: WalkerSmall, intro: WalkerIntro, name: 'Walker', sounds: 9, type: ZOMBIE }, Runner: { img: Runner, imgSmall: RunnerSmall, intro: RunnerIntro, name: 'Runner', sounds: 5, special: 'Instant kill', type: ZOMBIE }, Fatty: { img: Fatty, imgSmall: FattySmall, intro: FattyIntro, name: 'Fatty', sounds: 5, type: ZOMBIE }, Abomination: { img: Abomination, imgSmall: AbominationSmall, intro: AbominationIntro, name: 'Abomination', sounds: 4, type: ZOMBIE }, Horde: { img: Horde, imgSmall: HordeSmall, name: 'Horde', sounds: 2, type: ZOMBIE, special: 'Feast on survivor' } }; export const DOGZ = { Dogz: { img: Dogz, imgSmall: DogzSmall, intro: DogzIntro, name: 'Dogz', sounds: 5, special: 'Instant kill', type: ZOMBIE } };
TaffarelXavier/next.js-starter-project
storybook/config.js
import './styles'; import { configure } from '@storybook/react'; import { setOptions } from '@storybook/addon-options'; setOptions({ name: 'Project UI', url: '#', showAddonPanel: false, hierarchySeparator: /\/|\./, hierarchyRootSeparator: /\|/, }); function importAll(req) { req.keys().forEach(filename => req(filename)); } function loadStories() { let req; req = require.context('./stories', true, /\.story\.js$/); importAll(req); req = require.context('../src/components', true, /\.story\.js$/); importAll(req); } configure(loadStories, module);
jckr/react-sim
src/index.js
<filename>src/index.js import React from 'react'; import styles from './styles.module.css'; export { default as CanvasFrame, CanvasFrameComponent } from './canvas-frame'; export { default as CheckboxComponent } from './checkbox'; export { default as Controls, Checkbox, Input, Radio, Range, Select, Timer, Toggle } from './controls'; export { default as Grid, GridComponent } from './grid'; export { default as InputComponent } from './input'; export { default as Model, withTheme, withFrame, withControls } from './model'; export { default as RadioComponent } from './radio'; export { default as RangeComponent } from './range'; export { default as SelectComponent } from './select'; export { default as TimerComponent } from './timer'; export { TimeSeries, Indicator, Counter, CounterComponent, IndicatorComponent, TimeSeriesComponent } from './time-series'; export { default as ToggleComponent } from './toggle'; export const ExampleComponent = ({ text }) => { return <div className={styles.test}>Example Component: {text}</div>; };
ludovic-chaboud/docker-dashboard
index/routes/images.js
<reponame>ludovic-chaboud/docker-dashboard<gh_stars>0 module.exports = __ => { const {app, docker} = __; app.get('/images', function(req, res) { docker.listImages({all: true}, function(err, images) { if(err) { res.send(err) } else { res.send(images) } }); }); require('./images/remove')(__); }
fredsterorg/incubator-pinot
pinot-plugins/pinot-batch-ingestion/v0_deprecated/pinot-hadoop/src/main/java/org/apache/pinot/hadoop/job/reducers/AvroDataPreprocessingReducer.java
/** * 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.pinot.hadoop.job.reducers; import java.io.IOException; import org.apache.avro.generic.GenericRecord; import org.apache.avro.mapred.AvroKey; import org.apache.avro.mapred.AvroValue; import org.apache.avro.mapreduce.AvroMultipleOutputs; import org.apache.commons.lang3.RandomStringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapreduce.Reducer; import org.apache.pinot.hadoop.job.InternalConfigConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AvroDataPreprocessingReducer<T> extends Reducer<T, AvroValue<GenericRecord>, AvroKey<GenericRecord>, NullWritable> { private static final Logger LOGGER = LoggerFactory.getLogger(AvroDataPreprocessingReducer.class); private AvroMultipleOutputs _multipleOutputs; private long _numRecords; private int _maxNumRecordsPerFile; private String _filePrefix; @Override public void setup(Context context) { Configuration configuration = context.getConfiguration(); // If it's 0, the output file won't be split into multiple files. // If not, output file will be split when the number of records reaches this number. _maxNumRecordsPerFile = configuration.getInt(InternalConfigConstants.PREPROCESSING_MAX_NUM_RECORDS_PER_FILE, 0); if (_maxNumRecordsPerFile > 0) { LOGGER.info("Using multiple outputs strategy."); _multipleOutputs = new AvroMultipleOutputs(context); _numRecords = 0L; _filePrefix = RandomStringUtils.randomAlphanumeric(4); LOGGER.info("Initialized AvroDataPreprocessingReducer with maxNumRecordsPerFile: {}", _maxNumRecordsPerFile); } else { LOGGER.info("Initialized AvroDataPreprocessingReducer without limit on maxNumRecordsPerFile"); } } @Override public void reduce(final T inputRecord, final Iterable<AvroValue<GenericRecord>> values, final Context context) throws IOException, InterruptedException { if (_maxNumRecordsPerFile > 0) { for (final AvroValue<GenericRecord> value : values) { String fileName = _filePrefix + (_numRecords++ / _maxNumRecordsPerFile); _multipleOutputs.write(new AvroKey<>(value.datum()), NullWritable.get(), fileName); } } else { for (final AvroValue<GenericRecord> value : values) { context.write(new AvroKey<>(value.datum()), NullWritable.get()); } } } @Override public void cleanup(Context context) throws IOException, InterruptedException { LOGGER.info("Clean up reducer."); if (_multipleOutputs != null) { _multipleOutputs.close(); _multipleOutputs = null; } LOGGER.info("Finished cleaning up reducer."); } }
froyomu/imsdk-android
imsdk/src/main/java/com/qunar/im/ui/util/atmanager/AtContactsModel.java
package com.qunar.im.ui.util.atmanager; import com.qunar.im.base.util.LogUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Created by hzchenkang on 2017/7/7. * * @ 联系人数据 */ public class AtContactsModel { // 已@ 的成员 private Map<String, AtBlock> AtBlocks = new HashMap<>(); // 清除所有的@块 public void reset() { AtBlocks.clear(); } public Map<String, String> getAtBlocks() { Map<String, String> map = new HashMap<>(); Iterator<String> iterator = AtBlocks.keySet().iterator(); while (iterator.hasNext()) { String account = iterator.next(); AtBlock block = AtBlocks.get(account); if (block.valid()) { LogUtil.i("atmanager", "block : account = " + account + " text = " + block.text); map.put(account, block.text); } } return map; } public void addAtMember(String account, String name, int start) { AtBlock AtBlock = AtBlocks.get(account); if (AtBlock == null) { AtBlock = new AtBlock(name); AtBlocks.put(account, AtBlock); } AtBlock.addSegment(start); } // 查所有被@的群成员 public List<String> getAtTeamMember() { List<String> teamMembers = new ArrayList<>(); Iterator<String> iterator = AtBlocks.keySet().iterator(); while (iterator.hasNext()) { String account = iterator.next(); AtBlock block = AtBlocks.get(account); if (block.valid()) { teamMembers.add(account); } } return teamMembers; } public AtBlock getAtBlock(String account) { return AtBlocks.get(account); } // 找到 curPos 恰好命中 end 的segment public AtBlock.AtSegment findAtSegmentByEndPos(int start) { Iterator<String> iterator = AtBlocks.keySet().iterator(); while (iterator.hasNext()) { String account = iterator.next(); AtBlock block = AtBlocks.get(account); AtBlock.AtSegment segment = block.findLastSegmentByEnd(start); if (segment != null) { return segment; } } return null; } // 文本插入后更新@块的起止位置 public void onInsertText(int start, String changeText) { Iterator<String> iterator = AtBlocks.keySet().iterator(); while (iterator.hasNext()) { String account = iterator.next(); AtBlock block = AtBlocks.get(account); block.moveRight(start, changeText); if (!block.valid()) { iterator.remove(); } } } // 文本删除后更新@块的起止位置 public void onDeleteText(int start, int length) { Iterator<String> iterator = AtBlocks.keySet().iterator(); while (iterator.hasNext()) { String account = iterator.next(); AtBlock block = AtBlocks.get(account); block.moveLeft(start, length); if (!block.valid()) { iterator.remove(); } } } }
hyh123a/myems
web/src/components/MyEMS/auth/basic/ChangePassword.js
<filename>web/src/components/MyEMS/auth/basic/ChangePassword.js import React from 'react'; import ChangePasswordForm from '../ChangePasswordForm'; import { withTranslation } from 'react-i18next'; const ChangePassword = ({ t }) => { return ( <ChangePasswordForm /> ); }; export default withTranslation()(ChangePassword);
ChiaraCism/mondora-website-front
app/pages/inbox/inbox.js
angular.module("mnd-web.pages") .controller("InboxController", ["$scope", function ($scope) { var notificationsRQ = $scope.Notifications.reactiveQuery({}); notificationsRQ.on("change", function () { $scope.safeApply(function () { $scope.notifications = notificationsRQ.result; }); }); $scope.notifications = notificationsRQ.result; }]);
Segfault5/HoverCar
XivelySDKAndroid/src/main/java/com/xively/internal/connection/package-info.java
<reponame>Segfault5/HoverCar<filename>XivelySDKAndroid/src/main/java/com/xively/internal/connection/package-info.java /** * Connection APIs for Xively Messaging (MQTT). */ package com.xively.internal.connection;
AswinBarath/C-Programming-for-Engineers
PSP Lab Work/Lab 5 - Solving problems using String Functions/StringConcatenation.c
// strcat(s1, s2) concatenates(joins) the second string s2 to the first string s1. #include <stdio.h> #include <string.h> int main() { char s2[] = "World"; char s1[20] = "Hello"; strcat(s1, s2); printf("Source string = %s\n", s2); printf("Target string = %s\n", s1); return 0; }
biocodellc/biscicol-ui
webpack.config.js
<reponame>biocodellc/biscicol-ui const path = require('path'); const fs = require('fs'); // Modules const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); /** * Env * Get npm lifecycle event to identify the environment */ const ENV = process.env.npm_lifecycle_event; const isTest = ENV === 'test' || ENV === 'test-watch'; const isProd = ENV === 'build'; const PORT = 3000; // Helper functions function root(args) { args = Array.prototype.slice.call(arguments, 0); return path.join(...[__dirname].concat(args)); } const css = (extend = []) => { if (isTest) return ['null-loader']; // Reference: https://github.com/postcss/postcss-loader // Postprocess your css with PostCSS plugins // Reference: https://github.com/webpack-contrib/mini-css-extract-plugin // Extract css files in production builds // // Reference: https://github.com/webpack/style-loader // Use style-loader in development. return [ isProd ? { loader: MiniCssExtractPlugin.loader, options: { hmr: !isProd, }, } : 'style-loader', isProd ? 'css-loader' : { loader: 'css-loader', options: { sourceMap: !isProd, importLoaders: 1 }, }, isProd ? 'postcss-loader' : { loader: 'postcss-loader', options: { sourceMap: !isProd, config: { path: './postcss.config.js' }, }, }, ].concat(extend); }; module.exports = (function makeWebpackConfig() { /** * Config * Reference: http://webpack.github.io/docs/configuration.html * This is the object where all configuration gets set */ const config = {}; config.mode = isProd ? 'production' : 'development'; /** * Entry * Reference: http://webpack.github.io/docs/configuration.html#entry * Should be an empty object if it's generating a test build * Karma will set this when it's a test build */ config.entry = isTest ? void 0 : { app: ['babel-polyfill', './src/app/app.js'], }; /** * Output * Reference: http://webpack.github.io/docs/configuration.html#output * Should be an empty object if it's generating a test build * Karma will handle setting it up for you when it's a test build */ config.output = isTest ? {} : { // Absolute output directory path: `${__dirname}/dist`, // Output path from the view of the page // Uses webpack-dev-server in development // publicPath: isProd ? '/' : `http://0.0.0.0:${PORT}/`, publicPath: isProd ? '/' : `http://localhost:${PORT}/`, // Filename for entry points // Only adds hash in build mode filename: isProd ? '[name].[hash].js' : '[name].bundle.js', // Filename for non-entry points // Only adds hash in build mode chunkFilename: isProd ? '[name].[hash].js' : '[name].bundle.js', pathinfo: !isProd, // needed for Web Workers globalObject: 'this', }; /** * Loaders * Reference: http://webpack.github.io/docs/configuration.html#module-loaders * List: http://webpack.github.io/docs/list-of-loaders.html * This handles most of the magic responsible for converting modules */ // Initialize module config.module = { rules: [ { // JS LOADER // Reference: https://github.com/babel/babel-loader // Transpile .js files using babel-loader // Compiles ES6 and ES7 into ES5 code // NOTICE: babel-loader must be the first loader. Otherwise // the sourceMappings will be incorrect, preventing breakpoints from being set in // certain situations test: /\.js$/, use: [ { loader: 'babel-loader', }, ], include: [ path.resolve(__dirname, 'src', 'app'), path.resolve(__dirname, 'config'), ], }, // WebWorker loader { test: /\.worker\.js$/, use: { loader: 'worker-loader' }, }, { // support for .scss files // all sass not in src/app will be bundled in an external css file test: /\.(scss|sass)$/, exclude: root('src', 'app'), use: css([ { loader: 'sass-loader', options: { sourceComments: !isProd, sourceMap: !isProd }, }, ]), }, { // all sass required in src/app files will be merged in js files test: /\.(scss|sass)$/, include: root('src', 'app'), loader: 'style!css?sourceMap!postcss?sourceMap!sass?sourceMap', }, { // CSS LOADER // Reference: https://github.com/webpack/css-loader // Allow loading css through js test: /\.css$/, use: css(), }, { // ASSET LOADER // Reference: https://github.com/webpack/file-loader // Copy png, jpg, jpeg, gif, svg, woff, woff2, ttf, eot files to output // Rename the file using the asset hash // Pass along the updated reference to your code // You can add here any file extension you want to get copied to your output test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/, loader: 'file-loader', }, { // HTML LOADER // Reference: https://github.com/webpack/raw-loader // Allow loading html through js test: /\.html$/, loader: 'raw-loader', }, ], }; // creates an alias "config" that we can use to import a config file // dependent on the current CONFIG_ENV const fallbackConfig = fs.existsSync( path.join(__dirname, 'config', 'local.js'), ) ? 'local' : 'default'; config.resolve = { alias: { config: path.join( __dirname, 'config', process.env.CONFIG_ENV ? process.env.CONFIG_ENV : fallbackConfig, ), }, }; // ISTANBUL LOADER // https://github.com/deepsweet/istanbul-instrumenter-loader // Instrument JS files with istanbul-lib-instrument for subsequent code coverage reporting // Skips node_modules and files that end with .spec.js if (isTest) { config.module.rules.push({ enforce: 'pre', test: /\.js$/, exclude: [/node_modules/, /\.spec\.js$/], loader: 'istanbul-instrumenter-loader', query: { esModules: true, }, }); } /** * PostCSS * Reference: https://github.com/postcss/autoprefixer-core * Add vendor prefixes to your css */ // NOTE: This is now handled in the `postcss.config.js` /** * Plugins * Reference: http://webpack.github.io/docs/configuration.html#plugins * List: http://webpack.github.io/docs/list-of-plugins.html */ config.plugins = [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', L: 'leaflet', }), new webpack.HotModuleReplacementPlugin(), ]; // Skip rendering index.html in test mode if (!isTest) { // Reference: https://github.com/ampedandwired/html-webpack-plugin // Render index.html config.plugins.push( new HtmlWebpackPlugin({ template: './src/public/index.html', inject: 'body', }), new webpack.EnvironmentPlugin({ MAPBOX_TOKEN: null, FIMS_CLIENT_ID: null, }), ); } /** * Devtool * Reference: http://webpack.github.io/docs/configuration.html#devtool * Type of sourcemap to use per build type */ if (isTest) { config.devtool = 'inline-source-map'; } else if (isProd) { config.devtool = 'source-map'; } else { // config.devtool = 'cheap-module-source-map'; config.devtool = 'eval-source-map'; } if (isProd) { // configure optimizations config.optimization = { splitChunks: { cacheGroups: { // create a seperate bundle for node_modules vendors: { name: 'vendors', test: /[\\/]node_modules|(src\/vendor)[\\/]/, chunks: 'all', reuseExistingChunk: true, }, // Extract css to single file https://github.com/webpack-contrib/mini-css-extract-plugin#extracting-all-css-in-a-single-file styles: { name: 'styles', test: /\.css$/, chunks: 'all', enforce: true, }, }, }, }; // Add build specific plugins config.plugins.push( // Reference: https://github.com/webpack-contrib/mini-css-extract-plugin // Extract css files new MiniCssExtractPlugin({ filename: 'css/[name]-[hash:6].css', allChunks: true, }), // Copy assets from the public folder // Reference: https://github.com/kevlened/copy-webpack-plugin new CopyWebpackPlugin([ { from: `${__dirname}/src/public`, }, ]), ); } /** * Dev server configuration * Reference: http://webpack.github.io/docs/configuration.html#devserver * Reference: http://webpack.github.io/docs/webpack-dev-server.html */ config.devServer = { contentBase: './src/public', historyApiFallback: true, // hot: true, hotOnly: true, // no page reload as fallback // stats: 'minimal', port: PORT, }; return config; })();
comprakt/comprakt-fuzz-tests
output/af8df178b1894a91b5c68a7433bf72b9.java
class lnWY9pbh6 { } class Y { public static void ouuWhlxZ98 (String[] RVkyx2o) throws Dc9aEn { !!--null[ !!-new gdHxImHYe0gK()[ false[ -!new AMb()[ VvmjyG55ciyqKU()[ new v().VvwNpSnzeiV0db]]]]]; } public void[][] Ckxqx; public boolean _7gpN () throws TDOtiBz64 { { int bOvSvsByqB66w; R q9BXpmlaU; int[] dF7EREJ0oxC34J; boolean[][][][] T; int[][] xsg8_51ZYGqj; void[] _jZ; void[] A; while ( this[ -!-( 8752.u()).N7l3JNC7()]) while ( -!-gJE261.KkhZ09hXrQdjBv()) return; void[] AbNR; while ( !!new BQWS().J3XOnUYm_gs) if ( false[ ---!!this[ !false[ !-new ghsFpJQzd0().BQBIn]]]) if ( new boolean[ null[ false[ !!-this[ !-new void[ ---true.HTEoN9bP].GxMnzBHe()]]]][ --new void[ this[ null[ uJQ7h.fORnAWSjs()]]].Raz]) new gExZDfWWMbFdO5()._mnVN692(); void[] JxUSLo9; while ( 4[ new pYPNT().H0pN77Ck()]) this.EPDlpdxCRb; } EUhKAr[] lJK3XpHqlpu; boolean P = !-new gFg5loy1oGH8Z().sba70s; while ( !-NojiPUty8sLcxG.Rlf2mmObCqk) return; K Ukqi_jMvB_O8; void gQrqWKffOkxm0 = -!-!309124[ AoRWaP1.LL7HH3a3D] = -( this.VBbExs9GqyDPS).ouWL(); !true[ !( new qC9t[ bhoT4ADl44C()[ -this[ !new t3NJCa()[ -new l7Sfa5sZ().Pz5g()]]]].gW)[ null.CMrzVILWegKeaw()]]; false.QxyGk; while ( -true.gKcEoVmiMfAyjQ) !new x6YpHoabE5[ -!-!--new bZ04Y1().Lte7].AL1JP1KO8pBFa(); boolean jpytvq = !!( -this.qGD).cqZV5mzS0() = --!--new P9BJVpb()[ -!false.X8H1fnw908YFA2()]; int cHiYwbIPJg5L; void sBwd5H; ; return true.wUPK; if ( -ErM.ajtXk0XkGKfG()) { return; } while ( !-!-new boolean[ 7067705.sm1Ad47wZXj()].lxlPru1) while ( -!7095924.nCL8bGW0()) null[ -43.GeClmJ8ERjXPD]; ; mf[] dQi = this.qI5ZNhGL_J(); boolean eI4y32SVAUfCQ = true[ -new int[ 1362144.qOjoTiSe][ cDc0g6JR().AT52FXx]] = null[ !bSF0W.JQMMNuBeX]; if ( -!!-f9R.l1cN()) ;else { void f; } } public boolean DA () throws i3M7BJvNV { void[] CUJ = !!true.AWYwGM4t; { if ( -CpwAMig4L8.x) while ( !null[ --new int[ !!new boolean[ IuX8fdX[ this[ ( !true[ !-!-!!-!og.dmMks3()]).pXGVtPLXEH_o()]]][ !!false.Er()]][ !null[ -new cHdjSwj1qm()[ ( -new iugQc6538hd3T()[ true.pRRXql9W]).cE_6GpnM]]]]) { while ( this[ 43.qSDUdmxToxmeB]) return; } return; } XDBo9wQ[] _XfWvT; rR8v4Fn oD7lTrPm14xaq7; { return; { boolean[] xlgqOedi; } return; -!-new PkoJfBBLt4()[ !!!new rl9d6fIcYr().pw]; boolean[][][] Q7o6; R_0Xq_kzHtDho[][] ihR5FHPstX; while ( !this.cdeV0NPth_) 2.Sl8PwGU(); int xkI; ; Gu CmiIvNYbW; return; KYf0CoFVTD[][][] hJCTevlUm0s; while ( !!new int[ !---!this[ true.ISWpDl()]].RAgDIoI()) if ( 987385559[ -MkfazrAttPsam2().UOFJbXmGf__()]) if ( 6.O1mxKI) return; int fE2SOSe; !false[ w6()[ true.olFDnr4VL()]]; int[] F97ziumaf; boolean p_8; } } public int ubf () throws nb9zpfHPkLCcQ { { void sveQegqxrI; void B_qB7K; !new void[ sey28.VroMdlRkfE].CvnEqyp0RW(); if ( null.y8A9_FL6v) -false.LOXORzpwo; boolean[] jHfr; I8NZ gTQPl; while ( 635453.H) ; 71128700.Ap; boolean[][][][][] k_BPNlkCp; while ( new dFUXuctTi()[ false.top()]) { void[][][][][][][] zXA; } new TPfhqF9().fr8PMRBM4qCVk(); void[] nmUlEfVVEm; Jrry[][][] OymqmuA; return; void rIckC1HQt_wa; while ( null.ag()) while ( SDW23K[ !false[ 56144354.vXShuFUldyn]]) return; int[][][] C27WELyzGTLTvA; { return; } } return this.lLcpNtZ(); void[][] u4Cb1ZA7b; { if ( -this.kare2lqxxNhn()) return; this[ -null[ !( jpXZil0CUUWO()[ this.XNHs])[ -!!68732.xH()]]]; boolean e0vQb; while ( false[ ( Vi()[ SIsV1OY0BS.y_FAfEA0()]).VkNVvYnM]) while ( new int[ oQENZ2P.EzyB3nuePH][ false[ !null.AgT4NJ()]]) -!( UkcplIsgROt().GFEFAKurwbU).H8W(); int[] tLQz2Ig8ob; LFokIIFsfYZA[] or_ZastLjYjIj; return; boolean[][][][] ed; while ( 5464.MrJML3mGQW) return; w9Wc Ql14tGlgSo; ; boolean K7KyskMm9; boolean[][][][][][] N7cVqBEpXti; if ( this[ --( --!!---false.NoWDg07ZY2U()).fzx()]) while ( !!-!!null[ -null[ ( null.Ka).UinH6O()]]) ; } void QwZZkJAc = --!false.MNw3msUgGNPb(); ; { void[] ovy0b916hp; this[ t5().BED()]; new void[ EpJpL()[ null.yLx6vU()]][ -!-5151.xID7muu67ueOkA]; boolean sB0GJJPSO8X4; while ( true[ ---this[ -!!-0497.EnGO]]) if ( !-!!-true[ new MVm()[ !new BBStZ().mFi()]]) return; !-!( true.N_).QrWsLep; jsTY3q8[][][][] X8F_7yfJ8WxW6; { void O59uQBT_xCC6x; } if ( this.bQMURJtaziW()) return; void dukkug; ; void CLxnhqUhmt_; while ( -!xriKxvOXKg[ !!-574645075.oRJdSYYwPIeJ()]) return; int[] tQA4pvmEFk; boolean[] GvxfV3; return; if ( NDbkFquNrP().X8QGGXPx5SZSAX()) while ( new udMx4()[ !-!!!this.fN2w_zyF]) if ( !true[ !--null[ new Dx().IVg2pu9()]]) { int TdWwl0BUFqz5i; } while ( -this[ off().V()]) if ( !false.HO()) while ( wuIvo3zCTcvF.Jo7kmwTiAA6tW()) return; ; } void yfLrU = !Dt().EXolvfGTDYby(); ZK9hAydVP17K[] fwCrAkyyDMll = PNtJRo.yey = -true.elPfeiac; boolean[] I8kWz8 = null.jFcrsP4E = 759.fMtB6x1Qhh8gm(); null[ --new boolean[ uje8Tni2.pj6gSac7U5B][ this.cTMU3]]; void[][] DEq; while ( -!new p().RDJQ4()) { boolean Ab4BwU8fd; } ; } }
AlexanderKindel/solver
stack/stack.h
<gh_stars>1-10 /*Let a function's result refer to its return value together with the values to which it assigns its out parameters, if it has any. Let the reference graph of a value of a primitive data type refer to the value, the reference graph of a pointer refer to the reference graph of the value it points to, and the reference graph of an aggregate data type, to the union of the reference graphs of its elements. If the reference graph of a function's result contains dynamically allocated elements, then the function takes an output_stack parameter, and allocates all such elements on that Stack. This means that functions never assign dynamically allocated values passed in by their callers directly into the reference graphs of their results, instead deep-copying such values to output_stack first. Functions that need to do dynamic allocations in service of calculating their results but that are not themselves part of the result occasionally do such allocations on output_stack for efficiency reasons, but most of the time, they take a local_stack parameter and do the allocations on that. Any allocations a function does on a local_stack are popped before the function returns. The few functions that do a significant amount of allocation on output_stack that isn't part of their results are identified with comments.*/ void stack_initialize(struct Stack*out, void*start, size_t size); void stack_reset(struct Stack*stack); void*align_cursor(struct Stack*output_stack, size_t alignment); void unaligned_stack_slot_allocate(struct Stack*output_stack, size_t element_size); void*stack_slot_allocate(struct Stack*output_stack, size_t slot_size, size_t alignment);
mehrdad-shokri/retdec
src/unpackertool/plugins/upx/decompressors/decompressor_nrv.h
<filename>src/unpackertool/plugins/upx/decompressors/decompressor_nrv.h /** * @file src/unpackertool/plugins/upx/decompressors/decompressor_nrv.h * @brief Declaration of NRV decompressor visitor for unpacking packed data. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #ifndef UNPACKERTOOL_PLUGINS_UPX_DECOMPRESSORS_DECOMPRESSOR_NRV_H #define UNPACKERTOOL_PLUGINS_UPX_DECOMPRESSORS_DECOMPRESSOR_NRV_H #include "unpackertool/plugins/upx/decompressors/decompressor.h" #include "retdec/unpacker/decompression/nrv/bit_parsers.h" using namespace retdec::utils; namespace retdec { namespace unpackertool { namespace upx { /** * Visitor-like decompressor for LZMA decompression. */ class DecompressorNrv : public Decompressor { public: explicit DecompressorNrv(std::unique_ptr<retdec::unpacker::BitParser> bitParser = nullptr); virtual void setupPackingMethod(ElfUpxStub<32>* stub, std::uint8_t packingMethod) override; virtual void decompress(ElfUpxStub<32>* stub, DynamicBuffer& packedData, DynamicBuffer& unpackedData) override; virtual void setupPackingMethod(ElfUpxStub<64>* stub, std::uint8_t packingMethod) override; virtual void decompress(ElfUpxStub<64>* stub, DynamicBuffer& packedData, DynamicBuffer& unpackedData) override; virtual void setupPackingMethod(MachOUpxStub<32>* stub, std::uint8_t packingMethod) override; virtual void decompress(MachOUpxStub<32>* stub, DynamicBuffer& packedData, DynamicBuffer& unpackedData) override; virtual void setupPackingMethod(MachOUpxStub<64>* stub, std::uint8_t packingMethod) override; virtual void decompress(MachOUpxStub<64>* stub, DynamicBuffer& packedData, DynamicBuffer& unpackedData) override; virtual void setupPackingMethod(PeUpxStub<32>* stub, std::uint8_t packingMethod) override; virtual void readUnpackingStub(PeUpxStub<32>* stub, DynamicBuffer& unpackingStub) override; virtual void readPackedData(PeUpxStub<32>* stub, DynamicBuffer& packedData, bool trustMetadata) override; virtual void decompress(PeUpxStub<32>* stub, DynamicBuffer& packedData, DynamicBuffer& unpackedData, bool trustMetadata) override; virtual void setupPackingMethod(PeUpxStub<64>* stub, std::uint8_t packingMethod) override; virtual void readUnpackingStub(PeUpxStub<64>* stub, DynamicBuffer& unpackingStub) override; virtual void readPackedData(PeUpxStub<64>* stub, DynamicBuffer& packedData, bool trustMetadata) override; virtual void decompress(PeUpxStub<64>* stub, DynamicBuffer& packedData, DynamicBuffer& unpackedData, bool trustMetadata) override; protected: void setupPackingMethod(std::uint8_t packingMethod); void decompress(DynamicBuffer& packedData, DynamicBuffer& unpackedData); private: char _nrvVersion; std::unique_ptr<retdec::unpacker::BitParser> _bitParser; }; } // namespace upx } // namespace unpackertool } // namespace retdec #endif
icokeamy2/ResearchProjectFrontend
src/components/ecommerce/SalesReport.js
<filename>src/components/ecommerce/SalesReport.js import React from "react"; import PropTypes from "prop-types"; import { Card, CardHeader, CardBody, Row, Col, ButtonGroup, Button } from "shards-react"; import RangeDatePicker from "../common/RangeDatePicker"; import Chart from "../../utils/chart"; class SalesReport extends React.Component { constructor(props) { super(props); this.legendRef = React.createRef(); this.canvasRef = React.createRef(); } componentDidMount() { const chartOptions = { ...{ legend: false, // Uncomment the next line in order to disable the animations. // animation: false, tooltips: { enabled: false, mode: "index", position: "nearest" }, scales: { xAxes: [ { stacked: true, gridLines: false } ], yAxes: [ { stacked: true, ticks: { userCallback(label) { return label > 999 ? `${(label / 1000).toFixed(0)}k` : label; } } } ] } }, ...this.props.chartOptions }; const SalesReportChart = new Chart(this.canvasRef.current, { type: "bar", data: this.props.chartData, options: chartOptions }); // Generate the chart labels. this.legendRef.current.innerHTML = SalesReportChart.generateLegend(); // Hide initially the first and last chart points. // They can still be triggered on hover. const meta = SalesReportChart.getDatasetMeta(0); meta.data[0]._model.radius = 0; meta.data[ this.props.chartData.datasets[0].data.length - 1 ]._model.radius = 0; // Render the chart. SalesReportChart.render(); } render() { const { title } = this.props; return ( <Card small className="h-100"> <CardHeader className="border-bottom"> <h6 className="m-0">{title}</h6> <div className="block-handle" /> </CardHeader> <CardBody className="pt-0"> <Row className="border-bottom py-2 bg-light"> {/* Time Interval */} <Col sm="6" className="col d-flex mb-2 mb-sm-0"> <ButtonGroup> <Button theme="white">Hour</Button> <Button theme="white">Day</Button> <Button theme="white">Week</Button> <Button theme="white" active> Month </Button> </ButtonGroup> </Col> {/* DatePicker */} <Col sm="6" className="col"> <RangeDatePicker className="justify-content-end" /> </Col> </Row> <div ref={this.legendRef} /> <canvas height="120" ref={this.canvasRef} style={{ maxWidth: "100% !important" }} className="sales-overview-sales-report" /> </CardBody> </Card> ); } } SalesReport.propTypes = { /** * The title of the component. */ title: PropTypes.string, /** * The chart data. */ chartData: PropTypes.object, /** * The Chart.js options. */ chartOptions: PropTypes.object }; SalesReport.defaultProps = { title: "Sales Report", chartData: { labels: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Nov", "Dec" ], datasets: [ { label: "Profit", fill: "start", data: [ 28922, 25317, 23182, 32119, 11291, 8199, 25182, 22120, 10219, 8771, 12992, 8221 ], backgroundColor: "rgba(0, 123, 255, 1)", borderColor: "rgba(0, 123, 255, 1)", pointBackgroundColor: "#FFFFFF", pointHoverBackgroundColor: "rgba(0, 123, 255, 1)", borderWidth: 1.5 }, { label: "Shipping", fill: "start", data: [ 2892, 2531, 2318, 3211, 1129, 819, 2518, 2212, 1021, 8771, 1299, 820 ], backgroundColor: "rgba(72, 160, 255, 1)", borderColor: "rgba(72, 160, 255, 1)", pointBackgroundColor: "#FFFFFF", pointHoverBackgroundColor: "rgba(0, 123, 255, 1)", borderWidth: 1.5 }, { label: "Tax", fill: "start", data: [ 1400, 1250, 1150, 1600, 500, 400, 1250, 1100, 500, 4000, 600, 500 ], backgroundColor: "rgba(153, 202, 255, 1)", borderColor: "rgba(153, 202, 255, 1)", pointBackgroundColor: "#FFFFFF", pointHoverBackgroundColor: "rgba(0, 123, 255, 1)", borderWidth: 1.5 } ] } }; export default SalesReport;
Justin-Fisher/webots
src/webots/gui/WbSingleTaskApplication.cpp
// Copyright 1996-2021 Cyberbotics Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "WbSingleTaskApplication.hpp" #include "WbApplicationInfo.hpp" #include "WbBasicJoint.hpp" #include "WbField.hpp" #include "WbProtoCachedInfo.hpp" #include "WbProtoList.hpp" #include "WbProtoModel.hpp" #include "WbSysInfo.hpp" #include "WbTokenizer.hpp" #include "WbVersion.hpp" #include "WbWorld.hpp" #include <QtCore/QCommandLineParser> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtGui/QOpenGLContext> #include <QtGui/QOpenGLFunctions> #include <QtOpenGL/QGLWidget> #include <QtWidgets/QMainWindow> #ifdef __APPLE__ #include <OpenGL/gl.h> #endif #include <iostream> using namespace std; void WbSingleTaskApplication::run() { if (mTask == WbGuiApplication::SYSINFO) showSysInfo(); else if (mTask == WbGuiApplication::HELP) showHelp(); else if (mTask == WbGuiApplication::VERSION) cout << tr("Webots version: %1").arg(WbApplicationInfo::version().toString(true, false, true)).toUtf8().constData() << endl; else if (mTask == WbGuiApplication::UPDATE_PROTO_CACHE) updateProtoCacheFiles(); else if (mTask == WbGuiApplication::UPDATE_WORLD) WbWorld::instance()->save(); else if (mTask == WbGuiApplication::CONVERT) convertProto(); emit finished(mTask == WbGuiApplication::FAILURE ? EXIT_FAILURE : EXIT_SUCCESS); } void WbSingleTaskApplication::convertProto() const { QCommandLineParser cliParser; cliParser.setApplicationDescription("Convert a PROTO file to URDF, WBO, or WRL file"); cliParser.addHelpOption(); cliParser.addPositionalArgument("input", "Path to the input PROTO file."); cliParser.addOption(QCommandLineOption("t", "Output type (URDF, WBO, or WRL).", "type", "URDF")); cliParser.addOption(QCommandLineOption("o", "Path to the output file.", "output")); cliParser.addOption(QCommandLineOption("p", "Override default PROTO parameters.", "parameter=value")); cliParser.process(mTaskArguments); const QStringList positionalArguments = cliParser.positionalArguments(); if (positionalArguments.size() != 1) cliParser.showHelp(1); const bool toStdout = cliParser.values("o").size() == 0; QString type = cliParser.values("t")[0]; QString outputFile; if (!toStdout) { outputFile = cliParser.values("o")[0]; type = outputFile.mid(outputFile.lastIndexOf(".")).toLower(); } // Compute absolute paths for input and output files QString inputFile = positionalArguments[0]; if (QDir::isRelativePath(inputFile)) inputFile = mStartupPath + '/' + inputFile; if (!toStdout && QDir::isRelativePath(outputFile)) outputFile = mStartupPath + '/' + outputFile; // Get user parameters strings QMap<QString, QString> userParameters; for (QString param : cliParser.values("p")) { QStringList pair = param.split("="); if (pair.size() != 2) { cerr << tr("A parameter is not properly formated!\n").toUtf8().constData(); cliParser.showHelp(1); } userParameters[pair[0]] = pair[1].replace(QRegExp("^\"*"), "").replace(QRegExp("\"*$"), ""); } // Parse PROTO new WbProtoList(QFileInfo(inputFile).absoluteDir().path()); WbNode::setInstantiateMode(false); WbProtoModel *model = WbProtoList::current()->readModel(inputFile, ""); if (!toStdout) cout << tr("Parsing the %1 PROTO...").arg(model->name()).toUtf8().constData() << endl; // Combine the user parameters with the default ones QVector<WbField *> fields; for (WbFieldModel *fieldModel : model->fieldModels()) { WbField *field = new WbField(fieldModel); if (userParameters.contains(field->name())) { WbTokenizer tokenizer; tokenizer.tokenizeString(userParameters[field->name()]); field->readValue(&tokenizer, ""); } if (!toStdout) cout << tr(" field %1 [%2] = %3") .arg(field->name()) .arg(field->value()->vrmlTypeName()) .arg(field->value()->toString()) .toUtf8() .constData() << endl; fields.append(field); } // Generate a node structure WbNode::setInstantiateMode(true); WbNode *node = WbNode::regenerateProtoInstanceFromParameters(model, fields, true, ""); for (WbNode *subNode : node->subNodes(true)) if (dynamic_cast<WbBasicJoint *>(subNode)) static_cast<WbBasicJoint *>(subNode)->updateEndPointZeroTranslationAndRotation(); // Export QString output; WbVrmlWriter writer(&output, "robot." + type); writer.writeHeader(outputFile); node->write(writer); writer.writeFooter(); // Output the content if (toStdout) cout << output.toUtf8().toStdString() << endl; else { QFile file(outputFile); if (!file.open(QIODevice::WriteOnly)) { cerr << tr("Cannot open the file!\n").toUtf8().constData(); cliParser.showHelp(1); } file.write(output.toUtf8()); file.close(); } if (!toStdout) cout << tr("The %1 PROTO is written to the file.").arg(model->name()).toUtf8().constData() << endl; } void WbSingleTaskApplication::showHelp() const { cout << tr("Usage: webots [options] [worldfile]").toUtf8().constData() << endl << endl; cout << tr("Options:").toUtf8().constData() << endl << endl; cout << " --help" << endl; cout << tr(" Display this help message and exit.").toUtf8().constData() << endl << endl; cout << " --version" << endl; cout << tr(" Display version information and exit.").toUtf8().constData() << endl << endl; cout << " --sysinfo" << endl; cout << tr(" Display information about the system and exit.").toUtf8().constData() << endl << endl; cout << " --mode=<mode>" << endl; cout << tr(" Choose the startup mode, overriding application preferences. The <mode>").toUtf8().constData() << endl; cout << tr(" argument must be either pause, realtime or fast.").toUtf8().constData() << endl << endl; cout << " --no-rendering" << endl; cout << tr(" Disable rendering in the main 3D view.").toUtf8().constData() << endl << endl; cout << " --fullscreen" << endl; cout << tr(" Start Webots in fullscreen.").toUtf8().constData() << endl << endl; cout << " --minimize" << endl; cout << tr(" Minimize the Webots window on startup.").toUtf8().constData() << endl << endl; cout << " --batch" << endl; cout << tr(" Prevent Webots from creating blocking pop-up windows.").toUtf8().constData() << endl << endl; cout << " --stdout" << endl; cout << tr(" Redirect the stdout of the controllers to the terminal.").toUtf8().constData() << endl << endl; cout << " --stderr" << endl; cout << tr(" Redirect the stderr of the controllers to the terminal.").toUtf8().constData() << endl << endl; cout << " --stream[=\"key[=value];...\"]" << endl; cout << tr(" Start the Webots streaming server. Parameters may be").toUtf8().constData() << endl; cout << tr(" given as an option:").toUtf8().constData() << endl; cout << tr(" port=1234 - Start the streaming server on port 1234.").toUtf8().constData() << endl; cout << tr(" mode=<x3d|mjpeg> - Specify the streaming mode: x3d (default) or mjpeg.").toUtf8().constData() << endl; cout << tr(" monitorActivity - Print a dot '.' on stdout every 5 seconds.").toUtf8().constData() << endl; cout << tr(" disableTextStreams - Disable the streaming of stdout and stderr.").toUtf8().constData() << endl << endl; cout << " --log-performance=<file>[,<steps>]" << endl; cout << tr(" Measure the performance of Webots and log it in the file specified in the").toUtf8().constData() << endl; cout << tr(" <file> argument. The optional <steps> argument is an integer value that").toUtf8().constData() << endl; cout << tr(" specifies how many steps are logged. If the --sysinfo option is used, the").toUtf8().constData() << endl; cout << tr(" system information is prepended into the log file.").toUtf8().constData() << endl << endl; cout << " convert" << endl; cout << tr(" Convert a PROTO file to a URDF, WBO, or WRL file.").toUtf8().constData() << endl << endl; cout << tr("Please report any bug to https://cyberbotics.com/bug").toUtf8().constData() << endl; } void WbSingleTaskApplication::showSysInfo() const { cout << tr("System: %1").arg(WbSysInfo::sysInfo()).toUtf8().constData() << endl; cout << tr("Processor: %1").arg(WbSysInfo::processor()).toUtf8().constData() << endl; cout << tr("Number of cores: %1").arg(WbSysInfo::coreCount()).toUtf8().constData() << endl; // create simply an OpenGL context QMainWindow mainWindow; QGLWidget glWidget(&mainWindow); mainWindow.setCentralWidget(&glWidget); mainWindow.show(); // An OpenGL context is required there for the OpenGL calls like `glGetString`. // The format is QSurfaceFormat::defaultFormat() => OpenGL 3.3 defined in main.cpp. QOpenGLContext *context = new QOpenGLContext(); context->create(); QOpenGLFunctions *gl = context->functions(); // QOpenGLFunctions_3_3_Core cannot be initialized here on some systems like // macOS High Sierra and some Ubuntu environments. #ifdef _WIN32 const quint32 vendorId = WbSysInfo::gpuVendorId(gl); const quint32 rendererId = WbSysInfo::gpuDeviceId(gl); #else const quint32 vendorId = 0; const quint32 rendererId = 0; #endif const char *vendor = (const char *)gl->glGetString(GL_VENDOR); const char *renderer = (const char *)gl->glGetString(GL_RENDERER); // cppcheck-suppress knownConditionTrueFalse if (vendorId == 0) cout << tr("OpenGL vendor: %1").arg(vendor).toUtf8().constData() << endl; else cout << tr("OpenGL vendor: %1 (0x%2)").arg(vendor).arg(vendorId, 0, 16).toUtf8().constData() << endl; // cppcheck-suppress knownConditionTrueFalse if (rendererId == 0) cout << tr("OpenGL renderer: %1").arg(renderer).toUtf8().constData() << endl; else cout << tr("OpenGL renderer: %1 (0x%2)").arg(renderer).arg(rendererId, 0, 16).toUtf8().constData() << endl; cout << tr("OpenGL version: %1").arg((const char *)gl->glGetString(GL_VERSION)).toUtf8().constData() << endl; delete context; } void WbSingleTaskApplication::updateProtoCacheFiles() const { const QString path = (mTaskArguments.size() > 0) ? mTaskArguments[0] : ""; QFileInfo argumentInfo(path); if (argumentInfo.isFile()) { if (argumentInfo.completeSuffix() == "proto") WbProtoCachedInfo::computeInfo(argumentInfo.absoluteFilePath()); else cout << tr("Invalid file: a PROTO file with suffix '.proto' is expected.").toUtf8().constData() << endl; return; } QString dirPath = QDir::currentPath(); if (argumentInfo.isDir()) dirPath = path; // init proto list new WbProtoList(dirPath); // get all proto files QFileInfoList protoList; WbProtoList::findProtosRecursively(dirPath, protoList); if (protoList.isEmpty()) { cout << tr("Folder '%1' doesn't contain any valid PROTO file.").arg(dirPath).toUtf8().constData() << endl; return; } // recompute PROTO cache information foreach (QFileInfo protoInfo, protoList) WbProtoCachedInfo::computeInfo(protoInfo.absoluteFilePath()); }
hawkaa/trimesh
tests/test_repr.py
try: from . import generic as g except BaseException: import generic as g class ReprTest(g.unittest.TestCase): def test_repr(self): m = g.trimesh.creation.icosphere() r = str(m) assert 'trimesh.Trimesh' in r assert 'vertices' in r assert 'faces' in r s = m.scene() assert isinstance(s, g.trimesh.Scene) r = str(s) assert 'Scene' in r assert 'geometry' in r p = g.trimesh.PointCloud(m.vertices) r = str(p) assert 'trimesh.PointCloud' in r assert 'vertices' in r p = g.trimesh.path.creation.rectangle([[0, 0], [1, 1]]) assert isinstance(p, g.trimesh.path.Path2D) r = str(p) assert 'trimesh.Path2D' in r assert 'entities' in r assert 'vertices' in r p = p.to_3D() assert isinstance(p, g.trimesh.path.Path3D) r = str(p) assert 'trimesh.Path3D' in r assert 'entities' in r assert 'vertices' in r if __name__ == '__main__': g.trimesh.util.attach_to_log() g.unittest.main()
luizgribeiro/airbyte
airbyte-integrations/connectors/source-e2e-test/src/test/java/io/airbyte/integrations/source/e2e_test/ExceptionAfterNSourceTest.java
/* * MIT License * * Copyright (c) 2020 Airbyte * * 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 io.airbyte.integrations.source.e2e_test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableMap; import io.airbyte.commons.json.Jsons; import io.airbyte.commons.util.AutoCloseableIterator; import io.airbyte.protocol.models.AirbyteMessage; import io.airbyte.protocol.models.AirbyteMessage.Type; import io.airbyte.protocol.models.AirbyteRecordMessage; import io.airbyte.protocol.models.AirbyteStateMessage; import io.airbyte.protocol.models.CatalogHelpers; import io.airbyte.protocol.models.ConfiguredAirbyteCatalog; import io.airbyte.protocol.models.SyncMode; import java.time.Instant; import org.junit.jupiter.api.Test; class ExceptionAfterNSourceTest { @SuppressWarnings("Convert2MethodRef") @Test void test() { final ConfiguredAirbyteCatalog configuredCatalog = CatalogHelpers.toDefaultConfiguredCatalog(ExceptionAfterNSource.CATALOG); configuredCatalog.getStreams().get(0).setSyncMode(SyncMode.INCREMENTAL); final JsonNode config = Jsons.jsonNode(ImmutableMap.of("throw_after_n_records", 10)); final AutoCloseableIterator<AirbyteMessage> read = new ExceptionAfterNSource().read(config, configuredCatalog, null); assertEquals(getStateMessage(0L).getState().getData(), read.next().getState().getData()); assertEquals(getRecordMessage(1L).getRecord().getData(), read.next().getRecord().getData()); assertEquals(getRecordMessage(2L).getRecord().getData(), read.next().getRecord().getData()); assertEquals(getRecordMessage(3L).getRecord().getData(), read.next().getRecord().getData()); assertEquals(getRecordMessage(4L).getRecord().getData(), read.next().getRecord().getData()); assertEquals(getRecordMessage(5L).getRecord().getData(), read.next().getRecord().getData()); assertEquals(getStateMessage(5L).getState().getData(), read.next().getState().getData()); assertEquals(getRecordMessage(6L).getRecord().getData(), read.next().getRecord().getData()); assertEquals(getRecordMessage(7L).getRecord().getData(), read.next().getRecord().getData()); assertEquals(getRecordMessage(8L).getRecord().getData(), read.next().getRecord().getData()); assertEquals(getRecordMessage(9L).getRecord().getData(), read.next().getRecord().getData()); assertEquals(getRecordMessage(10L).getRecord().getData(), read.next().getRecord().getData()); assertEquals(getStateMessage(10L).getState().getData(), read.next().getState().getData()); assertThrows(IllegalStateException.class, read::next); } private static AirbyteMessage getRecordMessage(long i) { return new AirbyteMessage() .withType(Type.RECORD) .withRecord(new AirbyteRecordMessage() .withStream("data") .withEmittedAt(Instant.now().toEpochMilli()) .withData(Jsons.jsonNode(ImmutableMap.of("column1", i)))); } private static AirbyteMessage getStateMessage(long i) { return new AirbyteMessage() .withType(Type.STATE) .withState(new AirbyteStateMessage().withData(Jsons.jsonNode(ImmutableMap.of("column1", i)))); } }
Ehtisham-Ayaan/aoo-ghr-bnain-update
node_modules/@iconify/icons-mdi/guitar-acoustic.js
var data = { "body": "<path d=\"M19.59 3H22v2h-1.59l-4.24 4.24c-.37-.56-.85-1.04-1.41-1.41L19.59 3M12 8a4 4 0 0 1 4 4a3.99 3.99 0 0 1-3 3.87V16a5 5 0 0 1-5 5a5 5 0 0 1-5-5a5 5 0 0 1 5-5h.13c.45-1.76 2.04-3 3.87-3m0 2.5a1.5 1.5 0 0 0-1.5 1.5a1.5 1.5 0 0 0 1.5 1.5a1.5 1.5 0 0 0 1.5-1.5a1.5 1.5 0 0 0-1.5-1.5m-5.06 3.74l-.71.7l2.83 2.83l.71-.71l-2.83-2.82z\" fill=\"currentColor\"/>", "width": 24, "height": 24 }; exports.__esModule = true; exports.default = data;
aleks-pro/resolve
packages/adapters/snapshot-adapters/resolve-snapshot-mysql/test/index.test.js
<reponame>aleks-pro/resolve<filename>packages/adapters/snapshot-adapters/resolve-snapshot-mysql/test/index.test.js import MySQL from 'mysql2/promise' import createSnapshotAdapter from '../src' describe('resolve-snapshot-mysql', () => { const bucketSize = 5 let snapshotAdapter = null beforeEach(async () => { snapshotAdapter = createSnapshotAdapter({ host: 'localhost', port: 3306, user: 'user', password: 'password', database: 'database', bucketSize }) MySQL.createConnection().execute.mockImplementation(() => {}) }) afterEach(async () => { MySQL.createConnection().execute.mockReset() if (snapshotAdapter != null) { await snapshotAdapter.dispose() } }) test(`"saveSnapshot" should save the snapshot every 5 times`, async () => { await snapshotAdapter.init() for (let index = 0; index < bucketSize; index++) { await snapshotAdapter.saveSnapshot('key', `value = ${index}`) } await snapshotAdapter.saveSnapshot('key', `value = ${bucketSize}`) expect(MySQL.createConnection().execute.mock.calls).toMatchSnapshot() }) test(`"loadSnapshot" should load the snapshot`, async () => { MySQL.createConnection().execute.mockReturnValueOnce([ [{ SnapshotContent: '"value"' }] ]) const value = await snapshotAdapter.loadSnapshot('key') expect(MySQL.createConnection().execute.mock.calls).toMatchSnapshot() expect(value).toMatchSnapshot() }) test(`"drop" should drop the snapshotAdapter`, async () => { await snapshotAdapter.dropSnapshot('key') expect(MySQL.createConnection().execute.mock.calls).toMatchSnapshot() }) test(`"dispose" should dispose the snapshotAdapter`, async () => { await snapshotAdapter.init() await snapshotAdapter.dispose() try { await snapshotAdapter.dispose() snapshotAdapter = null return Promise.reject(new Error('Test failed')) } catch (error) { expect(error).toBeInstanceOf(Error) expect(error.message).toEqual('Adapter is disposed') snapshotAdapter = null } }) })
loongX/AndroidDemo
component/XModulable-master/im/src/main/java/com/xpleemoon/im/IMActivity.java
package com.xpleemoon.im; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.alibaba.android.arouter.facade.annotation.Route; import com.xpleemoon.common.app.BaseCommonActivity; import com.xpleemoon.common.router.module.ModuleName; import com.xpleemoon.common.router.module.im.IMModule; import com.xpleemoon.xmodulable.annotation.InjectXModule; import com.xpleemoon.im.router.path.PathConstants; @Route(path = PathConstants.PATH_VIEW_IM) public class IMActivity extends BaseCommonActivity { @InjectXModule(name = ModuleName.IM) IMModule imModule; private EditText mContractEdt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.im_activity_im); mContractEdt = (EditText) findViewById(R.id.contract_edt); mContractEdt.setText(imModule.getIMDaoService().getContact()); } public void onClick(View view) { int id = view.getId(); if (id == R.id.update_contract) { imModule.getIMDaoService().updateContact(mContractEdt.getText().toString()); Toast.makeText(getApplication(), "联系人更新成功", Toast.LENGTH_SHORT).show(); } } }
maxxcs/swc
crates/swc/tests/tsc-references/es6/destructuring/destructuringObjectBindingPatternAndAssignment4/input.ts/es2015.1.normal/output.js
<reponame>maxxcs/swc<filename>crates/swc/tests/tsc-references/es6/destructuring/destructuringObjectBindingPatternAndAssignment4/input.ts/es2015.1.normal/output.js<gh_stars>1000+ const { a =1 , b =2 , c =b , d =a , e =f , f =f // error } = { };
terminux/jdk1.7.0_80
src/com/sun/jmx/snmp/IPAcl/JDMIpAddress.java
/* * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ /* Generated By:JJTree: Do not edit this line. JDMIpAddress.java */ package com.sun.jmx.snmp.IPAcl; import java.lang.StringBuffer; import java.net.UnknownHostException; class JDMIpAddress extends Host { private static final long serialVersionUID = 849729919486384484L; protected StringBuffer address= new StringBuffer(); JDMIpAddress(int id) { super(id); } JDMIpAddress(Parser p, int id) { super(p, id); } public static Node jjtCreate(int id) { return new JDMIpAddress(id); } public static Node jjtCreate(Parser p, int id) { return new JDMIpAddress(p, id); } protected String getHname() { return address.toString(); } protected PrincipalImpl createAssociatedPrincipal() throws UnknownHostException { return new PrincipalImpl(address.toString()); } }
RoboticExplorationLab/micropython-ulab
tests/common/buffer.py
try: from ulab import numpy as np except: import numpy as np def print_as_buffer(a): print(len(memoryview(a)), list(memoryview(a))) print_as_buffer(np.ones(3)) print_as_buffer(np.zeros(3)) print_as_buffer(np.eye(4)) print_as_buffer(np.ones(1, dtype=np.int8)) print_as_buffer(np.ones(2, dtype=np.uint8)) print_as_buffer(np.ones(3, dtype=np.int16)) print_as_buffer(np.ones(4, dtype=np.uint16)) print_as_buffer(np.ones(5, dtype=np.float)) print_as_buffer(np.linspace(0, 1, 9))
ajesse11x/dremio-oss
sabot/kernel/src/test/java/com/dremio/exec/catalog/TestDatasetManager.java
/* * Copyright (C) 2017-2019 Dremio Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dremio.exec.catalog; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Collections; import javax.inject.Provider; import org.junit.Test; import com.dremio.exec.catalog.conf.ConnectionConf; import com.dremio.exec.ops.ViewExpansionContext; import com.dremio.exec.server.SabotContext; import com.dremio.exec.store.SchemaConfig; import com.dremio.exec.store.StoragePlugin; import com.dremio.exec.store.dfs.ImpersonationConf; import com.dremio.options.OptionManager; import com.dremio.service.namespace.NamespaceKey; import com.dremio.service.namespace.NamespaceService; import com.dremio.service.namespace.dataset.proto.DatasetConfig; import com.dremio.service.namespace.dataset.proto.DatasetType; import com.dremio.service.namespace.dataset.proto.ReadDefinition; import com.dremio.service.namespace.proto.EntityId; /** * Tests for DatasetManager */ public class TestDatasetManager { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TestDatasetManager.class); @Test public void testAccessUsernameOverride() throws Exception { final NamespaceKey namespaceKey = new NamespaceKey("test"); final ViewExpansionContext viewExpansionContext = mock(ViewExpansionContext.class); when(viewExpansionContext.getQueryUser()).thenReturn("newaccessuser"); final SchemaConfig schemaConfig = mock(SchemaConfig.class); when(schemaConfig.getUserName()).thenReturn("username"); when(schemaConfig.getViewExpansionContext()).thenReturn(viewExpansionContext); final MetadataStatsCollector statsCollector = mock(MetadataStatsCollector.class); final MetadataRequestOptions metadataRequestOptions = mock(MetadataRequestOptions.class); when(metadataRequestOptions.getSchemaConfig()).thenReturn(schemaConfig); when(metadataRequestOptions.getStatsCollector()).thenReturn(statsCollector); final ReadDefinition readDefinition = new ReadDefinition(); readDefinition.setSplitVersion(0L); final DatasetConfig datasetConfig = new DatasetConfig(); datasetConfig.setType(DatasetType.PHYSICAL_DATASET); datasetConfig.setId(new EntityId("test")); datasetConfig.setFullPathList(Collections.singletonList("test")); datasetConfig.setReadDefinition(readDefinition); datasetConfig.setTotalNumSplits(0); class FakeSource extends ConnectionConf<FakeSource, StoragePlugin> implements ImpersonationConf { @Override public StoragePlugin newPlugin(SabotContext context, String name, Provider<StoragePluginId> pluginIdProvider) { return null; } @Override public String getAccessUserName(String delegatedUser, String queryUserName) { return queryUserName; } } final FakeSource fakeSource = new FakeSource(); final ManagedStoragePlugin managedStoragePlugin = mock(ManagedStoragePlugin.class); when(managedStoragePlugin.getId()).thenReturn(mock(StoragePluginId.class)); doReturn(fakeSource).when(managedStoragePlugin).getConnectionConf(); when(managedStoragePlugin.isValid(any(), any())).thenReturn(true); // newaccessuser should be used and not username doThrow(new RuntimeException("Wrong username")) .when(managedStoragePlugin).checkAccess(namespaceKey, datasetConfig, "username", metadataRequestOptions); final PluginRetriever pluginRetriever = mock(PluginRetriever.class); when(pluginRetriever.getPlugin(namespaceKey.getRoot(), false)).thenReturn(managedStoragePlugin); final NamespaceService namespaceService = mock(NamespaceService.class); when(namespaceService.getDataset(namespaceKey)).thenReturn(datasetConfig); final OptionManager optionManager = mock(OptionManager.class); final DatasetManager datasetManager = new DatasetManager(pluginRetriever, namespaceService, optionManager); datasetManager.getTable(namespaceKey, metadataRequestOptions); } }
jeongjoonyoo/AMD_RGA
RadeonGPUAnalyzerGUI/Src/rgViewContainer.cpp
// C++. #include <cassert> // Qt. #include <QAction> #include <QHBoxLayout> #include <QPushButton> #include <QResizeEvent> #include <QSpacerItem> #include <QStyle> #include <QWidget> // Local. #include <RadeonGPUAnalyzerGUI/Include/Qt/rgViewContainer.h> #include <RadeonGPUAnalyzerGUI/Include/rgDefinitions.h> #include <RadeonGPUAnalyzerGUI/Include/rgUtils.h> // Identifying widget names. static const char* s_MAXIMIZE_BUTTON_NAME = "viewMaximizeButton"; static const char* s_TITLEBAR_WIDGET_NAME = "viewTitlebar"; // Identifying property names. static const char* s_MAXIMIZED_STATE_PROPERTY_NAME = "isMaximized"; static const char* s_HOVERED_STATE_PROPERTY_NAME = "viewHovered"; static const char* s_FOCUSED_STATE_PROPERTY_NAME = "viewFocused"; rgViewContainer::rgViewContainer(QWidget* pParent) : QWidget(pParent) { // Default initialize state properties. setProperty(s_MAXIMIZED_STATE_PROPERTY_NAME, false); setProperty(s_HOVERED_STATE_PROPERTY_NAME, false); setProperty(s_FOCUSED_STATE_PROPERTY_NAME, false); setFocusPolicy(Qt::StrongFocus); } void rgViewContainer::SwitchContainerSize() { SetMaximizedState(!m_isInMaximizedState); emit MaximizeButtonClicked(); } void rgViewContainer::SetIsMaximizable(bool isEnabled) { m_isMaximizable = isEnabled; if (m_pMaximizeButton != nullptr) { // Toggle the visibility of the maximize/restore button in the container's titlebar. m_pMaximizeButton->setVisible(isEnabled); } } void rgViewContainer::SetMainWidget(QWidget* pWidget) { if (pWidget != nullptr) { // Reparent the widget. pWidget->setParent(this); // Force the same max size as the main widget. setMaximumSize(pWidget->maximumSize()); // Store pointer to main widget. m_pMainWidget = pWidget; // Use the main widget as the focus proxy for this container. setFocusProxy(pWidget); // Extract the title bar if it isn't set. if (m_pTitleBarWidget == nullptr) { ExtractTitlebar(); } // Extract the maximize button. ExtractMaximizeButton(); // Refresh widget sizes. RefreshGeometry(); } } void rgViewContainer::SetTitlebarWidget(QWidget* pWidget) { if (pWidget != nullptr) { // Reparent the widget. pWidget->setParent(this); } // Store pointer to title bar widget. m_pTitleBarWidget = pWidget; // Indicate the title bar is not embedded. m_isEmbeddedTitlebar = false; // Extract the maximize button. ExtractMaximizeButton(); // Refresh widget sizes. RefreshGeometry(); } QWidget* rgViewContainer::GetTitleBar() { return m_pTitleBarWidget; } void rgViewContainer::SetMaximizedState(bool isMaximized) { setProperty(s_MAXIMIZED_STATE_PROPERTY_NAME, isMaximized); m_isInMaximizedState = isMaximized; rgUtils::StyleRepolish(this, true); } void rgViewContainer::SetFocusedState(bool isFocused) { setProperty(s_FOCUSED_STATE_PROPERTY_NAME, isFocused); rgUtils::StyleRepolish(this, true); } bool rgViewContainer::IsInMaximizedState() const { return m_isInMaximizedState; } void rgViewContainer::SetHiddenState(bool isHidden) { m_isInHiddenState = isHidden; } bool rgViewContainer::IsMaximizable() const { return m_isMaximizable; } bool rgViewContainer::IsInHiddenState() const { return m_isInHiddenState; } QWidget* rgViewContainer::GetMainWidget() const { return m_pMainWidget; } void rgViewContainer::resizeEvent(QResizeEvent* pEvent) { // Refresh widget sizes. RefreshGeometry(); // Normal event processing. QWidget::resizeEvent(pEvent); } QSize rgViewContainer::sizeHint() const { QSize ret(0, 0); // Use the main widget size hint, if it exists. if (m_pMainWidget != nullptr) { ret = m_pMainWidget->sizeHint(); } else { ret = QWidget::sizeHint(); } return ret; } QSize rgViewContainer::minimumSizeHint() const { QSize ret(0, 0); // Use the main widget minimum size hint, if it exists. if (m_pMainWidget != nullptr) { ret = m_pMainWidget->minimumSizeHint(); } else { ret = QWidget::minimumSizeHint(); } return ret; } void rgViewContainer::enterEvent(QEvent* pEvent) { setProperty(s_HOVERED_STATE_PROPERTY_NAME, true); if (m_pTitleBarWidget != nullptr) { rgUtils::StyleRepolish(m_pTitleBarWidget, true); } } void rgViewContainer::leaveEvent(QEvent* pEvent) { setProperty(s_HOVERED_STATE_PROPERTY_NAME, false); if (m_pTitleBarWidget != nullptr) { rgUtils::StyleRepolish(m_pTitleBarWidget, true); } } void rgViewContainer::mouseDoubleClickEvent(QMouseEvent* pEvent) { if (pEvent != nullptr && pEvent->button() == Qt::LeftButton) { // A double-click on the top bar should behave like a click on the Resize button. MaximizeButtonClicked(); } } void rgViewContainer::mousePressEvent(QMouseEvent* pEvent) { // A click in this view should unfocus the build settings view. emit ViewContainerMouseClickEventSignal(); // Pass the event onto the base class. QWidget::mousePressEvent(pEvent); } void rgViewContainer::RefreshGeometry() { bool doOverlayTitlebar = false; int titlebarHeight = 0; // If there is a titlebar, position it at the top and always on top of the main widget. if (m_pTitleBarWidget != nullptr && !m_isEmbeddedTitlebar) { // Get height of titlebar area. titlebarHeight = m_pTitleBarWidget->minimumSize().height(); m_pTitleBarWidget->raise(); m_pTitleBarWidget->setGeometry(0, 0, size().width(), titlebarHeight); } if (m_pMainWidget != nullptr) { // If there is no titlebar or if the titlebar is being overlayed, fill the entire // container with the main widget. Otherwise leave room for a titlebar. if (m_pTitleBarWidget == nullptr || doOverlayTitlebar || m_isEmbeddedTitlebar) { m_pMainWidget->setGeometry(0, 0, size().width(), size().height()); } else { m_pMainWidget->setGeometry(0, titlebarHeight, size().width(), size().height() - titlebarHeight); } } } void rgViewContainer::ExtractTitlebar() { m_pTitleBarWidget = nullptr; if (m_pMainWidget != nullptr) { // Get the titlebar by name. m_pTitleBarWidget = m_pMainWidget->findChild<QWidget*>(s_TITLEBAR_WIDGET_NAME); if (m_pTitleBarWidget != nullptr) { // Indicate the titlebar is embedded. m_isEmbeddedTitlebar = true; } } } void rgViewContainer::ExtractMaximizeButton() { m_pMaximizeButton = nullptr; // Try to get the button from the titlebar. if (m_pTitleBarWidget != nullptr) { // Get the maximize button by name. m_pMaximizeButton = m_pTitleBarWidget->findChild<QAbstractButton*>(s_MAXIMIZE_BUTTON_NAME); } // Try to get the button from the main widget. if (m_pMaximizeButton == nullptr && m_pMainWidget != nullptr) { // Get the maximize button by name. m_pMaximizeButton = m_pMainWidget->findChild<QAbstractButton*>(s_MAXIMIZE_BUTTON_NAME); } // Connect the button's signals/slots if a valid one is found. if (m_pMaximizeButton != nullptr) { bool isConnected = connect(m_pMaximizeButton, &QAbstractButton::clicked, this, &rgViewContainer::MaximizeButtonClicked); assert(isConnected); } }
Dineshs91/uptime
internal/api/dashboard.go
package api import ( "net/http" "github.com/defraglabs/uptime/internal/utils" "github.com/defraglabs/uptime/internal/db" ) // DashboardStatsHandler returns dashboard stats. func DashboardStatsHandler(w http.ResponseWriter, r *http.Request) { authToken := r.Header.Get("Authorization") user, authErr := db.ValidateJWT(authToken) if authErr != nil { writeErrorResponse(w, "Authentication failed") return } datastore := db.New() monitoringURLCount := datastore.GetMonitoringURLSByUserIDCount(user.ID) upMonitoringURLCount := datastore.GetMonitoringURLSByUserIDAndStatus(user.ID, utils.StatusUp) downMonitoringURLCount := datastore.GetMonitoringURLSByUserIDAndStatus(user.ID, utils.StatusDown) stats := make(map[string]interface{}) stats["monitoring_urls_count"] = monitoringURLCount stats["up_monitoring_urls_count"] = upMonitoringURLCount stats["down_monitoring_urls_count"] = downMonitoringURLCount writeSuccessStructResponse(w, stats, http.StatusOK) }
jgaudio/king-http-client
integration-tests/src/test/java/com/king/platform/net/http/integration/HttpDelete.java
// Copyright (C) king.com Ltd 2015 // https://github.com/king/king-http-client // Author: <NAME> // License: Apache 2.0, https://raw.github.com/king/king-http-client/LICENSE-APACHE package com.king.platform.net.http.integration; import com.king.platform.net.http.HttpClient; import org.junit.After; import org.junit.Before; import org.junit.Test; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static org.junit.Assert.assertEquals; public class HttpDelete { IntegrationServer integrationServer; private HttpClient httpClient; private int port; private String okBody = "EVERYTHING IS OKAY!"; @Before public void setUp() throws Exception { integrationServer = new JettyIntegrationServer(); integrationServer.start(); port = integrationServer.getPort(); httpClient = new TestingHttpClientFactory().create(); httpClient.start(); } @Test public void delete200() throws Exception { integrationServer.addServlet(new HttpServlet() { @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write(okBody); resp.getWriter().flush(); } }, "/testOk"); BlockingHttpCallback httpCallback = new BlockingHttpCallback(); httpClient.createDelete("http://localhost:" + port + "/testOk").build().withHttpCallback(httpCallback).execute(); httpCallback.waitForCompletion(); assertEquals(okBody, httpCallback.getBody()); assertEquals(200, httpCallback.getStatusCode()); } @Test public void delete404() throws Exception { integrationServer.addServlet(new HttpServlet() { @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(404); } }, "/test404"); BlockingHttpCallback httpCallback = new BlockingHttpCallback(); httpClient.createDelete("http://localhost:" + port + "/test404").build().withHttpCallback(httpCallback).execute(); httpCallback.waitForCompletion(); assertEquals("", httpCallback.getBody()); assertEquals(404, httpCallback.getStatusCode()); } @After public void tearDown() throws Exception { integrationServer.shutdown(); httpClient.shutdown(); } }
factman/api-app
app/services/brand/routes.js
<reponame>factman/api-app /* * @author 4Dcoder */ import express from "express"; import * as brand from "./controller"; const router = express.Router(); // Create a new brand router.post("/brands", brand.create); // Retrieve all Notes router.get("/brands", brand.findAll); // Retrieve a single brand with brandId router.get("/brands/:brandId", brand.findOne); // Update a brand with brandId router.put("/brands/:brandId", brand.update); // Delete a brand with brandId router.delete("/brands/:brandId", brand.delete); export default router;
tinapiao/Software-IC-Automation
laygo/generators/splash/adc_sar_sarsamp_schematic_generator_bb.py
# -*- coding: utf-8 -*- import pprint import bag import numpy as np import yaml lib_name = 'adc_sar_templates' cell_name = 'sarsamp_bb' impl_lib = 'adc_sar_generated' params = dict( lch=16e-9, pw=4, nw=4, m_sw=4, m_sw_arr=6, m_inbuf_list=[16, 24], m_outbuf_list=[8, 32], device_intent='fast', ) load_from_file=True yamlfile_spec="adc_sar_spec.yaml" yamlfile_size="adc_sar_size.yaml" if load_from_file==True: with open(yamlfile_spec, 'r') as stream: specdict = yaml.load(stream) with open(yamlfile_size, 'r') as stream: sizedict = yaml.load(stream) params['m_sw']=sizedict['sarsamp']['m_sw'] params['m_sw_arr']=sizedict['sarsamp']['m_sw_arr'] params['m_inbuf_list']=sizedict['sarsamp']['m_inbuf_list'] params['m_outbuf_list']=sizedict['sarsamp']['m_outbuf_list'] params['lch']=sizedict['lch'] params['pw']=sizedict['pw'] params['nw']=sizedict['nw'] params['device_intent']=sizedict['device_intent'] print('creating BAG project') prj = bag.BagProject() # create design module and run design method. print('designing module') dsn = prj.create_design_module(lib_name, cell_name) print('design parameters:\n%s' % pprint.pformat(params)) dsn.design(**params) # implement the design print('implementing design with library %s' % impl_lib) dsn.implement_design(impl_lib, top_cell_name=cell_name, erase=True)
ckamtsikis/cmssw
PhysicsTools/PatAlgos/python/recoLayer0/jetCorrections_cff.py
import FWCore.ParameterSet.Config as cms from PhysicsTools.PatAlgos.recoLayer0.jetCorrFactors_cfi import * from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import * ## for scheduled mode patJetCorrectionsTask = cms.Task(patJetCorrFactors) patJetCorrections = cms.Sequence(patJetCorrectionsTask)
figassis/iso20022
DataFormat2Choice.go
<reponame>figassis/iso20022 package iso20022 // Choice between the specification of the data in a structured or unstructured form. type DataFormat2Choice struct { // Specification of data in a structured form. Structured *GenericIdentification1 `xml:"Strd"` // Specification of data for which there isn't a structured form. Unstructured *Max140Text `xml:"Ustrd"` } func (d *DataFormat2Choice) AddStructured() *GenericIdentification1 { d.Structured = new(GenericIdentification1) return d.Structured } func (d *DataFormat2Choice) SetUnstructured(value string) { d.Unstructured = (*Max140Text)(&value) }
senagbe/stroke
src/com/isode/stroke/serializer/StartTLSFailureSerializer.java
/* * Copyright (c) 2011, Isode Limited, London, England. * All rights reserved. */ /* * Copyright (c) 2010, <NAME>. * All rights reserved. */ package com.isode.stroke.serializer; import com.isode.stroke.elements.Element; import com.isode.stroke.elements.StartTLSFailure; import com.isode.stroke.serializer.xml.XMLElement; import com.isode.stroke.base.SafeByteArray; public class StartTLSFailureSerializer extends GenericElementSerializer<StartTLSFailure> { public StartTLSFailureSerializer() { super(StartTLSFailure.class); } public SafeByteArray serialize(Element element) { return new SafeByteArray(new XMLElement("failure", "urn:ietf:params:xml:ns:xmpp-tls").serialize()); } }
martinrohrbach/vsphere-automation-sdk-go
services/nsxt-mp/api/ManagementPlaneAPINetworkingLogicalBridgingBridgeEndpointsClient.go
<gh_stars>10-100 // Copyright © 2019-2021 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: BSD-2-Clause // Auto generated code. DO NOT EDIT. // Interface file for service: ManagementPlaneAPINetworkingLogicalBridgingBridgeEndpoints // Used by client-side stubs. package api import ( "github.com/vmware/vsphere-automation-sdk-go/lib/vapi/std/errors" "github.com/vmware/vsphere-automation-sdk-go/runtime/bindings" "github.com/vmware/vsphere-automation-sdk-go/runtime/core" "github.com/vmware/vsphere-automation-sdk-go/runtime/lib" "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" "github.com/vmware/vsphere-automation-sdk-go/services/nsxt-mp/model" ) const _ = core.SupportedByRuntimeVersion1 type ManagementPlaneAPINetworkingLogicalBridgingBridgeEndpointsClient interface { // Creates a Bridge Endpoint. It describes the physical attributes of the bridge like vlan. A logical port can be attached to a vif providing bridging functionality from the logical overlay network to the physical vlan network // // @param bridgeEndpointParam (required) // @return com.vmware.model.BridgeEndpoint // @throws InvalidRequest Bad Request, Precondition Failed // @throws Unauthorized Forbidden // @throws ServiceUnavailable Service Unavailable // @throws InternalServerError Internal Server Error // @throws NotFound Not Found CreateBridgeEndpoint(bridgeEndpointParam model.BridgeEndpoint) (model.BridgeEndpoint, error) // Deletes the specified Bridge Endpoint. // // @param bridgeendpointIdParam (required) // @throws InvalidRequest Bad Request, Precondition Failed // @throws Unauthorized Forbidden // @throws ServiceUnavailable Service Unavailable // @throws InternalServerError Internal Server Error // @throws NotFound Not Found DeleteBridgeEndpoint(bridgeendpointIdParam string) error // Returns information about a specified bridge endpoint. // // @param bridgeendpointIdParam (required) // @return com.vmware.model.BridgeEndpoint // @throws InvalidRequest Bad Request, Precondition Failed // @throws Unauthorized Forbidden // @throws ServiceUnavailable Service Unavailable // @throws InternalServerError Internal Server Error // @throws NotFound Not Found GetBridgeEndpoint(bridgeendpointIdParam string) (model.BridgeEndpoint, error) // Get the statistics for the Bridge Endpoint of the given Endpoint id (endpoint-id) // // @param endpointIdParam (required) // @param sourceParam Data source type. (optional) // @return com.vmware.model.BridgeEndpointStatistics // @throws InvalidRequest Bad Request, Precondition Failed // @throws Unauthorized Forbidden // @throws ServiceUnavailable Service Unavailable // @throws InternalServerError Internal Server Error // @throws NotFound Not Found GetBridgeEndpointStatistics(endpointIdParam string, sourceParam *string) (model.BridgeEndpointStatistics, error) // Get the status for the Bridge Endpoint of the given Endpoint id // // @param endpointIdParam (required) // @param sourceParam Data source type. (optional) // @return com.vmware.model.BridgeEndpointStatus // @throws InvalidRequest Bad Request, Precondition Failed // @throws Unauthorized Forbidden // @throws ServiceUnavailable Service Unavailable // @throws InternalServerError Internal Server Error // @throws NotFound Not Found GetBridgeEndpointStatus(endpointIdParam string, sourceParam *string) (model.BridgeEndpointStatus, error) // Returns information about all configured bridge endoints // // @param bridgeClusterIdParam Bridge Cluster Identifier (optional) // @param bridgeEndpointProfileIdParam Bridge endpoint profile used by the edge cluster (optional) // @param cursorParam Opaque cursor to be used for getting next page of records (supplied by current result page) (optional) // @param includedFieldsParam Comma separated list of fields that should be included in query result (optional) // @param logicalSwitchIdParam Logical Switch Identifier (optional) // @param pageSizeParam Maximum number of results to return in this page (server may return fewer) (optional, default to 1000) // @param sortAscendingParam (optional) // @param sortByParam Field by which records are sorted (optional) // @param vlanTransportZoneIdParam VLAN transport zone id used by the edge cluster (optional) // @return com.vmware.model.BridgeEndpointListResult // @throws InvalidRequest Bad Request, Precondition Failed // @throws Unauthorized Forbidden // @throws ServiceUnavailable Service Unavailable // @throws InternalServerError Internal Server Error // @throws NotFound Not Found ListBridgeEndpoints(bridgeClusterIdParam *string, bridgeEndpointProfileIdParam *string, cursorParam *string, includedFieldsParam *string, logicalSwitchIdParam *string, pageSizeParam *int64, sortAscendingParam *bool, sortByParam *string, vlanTransportZoneIdParam *string) (model.BridgeEndpointListResult, error) // Modifies a existing bridge endpoint. // // @param bridgeendpointIdParam (required) // @param bridgeEndpointParam (required) // @return com.vmware.model.BridgeEndpoint // @throws InvalidRequest Bad Request, Precondition Failed // @throws Unauthorized Forbidden // @throws ServiceUnavailable Service Unavailable // @throws InternalServerError Internal Server Error // @throws NotFound Not Found UpdateBridgeEndpoint(bridgeendpointIdParam string, bridgeEndpointParam model.BridgeEndpoint) (model.BridgeEndpoint, error) } type managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsClient struct { connector client.Connector interfaceDefinition core.InterfaceDefinition errorsBindingMap map[string]bindings.BindingType } func NewManagementPlaneAPINetworkingLogicalBridgingBridgeEndpointsClient(connector client.Connector) *managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsClient { interfaceIdentifier := core.NewInterfaceIdentifier("com.vmware.api.management_plane_API_networking_logical_bridging_bridge_endpoints") methodIdentifiers := map[string]core.MethodIdentifier{ "create_bridge_endpoint": core.NewMethodIdentifier(interfaceIdentifier, "create_bridge_endpoint"), "delete_bridge_endpoint": core.NewMethodIdentifier(interfaceIdentifier, "delete_bridge_endpoint"), "get_bridge_endpoint": core.NewMethodIdentifier(interfaceIdentifier, "get_bridge_endpoint"), "get_bridge_endpoint_statistics": core.NewMethodIdentifier(interfaceIdentifier, "get_bridge_endpoint_statistics"), "get_bridge_endpoint_status": core.NewMethodIdentifier(interfaceIdentifier, "get_bridge_endpoint_status"), "list_bridge_endpoints": core.NewMethodIdentifier(interfaceIdentifier, "list_bridge_endpoints"), "update_bridge_endpoint": core.NewMethodIdentifier(interfaceIdentifier, "update_bridge_endpoint"), } interfaceDefinition := core.NewInterfaceDefinition(interfaceIdentifier, methodIdentifiers) errorsBindingMap := make(map[string]bindings.BindingType) mIface := managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsClient{interfaceDefinition: interfaceDefinition, errorsBindingMap: errorsBindingMap, connector: connector} return &mIface } func (mIface *managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsClient) GetErrorBindingType(errorName string) bindings.BindingType { if entry, ok := mIface.errorsBindingMap[errorName]; ok { return entry } return errors.ERROR_BINDINGS_MAP[errorName] } func (mIface *managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsClient) CreateBridgeEndpoint(bridgeEndpointParam model.BridgeEndpoint) (model.BridgeEndpoint, error) { typeConverter := mIface.connector.TypeConverter() executionContext := mIface.connector.NewExecutionContext() sv := bindings.NewStructValueBuilder(managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsCreateBridgeEndpointInputType(), typeConverter) sv.AddStructField("BridgeEndpoint", bridgeEndpointParam) inputDataValue, inputError := sv.GetStructValue() if inputError != nil { var emptyOutput model.BridgeEndpoint return emptyOutput, bindings.VAPIerrorsToError(inputError) } operationRestMetaData := managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsCreateBridgeEndpointRestMetadata() connectionMetadata := map[string]interface{}{lib.REST_METADATA: operationRestMetaData} connectionMetadata["isStreamingResponse"] = false mIface.connector.SetConnectionMetadata(connectionMetadata) methodResult := mIface.connector.GetApiProvider().Invoke("com.vmware.api.management_plane_API_networking_logical_bridging_bridge_endpoints", "create_bridge_endpoint", inputDataValue, executionContext) var emptyOutput model.BridgeEndpoint if methodResult.IsSuccess() { output, errorInOutput := typeConverter.ConvertToGolang(methodResult.Output(), managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsCreateBridgeEndpointOutputType()) if errorInOutput != nil { return emptyOutput, bindings.VAPIerrorsToError(errorInOutput) } return output.(model.BridgeEndpoint), nil } else { methodError, errorInError := typeConverter.ConvertToGolang(methodResult.Error(), mIface.GetErrorBindingType(methodResult.Error().Name())) if errorInError != nil { return emptyOutput, bindings.VAPIerrorsToError(errorInError) } return emptyOutput, methodError.(error) } } func (mIface *managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsClient) DeleteBridgeEndpoint(bridgeendpointIdParam string) error { typeConverter := mIface.connector.TypeConverter() executionContext := mIface.connector.NewExecutionContext() sv := bindings.NewStructValueBuilder(managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsDeleteBridgeEndpointInputType(), typeConverter) sv.AddStructField("BridgeendpointId", bridgeendpointIdParam) inputDataValue, inputError := sv.GetStructValue() if inputError != nil { return bindings.VAPIerrorsToError(inputError) } operationRestMetaData := managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsDeleteBridgeEndpointRestMetadata() connectionMetadata := map[string]interface{}{lib.REST_METADATA: operationRestMetaData} connectionMetadata["isStreamingResponse"] = false mIface.connector.SetConnectionMetadata(connectionMetadata) methodResult := mIface.connector.GetApiProvider().Invoke("com.vmware.api.management_plane_API_networking_logical_bridging_bridge_endpoints", "delete_bridge_endpoint", inputDataValue, executionContext) if methodResult.IsSuccess() { return nil } else { methodError, errorInError := typeConverter.ConvertToGolang(methodResult.Error(), mIface.GetErrorBindingType(methodResult.Error().Name())) if errorInError != nil { return bindings.VAPIerrorsToError(errorInError) } return methodError.(error) } } func (mIface *managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsClient) GetBridgeEndpoint(bridgeendpointIdParam string) (model.BridgeEndpoint, error) { typeConverter := mIface.connector.TypeConverter() executionContext := mIface.connector.NewExecutionContext() sv := bindings.NewStructValueBuilder(managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsGetBridgeEndpointInputType(), typeConverter) sv.AddStructField("BridgeendpointId", bridgeendpointIdParam) inputDataValue, inputError := sv.GetStructValue() if inputError != nil { var emptyOutput model.BridgeEndpoint return emptyOutput, bindings.VAPIerrorsToError(inputError) } operationRestMetaData := managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsGetBridgeEndpointRestMetadata() connectionMetadata := map[string]interface{}{lib.REST_METADATA: operationRestMetaData} connectionMetadata["isStreamingResponse"] = false mIface.connector.SetConnectionMetadata(connectionMetadata) methodResult := mIface.connector.GetApiProvider().Invoke("com.vmware.api.management_plane_API_networking_logical_bridging_bridge_endpoints", "get_bridge_endpoint", inputDataValue, executionContext) var emptyOutput model.BridgeEndpoint if methodResult.IsSuccess() { output, errorInOutput := typeConverter.ConvertToGolang(methodResult.Output(), managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsGetBridgeEndpointOutputType()) if errorInOutput != nil { return emptyOutput, bindings.VAPIerrorsToError(errorInOutput) } return output.(model.BridgeEndpoint), nil } else { methodError, errorInError := typeConverter.ConvertToGolang(methodResult.Error(), mIface.GetErrorBindingType(methodResult.Error().Name())) if errorInError != nil { return emptyOutput, bindings.VAPIerrorsToError(errorInError) } return emptyOutput, methodError.(error) } } func (mIface *managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsClient) GetBridgeEndpointStatistics(endpointIdParam string, sourceParam *string) (model.BridgeEndpointStatistics, error) { typeConverter := mIface.connector.TypeConverter() executionContext := mIface.connector.NewExecutionContext() sv := bindings.NewStructValueBuilder(managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsGetBridgeEndpointStatisticsInputType(), typeConverter) sv.AddStructField("EndpointId", endpointIdParam) sv.AddStructField("Source", sourceParam) inputDataValue, inputError := sv.GetStructValue() if inputError != nil { var emptyOutput model.BridgeEndpointStatistics return emptyOutput, bindings.VAPIerrorsToError(inputError) } operationRestMetaData := managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsGetBridgeEndpointStatisticsRestMetadata() connectionMetadata := map[string]interface{}{lib.REST_METADATA: operationRestMetaData} connectionMetadata["isStreamingResponse"] = false mIface.connector.SetConnectionMetadata(connectionMetadata) methodResult := mIface.connector.GetApiProvider().Invoke("com.vmware.api.management_plane_API_networking_logical_bridging_bridge_endpoints", "get_bridge_endpoint_statistics", inputDataValue, executionContext) var emptyOutput model.BridgeEndpointStatistics if methodResult.IsSuccess() { output, errorInOutput := typeConverter.ConvertToGolang(methodResult.Output(), managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsGetBridgeEndpointStatisticsOutputType()) if errorInOutput != nil { return emptyOutput, bindings.VAPIerrorsToError(errorInOutput) } return output.(model.BridgeEndpointStatistics), nil } else { methodError, errorInError := typeConverter.ConvertToGolang(methodResult.Error(), mIface.GetErrorBindingType(methodResult.Error().Name())) if errorInError != nil { return emptyOutput, bindings.VAPIerrorsToError(errorInError) } return emptyOutput, methodError.(error) } } func (mIface *managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsClient) GetBridgeEndpointStatus(endpointIdParam string, sourceParam *string) (model.BridgeEndpointStatus, error) { typeConverter := mIface.connector.TypeConverter() executionContext := mIface.connector.NewExecutionContext() sv := bindings.NewStructValueBuilder(managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsGetBridgeEndpointStatusInputType(), typeConverter) sv.AddStructField("EndpointId", endpointIdParam) sv.AddStructField("Source", sourceParam) inputDataValue, inputError := sv.GetStructValue() if inputError != nil { var emptyOutput model.BridgeEndpointStatus return emptyOutput, bindings.VAPIerrorsToError(inputError) } operationRestMetaData := managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsGetBridgeEndpointStatusRestMetadata() connectionMetadata := map[string]interface{}{lib.REST_METADATA: operationRestMetaData} connectionMetadata["isStreamingResponse"] = false mIface.connector.SetConnectionMetadata(connectionMetadata) methodResult := mIface.connector.GetApiProvider().Invoke("com.vmware.api.management_plane_API_networking_logical_bridging_bridge_endpoints", "get_bridge_endpoint_status", inputDataValue, executionContext) var emptyOutput model.BridgeEndpointStatus if methodResult.IsSuccess() { output, errorInOutput := typeConverter.ConvertToGolang(methodResult.Output(), managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsGetBridgeEndpointStatusOutputType()) if errorInOutput != nil { return emptyOutput, bindings.VAPIerrorsToError(errorInOutput) } return output.(model.BridgeEndpointStatus), nil } else { methodError, errorInError := typeConverter.ConvertToGolang(methodResult.Error(), mIface.GetErrorBindingType(methodResult.Error().Name())) if errorInError != nil { return emptyOutput, bindings.VAPIerrorsToError(errorInError) } return emptyOutput, methodError.(error) } } func (mIface *managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsClient) ListBridgeEndpoints(bridgeClusterIdParam *string, bridgeEndpointProfileIdParam *string, cursorParam *string, includedFieldsParam *string, logicalSwitchIdParam *string, pageSizeParam *int64, sortAscendingParam *bool, sortByParam *string, vlanTransportZoneIdParam *string) (model.BridgeEndpointListResult, error) { typeConverter := mIface.connector.TypeConverter() executionContext := mIface.connector.NewExecutionContext() sv := bindings.NewStructValueBuilder(managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsListBridgeEndpointsInputType(), typeConverter) sv.AddStructField("BridgeClusterId", bridgeClusterIdParam) sv.AddStructField("BridgeEndpointProfileId", bridgeEndpointProfileIdParam) sv.AddStructField("Cursor", cursorParam) sv.AddStructField("IncludedFields", includedFieldsParam) sv.AddStructField("LogicalSwitchId", logicalSwitchIdParam) sv.AddStructField("PageSize", pageSizeParam) sv.AddStructField("SortAscending", sortAscendingParam) sv.AddStructField("SortBy", sortByParam) sv.AddStructField("VlanTransportZoneId", vlanTransportZoneIdParam) inputDataValue, inputError := sv.GetStructValue() if inputError != nil { var emptyOutput model.BridgeEndpointListResult return emptyOutput, bindings.VAPIerrorsToError(inputError) } operationRestMetaData := managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsListBridgeEndpointsRestMetadata() connectionMetadata := map[string]interface{}{lib.REST_METADATA: operationRestMetaData} connectionMetadata["isStreamingResponse"] = false mIface.connector.SetConnectionMetadata(connectionMetadata) methodResult := mIface.connector.GetApiProvider().Invoke("com.vmware.api.management_plane_API_networking_logical_bridging_bridge_endpoints", "list_bridge_endpoints", inputDataValue, executionContext) var emptyOutput model.BridgeEndpointListResult if methodResult.IsSuccess() { output, errorInOutput := typeConverter.ConvertToGolang(methodResult.Output(), managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsListBridgeEndpointsOutputType()) if errorInOutput != nil { return emptyOutput, bindings.VAPIerrorsToError(errorInOutput) } return output.(model.BridgeEndpointListResult), nil } else { methodError, errorInError := typeConverter.ConvertToGolang(methodResult.Error(), mIface.GetErrorBindingType(methodResult.Error().Name())) if errorInError != nil { return emptyOutput, bindings.VAPIerrorsToError(errorInError) } return emptyOutput, methodError.(error) } } func (mIface *managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsClient) UpdateBridgeEndpoint(bridgeendpointIdParam string, bridgeEndpointParam model.BridgeEndpoint) (model.BridgeEndpoint, error) { typeConverter := mIface.connector.TypeConverter() executionContext := mIface.connector.NewExecutionContext() sv := bindings.NewStructValueBuilder(managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsUpdateBridgeEndpointInputType(), typeConverter) sv.AddStructField("BridgeendpointId", bridgeendpointIdParam) sv.AddStructField("BridgeEndpoint", bridgeEndpointParam) inputDataValue, inputError := sv.GetStructValue() if inputError != nil { var emptyOutput model.BridgeEndpoint return emptyOutput, bindings.VAPIerrorsToError(inputError) } operationRestMetaData := managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsUpdateBridgeEndpointRestMetadata() connectionMetadata := map[string]interface{}{lib.REST_METADATA: operationRestMetaData} connectionMetadata["isStreamingResponse"] = false mIface.connector.SetConnectionMetadata(connectionMetadata) methodResult := mIface.connector.GetApiProvider().Invoke("com.vmware.api.management_plane_API_networking_logical_bridging_bridge_endpoints", "update_bridge_endpoint", inputDataValue, executionContext) var emptyOutput model.BridgeEndpoint if methodResult.IsSuccess() { output, errorInOutput := typeConverter.ConvertToGolang(methodResult.Output(), managementPlaneAPINetworkingLogicalBridgingBridgeEndpointsUpdateBridgeEndpointOutputType()) if errorInOutput != nil { return emptyOutput, bindings.VAPIerrorsToError(errorInOutput) } return output.(model.BridgeEndpoint), nil } else { methodError, errorInError := typeConverter.ConvertToGolang(methodResult.Error(), mIface.GetErrorBindingType(methodResult.Error().Name())) if errorInError != nil { return emptyOutput, bindings.VAPIerrorsToError(errorInError) } return emptyOutput, methodError.(error) } }
jscrdev/LeetCode-in-Java
src.save/test/java/g1501_1600/s1520_maximum_number_of_non_overlapping_substrings/SolutionTest.java
<reponame>jscrdev/LeetCode-in-Java package g1501_1600.s1520_maximum_number_of_non_overlapping_substrings; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import java.util.Arrays; import org.junit.jupiter.api.Test; class SolutionTest { @Test void maxNumOfSubstrings() { assertThat( new Solution().maxNumOfSubstrings("adefaddaccc"), equalTo(Arrays.asList("e", "f", "ccc"))); } @Test void maxNumOfSubstrings2() { assertThat( new Solution().maxNumOfSubstrings("abbaccd"), equalTo(Arrays.asList("bb", "cc", "d"))); } }
webfx-project/webfx-platform
webfx-platform-independent-util/webfx-platform-shared-util/src/main/java/dev/webfx/platform/shared/util/tuples/Unit.java
<filename>webfx-platform-independent-util/webfx-platform-shared-util/src/main/java/dev/webfx/platform/shared/util/tuples/Unit.java<gh_stars>0 package dev.webfx.platform.shared.util.tuples; /** * @author <NAME> */ public final class Unit<T> { private T o1; public Unit() { } public Unit(T o1) { this.o1 = o1; } public T get() { return o1; } public void set(T object) { this.o1 = object; } }
JhonataSantos36/Mercado-pago
sdk/src/test/java/com/mercadopago/mocks/Payments.java
package com.mercadopago.mocks; import com.mercadopago.model.ApiException; import com.mercadopago.model.Payment; import com.mercadopago.util.JsonUtil; import com.mercadopago.utils.ResourcesUtil; public class Payments { public static Payment getApprovedPayment() { String json = ResourcesUtil.getStringResource("approved_payment.json"); return JsonUtil.getInstance().fromJson(json, Payment.class); } public static Payment getRejectedPayment() { String json = ResourcesUtil.getStringResource("rejected_payment.json"); return JsonUtil.getInstance().fromJson(json, Payment.class); } public static Payment getPendingPayment() { String json = ResourcesUtil.getStringResource("pending_payment.json"); return JsonUtil.getInstance().fromJson(json, Payment.class); } public static Payment getCallForAuthPayment() { String json = ResourcesUtil.getStringResource("call_for_auth_payment.json"); return JsonUtil.getInstance().fromJson(json, Payment.class); } public static ApiException getInvalidESCPayment() { String json = ResourcesUtil.getStringResource("invalid_esc_payment.json"); return JsonUtil.getInstance().fromJson(json, ApiException.class); } public static ApiException getInvalidIdentificationPayment() { String json = ResourcesUtil.getStringResource("invalid_identification_payment.json"); return JsonUtil.getInstance().fromJson(json, ApiException.class); } }
RazvanRotari/iaP
services/utils/rsql.py
#!/usr/bin/env python3 import re import sys import model PATTERN = "\{\{.*?\}\}" class RSQL: def __init__(self): self.prefix = {} def find_term_intern(self, item): (cls_name, field) = item.replace("{", "").replace("}", "").split(".") try: getattr(model, cls_name) except: print("Invalid class: ", cls_name, " in the input file") obj = getattr(model, cls_name)("test") link = obj.data[field]["link"] self.prefix[link[2]] = link[0] return link[2]+":"+link[1] def find_term(self, match_group): mat = match_group.group() return self.find_term_intern(mat) def __call__(self, group): return self.find_term(group) def main(): if len(sys.argv) < 2: print("Usage qsql.py <file>") return file_name = sys.argv[1] data = "" with open(file_name, "r") as fd: data = fd.read() ql = RSQL() output = re.sub(PATTERN, ql, data) prefix_str = "" for prefix in ql.prefix.items(): prefix_str += "\nPREFIX {prefix}:<{link}>".format(prefix=prefix[0], link=prefix[1]) output = prefix_str + "\n" + output print(output) #{{item.field}} if __name__ == "__main__": main()
AnikaZN/AnikaDS
Study_Ahead/Flask Basics/dynamic_page.py
from flask import Flask app = Flask(__name__) @app.route ('/') def index(): return '<h1>This is a happy puppy!</h1>' @app.route('/info') def info(): return '<h2>This is information!</h2>' @app.route('/puppy/<name>') def puppy(name): return '<h3>This page is for {}</h3>'.format(name) #this is like on a Lambda dashboard if __name__ == '__main__': app.run()
svher/TigerCompiler
ch06/translate.h
<gh_stars>10-100 #ifndef TRANSLATE_H_ #define TRANSLATE_H_ #include "temp.h" typedef struct Tr_level_ *Tr_level; typedef struct Tr_access_ *Tr_access; typedef struct Tr_accessList_ *Tr_accessList; struct Tr_accessList_ { Tr_access head; Tr_accessList tail; }; Tr_accessList Tr_AccessList(Tr_access head, Tr_accessList tail); Tr_level Tr_outermost(); Tr_level Tr_newLevel(Tr_level parent, Temp_label name, U_boolList formals); Tr_accessList Tr_formals(Tr_level level); Tr_access Tr_allocLocal(Tr_level level, bool escape); #endif
gregzanch/functional-acoustics
functional-acoustics/util/mean.js
const mean = x => x.reduce((p, c) => p + c, 0) / x.length; export default mean;
chu10/xmfcn-spring-cloud
xmfcn-spring-cloud-sys-elasticsearch-service/src/main/java/com/cn/xmf/service/es/ElasticsearchHelperService.java
package com.cn.xmf.service.es; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.cn.xmf.base.model.ResultCodeMessage; import com.cn.xmf.base.model.RetData; import com.cn.xmf.model.es.EsModel; import com.cn.xmf.model.es.EsPage; import com.cn.xmf.model.es.EsPartion; import com.cn.xmf.service.common.SysCommonService; import com.cn.xmf.util.ConstantUtil; import com.cn.xmf.util.StringUtil; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import io.searchbox.client.JestClient; import io.searchbox.client.JestResult; import io.searchbox.core.Search; import io.searchbox.core.search.sort.Sort; import io.searchbox.indices.CreateIndex; import io.searchbox.indices.DeleteIndex; import io.searchbox.indices.IndicesExists; import io.searchbox.indices.mapping.PutMapping; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.RangeQueryBuilder; import org.elasticsearch.search.aggregations.AggregationBuilder; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval; import org.elasticsearch.search.aggregations.bucket.histogram.ExtendedBounds; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.joda.time.DateTimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.*; /** * ES 辅助类 * * @version 2019-05-23 * @Author rufei.cn */ @Service @SuppressWarnings("all") public class ElasticsearchHelperService { private static Logger logger = LoggerFactory.getLogger(ElasticsearchHelperService.class); @Autowired private JestClient jestClient; @Autowired private SysCommonService sysCommonService; /** * 创建mapping * * @param es * @return */ public JestResult createMapping(EsModel es) { JestResult result = null; RetData aReturn = validateParms(es); if (aReturn.getCode() == ResultCodeMessage.FAILURE) { return result; } String message = es.getMessage(); String indexName = es.getIndex(); String type = es.getType(); JSONObject messageJson = JSONObject.parseObject(message); if (messageJson == null || messageJson.size() <= 0) { return result; } try { Iterator<Map.Entry<String, Object>> iterator = messageJson.entrySet().iterator(); JSONObject typeName = new JSONObject(); while (iterator.hasNext()) { Map.Entry<String, Object> next = iterator.next(); String key = next.getKey(); if (key == null) { continue; } JSONObject object = new JSONObject(); object.put("type", "text"); if ("createTime".equals(key)) { object.put("type", "date"); object.put("format", "yyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"); } if ("time".equals(key)) { object.put("type", "keyword"); } if ("level".equals(key)) { object.put("type", "keyword"); } if ("subSysName".equals(key)) { object.put("type", "keyword"); } if ("traceId".equals(key)) { object.put("type", "keyword"); } if ("id".equals(key)) { object.put("type", "keyword"); } typeName.put(key, object); } JSONObject properties = new JSONObject(); properties.put("properties", typeName); JSONObject fieldMapping = new JSONObject(); fieldMapping.put(type, properties); logger.info("properties={}", properties); PutMapping putMapping = new PutMapping.Builder(indexName, type, properties.toString()).build(); result = jestClient.execute(putMapping); logger.info("result={}", result.getJsonString()); } catch (IOException e) { String exceptionMsg = StringUtil.getExceptionMsg(e); logger.info(exceptionMsg); } catch (Exception e) { String exceptionMsg = StringUtil.getExceptionMsg(e); logger.info(exceptionMsg); } return result; } /** * 判断 ES集群中 是否含有 此索引名的索引 * * @param indexName * @return */ public JestResult indicesExists(String indexName) { JestResult result = null; try { IndicesExists indicesExists = new IndicesExists.Builder(indexName).build(); result = jestClient.execute(indicesExists); } catch (IOException e) { String exceptionMsg = StringUtil.getExceptionMsg(e); logger.info(exceptionMsg); } catch (Exception e) { String exceptionMsg = StringUtil.getExceptionMsg(e); logger.info(exceptionMsg); } return result; } /** * 删除索引 * * @param indexName * @throws Exception */ public JestResult deleteIndex(EsModel es) { JestResult result = null; RetData aReturn = validateParms(es); if (aReturn.getCode() == ResultCodeMessage.FAILURE) { return result; } String message = es.getMessage(); String indexName = es.getIndex(); String type = es.getType(); result = indicesExists(indexName); if (result == null) { return result; } int responseCode = result.getResponseCode(); if (responseCode != 200) { return result; } try { result = jestClient.execute(new DeleteIndex.Builder(indexName).build()); } catch (Exception e) { String exceptionMsg = StringUtil.getExceptionMsg(e); logger.info(exceptionMsg); } return result; } /** * 创建索引 * * @param indexName * @throws Exception */ public JestResult createIndex(EsModel es) { JestResult result = null; RetData aReturn = validateParms(es); if (aReturn.getCode() == ResultCodeMessage.FAILURE) { return result; } String message = es.getMessage(); String indexName = es.getIndex(); String type = es.getType(); result = indicesExists(indexName); if (result == null) { return result; } int responseCode = result.getResponseCode(); try { if (responseCode == 404) { result = jestClient.execute(new CreateIndex.Builder(indexName).build()); responseCode = result.getResponseCode(); if (responseCode == 200) { result = createMapping(es); } } } catch (Exception e) { String exceptionMsg = StringUtil.getExceptionMsg(e); logger.info(exceptionMsg); } return result; } /** * 保存单条数据到ES * * @param message * @return */ public RetData validateParms(EsModel es) { RetData dataReturn = new RetData(); if (es == null) { dataReturn.setMessage("json 不能为空"); return dataReturn; } String message = es.getMessage(); String indexName = es.getIndex(); String type = es.getType(); if (StringUtil.isBlank(message)) { dataReturn.setMessage("message 消息不能为空"); return dataReturn; } if (StringUtil.isBlank(indexName)) { dataReturn.setMessage("indexName 不能为空"); return dataReturn; } if (StringUtil.isBlank(type)) { dataReturn.setMessage("type 不能为空"); return dataReturn; } dataReturn.setCode(ResultCodeMessage.SUCCESS); return dataReturn; } /** * 组装搜索条件 * * @param EsModel es * keywords * highlights * @return */ public Search searchCondition(EsModel es) { Search search = null; if (es == null) { return search; } JSONObject keywords = es.getKeyWord(); JSONObject hightWord = es.getHightWord(); EsPage esPage = es.getEsPage(); String indexName = es.getIndex(); String type = es.getType(); boolean isVague = es.isVague();//是否模糊搜索 boolean isAccuracySort = es.isAccuracySort();//是否根据精确度排序 boolean isAndSearch = es.isAndSearch();//是否And搜索 if (StringUtil.isBlank(indexName)) { return search; } if (StringUtil.isBlank(type)) { return search; } int pageNo = 1; int pageSize = 10; int startIndex = 0; if (esPage != null) { pageNo = esPage.getPageNo(); pageSize = esPage.getPageSize(); startIndex = esPage.getStartIndex(); } SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); AddKeyWords(keywords, searchSourceBuilder); HighlightBuilder highlightBuilder = new HighlightBuilder(); AddHighLigh(keywords, highlightBuilder); searchSourceBuilder.explain(isAccuracySort); searchSourceBuilder.from(startIndex); searchSourceBuilder.size(pageSize); Sort sort = new Sort("time", Sort.Sorting.DESC); searchSourceBuilder.highlighter(highlightBuilder); search = new Search.Builder(searchSourceBuilder.toString()) .addIndex(indexName).addType(type).addSort(sort).build(); return search; } /** * 通过SQL统计ES数据 * * @param sql * @return */ public JSONObject getEsDataBySQl(String sql) { JSONObject jsonObject = null; if (StringUtil.isBlank(sql)) { return jsonObject; } String es_http_rest_url = sysCommonService.getDictValue(ConstantUtil.DICT_TYPE_BASE_CONFIG, "es_http_rest_url");//获取kafka地址 包括端口号 if (StringUtil.isBlank(es_http_rest_url)) { return jsonObject; } es_http_rest_url = es_http_rest_url + "/_xpack/sql"; JSONObject parms = new JSONObject(); parms.put("query", sql); String doHttpPost = null; try { //doHttpPost = HttpClientUtil.excuteRequestEntity(kafaka_address, parms, "utf-8", 5000); if (StringUtil.isNotBlank(doHttpPost)) { JSONObject.parseObject(doHttpPost); } } catch (Exception e) { String exceptionMsg = sql + "=======》" + StringUtil.getExceptionMsg(e); logger.error(exceptionMsg); } return jsonObject; } /** * 增加高亮词 * * @param keywords * @param highlightBuilder */ private void AddHighLigh(JSONObject keywords, HighlightBuilder highlightBuilder) { if (keywords == null || keywords.size() <= 0) { return; } Iterator<Map.Entry<String, Object>> iterator = keywords.entrySet().iterator(); if (iterator == null) { return; } while (iterator.hasNext()) { Map.Entry<String, Object> next = iterator.next(); String key = next.getKey(); Object value = next.getValue(); if (value == null || value.toString().length() <= 0) { continue; } highlightBuilder.preTags("<span style=color:red>"); highlightBuilder.postTags("</span>"); highlightBuilder.field(key); } } /** * 添加查询条件(等值查询) * * @param keywords * @param searchSourceBuilder */ private void AddKeyWords(JSONObject keywords, SearchSourceBuilder searchSourceBuilder) { if (keywords == null || keywords.size() <= 0) { return; } Iterator<Map.Entry<String, Object>> iterator = keywords.entrySet().iterator(); if (iterator == null) { return; } while (iterator.hasNext()) { Map.Entry<String, Object> next = iterator.next(); String key = next.getKey(); Object value = next.getValue(); if (value == null || value.toString().length() <= 0) { continue; } if ("id".equals(key)) { searchSourceBuilder.query(QueryBuilders.termQuery(key, value)); } else { searchSourceBuilder.query(QueryBuilders.commonTermsQuery(key, value)); } } } /** * 按天统计 各个日志级别的数量 查询条件 * * @param EsModel es * keywords * highlights * @return */ public Search statisticsDayCondition(EsModel es) { Search search = null; if (es == null) { return search; } String indexName = es.getIndex(); String type = es.getType(); String startTime = es.getStartTime(); String endTime = es.getEndTime(); JSONObject keywords = es.getKeyWord(); if (StringUtil.isBlank(indexName)) { return search; } if (StringUtil.isBlank(type)) { return search; } SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); if (StringUtil.isNotBlank(startTime) && StringUtil.isNotBlank(endTime)) { RangeQueryBuilder rangequerybuilder = QueryBuilders .rangeQuery("createTime") .from(startTime).to(endTime); searchSourceBuilder.query(rangequerybuilder); } AddKeyWords(keywords, searchSourceBuilder); ExtendedBounds extendedBounds = new ExtendedBounds(startTime, endTime); AggregationBuilder levelAgg = AggregationBuilders.terms("level_count").field("level").minDocCount(0); AggregationBuilder dateAgg = AggregationBuilders.dateHistogram("day_count") .field("createTime") .dateHistogramInterval(DateHistogramInterval.DAY) .format("yyyy-MM-dd") .extendedBounds(extendedBounds) .minDocCount(0L)//为空0补充 .timeZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+8"))); AggregationBuilder builder = dateAgg.subAggregation(levelAgg); searchSourceBuilder.aggregation(builder).size(0); search = new Search.Builder(searchSourceBuilder.toString()) .addIndex(indexName).addType(type).build(); return search; } /** * 按天统计 各个日志级别的数量结果处理 * * @param result * @return */ public JSONObject getDayStatisticsResult(JestResult result) { JSONObject object = null; JsonElement aggregations = result.getJsonObject().get("aggregations"); if (aggregations == null) { return object; } JsonElement day_count = aggregations.getAsJsonObject().get("day_count"); if (day_count == null) { return object; } JsonArray jsonArray = day_count.getAsJsonObject().getAsJsonArray("buckets"); if (jsonArray == null || jsonArray.size() <= 0) { return object; } int size = jsonArray.size(); object = new JSONObject(); List<String> dayList = new ArrayList<String>(); List<Integer> dayCountInfoList = new ArrayList<Integer>(); List<Integer> dayCountErrorList = new ArrayList<Integer>(); List<Integer> dayCountWarnList = new ArrayList<Integer>(); List<Integer> dayCountDebugList = new ArrayList<Integer>(); for (int i = 0; i < size; i++) { JsonElement jsonElement = jsonArray.get(i); if (jsonElement == null) { continue; } JSONObject jsonObject = JSONObject.parseObject(jsonElement.toString()); if (jsonObject == null) { continue; } String day = jsonObject.getString("key_as_string"); JSONObject levelCount = jsonObject.getJSONObject("level_count"); if (jsonObject == null || jsonObject.size() <= 0) { continue; } JSONArray buckets = levelCount.getJSONArray("buckets"); if (jsonArray == null || jsonArray.size() <= 0) { return object; } int sizeLengt = buckets.size(); dayList.add(day); int infoCount = 0; int errorCount = 0; int warnCount = 0; int debugCount = 0; for (int j = 0; j < sizeLengt; j++) { JSONObject bucketsJSONObject = buckets.getJSONObject(j); if (bucketsJSONObject == null) { continue; } String key = bucketsJSONObject.getString("key"); if (StringUtil.isBlank(key)) { continue; } int doc_count = bucketsJSONObject.getIntValue("doc_count"); String value = "0"; switch (key) { case "INFO": infoCount = infoCount + doc_count; break; case "ERROR": errorCount = errorCount + doc_count; break; case "WARN": warnCount = warnCount + doc_count; break; case "DEBUG": debugCount = debugCount + doc_count; break; default: debugCount = 0; } } dayCountInfoList.add(infoCount); dayCountErrorList.add(errorCount); dayCountWarnList.add(warnCount); dayCountDebugList.add(debugCount); } object.put("dayList", dayList); object.put("dayCountInfoList", dayCountInfoList); object.put("dayCountErrorList", dayCountErrorList); object.put("dayCountWarnList", dayCountWarnList); object.put("dayCountDebugList", dayCountDebugList); return object; } /** * 按天Level统计 各个日志级别的数量 查询条件 * * @param EsModel es * keywords * highlights * @return */ public Search statisticsLevelCondition(EsModel es) { Search search = null; if (es == null) { return search; } String indexName = es.getIndex(); String type = es.getType(); String startTime = es.getStartTime(); String endTime = es.getEndTime(); JSONObject keywords = es.getKeyWord(); if (StringUtil.isBlank(indexName)) { return search; } if (StringUtil.isBlank(type)) { return search; } SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); if (StringUtil.isNotBlank(startTime) && StringUtil.isNotBlank(endTime)) { RangeQueryBuilder rangequerybuilder = QueryBuilders .rangeQuery("createTime") .from(startTime).to(endTime); searchSourceBuilder.query(rangequerybuilder); } AddKeyWords(keywords, searchSourceBuilder); ExtendedBounds extendedBounds = new ExtendedBounds(startTime, endTime); AggregationBuilder levelAgg = AggregationBuilders.terms("level_count").field("level").minDocCount(0); searchSourceBuilder.aggregation(levelAgg).size(0); search = new Search.Builder(searchSourceBuilder.toString()) .addIndex(indexName).addType(type).build(); return search; } /** * 按天Level统计 各个日志级别的数量 * * @param result * @return */ public JSONObject getLevelStatisticsResult(JestResult result) { JSONObject object = null; JsonElement aggregations = result.getJsonObject().get("aggregations"); if (aggregations == null) { return object; } JsonElement day_count = aggregations.getAsJsonObject().get("level_count"); if (day_count == null) { return object; } JsonArray jsonArray = day_count.getAsJsonObject().getAsJsonArray("buckets"); if (jsonArray == null || jsonArray.size() <= 0) { return object; } int size = jsonArray.size(); object = new JSONObject(); for (int i = 0; i < size; i++) { JsonElement jsonElement = jsonArray.get(i); if (jsonElement == null) { continue; } JSONObject jsonObject = JSONObject.parseObject(jsonElement.toString()); if (jsonObject == null) { continue; } String key = jsonObject.getString("key"); String doc_count = jsonObject.getString("doc_count"); if (StringUtil.isBlank(doc_count)) { doc_count = "0"; } switch (key) { case "INFO": object.put("infoCount", doc_count); break; case "ERROR": object.put("errorCount", doc_count); break; case "WARN": object.put("warnCount", doc_count); break; case "DEBUG": object.put("debugCount", doc_count); break; default: object.put("debugCount", doc_count); } } return object; } /** * 获取搜索结果,处理高亮词 * * @param result * @param esPage */ public EsPartion getSearchResult(JestResult result, EsPage esPage) { EsPartion pt = null; int totalCount = result.getJsonObject().get("hits").getAsJsonObject().get("total").getAsInt(); JsonArray asJsonArray = result.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray(); List<JSONObject> list = new ArrayList<>(); for (int i = 0; i < asJsonArray.size(); i++) { JsonElement jsonElement = asJsonArray.get(i); JsonObject source = jsonElement.getAsJsonObject().getAsJsonObject("_source").getAsJsonObject(); JsonObject highlight = jsonElement.getAsJsonObject().getAsJsonObject("highlight"); Set<Map.Entry<String, JsonElement>> entries = null; if (highlight != null) { entries = highlight.entrySet(); } if (source == null || source.size() <= 0) { continue; } JSONObject jsonObject = JSONObject.parseObject(source.toString()); if (jsonObject == null || jsonObject.size() <= 0) { continue; } jsonObject = addHightWord(entries, jsonObject); list.add(jsonObject); } pt = new EsPartion(esPage, list, totalCount); return pt; } /** * 添加高亮词到结果集中 * * @param entries * @param jsonObject * @return */ private JSONObject addHightWord(Set<Map.Entry<String, JsonElement>> entries, JSONObject jsonObject) { if (entries == null) { return jsonObject; } if (jsonObject == null) { return jsonObject; } Iterator<Map.Entry<String, JsonElement>> iterator = entries.iterator(); while (iterator.hasNext()) { Map.Entry<String, JsonElement> next = iterator.next(); String key = next.getKey(); String value = next.getValue().toString(); if ("id".equals(key)) { continue; } jsonObject.put(key, value); } return jsonObject; } }
Hathoute/ENSEEIHT
TOB/tps/TP02/PointTest.java
import org.junit.*; import java.awt.*; import static org.junit.Assert.*; /** Programme de test de la classe Point. * @author <NAME> * @version 1.11 */ public class PointTest { public static final double EPSILON = 1e-6; // précision pour la comparaison entre réels. private Point p1; private Point p2; @Before public void setUp() { p1 = new Point(1, 2); p2 = new Point(4, -2); } @Test public void testInitialisation() { assertTrue(p1 != null); assertTrue(p2 != null); assertTrue(p1.getX() == 1); assertTrue(p1.getY() == 2); assertTrue(p2.getX() == 4); assertTrue(p2.getY() == -2); } @Test public void testInitialisationMieux() { assertNotNull(p1); assertNotNull(p2); // Remarque : faire un test d'égalité sur des réels est à éviter // à cause des erreurs d'arrondi. En conséquence, il faut // vérifier que les deux nombres sont égaux à EPSILON près. // C'est ce que fait assertEquals(attendu, réel, précision) assertEquals(1.0, p1.getX(), EPSILON); assertEquals(2.0, p1.getY(), EPSILON); assertEquals(4.0, p2.getX(), EPSILON); assertEquals(-2.0, p2.getY(), EPSILON); } @Test public void testSetX() { p1.setX(10); assertEquals(10.0, p1.getX(), EPSILON); p1.setX(-5); assertEquals(-5.0, p1.getX(), EPSILON); } @Test public void testSetY() { p1.setY(10); assertEquals(10.0, p1.getY(), EPSILON); p1.setY(-5); assertEquals(-5.0, p1.getY(), EPSILON); } @Test public void testDistance() { assertEquals(0.0, p1.distance(p1), EPSILON); assertEquals(0.0, p2.distance(p2), EPSILON); assertEquals(5.0, p1.distance(p2), EPSILON); assertEquals(5.0, p2.distance(p1), EPSILON); } @Test public void testTranslater1() { p1.translater(2, 4); assertEquals(3.0, p1.getX(), EPSILON); assertEquals(6.0, p1.getY(), EPSILON); } @Test public void testTranslater2() { p2.translater(-2, -4); assertEquals(2.0, p2.getX(), EPSILON); assertEquals(-6.0, p2.getY(), EPSILON); } @Test public void testGetCouleur() { assertEquals(Color.GREEN, p1.getCouleur()); assertEquals(Color.GREEN, p2.getCouleur()); } @Test public void testSetCouleur() { p1.setCouleur(Color.BLACK); p2.setCouleur(Color.RED); assertEquals(Color.BLACK, p1.getCouleur()); assertEquals(Color.RED, p2.getCouleur()); } }
pcdd05/iiixTibaMe_java
java_2018.Dec-2019.Jan/HomeWork_07_01.java
package xxx; import java.io.File; public class HomeWork_07_01 { //請寫一個程式,可以在讀入一個檔案後,顯示有多少個位元組 public static void main (String[] args) { File inputfile = new File("D:\\CA107_Workspace\\JAVA\\Homework\\Homework_07.pdf"); if (inputfile.isFile()) { System.out.println(inputfile.getName()+"共有"+inputfile.length()+"個位元組"); } } }
gpillusion/Avrilpedia
app/src/main/java/com/illusion/avrillavigne/util/Data.java
<gh_stars>1-10 package com.illusion.avrillavigne.util; public class Data { public static String BASE = "http://i.imgur.com/"; public static String EXT = ".jpg"; public static String[] URLS_hdpi = { BASE + "8XfDo7N" + EXT, BASE + "L6FumDP" + EXT, BASE + "p8XHWXT" + EXT, BASE + "cyBIZnR" + EXT, BASE + "uwmHXWV" + EXT }; public static String[] URLS_xhdpi = { BASE + "0WMNrmF" + EXT, BASE + "b37bAga" + EXT, BASE + "ZnIpq3c" + EXT, BASE + "GTd25or" + EXT, BASE + "ykagAmt" + EXT }; public static String[] URLS_xxhdpi = { BASE + "bzglVBl" + EXT, BASE + "iFIoLNh" + EXT, BASE + "mqLkiGL" + EXT, BASE + "jeo6o3C" + EXT, BASE + "6MMqO0S" + EXT }; private Data() { } }
jguillaumes/muxx
h/a.out.h
/*- * Copyright (c) 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)a.out.h 5.6.1 (2.11BSD GTE) 1/6/94 */ /* ** This code has been pulled from the 2.11BSD source tree. ** ** The differences respect the original code are marked with ** comment blocks. */ #ifndef _AOUT_H_ #define _AOUT_H_ #include "exec.h" #define N_BADMAG(x) \ (((x).a_magic)!=A_MAGIC1 && ((x).a_magic)!=A_MAGIC2 && \ ((x).a_magic)!=A_MAGIC3 && ((x).a_magic)!=A_MAGIC4 && \ ((x).a_magic)!=A_MAGIC5 && ((x).a_magic)!=A_MAGIC6) #define N_TXTOFF(x) \ ((x).a_magic==A_MAGIC5 || (x).a_magic==A_MAGIC6 ? \ sizeof(struct ovlhdr) + sizeof(struct exec) : sizeof(struct exec)) /* * The following were added as part of the new object file format. They * call functions because calculating the sums of overlay sizes was too * messy (and verbose) to do 'inline'. * * NOTE: if the magic number is that of an overlaid object the program * must pass an extended header ('xexec') as the argument. */ /* ** Note: the following block has been commented out for its inclusion ** in bin2load. */ /******************************************************************** #include <sys/types.h> off_t n_stroff(), n_symoff(), n_datoff(), n_dreloc(), n_treloc(); #define N_STROFF(e) (n_stroff(&e)) #define N_SYMOFF(e) (n_symoff(&e)) #define N_DATOFF(e) (n_datoff(&e)) #define N_DRELOC(e) (n_dreloc(&e)) #define N_TRELOC(e) (n_treloc(&e)) ********************************************************************/ #define _AOUT_INCLUDE_ /* ** The following line has been commented out for its inclussion in ** bin2load */ /* #include <nlist.h> */ #endif /* !_AOUT_H_ */
bcgov/mds
services/core-web/src/tests/components/noticeOfWork/applications/referals/ReferralTabs.spec.js
import React from "react"; import { shallow } from "enzyme"; import { ReferralTabs } from "@/components/noticeOfWork/applications/referals/ReferralTabs"; import * as NOW_MOCK from "@/tests/mocks/noticeOfWorkMocks"; const dispatchProps = {}; const reducerProps = {}; const setupDispatchProps = () => { dispatchProps.openModal = jest.fn(); dispatchProps.closeModal = jest.fn(); dispatchProps.createNoticeOfWorkApplicationReview = jest.fn(); dispatchProps.fetchNoticeOfWorkApplicationReviews = jest.fn(() => Promise.resolve()); dispatchProps.updateNoticeOfWorkApplicationReview = jest.fn(); dispatchProps.deleteNoticeOfWorkApplicationReview = jest.fn(); dispatchProps.deleteNoticeOfWorkApplicationDocument = jest.fn(); dispatchProps.updateNoticeOfWorkApplication = jest.fn(); dispatchProps.setNoticeOfWorkApplicationDocumentDownloadState = jest.fn(); dispatchProps.fetchImportedNoticeOfWorkApplication = jest.fn(); }; const setupReducerProps = () => { reducerProps.fixedTop = false; reducerProps.noticeOfWork = NOW_MOCK.NOTICE_OF_WORK; reducerProps.noticeOfWorkReviewTypesHash = {}; reducerProps.type = "REF"; reducerProps.importNowSubmissionDocumentsJob = {}; reducerProps.noticeOfWorkReviewTypes = []; reducerProps.noticeOfWorkReviews = []; }; beforeEach(() => { setupDispatchProps(); setupReducerProps(); }); describe("ReferralTabs", () => { it("renders properly", () => { const component = shallow(<ReferralTabs {...dispatchProps} {...reducerProps} />); expect(component).toMatchSnapshot(); }); });
peter-lawrey/hazelcast-stabilizer
stabilizer/src/main/java/com/hazelcast/stabilizer/agent/workerjvm/WorkerJvm.java
/* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.stabilizer.agent.workerjvm; import com.hazelcast.stabilizer.worker.commands.CommandRequest; import java.io.File; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class WorkerJvm { public Mode mode; public volatile boolean detectFailure = true; public final String id; public volatile String memberAddress; public Process process; public File workerHome; public volatile long lastSeen = System.currentTimeMillis(); public volatile boolean oomeDetected = false; public final BlockingQueue<CommandRequest> commandQueue = new LinkedBlockingQueue<CommandRequest>(); public WorkerJvm(String id) { this.id = id; } @Override public String toString() { return "WorkerJvm{" + "id='" + id + '\'' + ", memberAddress='" + memberAddress + '\'' + ", workerHome=" + workerHome + '}'; } public static enum Mode { SERVER, CLIENT, MIXED } }
blindsubmissions/icse19replication
generated-tests/qmosa/tests/s1023/85_shop/evosuite-tests/umd/cs/shop/JSJshop_ESTest.java
/* * This file was automatically generated by EvoSuite * Fri Aug 24 16:04:19 GMT 2018 */ package umd.cs.shop; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.runtime.EvoAssertions.*; import java.awt.GridLayout; import java.awt.HeadlessException; import java.io.BufferedReader; import java.io.StreamTokenizer; import java.io.StringReader; import javax.swing.JApplet; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.evosuite.runtime.System; import org.evosuite.runtime.testdata.EvoSuiteFile; import org.evosuite.runtime.testdata.FileSystemHandling; import org.junit.runner.RunWith; import umd.cs.shop.JSJshop; import umd.cs.shop.JSJshopNode; import umd.cs.shop.JSJshopVars; import umd.cs.shop.JSMethod; import umd.cs.shop.JSPlanningProblem; import umd.cs.shop.JSTaskAtom; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true) public class JSJshop_ESTest extends JSJshop_ESTest_scaffolding { /** //Test case number: 0 /*Coverage entropy=1.0986122886681096 */ @Test(timeout = 4000) public void test00() throws Throwable { JSJshop jSJshop0 = new JSJshop(); String[] stringArray0 = new String[9]; stringArray0[0] = "Ld"; stringArray0[1] = ""; stringArray0[2] = "Qe+j#8YU_>)V?"; stringArray0[3] = ""; stringArray0[4] = ">/?a`DFOPxT!T^"; stringArray0[5] = "parserOpsMethsAxs: expected ( or )"; stringArray0[6] = ""; stringArray0[7] = ""; stringArray0[8] = "V"; JSJshop.main(stringArray0); JSJshopNode jSJshopNode0 = jSJshop0.getTree(); assertNull(jSJshopNode0); } /** //Test case number: 1 /*Coverage entropy=1.3862943611198906 */ @Test(timeout = 4000) public void test01() throws Throwable { JSJshop jSJshop0 = new JSJshop(); jSJshop0.getDeleteList(); jSJshop0.sol(); JSJshopVars.dot = (-3); // Undeclared exception! jSJshop0.getBufferedReader("Reading file ", "Reading file "); } /** //Test case number: 2 /*Coverage entropy=1.7917594692280547 */ @Test(timeout = 4000) public void test02() throws Throwable { JSJshop jSJshop0 = new JSJshop(); jSJshop0.getAddList(); JSJshopVars.exclamation = 0; JSJshopVars.dot = 0; jSJshop0.tree(); jSJshop0.sol(); JSJshopVars.apostrophe = 0; jSJshop0.dom(); String string0 = "\"_'G~B@&ipodv(+d<>&"; // Undeclared exception! jSJshop0.getBufferedReader("\"_'G~B@&ipodv(+d<>&", "\"_'G~B@&ipodv(+d<>&"); } /** //Test case number: 3 /*Coverage entropy=1.7917594692280547 */ @Test(timeout = 4000) public void test03() throws Throwable { JSJshop jSJshop0 = new JSJshop(); jSJshop0.getDeleteList(); jSJshop0.getSolution(); jSJshop0.tree(); jSJshop0.dom(); jSJshop0.dom(); StringReader stringReader0 = new StringReader(";[a-$^Pg5lN"); StreamTokenizer streamTokenizer0 = new StreamTokenizer(stringReader0); streamTokenizer0.ordinaryChar(0); // Undeclared exception! try { jSJshop0.processToken(streamTokenizer0); fail("Expecting exception: Error"); } catch(Error e) { // // no message in exception (getMessage() returned null) // verifyException("umd.cs.shop.JSJshop", e); } } /** //Test case number: 4 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test04() throws Throwable { String[] stringArray0 = new String[3]; stringArray0[1] = "<"; JSJshop.main(stringArray0); int int0 = (-212); JApplet jApplet0 = null; try { jApplet0 = new JApplet(); fail("Expecting exception: HeadlessException"); } catch(HeadlessException e) { // // no message in exception (getMessage() returned null) // verifyException("java.applet.Applet", e); } } /** //Test case number: 5 /*Coverage entropy=1.945910149055313 */ @Test(timeout = 4000) public void test05() throws Throwable { JSJshop jSJshop0 = new JSJshop(); jSJshop0.getAddList(); JSJshopVars.greaterT = (-2721); JSJshopVars.minus = (-2721); JSJshopVars.astherisk = 1367; FileSystemHandling.shouldAllThrowIOExceptions(); jSJshop0.getTree(); jSJshop0.getDeleteList(); jSJshop0.getAddList(); JApplet jApplet0 = JSJshop.applet; JSJshopVars.leftBrac = 0; jSJshop0.getBufferedReader((String) null, "B_", (JApplet) null); jSJshop0.tree(); JSPlanningProblem jSPlanningProblem0 = jSJshop0.prob(); assertNull(jSPlanningProblem0); } /** //Test case number: 6 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test06() throws Throwable { String[] stringArray0 = new String[0]; JSJshop.main(stringArray0); JApplet jApplet0 = null; try { jApplet0 = new JApplet(); fail("Expecting exception: HeadlessException"); } catch(HeadlessException e) { // // no message in exception (getMessage() returned null) // verifyException("java.applet.Applet", e); } } /** //Test case number: 7 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test07() throws Throwable { JSJshop jSJshop0 = new JSJshop(); String string0 = "."; int int0 = 0; JSJshopVars.greaterT = 0; JApplet jApplet0 = null; // Undeclared exception! try { jSJshop0.getAppletURL(".", (JApplet) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("umd.cs.shop.JSJshop", e); } } /** //Test case number: 8 /*Coverage entropy=1.7478680974667573 */ @Test(timeout = 4000) public void test08() throws Throwable { JSJshop jSJshop0 = new JSJshop(); String[] stringArray0 = new String[9]; stringArray0[0] = "all"; stringArray0[1] = "0^(fgU~}J|f$V54;XRb"; stringArray0[2] = "Qe+j#8!U_>)V?"; StringReader stringReader0 = new StringReader("0^(fgU~}J|f$V54;XRb"); jSJshop0.getDeleteList(); JApplet jApplet0 = JSJshop.applet; jSJshop0.getBufferedReader("all", "m", (JApplet) null); jSJshop0.tree(); jSJshop0.prob(); jSJshop0.getBufferedReader("0^(fgU~}J|f$V54;XRb", (String) null, (JApplet) null); // Undeclared exception! try { jSJshop0.testParser(); fail("Expecting exception: System.SystemExitException"); } catch(System.SystemExitException e) { // // no message in exception (getMessage() returned null) // verifyException("org.evosuite.runtime.System", e); } } /** //Test case number: 9 /*Coverage entropy=1.3862943611198906 */ @Test(timeout = 4000) public void test09() throws Throwable { EvoSuiteFile evoSuiteFile0 = new EvoSuiteFile("Expecting list of tasks"); FileSystemHandling.appendStringToFile(evoSuiteFile0, "one"); FileSystemHandling.appendStringToFile(evoSuiteFile0, (String) null); JSJshop jSJshop0 = null; try { jSJshop0 = new JSJshop("Expecting list of tasks", (JSTaskAtom) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("umd.cs.shop.JSJshop", e); } } /** //Test case number: 10 /*Coverage entropy=0.9502705392332347 */ @Test(timeout = 4000) public void test10() throws Throwable { byte[] byteArray0 = new byte[5]; byteArray0[0] = (byte) (-1); byteArray0[1] = (byte)31; byteArray0[2] = (byte)4; byteArray0[3] = (byte)85; byteArray0[4] = (byte)9; FileSystemHandling.appendDataToFile((EvoSuiteFile) null, byteArray0); String[] stringArray0 = new String[2]; stringArray0[1] = stringArray0[0]; // Undeclared exception! try { JSJshop.main(stringArray0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.evosuite.runtime.mock.java.io.MockFileInputStream", e); } } /** //Test case number: 11 /*Coverage entropy=1.0397207708399179 */ @Test(timeout = 4000) public void test11() throws Throwable { EvoSuiteFile evoSuiteFile0 = new EvoSuiteFile("Expecting list of tasks"); FileSystemHandling.appendLineToFile(evoSuiteFile0, ""); FileSystemHandling.appendStringToFile(evoSuiteFile0, (String) null); JSJshop jSJshop0 = null; try { jSJshop0 = new JSJshop("Expecting list of tasks", (JSTaskAtom) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("umd.cs.shop.JSJshop", e); } } /** //Test case number: 12 /*Coverage entropy=2.253857589601352 */ @Test(timeout = 4000) public void test12() throws Throwable { JSJshop jSJshop0 = new JSJshop(); JSJshopVars.flagExit = false; jSJshop0.getAddList(); FileSystemHandling.shouldAllThrowIOExceptions(); jSJshop0.getTree(); jSJshop0.getDeleteList(); jSJshop0.getAddList(); JApplet jApplet0 = JSJshop.applet; jSJshop0.getBufferedReader((String) null, "9CW\"^+!#2ceft2=!e", (JApplet) null); jSJshop0.tree(); JSJshop jSJshop1 = new JSJshop("B_", "9CW\"^+!#2ceft2=!e"); JSJshopVars.whiteSpace = 6; JSJshop jSJshop2 = null; try { jSJshop2 = new JSJshop((String) null, (JSTaskAtom) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.evosuite.runtime.mock.java.io.MockFileInputStream", e); } } /** //Test case number: 13 /*Coverage entropy=0.7963116401738131 */ @Test(timeout = 4000) public void test13() throws Throwable { FileSystemHandling.shouldAllThrowIOExceptions(); String[] stringArray0 = new String[3]; stringArray0[0] = "IN"; stringArray0[1] = "IN"; stringArray0[2] = "one"; // Undeclared exception! try { JSJshop.main(stringArray0); fail("Expecting exception: System.SystemExitException"); } catch(System.SystemExitException e) { // // no message in exception (getMessage() returned null) // verifyException("org.evosuite.runtime.System", e); } } /** //Test case number: 14 /*Coverage entropy=0.5623351446188083 */ @Test(timeout = 4000) public void test14() throws Throwable { JSJshop jSJshop0 = new JSJshop(); EvoSuiteFile evoSuiteFile0 = new EvoSuiteFile("Expecting list of tasks/Expecting list of tasks"); FileSystemHandling.appendLineToFile(evoSuiteFile0, "S[juCekj@"); EvoSuiteFile evoSuiteFile1 = new EvoSuiteFile("Expecting list of tasks/Expecting list of tasks"); JSJshopVars.plus = (-2561); FileSystemHandling.shouldThrowIOException(evoSuiteFile1); FileSystemHandling.shouldAllThrowIOExceptions(); BufferedReader bufferedReader0 = jSJshop0.getBufferedReader("Expecting list of tasks", "Expecting list of tasks", (JApplet) null); assertNotNull(bufferedReader0); } /** //Test case number: 15 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test15() throws Throwable { EvoSuiteFile evoSuiteFile0 = new EvoSuiteFile("Expecting list of tasks"); FileSystemHandling.appendStringToFile(evoSuiteFile0, ""); EvoSuiteFile evoSuiteFile1 = new EvoSuiteFile("Expecting list of tasks"); FileSystemHandling.createFolder(evoSuiteFile1); JSJshop jSJshop0 = null; try { jSJshop0 = new JSJshop("Expecting list of tasks", ",PYe"); fail("Expecting exception: System.SystemExitException"); } catch(System.SystemExitException e) { // // no message in exception (getMessage() returned null) // verifyException("org.evosuite.runtime.System", e); } } /** //Test case number: 16 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test16() throws Throwable { EvoSuiteFile evoSuiteFile0 = new EvoSuiteFile("Expecting list of tasks"); FileSystemHandling.appendStringToFile(evoSuiteFile0, ""); boolean boolean0 = JSJshop.corbaToHicap; FileSystemHandling.createFolder(evoSuiteFile0); JSJshop jSJshop0 = new JSJshop("Expecting list of tasks", "Expecting list of tasks"); JSJshop jSJshop1 = null; try { jSJshop1 = new JSJshop("#ztsq}@vca+#kj", "#ztsq}@vca+#kj"); fail("Expecting exception: System.SystemExitException"); } catch(System.SystemExitException e) { // // no message in exception (getMessage() returned null) // verifyException("org.evosuite.runtime.System", e); } } }
78182648/blibli-go
app/admin/main/growup/http/upload.go
<gh_stars>10-100 package http import ( "io/ioutil" "mime/multipart" "net/http" "path" "strings" "time" "bytes" "crypto/md5" "fmt" "go-common/app/admin/main/growup/conf" "go-common/app/admin/main/growup/dao" "go-common/library/ecode" "go-common/library/log" bm "go-common/library/net/http/blademaster" "go-common/library/net/http/blademaster/render" "io" "os" ) // upload func upload(c *bm.Context) { var ( fileTpye string file multipart.File header *multipart.FileHeader fileName string body []byte location string err error ) if file, header, err = c.Request.FormFile("file"); err != nil { c.JSON(nil, ecode.RequestErr) log.Error("c.Request().FormFile(\"file\") error(%v)", err) return } defer file.Close() fileName = header.Filename fileTpye = strings.TrimPrefix(path.Ext(fileName), ".") if body, err = ioutil.ReadAll(file); err != nil { c.JSON(nil, ecode.RequestErr) log.Error("ioutil.ReadAll(c.Request().Body) error(%v)", err) return } if location, err = svr.Upload(c, "", fileTpye, time.Now(), body); err != nil { c.JSON(nil, err) return } c.Render(http.StatusOK, render.MapJSON(map[string]interface{}{ "code": 0, "message": "0", "data": struct { URL string `json:"url"` }{ location, }, })) } const ( uploadFilePath = "/data/uploadfiles/" ) type localUploadResult struct { FileName string `json:"filename"` } type uploadResult struct { localUploadResult MemberCount int64 `json:"member_count"` } // upload func uploadLocal(c *bm.Context) { var ( file multipart.File header *multipart.FileHeader result uploadResult err error ) switch { default: if file, header, err = c.Request.FormFile("file"); err != nil { log.Error("c.Request().FormFile(\"file\") error(%v)", err) break } if header.Size >= int64(conf.Conf.Bfs.MaxFileSize) { log.Error("file is too big, filesize=%d, expected<=%d", conf.Conf.Bfs.MaxFileSize, header.Size) err = fmt.Errorf("文件过大,需要小于%dkb", conf.Conf.Bfs.MaxFileSize/1024) break } var ext = path.Ext(header.Filename) if ext != ".csv" && ext != ".txt" { log.Error("only csv or txt supported") err = fmt.Errorf("只支持csv或txt格式文件,以逗号或换行分隔") break } defer file.Close() // 创建保存文件 if _, e := os.Stat(uploadFilePath); os.IsNotExist(e) { os.MkdirAll(uploadFilePath, 0777) } var h = md5.New() h.Write([]byte(header.Filename)) var filenameMd5 = fmt.Sprintf("%x", h.Sum(nil)) var desfilename = filenameMd5 + ext var destFile *os.File destFile, err = os.Create(uploadFilePath + desfilename) if err != nil { log.Error("Create failed: %s\n", err) break } defer destFile.Close() var membuf = bytes.NewBuffer(nil) _, err = io.Copy(membuf, file) if err != nil { log.Error("err copy file, err=%s", err) break } var midList = dao.ParseMidsFromString(membuf.String()) result.MemberCount = int64(len(midList)) _, err = destFile.Write(membuf.Bytes()) if err != nil { log.Error("write file error, err=%s", err) break } result.FileName = desfilename } if err != nil { bmHTTPErrorWithMsg(c, err, err.Error()) } else { c.JSON(&result, err) } }
Financial-Times/origami-repo-data
data/migration/20171107161007_normalise-versions.js
<reponame>Financial-Times/origami-repo-data 'use strict'; const semver = require('semver'); exports.up = async database => { // Add a normalised version field to the versions table, // and also start to index the version field as we're // querying against it now await database.schema.table('versions', table => { table.string('version_normalised'); table.index('version'); table.index('version_normalised'); }); // Add normalised version numbers to existing versions const versions = await database.select().from('versions'); for (const version of versions) { await database('versions').where('id', version.id).update({ version_normalised: semver.valid(version.version) }); } }; exports.down = async database => { // Remove the normalised version field from the versions table // and drop the index for the version field await database.schema.table('versions', table => { table.dropColumn('version_normalised'); table.dropIndex('version'); }); };
ankithans/dsa
trees/interviewbit/Root to leaf/Burn A Tree.cpp
<filename>trees/interviewbit/Root to leaf/Burn A Tree.cpp int findMaxDistance(unordered_map<TreeNode*, TreeNode*> &parentMap, TreeNode* target) { queue<TreeNode*> q; q.push(target); unordered_map<TreeNode*, int> visited; visited[target] = 1; int maxi = 0; while(!q.empty()) { int size = q.size(); int flag = 0; for(int i = 0; i < size; i++) { TreeNode* curr = q.front(); q.pop(); if(parentMap[curr] && !visited[parentMap[curr]]) { flag = 1; visited[parentMap[curr]] = 1; q.push(parentMap[curr]); } if(curr->left && !visited[curr->left]) { flag = 1; visited[curr->left] = 1; q.push(curr->left); } if(curr->right && !visited[curr->right]) { flag = 1; visited[curr->right] = 1; q.push(curr->right); } } if(flag) maxi++; } return maxi; } TreeNode* bfsToMapParents(TreeNode* root, unordered_map<TreeNode*, TreeNode*> &parentMap, int start) { queue<TreeNode*> q; q.push(root); TreeNode* res; while(!q.empty()) { TreeNode* curr = q.front(); if(curr->val == start) res = curr; q.pop(); if(curr->left) { parentMap[curr->left] = curr; q.push(curr->left); } if(curr->right) { parentMap[curr->right] = curr; q.push(curr->right); } } return res; } int Solution::solve(TreeNode* root, int start) { unordered_map<TreeNode*, TreeNode*> parentMap; TreeNode* target = bfsToMapParents(root, parentMap, start); int maxi = findMaxDistance(parentMap, target); return maxi; }
hocgin/spring-boot-starters-project
spring-boot-web/web-core/src/main/java/in/hocg/boot/web/exception/ServiceException.java
package in.hocg.boot.web.exception; import cn.hutool.core.util.StrUtil; import cn.hutool.http.HttpStatus; import lombok.Getter; import java.util.function.Supplier; /** * Created by hocgin on 2019-09-24. * email: <EMAIL> * * @author hocgin */ public class ServiceException extends RuntimeException { @Getter private final int code; protected ServiceException(int code, String message) { super(message); this.code = code; } public static Supplier<ServiceException> supplier(CharSequence template, Object... args) { return () -> ServiceException.wrap(StrUtil.format(template, args)); } public static ServiceException wrap(Exception e) { return wrap(e.getMessage()); } public static ServiceException wrap(CharSequence message, Object... args) { return wrap(HttpStatus.HTTP_INTERNAL_ERROR, message, args); } public static ServiceException wrap(int code, CharSequence message, Object... args) { return new ServiceException(code, StrUtil.format(message, args)); } }
rascazzione/answerator
app_demo/node_modules/@progress/kendo-react-popup/dist/npm/Popup.js
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; Object.defineProperty(exports, "__esModule", { value: true }); var React = require("react"); var ReactDOM = require("react-dom"); var PropTypes = require("prop-types"); var animation_1 = require("./animation"); var kendo_react_common_1 = require("@progress/kendo-react-common"); var util_1 = require("./util"); var alignService_1 = require("./services/alignService"); var domService_1 = require("./services/domService"); var positionService_1 = require("./services/positionService"); var kendo_licensing_1 = require("@progress/kendo-licensing"); var package_metadata_1 = require("./package-metadata"); function isEquivalent(a, b) { if (a === b) { return true; } if (!!a !== !!b) { return false; } var aProps = Object.getOwnPropertyNames(a); var bProps = Object.getOwnPropertyNames(b); if (aProps.length !== bProps.length) { return false; } for (var i = 0; i < aProps.length; i++) { var propName = aProps[i]; if (a[propName] !== b[propName]) { return false; } } return true; } var DEFAULT_OFFSET = { left: -1000, top: 0 }; var Status; (function (Status) { Status["hiding"] = "hiding"; Status["hidden"] = "hidden"; Status["showing"] = "showing"; Status["shown"] = "shown"; Status["reposition"] = "reposition"; })(Status || (Status = {})); var ANIMATION_CONTAINER = 'k-animation-container'; var ANIMATION_CONTAINER_SHOWN = 'k-animation-container-shown'; var ANIMATION_CONTAINER_RELATIVE = 'k-animation-container-relative'; var ANIMATION_CONTAINER_CHILD = 'k-child-animation-container'; var K_POPUP = 'k-popup'; /** * @hidden */ var Popup = /** @class */ (function (_super) { __extends(Popup, _super); function Popup(props) { var _this = _super.call(this, props) || this; /** * @hidden */ _this.state = { current: Status.hidden, previous: Status.hidden, props: {} }; _this._popup = null; _this.show = function (popup) { _this.setPosition(popup); _this.animate(popup.firstChild, 'enter', _this.onOpened); _this.setState({ current: Status.shown, previous: _this.state.current }); }; _this.setPosition = function (popup) { var _a = _this.props, anchorAlign = _a.anchorAlign, popupAlign = _a.popupAlign, collision = _a.collision, offset = _a.offset, anchor = _a.anchor; var popupContent = popup.firstElementChild; var alignedOffset = _this._alignService.alignElement({ anchor: anchor, element: popupContent, elementAlign: popupAlign, anchorAlign: anchorAlign, offset: offset }); var position = _this._positionService.positionElement({ anchor: anchor, anchorAlign: anchorAlign, collisions: collision, element: popupContent, currentLocation: alignedOffset, elementAlign: popupAlign }); if (position.offset) { popup.style.top = position.offset.top + 'px'; popup.style.left = position.offset.left + 'px'; popupContent.style.position = ''; } _this._flipped = position.flipped; }; _this.onOpened = function () { var element = _this._popup; if (!element) { return; } if (_this.props.show) { element.classList.add(ANIMATION_CONTAINER_SHOWN); } _this.attachRepositionHandlers(element); if (_this.props.onOpen) { _this.props.onOpen.call(undefined, { target: _this }); } }; _this.animate = function (element, type, callback) { animation_1.slide(element, _this._flipped ? 'up' : 'down', _this.animationDuration[type], type, callback); }; _this.onClosing = function (popup) { if (!_this.props.show) { popup.classList.remove(ANIMATION_CONTAINER_SHOWN); } _this.detachRepositionHandlers(); }; _this.onClosed = function () { if (_this.state.current === Status.hiding && _this.state.previous === Status.shown) { _this.setState({ current: Status.hidden, previous: _this.state.current }); } if (_this.props.onClose) { _this.props.onClose.call(undefined, { target: _this }); } }; kendo_licensing_1.validatePackage(package_metadata_1.packageMetadata); _this._domService = new domService_1.DOMService(); _this._alignService = new alignService_1.AlignService(_this._domService); _this._positionService = new positionService_1.PositionService(_this._domService); _this.reposition = util_1.throttle(_this.reposition.bind(_this), util_1.FRAME_DURATION); return _this; } /** * @hidden */ Popup.getDerivedStateFromProps = function (props, state) { var show = props.show, anchor = props.anchor, anchorAlign = props.anchorAlign, appendTo = props.appendTo, collision = props.collision, popupAlign = props.popupAlign, className = props.className, popupClass = props.popupClass, style = props.style, offset = props.offset, contentKey = props.contentKey; var nextState = __assign({}, state, { props: { show: show, anchor: anchor, anchorAlign: anchorAlign, appendTo: appendTo, collision: collision, popupAlign: popupAlign, className: className, popupClass: popupClass, style: style, offset: offset, contentKey: contentKey } }); if (props.show) { if (state.current === Status.hidden || state.current === Status.hiding) { return __assign({}, nextState, { current: Status.showing, previous: state.current }); } else if (state.current === Status.showing) { return __assign({}, nextState, { current: Status.shown, previous: state.current }); } if (state.current === Status.shown && (!isEquivalent(offset, state.props.offset) || !isEquivalent(anchorAlign, state.props.anchorAlign) || !isEquivalent(appendTo, state.props.appendTo) || !isEquivalent(collision, state.props.collision) || !isEquivalent(popupAlign, state.props.popupAlign) || !isEquivalent(style, state.props.style) || anchor !== state.props.anchor || popupClass !== state.props.popupClass || className !== state.props.className)) { return __assign({}, nextState, { current: Status.reposition, previous: state.current }); } } else { if (state.current === Status.shown || state.current === Status.showing) { return __assign({}, nextState, { current: Status.hiding, previous: state.current }); } else if (state.current === Status.hiding) { return __assign({}, nextState, { current: Status.hidden, previous: state.current }); } } return nextState; }; /** * @hidden */ Popup.prototype.componentDidUpdate = function (prevProps) { if (this.state.current === Status.showing && this._popup) { this.show(this._popup); } else if (this.state.current === Status.hiding && this._popup) { this.onClosing(this._popup); this.animate(this._popup.firstChild, 'exit', this.onClosed); } else if (this.state.current === Status.reposition && this.state.previous === Status.shown) { this.setState({ current: Status.shown, previous: this.state.current }); } else if (this.state.current === Status.shown && prevProps.contentKey !== this.props.contentKey && this._popup) { this.setPosition(this._popup); } }; /** * @hidden */ Popup.prototype.componentDidMount = function () { if (this.state.current === Status.showing && this._popup) { this.show(this._popup); } }; /** * @hidden */ Popup.prototype.componentWillUnmount = function () { this.detachRepositionHandlers(); }; /** * @hidden */ Popup.prototype.render = function () { var _this = this; var _a = this.props, children = _a.children, className = _a.className, popupClass = _a.popupClass, show = _a.show, id = _a.id, _b = _a.appendTo, appendTo = _b === void 0 ? kendo_react_common_1.canUseDOM ? document.body : undefined : _b; if (this.state.current === Status.reposition && this.state.previous === Status.shown && this._popup) { this.setPosition(this._popup); } var style = Object.assign({}, { position: 'absolute' }, this.props.style || {}); var closing = this.state.current === Status.hiding && this.state.previous === Status.shown; if ((show || closing) && appendTo) { var popup = (React.createElement("div", { className: kendo_react_common_1.classNames(ANIMATION_CONTAINER, ANIMATION_CONTAINER_RELATIVE, className), id: id, ref: function (e) { return _this._popup = e; }, style: style }, React.createElement("div", { className: kendo_react_common_1.classNames(popupClass, K_POPUP, ANIMATION_CONTAINER_CHILD), style: { transitionDelay: '0ms', position: 'absolute' } }, children))); return ReactDOM.createPortal(popup, appendTo); } return null; }; Object.defineProperty(Popup.prototype, "animationDuration", { get: function () { var animate = this.props.animate; var enter = 0; var exit = 0; if (animate) { if (animate === true) { enter = exit = 300; } else { enter = animate.openDuration || 0; exit = animate.closeDuration || 0; } } return { enter: enter, exit: exit }; }, enumerable: true, configurable: true }); Popup.prototype.attachRepositionHandlers = function (element) { var _this = this; this.detachRepositionHandlers(); this._scrollableParents = this._domService.scrollableParents(this.props.anchor || element); this._scrollableParents.map(function (p) { return p.addEventListener('scroll', _this.reposition); }); window.addEventListener('resize', this.reposition); }; Popup.prototype.detachRepositionHandlers = function () { var _this = this; if (this._scrollableParents) { this._scrollableParents.map(function (p) { return p.removeEventListener('scroll', _this.reposition); }); this._scrollableParents = undefined; } window.removeEventListener('resize', this.reposition); }; Popup.prototype.reposition = function () { this.setState({ current: Status.reposition, previous: this.state.current }); }; /** * @hidden */ Popup.propTypes = { anchor: function (props) { var anchor = props.anchor; if (anchor && typeof anchor.nodeType !== 'number') { return new Error('Invalid prop `anchor` supplied to `Kendo React Popup`. Validation failed.'); } }, appendTo: function (props) { var element = props.appendTo; if (element && typeof element.nodeType !== 'number') { return new Error('Invalid prop `appendTo` supplied to `Kendo React Popup`. Validation failed.'); } }, className: PropTypes.string, id: PropTypes.string, popupClass: PropTypes.string, collision: PropTypes.shape({ horizontal: PropTypes.oneOf([ util_1.CollisionType.fit, util_1.CollisionType.flip ]), vertical: PropTypes.oneOf([ util_1.CollisionType.fit, util_1.CollisionType.flip ]) }), anchorAlign: PropTypes.shape({ horizontal: PropTypes.oneOf([ util_1.AlignPoint.left, util_1.AlignPoint.center, util_1.AlignPoint.right ]), vertical: PropTypes.oneOf([ util_1.AlignPoint.top, util_1.AlignPoint.center, util_1.AlignPoint.bottom ]) }), popupAlign: PropTypes.shape({ horizontal: PropTypes.oneOf([ util_1.AlignPoint.left, util_1.AlignPoint.center, util_1.AlignPoint.right ]), vertical: PropTypes.oneOf([ util_1.AlignPoint.top, util_1.AlignPoint.center, util_1.AlignPoint.bottom ]) }), offset: PropTypes.shape({ left: PropTypes.number, top: PropTypes.number }), children: PropTypes.oneOfType([ PropTypes.element, PropTypes.node ]), show: PropTypes.bool, animate: PropTypes.oneOfType([ PropTypes.bool, PropTypes.shape({ openDuration: PropTypes.number, closeDuration: PropTypes.number }) ]) }; /** * @hidden */ Popup.defaultProps = { collision: { horizontal: util_1.CollisionType.fit, vertical: util_1.CollisionType.flip }, anchorAlign: { horizontal: util_1.AlignPoint.left, vertical: util_1.AlignPoint.bottom }, popupAlign: { horizontal: util_1.AlignPoint.left, vertical: util_1.AlignPoint.top }, offset: DEFAULT_OFFSET, animate: true, // appendTo: document.body, show: false }; return Popup; }(React.Component)); exports.Popup = Popup; //# sourceMappingURL=Popup.js.map
ireina7/gzsl-seg
src/util/typing/typeclass/__init__.py
all = [ 'core', 'typeclass', 'instances', ] # from util.typing.typeclass import * from util.typing.typeclass.typeclass import * # Monoid[int]()
delcypher/stp
include/stp/AST/NodeFactory/NodeFactory.h
/******************************************************************** * AUTHORS: <NAME> * * BEGIN DATE: Feb, 2010 * 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. ********************************************************************/ // Abstract base class for all the node factories. #ifndef NODEFACTORY_H #define NODEFACTORY_H #include <vector> #include "stp/AST/ASTKind.h" namespace BEEV { class ASTNode; typedef std::vector<ASTNode> ASTVec; extern ASTVec _empty_ASTVec; class STPMgr; typedef unsigned int* CBV; } using BEEV::ASTNode; using BEEV::Kind; using BEEV::ASTVec; using BEEV::_empty_ASTVec; class NodeFactory // not copyable { protected: BEEV::STPMgr& bm; public: NodeFactory(BEEV::STPMgr& bm_) : bm(bm_) {} virtual ~NodeFactory(); virtual BEEV::ASTNode CreateTerm(Kind kind, unsigned int width, const BEEV::ASTVec& children) = 0; virtual BEEV::ASTNode CreateArrayTerm(Kind kind, unsigned int index, unsigned int width, const BEEV::ASTVec& children); virtual BEEV::ASTNode CreateNode(Kind kind, const BEEV::ASTVec& children) = 0; ASTNode CreateSymbol(const char* const name, unsigned indexWidth, unsigned valueWidth); ASTNode CreateTerm(Kind kind, unsigned int width, const ASTNode& child0, const ASTVec& children = _empty_ASTVec); ASTNode CreateTerm(Kind kind, unsigned int width, const ASTNode& child0, const ASTNode& child1, const ASTVec& children = _empty_ASTVec); ASTNode CreateTerm(Kind kind, unsigned int width, const ASTNode& child0, const ASTNode& child1, const ASTNode& child2, const ASTVec& children = _empty_ASTVec); ASTNode CreateNode(Kind kind, const ASTNode& child0, const ASTVec& back_children = _empty_ASTVec); ASTNode CreateNode(Kind kind, const ASTNode& child0, const ASTNode& child1, const ASTVec& back_children = _empty_ASTVec); ASTNode CreateNode(Kind kind, const ASTNode& child0, const ASTNode& child1, const ASTNode& child2, const ASTVec& back_children = _empty_ASTVec); ASTNode CreateArrayTerm(Kind kind, unsigned int index, unsigned int width, const ASTNode& child0, const ASTNode& child1, const ASTNode& child2, const ASTVec& children = _empty_ASTVec); ASTNode getTrue(); ASTNode getFalse(); ASTNode CreateConstant(BEEV::CBV cbv, unsigned width); virtual std::string getName() = 0; }; #endif
voei/megamol
core/src/AbstractNamedObject.cpp
<gh_stars>1-10 /* * AbstractNamedObject.cpp * * Copyright (C) 2009-2015 by MegaMol Team * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "mmcore/AbstractNamedObject.h" #include "vislib/assert.h" #include "vislib/sys/AutoLock.h" #include "vislib/sys/Log.h" #include "vislib/UnsupportedOperationException.h" using namespace megamol::core; /****************************************************************************/ /* * AbstractNamedObject::GraphLocker::GraphLocker */ AbstractNamedObject::GraphLocker::GraphLocker(AbstractNamedObject::const_ptr_type obj, bool writelock) : vislib::sys::SyncObject(), writelock(writelock), root(NULL) { ASSERT(obj != NULL); this->root = obj->RootModule(); } /* * AbstractNamedObject::GraphLocker::~GraphLocker */ AbstractNamedObject::GraphLocker::~GraphLocker(void) { this->root = NULL; // DO NOT DELETE } /* * AbstractNamedObject::GraphLocker::Lock */ void AbstractNamedObject::GraphLocker::Lock(void) { //if (this->writelock) { // this->root->ModuleGraphLock().LockExclusive(); //} else { // this->root->ModuleGraphLock().LockExclusive(); //} } /* * AbstractNamedObject::GraphLocker::Unlock */ void AbstractNamedObject::GraphLocker::Unlock(void) { //if (this->writelock) { // this->root->ModuleGraphLock().UnlockExclusive(); //} else { // this->root->ModuleGraphLock().UnlockExclusive(); //} } /****************************************************************************/ /* * AbstractNamedObject::~AbstractNamedObject */ AbstractNamedObject::~AbstractNamedObject(void) { this->parent.reset(); this->owner = nullptr; // DO NOT DELETE } /* * AbstractNamedObject::FullName */ vislib::StringA AbstractNamedObject::FullName(void) const { try { AbstractNamedObject::GraphLocker locker(this->shared_from_this(), false); vislib::sys::AutoLock lock(locker); vislib::StringA name; const_ptr_type ano = this->shared_from_this(); while (ano) { if (ano->Name().IsEmpty() && (!ano->Parent())) { break; } name.Prepend(ano->Name()); name.Prepend("::"); ano = ano->Parent(); } return name; } catch(...) { // evil multi-threading and broken shared ownership results in ill behaviour return ""; } } /* * AbstractNamedObject::SetAllCleanupMarks */ void AbstractNamedObject::SetAllCleanupMarks(void) { this->cleanupMark = true; } /* * AbstractNamedObject::ClearCleanupMark */ void AbstractNamedObject::ClearCleanupMark(void) { this->cleanupMark = false; } /* * AbstractNamedObject::PerformCleanup */ void AbstractNamedObject::PerformCleanup(void) { if (this->cleanupMark) { // message removed because of quickstart module peeking //vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_INFO + 850, // "Module \"%s\" marked for cleanup\n", this->Name().PeekBuffer()); } // intentionally empty } /* * AbstractNamedObject::DisconnectCalls */ void AbstractNamedObject::DisconnectCalls(void) { // intentionally empty } /* * AbstractNamedObject::IsParamRelevant */ bool AbstractNamedObject::IsParamRelevant( vislib::SingleLinkedList<const AbstractNamedObject*>& searched, const vislib::SmartPtr<param::AbstractParam>& param) const { throw vislib::UnsupportedOperationException( "AbstractNamedObject::IsParamRelevant", __FILE__, __LINE__); } /* * AbstractNamedObject::ModuleGraphLock */ vislib::sys::AbstractReaderWriterLock& AbstractNamedObject::ModuleGraphLock(void) { ASSERT(!this->parent.expired()); // HAZARD: better return a dummy object return this->RootModule()->ModuleGraphLock(); } /* * AbstractNamedObject::ModuleGraphLock */ vislib::sys::AbstractReaderWriterLock& AbstractNamedObject::ModuleGraphLock(void) const { ASSERT(!this->parent.expired()); // HAZARD: better return a dummy object return this->RootModule()->ModuleGraphLock(); } /* * AbstractNamedObject::isNameValid */ bool AbstractNamedObject::isNameValid(const vislib::StringA& name) { return name.Find(':') == vislib::StringA::INVALID_POS; } /* * AbstractNamedObject::AbstractNamedObject */ AbstractNamedObject::AbstractNamedObject(void) : enable_shared_from_this(), name(), parent(), owner(nullptr), cleanupMark(false) { // intentionally empty } /* * AbstractNamedObject::SetOwner */ void AbstractNamedObject::SetOwner(void *owner) { if (owner == nullptr) { this->owner = nullptr; } else { ASSERT(this->owner == nullptr); this->owner = owner; } } /* * AbstractNamedObject::setName */ void AbstractNamedObject::setName(const vislib::StringA& name) { this->name = name; } /* * AbstractNamedObject::setParent */ void AbstractNamedObject::setParent(AbstractNamedObject::weak_ptr_type parent) { this->parent = parent; }
eshuo/bfly
p2p-pay/src/main/java/info/bfly/pay/bean/user/VerifySinaBaseEntity.java
<reponame>eshuo/bfly package info.bfly.pay.bean.user; import org.springframework.beans.factory.annotation.Value; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * 用户认证参数on 2017/4/20 0020. */ public class VerifySinaBaseEntity extends SinaUserBaseEntity { private static final long serialVersionUID = 5201916103039767452L; @NotNull @Size(max = 100) private String verify_type = "MOBILE"; @NotNull @Value("#{refProperties['sinapay_client_ip']}") private String client_ip; public String getVerify_type() { return verify_type; } public void setVerify_type(String verify_type) { this.verify_type = verify_type; } public String getClient_ip() { return client_ip; } public void setClient_ip(String client_ip) { this.client_ip = client_ip; } }
TheAmeliaDeWitt/YAHoneyPot
modules/MarchCommand/src/main/java/com/marchnetworks/common/diagnostics/database/SystemInfoDAOImpl.java
<filename>modules/MarchCommand/src/main/java/com/marchnetworks/common/diagnostics/database/SystemInfoDAOImpl.java package com.marchnetworks.common.diagnostics.database; import com.marchnetworks.command.common.diagnostics.DatabaseNameEnum; import com.marchnetworks.command.common.diagnostics.IndexFragmentation; import org.hibernate.SQLQuery; import org.hibernate.Session; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.persistence.EntityManager; public class SystemInfoDAOImpl implements SystemInfoDAO { private EntityManager entityManager; public List<DatabaseSize> getDatabaseSize() { Session session = ( Session ) entityManager.getDelegate(); DatabaseSize command = new DatabaseSize( DatabaseNameEnum.COMMAND_DB.getName() ); DatabaseSize apps = new DatabaseSize( DatabaseNameEnum.APPS_DB.getName() ); List<DatabaseSize> sizes = Arrays.asList( new DatabaseSize[] {command, apps} ); List<Object[]> results = new ArrayList(); String sql = "SELECT name, type_desc, size, FILEPROPERTY(name, 'SpaceUsed') FROM sys.database_files"; SQLQuery query = session.createSQLQuery( "BEGIN TRANSACTION use [" + DatabaseNameEnum.APPS_DB.getName() + "] " + sql + " COMMIT" ); results.addAll( query.list() ); query = session.createSQLQuery( "BEGIN TRANSACTION use [" + DatabaseNameEnum.COMMAND_DB.getName() + "] " + sql + " COMMIT" ); results.addAll( query.list() ); for ( Object[] result : results ) { String name = ( ( String ) result[0] ).toLowerCase(); String type = ( String ) result[1]; long size = ( ( Integer ) result[2] ).intValue() * 8 / 1024; long usedSize = ( ( Integer ) result[3] ).intValue() * 8 / 1024; DatabaseSize database = null; if ( name.startsWith( DatabaseNameEnum.COMMAND_DB.getName() ) ) { database = command; } else { if ( !name.startsWith( DatabaseNameEnum.APPS_DB.getName() ) ) continue; database = apps; } if ( type.equals( "ROWS" ) ) { database.setDatabaseSize( size ); database.setDatabaseUsedSize( usedSize ); } else { database.setLogSize( size ); database.setLogUsedSize( usedSize ); } } return sizes; } public List<IndexFragmentation> getIndexFragmentation( String databaseName, String tableName ) { Session session = ( Session ) entityManager.getDelegate(); List<Object[]> queryResults = new ArrayList(); try { StringBuilder sb = new StringBuilder( "SELECT name, avg_fragmentation_in_percent FROM sys.dm_db_index_physical_stats " ); sb.append( "(DB_ID(N'" ); sb.append( databaseName ); sb.append( "'), OBJECT_ID(N'" ); sb.append( tableName ); sb.append( "'), NULL, NULL, NULL) AS a JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id;" ); SQLQuery query = session.createSQLQuery( "BEGIN TRANSACTION use [" + databaseName + "] " + sb.toString() + " COMMIT" ); queryResults.addAll( query.list() ); } finally { switchBackToCoreDatabase( session ); } List<IndexFragmentation> results = new ArrayList( queryResults.size() ); for ( Object[] row : queryResults ) { IndexFragmentation indexFragmentation = new IndexFragmentation( databaseName, tableName, ( String ) row[0], ( ( Double ) row[1] ).doubleValue() ); results.add( indexFragmentation ); } return results; } public void reorgIndexes( String databaseName, String tableName, String... indexes ) { Session session = ( Session ) entityManager.getDelegate(); try { for ( String index : indexes ) { StringBuilder sb = new StringBuilder( "ALTER INDEX " ); sb.append( index ); sb.append( " ON " ); sb.append( tableName ); sb.append( " REORGANIZE " ); SQLQuery query = session.createSQLQuery( "BEGIN TRANSACTION use [" + databaseName + "] " + sb.toString() + " COMMIT" ); query.executeUpdate(); } } finally { switchBackToCoreDatabase( session ); } } public void rebuildIndexes( String databaseName, String tableName, String... indexes ) { Session session = ( Session ) entityManager.getDelegate(); try { for ( String index : indexes ) { StringBuilder sb = new StringBuilder( "ALTER INDEX " ); sb.append( index ); sb.append( " ON " ); sb.append( tableName ); sb.append( " REBUILD " ); SQLQuery query = session.createSQLQuery( "BEGIN TRANSACTION use [" + databaseName + "] " + sb.toString() + " COMMIT" ); query.executeUpdate(); } } finally { switchBackToCoreDatabase( session ); } } private void switchBackToCoreDatabase( Session session ) { SQLQuery query = session.createSQLQuery( "BEGIN TRANSACTION use [" + DatabaseNameEnum.COMMAND_DB.getName() + "] COMMIT" ); query.executeUpdate(); } public void setEntityManager( EntityManager entityManager ) { this.entityManager = entityManager; } }
nathansmith11170/RandomGalaxyTool
target/generated-sources/jaxb/model/xml/generated/Order.java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.2 // See <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2021.09.29 at 05:27:09 PM EDT // package model.xml.generated; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element ref="{}param" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;attribute name="default" use="required" type="{http://www.w3.org/2001/XMLSchema}boolean" /&gt; * &lt;attribute name="order" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "param" }) @XmlRootElement(name = "order") public class Order { protected List<Param> param; @XmlAttribute(name = "default", required = true) protected boolean _default; @XmlAttribute(name = "order", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NCName") protected String order; /** * Gets the value of the param property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the param property. * * <p> * For example, to add a new item, do as follows: * <pre> * getParam().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Param } * * */ public List<Param> getParam() { if (param == null) { param = new ArrayList<Param>(); } return this.param; } /** * Gets the value of the default property. * */ public boolean isDefault() { return _default; } /** * Sets the value of the default property. * */ public void setDefault(boolean value) { this._default = value; } /** * Gets the value of the order property. * * @return * possible object is * {@link String } * */ public String getOrder() { return order; } /** * Sets the value of the order property. * * @param value * allowed object is * {@link String } * */ public void setOrder(String value) { this.order = value; } }
fdecampredon/jsx-typescript-old-version
tests/baselines/reference/selfReferencesInFunctionParameters.js
//// [selfReferencesInFunctionParameters.js] function foo(x) { if (typeof x === "undefined") { x = x; } } function bar(x0, x) { if (typeof x0 === "undefined") { x0 = ""; } if (typeof x === "undefined") { x = x; } } var C = (function () { function C(x, y) { if (typeof x === "undefined") { x = 1; } if (typeof y === "undefined") { y = y; } } C.prototype.bar = function (a, b) { if (typeof a === "undefined") { a = ""; } if (typeof b === "undefined") { b = b.toString(); } }; return C; })();
kevinzhwl/ZRXSDKMod
ZRXSDK/2014/arxport/dbtable.h
<reponame>kevinzhwl/ZRXSDKMod #ifndef __DBTABLE_H__ #define __DBTABLE_H__ #include "dbmain.h" #include "dbents.h" #include "AcField.h" #include "DbLinkedTableData.h" #include "dbformattedtabledata.h" #include "..\inc\zdbtable.h" #ifndef ACDB_DECLARE_MEMBERS #define ACDB_DECLARE_MEMBERS ZCDB_DECLARE_MEMBERS #endif //#ifndef ACDB_DECLARE_MEMBERS #ifndef ACHAR #define ACHAR ZTCHAR #endif //#ifndef ACHAR #ifndef ADESK_DEPRECATED #define ADESK_DEPRECATED ZSOFT_DEPRECATED #endif //#ifndef ADESK_DEPRECATED #ifndef AcCellRange #define AcCellRange ZcCellRange #endif //#ifndef AcCellRange #ifndef AcCmColor #define AcCmColor ZcCmColor #endif //#ifndef AcCmColor #ifndef AcDb #define AcDb ZcDb #endif //#ifndef AcDb #ifndef AcDbAuditInfo #define AcDbAuditInfo ZcDbAuditInfo #endif //#ifndef AcDbAuditInfo #ifndef AcDbBlockReference #define AcDbBlockReference ZcDbBlockReference #endif //#ifndef AcDbBlockReference #ifndef AcDbDataLink #define AcDbDataLink ZcDbDataLink #endif //#ifndef AcDbDataLink #ifndef AcDbDwgFiler #define AcDbDwgFiler ZcDbDwgFiler #endif //#ifndef AcDbDwgFiler #ifndef AcDbDxfFiler #define AcDbDxfFiler ZcDbDxfFiler #endif //#ifndef AcDbDxfFiler #ifndef AcDbEntity #define AcDbEntity ZcDbEntity #endif //#ifndef AcDbEntity #ifndef AcDbExtents #define AcDbExtents ZcDbExtents #endif //#ifndef AcDbExtents #ifndef AcDbFullSubentPathArray #define AcDbFullSubentPathArray ZcDbFullSubentPathArray #endif //#ifndef AcDbFullSubentPathArray #ifndef AcDbIntArray #define AcDbIntArray ZcDbIntArray #endif //#ifndef AcDbIntArray #ifndef AcDbLinkedTableData #define AcDbLinkedTableData ZcDbLinkedTableData #endif //#ifndef AcDbLinkedTableData #ifndef AcDbObject #define AcDbObject ZcDbObject #endif //#ifndef AcDbObject #ifndef AcDbObjectId #define AcDbObjectId ZcDbObjectId #endif //#ifndef AcDbObjectId #ifndef AcDbObjectIdArray #define AcDbObjectIdArray ZcDbObjectIdArray #endif //#ifndef AcDbObjectIdArray #ifndef AcDbTable #define AcDbTable ZcDbTable #endif //#ifndef AcDbTable #ifndef AcDbTableIterator #define AcDbTableIterator ZcDbTableIterator #endif //#ifndef AcDbTableIterator #ifndef AcDbTableTemplate #define AcDbTableTemplate ZcDbTableTemplate #endif //#ifndef AcDbTableTemplate #ifndef AcDbVoidPtrArray #define AcDbVoidPtrArray ZcDbVoidPtrArray #endif //#ifndef AcDbVoidPtrArray #ifndef AcField #define AcField ZcField #endif //#ifndef AcField #ifndef AcGeMatrix3d #define AcGeMatrix3d ZcGeMatrix3d #endif //#ifndef AcGeMatrix3d #ifndef AcGePoint3d #define AcGePoint3d ZcGePoint3d #endif //#ifndef AcGePoint3d #ifndef AcGePoint3dArray #define AcGePoint3dArray ZcGePoint3dArray #endif //#ifndef AcGePoint3dArray #ifndef AcGeVector3d #define AcGeVector3d ZcGeVector3d #endif //#ifndef AcGeVector3d #ifndef AcGiWorldDraw #define AcGiWorldDraw ZcGiWorldDraw #endif //#ifndef AcGiWorldDraw #ifndef AcGridProperty #define AcGridProperty ZcGridProperty #endif //#ifndef AcGridProperty #ifndef AcString #define AcString ZcString #endif //#ifndef AcString #ifndef AcSubentPathArray #define AcSubentPathArray ZcSubentPathArray #endif //#ifndef AcSubentPathArray #ifndef AcValue #define AcValue ZcValue #endif //#ifndef AcValue #ifndef Acad #define Acad Zcad #endif //#ifndef Acad #ifndef Adesk #define Adesk ZSoft #endif //#ifndef Adesk #endif //#ifndef __DBTABLE_H__
mysql/mysql-shell
unittest/scripts/auto/js_shell/scripts/authentication_kerberos_norecord.js
//@ {hasAuthEnvironment('KERBEROS') && !['windows', 'macos'].includes(__os_type)} //@<> Setup dba.verbose = 1 var keytab_file = os.path.join(__tmp_dir, "mysql2.keytab") testutil.cpfile(os.path.join(__data_path, "keytab", "mysql.keytab"), keytab_file) testutil.deployRawSandbox(__mysql_sandbox_port1, 'root', { "plugin-load-add": "authentication_kerberos.so", "authentication_kerberos_service_principal": "mysql_service/kerberos_auth_host@MYSQL.LOCAL", "authentication_kerberos_service_key_tab": keytab_file, "net_read_timeout": 360, "connect_timeout": 360 }); shell.connect(__sandbox_uri1); session.runSql("CREATE DATABASE test_user_db"); session.runSql(`CREATE USER '${KERBEROS_USER}' IDENTIFIED WITH authentication_kerberos BY 'MYSQL.LOCAL';`); session.runSql(`CREATE USER 'invalid_user' IDENTIFIED WITH authentication_kerberos BY 'MYSQL.LOCAL';`); session.runSql("GRANT ALL PRIVILEGES ON test_user_db.* TO 'invalid_user'"); session.runSql(`GRANT ALL PRIVILEGES ON *.* TO '${KERBEROS_USER}'`); session.close(); var test_list = { "SELECT current_user()": `${KERBEROS_USER}@%`, "SELECT user()": `${KERBEROS_USER}@localhost`, "SELECT @@local.proxy_user": null, "SELECT @@local.external_user": null }; // Cleans the Kerberos cache testutil.callMysqlsh(["--py", "-i", "-e", "import os;os.system('kdestroy')"]) //@<> WL14553-TSFR_8_2 - Kerberos session with no user/password, should fail as there's no cached TGT args = ["--mysql", "--host=localhost", `--port=${__mysql_sandbox_port1}`, '--schema=test_user_db', '--auth-method=authentication_kerberos_client', "--credential-store-helper=plaintext", `--mysql-plugin-dir=${MYSQL_PLUGIN_DIR}`] // WL14553-TSFR_9_4 - No user/password provided testutil.callMysqlsh(args.concat(["-i"])); // System user is not automatically added to the connection data EXPECT_OUTPUT_CONTAINS(`Creating a Classic session to 'localhost:${__mysql_sandbox_port1}/test_user_db?auth-method=authentication_kerberos_client`) // The client library will pick the system user anyway EXPECT_OUTPUT_CONTAINS(`Access denied for user '${__system_user}'@'localhost'`) WIPE_OUTPUT() //@<> WL14553-TSFR_9_4 - User given but no password testutil.callMysqlsh(args.concat(["-i", `--user=${KERBEROS_USER}`])); // System user is not automatically added to the connection data EXPECT_OUTPUT_CONTAINS(`Creating a Classic session to '${KERBEROS_USER}@localhost:${__mysql_sandbox_port1}/test_user_db?auth-method=authentication_kerberos_client`) // The client library will pick the system user anyway // NOTE: This is the error reported by the server on this scenario rather than a clear message // about wrong/missing password for the kerberos account EXPECT_OUTPUT_CONTAINS(`Unknown MySQL error`) WIPE_OUTPUT() args.push("--quiet-start=2") args.push("--sql") args.push("-e") cli_variants = [] // WL14553-TSFR_9_1 - Full credentials will cause the TGT to be created cli_variants.push([`--user=${KERBEROS_USER}`, `--password=${<PASSWORD>}`]) // The rest of the variants fall back to the cached TGT // WL14553-TSFR_9_2 - No User/Password cli_variants.push([]) // User but no password cli_variants.push([`--user=${KERBEROS_USER}`]) // WL14553-TSFR_8_1 - Password but no user cli_variants.push([`--password=<PASSWORD>`]) // User and wrong password cli_variants.push([`--user=${KERBEROS_USER}`, `--password=<PASSWORD>`]) //@<> Test TGT with independent shell instances for (variant_index in cli_variants) { for (query in test_list) { testutil.callMysqlsh(args.concat([`${query}`]).concat(cli_variants[variant_index])); EXPECT_OUTPUT_CONTAINS(test_list[query] ? test_list[query] : "NULL"); WIPE_OUTPUT(); } } //@<> Test TGT with interactive shell connections shell.options.mysqlPluginDir = MYSQL_PLUGIN_DIR; ok_variants = [] // Full credentials will cause the TGT to be created ok_variants.push(function () { shell.connect(`mysql://${KERBEROS_USER}:${KERBEROS_PWD}@localhost:${__mysql_sandbox_port1}/test_user_db?auth-method=authentication_kerberos_client`); }); // Repeats using the Shell API ok_variants.push(function () { session = mysql.getSession(`mysql://${KERBEROS_USER}:${KERBEROS_PWD}@localhost:${__mysql_sandbox_port1}/test_user_db?auth-method=authentication_kerberos_client`); }); // No user/password, falls back to cached TGT ok_variants.push(function () { shell.connect(`mysql://localhost:${__mysql_sandbox_port1}/test_user_db?auth-method=authentication_kerberos_client`); }); // Repeats using the Shell API ok_variants.push(function () { session = mysql.getSession(`mysql://localhost:${__mysql_sandbox_port1}/test_user_db?auth-method=authentication_kerberos_client`); }); // User and wrong password, ignores password and uses cached TGT ok_variants.push(function () { shell.connect(`mysql://${KERBEROS_USER}:fakepwd@localhost:${__mysql_sandbox_port1}/test_user_db?auth-method=authentication_kerberos_client`); }); // Repeats using the Shell API ok_variants.push(function () { session = mysql.getSession(`mysql://${KERBEROS_USER}:fakepwd@localhost:${__mysql_sandbox_port1}/test_user_db?auth-method=authentication_kerberos_client`); }); for (variant_index in ok_variants) { // Creates the session ok_variants[variant_index](); // Test queries for (query in test_list) { var result = session.runSql(query); var row = result.fetchOne(); EXPECT_EQ(test_list[query], row[0]); } // Closes the session session.close() } //@<> Cleanup testutil.rmfile(keytab_file) testutil.destroySandbox(__mysql_sandbox_port1);
zrsaber/piflow-web
piflow-web/src/main/java/cn/cnic/controller/api/NoteBookCtrl.java
<gh_stars>0 package cn.cnic.controller.api; import cn.cnic.base.utils.SessionUserUtil; import cn.cnic.component.livy.service.INoteBookService; import cn.cnic.component.user.service.LogHelper; import cn.cnic.controller.requestVo.NoteBookVoRequest; import io.swagger.annotations.Api; import io.swagger.annotations.ApiParam; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; @Api(value = "noteBoot api") @RestController @RequestMapping(value = "/noteBoot") public class NoteBookCtrl { @Resource private INoteBookService noteBookServiceImpl; @Resource private LogHelper logHelper; /** * saveOrUpdateNoteBook * * @param noteBookVo * @return * @throws Exception */ @RequestMapping(value = "/saveOrUpdateNoteBook", method = RequestMethod.POST) @ResponseBody public String saveOrUpdateNoteBook(@ApiParam(value = "noteBookVo", required = true) NoteBookVoRequest noteBookVo) throws Exception { String currentUsername = SessionUserUtil.getCurrentUsername(); boolean isAdmin = SessionUserUtil.isAdmin(); logHelper.logAuthSucceed("saveOrUpdateNoteBook " + noteBookVo.getName(),currentUsername); return noteBookServiceImpl.saveOrUpdateNoteBook(currentUsername, isAdmin, noteBookVo, false); } /** * checkNoteBookName * * @param noteBookName * @return */ @RequestMapping(value = "/checkNoteBookName", method = RequestMethod.POST) @ResponseBody public String checkNoteBookName(@ApiParam(value = "noteBookName", required = true)String noteBookName) { String currentUsername = SessionUserUtil.getCurrentUsername(); boolean isAdmin = SessionUserUtil.isAdmin(); return noteBookServiceImpl.checkNoteBookName(currentUsername, isAdmin, noteBookName); } /** * deleteNoteBook * * @param noteBookId * @return */ @RequestMapping(value = "/deleteNoteBook", method = RequestMethod.POST) @ResponseBody public String deleteNoteBook(@ApiParam(value = "noteBookId", required = true)String noteBookId) { String currentUsername = SessionUserUtil.getCurrentUsername(); boolean isAdmin = SessionUserUtil.isAdmin(); logHelper.logAuthSucceed("deleteNoteBook " + noteBookId,currentUsername); return noteBookServiceImpl.deleteNoteBook(currentUsername, isAdmin, noteBookId); } /** * "noteBook" list Pagination * * @param page * @param limit * @param param * @return */ @RequestMapping(value = "/noteBookListPage", method = RequestMethod.POST) @ResponseBody public String noteBookListPage(@ApiParam(value = "page", required = true)Integer page, @ApiParam(value = "limit", required = true)Integer limit, @ApiParam(value = "param", required = false)String param) { String currentUsername = SessionUserUtil.getCurrentUsername(); boolean isAdmin = SessionUserUtil.isAdmin(); return noteBookServiceImpl.getNoteBookListPage(currentUsername, isAdmin, page, limit, param); } /** * startNoteBookSession * * @param noteBookId * @return */ @RequestMapping(value = "/startNoteBookSession", method = RequestMethod.POST) @ResponseBody public String startNoteBookSession(String noteBookId) { String currentUsername = SessionUserUtil.getCurrentUsername(); boolean isAdmin = SessionUserUtil.isAdmin(); logHelper.logAuthSucceed("startNoteBookSession " + noteBookId,currentUsername); return noteBookServiceImpl.startNoteBookSession(currentUsername, isAdmin, noteBookId); } /** * deleteNoteBookSession * * @param noteBookId * @return */ @RequestMapping(value = "/deleteNoteBookSession", method = RequestMethod.POST) @ResponseBody public String deleteNoteBookSession(String noteBookId) { String currentUsername = SessionUserUtil.getCurrentUsername(); boolean isAdmin = SessionUserUtil.isAdmin(); logHelper.logAuthSucceed("deleteNoteBookSession " + noteBookId,currentUsername); return noteBookServiceImpl.delNoteBookSession(currentUsername, isAdmin, noteBookId); } }
no7hings/Lynxi
workspace/module/python-2.7/LxMtx/mtxMtdCore.py
<filename>workspace/module/python-2.7/LxMtx/mtxMtdCore.py # coding:utf-8 import functools import collections import MaterialX from LxGraphic import grhCfg from . import mtxCfg class Mtd_MtxBasic(mtxCfg.MtxUtility): MOD_materialx = MaterialX MOD_functools = functools class Mtd_MtxFile(Mtd_MtxBasic): @classmethod def _getNodeDefDict(cls, fileString): dic = cls.CLS_ordered_dict() doc = cls.MOD_materialx.createDocument() # noinspection PyArgumentList cls.MOD_materialx.readFromXmlFile(doc, fileString) # for i in doc.getNodeDefs(): typepathString = i.getNodeString() datatypeStr = i.getType() nodeDic = collections.OrderedDict() nodeDic[grhCfg.GrhUtility.DEF_grh__key_node_datatype] = datatypeStr nodeAttrLis = [] for input_ in i.getInputs(): portpathStr = input_.getName() datatypeStr = input_.getType() portrawStr = input_.getValueString() attrDic = collections.OrderedDict() attrDic[grhCfg.GrhUtility.DEF_grh__key_portpath] = portpathStr attrDic[grhCfg.GrhUtility.DEF_grh__key_porttype] = datatypeStr attrDic[grhCfg.GrhUtility.DEF_grh__key_port_datatype] = datatypeStr attrDic[grhCfg.GrhUtility.DEF_grh__key_portraw] = portrawStr attrDic[grhCfg.GrhUtility.DEF_grh__key_assign] = grhCfg.GrhPortAssignQuery.inport nodeAttrLis.append(attrDic) nodeDic[grhCfg.GrhUtility.DEF_grh__key_port] = nodeAttrLis dic[typepathString] = nodeDic return dic
qinFamily/freeVM
enhanced/archive/classlib/modules/rmi2/rmi-1.4.2/src/ar/org/fitc/test/rmi/integration/fase2/test/PerformanceTestCase.java
package ar.org.fitc.test.rmi.integration.fase2.test; import java.rmi.RemoteException; abstract public class PerformanceTestCase extends ExecutorTestCase { public PerformanceTestCase() { super(); } public PerformanceTestCase(String arg0) { super(arg0); } public static int NumberOfIteration = 10; protected void setUp() throws Exception { super.setUp(); oneTest(); oneTest(); } abstract protected long oneTest() throws RemoteException; public void testPerformance() throws RemoteException { System.out.println("\t\tTime one call:" + oneTest()); } public void testPerformanceAVG() throws RemoteException { long avg = 0; for (int i=0; i < NumberOfIteration; i++) { long x = oneTest(); avg += x; System.out.println("\t\tTime one call:" + x); } avg = avg / NumberOfIteration; System.out.println("\t\tTime avenger of " + NumberOfIteration +" calls:" + avg); } public void testPerformanceAVGandS2() throws RemoteException { long avg = 0; double s2 = 0; for (int i=0; i < NumberOfIteration; i++) { long x = oneTest(); avg += x; s2 += x*x; System.out.println("\t\tTime one call:" + x); } avg = avg / NumberOfIteration; s2 = (s2 / (NumberOfIteration-1)) - avg * avg; s2 = Math.sqrt(s2); System.out.println("\t\tTime avenger of " + NumberOfIteration +" calls:" + avg); System.out.println("\t\tStandard deviation of this calls:" + s2); } }
StrayDragon/OJ-Solutions
PTA/PAT_A/Cpp11/A1027_AC.cc
<reponame>StrayDragon/OJ-Solutions // --- // id : 1027 // title : Colors in Mars // difficulty : Easy // score : 20 // tag : Simple Simulation // keyword : conversion // status : AC // from : PAT (Advanced Level) Practice // --- #include <algorithm> #include <iostream> #include <string> using namespace std; string redix_convert(int n) { const int BASE = 13; string converted; do { int remain = n % BASE; if (remain == 10) converted += 'A'; else if (remain == 11) converted += 'B'; else if (remain == 12) converted += 'C'; else converted += '0' + remain; n /= BASE; } while (n != 0); std::reverse(converted.begin(), converted.end()); return converted; } int main() { int r, g, b; cin >> r >> g >> b; cout << "#"; string R = redix_convert(r), G = redix_convert(g), B = redix_convert(b); if (R.size() < 2) cout << '0'; cout << R; if (G.size() < 2) cout << '0'; cout << G; if (B.size() < 2) cout << '0'; cout << B; return 0; }
suryajak/pacbot
jobs/pacman-data-shipper/src/main/java/com/tmobile/cso/pacman/datashipper/util/AuthUtil.java
<gh_stars>1-10 package com.tmobile.cso.pacman.datashipper.util; import java.util.Map; public class AuthUtil { public static String authorise(String authApi,String authToken) throws Exception{ String response = HttpUtil.post(authApi+"/oauth/token?grant_type=client_credentials","",authToken,"Basic"); Map<String,Object> authInfo = Util.parseJson(response); Object accssToken = authInfo.get("access_token"); if( accssToken!=null){ return accssToken.toString(); } return ""; } }
FrankKwok/Oreo
com/android/internal/telephony/CarrierSignalAgent.java
/* * Copyright (C) 2016 The Android Open Source 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 com.android.internal.telephony; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.PersistableBundle; import android.telephony.CarrierConfigManager; import android.telephony.Rlog; import android.text.TextUtils; import android.util.LocalLog; import android.util.Log; import com.android.internal.util.ArrayUtils; import com.android.internal.util.IndentingPrintWriter; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static android.telephony.CarrierConfigManager.KEY_CARRIER_APP_WAKE_SIGNAL_CONFIG_STRING_ARRAY; import static android.telephony.CarrierConfigManager.KEY_CARRIER_APP_NO_WAKE_SIGNAL_CONFIG_STRING_ARRAY; /** * This class act as an CarrierSignalling Agent. * it load registered carrier signalling receivers from carrier config, cache the result to avoid * repeated polling and send the intent to the interested receivers. * Each CarrierSignalAgent is associated with a phone object. */ public class CarrierSignalAgent { private static final String LOG_TAG = CarrierSignalAgent.class.getSimpleName(); private static final boolean DBG = true; private static final boolean VDBG = Rlog.isLoggable(LOG_TAG, Log.VERBOSE); private static final boolean WAKE = true; private static final boolean NO_WAKE = false; /** delimiters for parsing config of the form: pakName./receiverName : signal1, signal2,..*/ private static final String COMPONENT_NAME_DELIMITER = "\\s*:\\s*"; private static final String CARRIER_SIGNAL_DELIMITER = "\\s*,\\s*"; /** Member variables */ private final Phone mPhone; /** * This is a map of intent action -> array list of component name of statically registered * carrier signal receivers(wakeup receivers). * Those intents are declared in the Manifest files, aiming to wakeup broadcast receivers. * Carrier apps should be careful when configuring the wake signal list to avoid unnecessary * wakeup. * @see CarrierConfigManager#KEY_CARRIER_APP_WAKE_SIGNAL_CONFIG_STRING_ARRAY */ private final Map<String, List<ComponentName>> mCachedWakeSignalConfigs = new HashMap<>(); /** * This is a map of intent action -> array list of component name of dynamically registered * carrier signal receivers(non-wakeup receivers). Those intents will not wake up the apps. * Note Carrier apps should avoid configuring no wake signals in there Manifest files. * @see CarrierConfigManager#KEY_CARRIER_APP_NO_WAKE_SIGNAL_CONFIG_STRING_ARRAY */ private final Map<String, List<ComponentName>> mCachedNoWakeSignalConfigs = new HashMap<>(); /** * This is a list of supported signals from CarrierSignalAgent */ private final Set<String> mCarrierSignalList = new HashSet<>(Arrays.asList( TelephonyIntents.ACTION_CARRIER_SIGNAL_PCO_VALUE, TelephonyIntents.ACTION_CARRIER_SIGNAL_REDIRECTED, TelephonyIntents.ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED, TelephonyIntents.ACTION_CARRIER_SIGNAL_RESET)); private final LocalLog mErrorLocalLog = new LocalLog(20); private final BroadcastReceiver mReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (DBG) log("CarrierSignalAgent receiver action: " + action); if (action.equals(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED)) { // notify carrier apps before cache get purged if (mPhone.getIccCard() != null && IccCardConstants.State.ABSENT == mPhone.getIccCard().getState()) { notifyCarrierSignalReceivers( new Intent(TelephonyIntents.ACTION_CARRIER_SIGNAL_RESET)); } loadCarrierConfig(); } } }; /** Constructor */ public CarrierSignalAgent(Phone phone) { mPhone = phone; loadCarrierConfig(); // reload configurations on CARRIER_CONFIG_CHANGED mPhone.getContext().registerReceiver(mReceiver, new IntentFilter(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED)); } /** * load carrier config and cached the results into a hashMap action -> array list of components. */ private void loadCarrierConfig() { CarrierConfigManager configManager = (CarrierConfigManager) mPhone.getContext() .getSystemService(Context.CARRIER_CONFIG_SERVICE); PersistableBundle b = null; if (configManager != null) { b = configManager.getConfig(); } if (b != null) { synchronized (mCachedWakeSignalConfigs) { mCachedWakeSignalConfigs.clear(); log("Loading carrier config: " + KEY_CARRIER_APP_WAKE_SIGNAL_CONFIG_STRING_ARRAY); parseAndCache(b.getStringArray(KEY_CARRIER_APP_WAKE_SIGNAL_CONFIG_STRING_ARRAY), mCachedWakeSignalConfigs); } synchronized (mCachedNoWakeSignalConfigs) { mCachedNoWakeSignalConfigs.clear(); log("Loading carrier config: " + KEY_CARRIER_APP_NO_WAKE_SIGNAL_CONFIG_STRING_ARRAY); parseAndCache(b.getStringArray(KEY_CARRIER_APP_NO_WAKE_SIGNAL_CONFIG_STRING_ARRAY), mCachedNoWakeSignalConfigs); } } } /** * Parse each config with the form {pakName./receiverName : signal1, signal2,.} and cached the * result internally to avoid repeated polling * @see #CARRIER_SIGNAL_DELIMITER * @see #COMPONENT_NAME_DELIMITER * @param configs raw information from carrier config */ private void parseAndCache(String[] configs, Map<String, List<ComponentName>> cachedConfigs) { if (!ArrayUtils.isEmpty(configs)) { for (String config : configs) { if (!TextUtils.isEmpty(config)) { String[] splitStr = config.trim().split(COMPONENT_NAME_DELIMITER, 2); if (splitStr.length == 2) { ComponentName componentName = ComponentName .unflattenFromString(splitStr[0]); if (componentName == null) { loge("Invalid component name: " + splitStr[0]); continue; } String[] signals = splitStr[1].split(CARRIER_SIGNAL_DELIMITER); for (String s : signals) { if (!mCarrierSignalList.contains(s)) { loge("Invalid signal name: " + s); continue; } List<ComponentName> componentList = cachedConfigs.get(s); if (componentList == null) { componentList = new ArrayList<>(); cachedConfigs.put(s, componentList); } componentList.add(componentName); if (VDBG) { logv("Add config " + "{signal: " + s + " componentName: " + componentName + "}"); } } } else { loge("invalid config format: " + config); } } } } } /** * Check if there are registered carrier broadcast receivers to handle the passing intent */ public boolean hasRegisteredReceivers(String action) { return mCachedWakeSignalConfigs.containsKey(action) || mCachedNoWakeSignalConfigs.containsKey(action); } /** * Broadcast the intents explicitly. * Some sanity check will be applied before broadcasting. * - for non-wakeup(runtime) receivers, make sure the intent is not declared in their manifests * and apply FLAG_EXCLUDE_STOPPED_PACKAGES to avoid wake-up * - for wakeup(manifest) receivers, make sure there are matched receivers with registered * intents. * * @param intent intent which signals carrier apps * @param receivers a list of component name for broadcast receivers. * Those receivers could either be statically declared in Manifest or * registered during run-time. * @param wakeup true indicate wakeup receivers otherwise non-wakeup receivers */ private void broadcast(Intent intent, List<ComponentName> receivers, boolean wakeup) { final PackageManager packageManager = mPhone.getContext().getPackageManager(); for (ComponentName name : receivers) { Intent signal = new Intent(intent); signal.setComponent(name); if (wakeup && packageManager.queryBroadcastReceivers(signal, PackageManager.MATCH_DEFAULT_ONLY).isEmpty()) { loge("Carrier signal receivers are configured but unavailable: " + signal.getComponent()); return; } if (!wakeup && !packageManager.queryBroadcastReceivers(signal, PackageManager.MATCH_DEFAULT_ONLY).isEmpty()) { loge("Runtime signals shouldn't be configured in Manifest: " + signal.getComponent()); return; } signal.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mPhone.getSubId()); signal.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); if (!wakeup) signal.setFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES); try { mPhone.getContext().sendBroadcast(signal); if (DBG) { log("Sending signal " + signal.getAction() + ((signal.getComponent() != null) ? " to the carrier signal receiver: " + signal.getComponent() : "")); } } catch (ActivityNotFoundException e) { loge("Send broadcast failed: " + e); } } } /** * Match the intent against cached tables to find a list of registered carrier signal * receivers and broadcast the intent. * @param intent broadcasting intent, it could belong to wakeup, non-wakeup signal list or both * */ public void notifyCarrierSignalReceivers(Intent intent) { List<ComponentName> receiverList; synchronized (mCachedWakeSignalConfigs) { receiverList = mCachedWakeSignalConfigs.get(intent.getAction()); if (!ArrayUtils.isEmpty(receiverList)) { broadcast(intent, receiverList, WAKE); } } synchronized (mCachedNoWakeSignalConfigs) { receiverList = mCachedNoWakeSignalConfigs.get(intent.getAction()); if (!ArrayUtils.isEmpty(receiverList)) { broadcast(intent, receiverList, NO_WAKE); } } } private void log(String s) { Rlog.d(LOG_TAG, "[" + mPhone.getPhoneId() + "]" + s); } private void loge(String s) { mErrorLocalLog.log(s); Rlog.e(LOG_TAG, "[" + mPhone.getPhoneId() + "]" + s); } private void logv(String s) { Rlog.v(LOG_TAG, "[" + mPhone.getPhoneId() + "]" + s); } public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); pw.println("mCachedWakeSignalConfigs:"); ipw.increaseIndent(); for (Map.Entry<String, List<ComponentName>> entry : mCachedWakeSignalConfigs.entrySet()) { pw.println("signal: " + entry.getKey() + " componentName list: " + entry.getValue()); } ipw.decreaseIndent(); pw.println("mCachedNoWakeSignalConfigs:"); ipw.increaseIndent(); for (Map.Entry<String, List<ComponentName>> entry : mCachedNoWakeSignalConfigs.entrySet()) { pw.println("signal: " + entry.getKey() + " componentName list: " + entry.getValue()); } ipw.decreaseIndent(); pw.println("error log:"); ipw.increaseIndent(); mErrorLocalLog.dump(fd, pw, args); ipw.decreaseIndent(); } }