max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,306 |
package io.github.biezhi.java8.lambda.lesson3;
import java.util.function.Function;
/**
* 数组引用
*
* @author biezhi
* @date 2018/2/10
*/
public class OtherReference {
public static void main(String[] args) {
Function<Integer, String[]> fun = x -> new String[x];
String[] strs = fun.apply(10);
System.out.println(strs.length);
Function<Integer, String[]> fun1 = String[]::new;
strs = fun1.apply(20);
System.out.println(strs.length);
}
}
| 236 |
742 |
<reponame>kuro-channel/knowledge-1<gh_stars>100-1000
package org.support.project.knowledge.logic.activity;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.support.project.aop.Aspect;
import org.support.project.common.config.Resources;
import org.support.project.common.log.Log;
import org.support.project.common.log.LogFactory;
import org.support.project.common.util.HtmlUtils;
import org.support.project.common.util.StringUtils;
import org.support.project.di.Container;
import org.support.project.di.DI;
import org.support.project.di.Instance;
import org.support.project.knowledge.config.AppConfig;
import org.support.project.knowledge.config.SystemConfig;
import org.support.project.knowledge.dao.ActivitiesDao;
import org.support.project.knowledge.dao.CommentsDao;
import org.support.project.knowledge.dao.PointUserHistoriesDao;
import org.support.project.knowledge.entity.ActivitiesEntity;
import org.support.project.knowledge.entity.CommentsEntity;
import org.support.project.knowledge.entity.KnowledgesEntity;
import org.support.project.knowledge.entity.PointUserHistoriesEntity;
import org.support.project.knowledge.logic.KnowledgeLogic;
import org.support.project.knowledge.vo.ActivityHistory;
import org.support.project.knowledge.vo.ContributionPointHistory;
import org.support.project.knowledge.vo.UserConfigs;
import org.support.project.ormapping.config.Order;
import org.support.project.web.bean.LoginedUser;
import org.support.project.web.dao.SystemConfigsDao;
import org.support.project.web.entity.SystemConfigsEntity;
import org.support.project.web.logic.DateConvertLogic;
@DI(instance = Instance.Singleton)
public class ActivityLogic {
/** ログ */
private static final Log LOG = LogFactory.getLog(ActivityLogic.class);
public static ActivityLogic get() {
return Container.getComp(ActivityLogic.class);
}
private List<ActivityProcessor> getActivityProcessors(Activity activity) {
List<ActivityProcessor> array = new ArrayList<>();
if (activity == Activity.KNOWLEDGE_POST_PUBLIC
|| activity == Activity.KNOWLEDGE_POST_PROTECTED
|| activity == Activity.KNOWLEDGE_POST_PRIVATE) {
array.add(KnowledgeSaveActivity.get());
} else if (activity == Activity.KNOWLEDGE_SHOW) {
array.add(KnowledgeShowActivity.get());
} else if (activity == Activity.KNOWLEDGE_LIKE) {
array.add(KnowledgeLikeActivity.get());
} else if (activity == Activity.KNOWLEDGE_STOCK) {
array.add(KnowledgeStockActivity.get());
} else if (activity == Activity.KNOWLEDGE_ANSWER) {
array.add(KnowledgeAnswerActivity.get());
} else if (activity == Activity.KNOWLEDGE_EVENT_ADD) {
array.add(KnowledgeEventActivity.get());
} else if (activity == Activity.COMMENT_INSERT) {
array.add(CommentInsertActivity.get());
} else if (activity == Activity.COMMENT_LIKE) {
array.add(CommentLikeActivity.get());
}
return array;
}
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
private void execute(Activity activity, LoginedUser eventUser, Date eventDateTime, KnowledgesEntity knowledge, CommentsEntity comment) {
List<ActivityProcessor> processors = this.getActivityProcessors(activity);
for (ActivityProcessor activityProcessor : processors) {
if (activityProcessor instanceof AbstractActivityProcessor) {
AbstractActivityProcessor processor = (AbstractActivityProcessor) activityProcessor;
processor.setEventUser(eventUser);
processor.setEventDateTime(eventDateTime);
}
if (activityProcessor instanceof AbstractAddPointForKnowledgeProcessor) {
if (knowledge == null) {
LOG.warn("bad parameter [knowledge], because it is null.");
continue;
}
AbstractAddPointForKnowledgeProcessor processor = (AbstractAddPointForKnowledgeProcessor) activityProcessor;
processor.setKnowledge(knowledge);
} else if (activityProcessor instanceof AbstractAddPointForCommentProcessor) {
if (comment == null) {
LOG.warn("bad parameter [comment], because it is null.");
continue;
}
AbstractAddPointForCommentProcessor processor = (AbstractAddPointForCommentProcessor) activityProcessor;
processor.setComment(comment);
}
if (activityProcessor instanceof AbstractActivityProcessor) {
AbstractActivityProcessor processor = (AbstractActivityProcessor) activityProcessor;
processor.setEventUser(eventUser);
processor.setEventDateTime(eventDateTime);
}
if (activityProcessor instanceof MultiActivityProcessor) {
MultiActivityProcessor processor = (MultiActivityProcessor) activityProcessor;
processor.setActivity(activity);
}
try {
activityProcessor.execute();
} catch (Exception e) {
// Activity処理は失敗しても、いったん無視する
LOG.error("error", e);
}
}
}
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public void processActivity(Activity activity, LoginedUser eventUser, Date eventDateTime) {
execute(activity, eventUser, eventDateTime, null, null);
}
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public void processActivity(Activity activity, LoginedUser eventUser, Date eventDateTime, KnowledgesEntity knowledge) {
execute(activity, eventUser, eventDateTime, knowledge, null);
}
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public void processActivity(Activity activity, LoginedUser eventUser, Date eventDateTime, CommentsEntity comment) {
execute(activity, eventUser, eventDateTime, null, comment);
}
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public void processKnowledgeSaveActivity(LoginedUser eventUser, Date eventDateTime, KnowledgesEntity knowledge) {
Activity activity = null;
int publicFlag = KnowledgeLogic.PUBLIC_FLAG_PRIVATE;
if (knowledge.getPublicFlag() != null) {
publicFlag = knowledge.getPublicFlag();
}
if (publicFlag == KnowledgeLogic.PUBLIC_FLAG_PUBLIC) {
activity = Activity.KNOWLEDGE_POST_PUBLIC;
} else if (publicFlag == KnowledgeLogic.PUBLIC_FLAG_PROTECT) {
activity = Activity.KNOWLEDGE_POST_PROTECTED;
} else if (publicFlag == KnowledgeLogic.PUBLIC_FLAG_PRIVATE) {
activity = Activity.KNOWLEDGE_POST_PRIVATE;
}
if (activity == null) {
LOG.warn("invalid public flag. knowledge[]" + knowledge.getKnowledgeId());
return;
}
execute(activity, eventUser, eventDateTime, knowledge, null);
}
public List<ContributionPointHistory> getUserPointHistoriesByDate(Integer userId, UserConfigs userConfigs) {
return PointUserHistoriesDao.get().selectPointHistoriesByDate(userId, userConfigs);
}
private String getDisplayDate(Date date, UserConfigs userConfigs) {
return DateConvertLogic.get().convertDate(date, userConfigs.getLocale(), userConfigs.getTimezoneOffset());
}
private String convKnowledgeLink(String systemUrl, String target) {
StringBuilder builder = new StringBuilder();
builder.append("<a href=\"");
builder.append(systemUrl);
builder.append("open.knowledge/view/");
builder.append(target);
builder.append("\">#");
builder.append(target);
builder.append("</a>");
return builder.toString();
}
private String convUserLink(String systemUrl, Integer userID, String userName) {
StringBuilder builder = new StringBuilder();
builder.append("<a href=\"");
builder.append(systemUrl);
builder.append("open.account/info/");
builder.append(userID);
builder.append("\">");
builder.append(HtmlUtils.escapeHTML(userName));
builder.append("</a>");
return builder.toString();
}
private String getActivityMsg(PointUserHistoriesEntity history, Map<Long, ActivitiesEntity> activities, UserConfigs userConfigs, String systemUrl) {
Resources resources = Resources.getInstance(userConfigs.getLocale());
ActivitiesEntity activity = activities.get(history.getActivityNo());
if (activity == null) {
return "";
}
if (history.getType() == ActivityProcessor.TYPE_KNOWLEDGE_DO_INSERT) {
return resources.getResource("knowledge.activity.type.11.do.insert", convKnowledgeLink(systemUrl, activity.getTarget()));
} else if (history.getType() == ActivityProcessor.TYPE_KNOWLEDGE_DO_SHOW) {
return resources.getResource("knowledge.activity.type.21.do.show", convKnowledgeLink(systemUrl, activity.getTarget()));
} else if (history.getType() == ActivityProcessor.TYPE_KNOWLEDGE_SHOWN_BY_OHER) {
return resources.getResource("knowledge.activity.type.22.shown", convKnowledgeLink(systemUrl, activity.getTarget()),
convUserLink(systemUrl, activity.getInsertUser(), activity.getUserName()));
} else if (history.getType() == ActivityProcessor.TYPE_KNOWLEDGE_DO_LIKE) {
return resources.getResource("knowledge.activity.type.31.do.like", convKnowledgeLink(systemUrl, activity.getTarget()),
convUserLink(systemUrl, activity.getInsertUser(), activity.getUserName()));
} else if (history.getType() == ActivityProcessor.TYPE_KNOWLEDGE_LIKED_BY_OHER) {
return resources.getResource("knowledge.activity.type.32.liked", convKnowledgeLink(systemUrl, activity.getTarget()),
convUserLink(systemUrl, activity.getInsertUser(), activity.getUserName()));
} else if (history.getType() == ActivityProcessor.TYPE_KNOWLEDGE_DO_STOCK) {
return resources.getResource("knowledge.activity.type.41.do.stock", convKnowledgeLink(systemUrl, activity.getTarget()),
convUserLink(systemUrl, activity.getInsertUser(), activity.getUserName()));
} else if (history.getType() == ActivityProcessor.TYPE_KNOWLEDGE_STOCKED_BY_OHER) {
return resources.getResource("knowledge.activity.type.42.stocked", convKnowledgeLink(systemUrl, activity.getTarget()),
convUserLink(systemUrl, activity.getInsertUser(), activity.getUserName()));
} else if (history.getType() == ActivityProcessor.TYPE_KNOWLEDGE_DO_ANSWER) {
return resources.getResource("knowledge.activity.type.51.do.ansewer", convKnowledgeLink(systemUrl, activity.getTarget()),
convUserLink(systemUrl, activity.getInsertUser(), activity.getUserName()));
} else if (history.getType() == ActivityProcessor.TYPE_KNOWLEDGE_ANSWERD_BY_OHER) {
return resources.getResource("knowledge.activity.type.52.answered", convKnowledgeLink(systemUrl, activity.getTarget()),
convUserLink(systemUrl, activity.getInsertUser(), activity.getUserName()));
} else if (history.getType() == ActivityProcessor.TYPE_KNOWLEDGE_DO_JOIN_EVENT) {
return resources.getResource("knowledge.activity.type.61.do.join", convKnowledgeLink(systemUrl, activity.getTarget()),
convUserLink(systemUrl, activity.getInsertUser(), activity.getUserName()));
} else if (history.getType() == ActivityProcessor.TYPE_KNOWLEDGE_JOINED_BY_OHER) {
return resources.getResource("knowledge.activity.type.62.joined", convKnowledgeLink(systemUrl, activity.getTarget()),
convUserLink(systemUrl, activity.getInsertUser(), activity.getUserName()));
} else if (history.getType() == ActivityProcessor.TYPE_KNOWLEDGE_DO_POST_PUBLIC) {
return resources.getResource("knowledge.activity.type.101.do.post.public", convKnowledgeLink(systemUrl, activity.getTarget()),
convUserLink(systemUrl, activity.getInsertUser(), activity.getUserName()));
} else if (history.getType() == ActivityProcessor.TYPE_KNOWLEDGE_DO_POST_PROTECT) {
return resources.getResource("knowledge.activity.type.111.do.post.protect", convKnowledgeLink(systemUrl, activity.getTarget()),
convUserLink(systemUrl, activity.getInsertUser(), activity.getUserName()));
} else if (history.getType() == ActivityProcessor.TYPE_KNOWLEDGE_DO_POST_PRIVATE) {
return resources.getResource("knowledge.activity.type.121.do.post.private", convKnowledgeLink(systemUrl, activity.getTarget()),
convUserLink(systemUrl, activity.getInsertUser(), activity.getUserName()));
} else if (history.getType() >= ActivityProcessor.TYPE_COMMENT_DO_INSERT) {
CommentsEntity comment = CommentsDao.get().selectOnKey(new Long(activity.getTarget()));
if (comment != null) {
if (history.getType() == ActivityProcessor.TYPE_COMMENT_DO_INSERT) {
return resources.getResource("knowledge.activity.type.1011.do.comment.insert",
convKnowledgeLink(systemUrl, String.valueOf(comment.getKnowledgeId())),
convUserLink(systemUrl, activity.getInsertUser(), activity.getUserName()));
} else if (history.getType() == ActivityProcessor.TYPE_COMMENT_DO_LIKE) {
return resources.getResource("knowledge.activity.type.1031.do.comment.like",
convKnowledgeLink(systemUrl, String.valueOf(comment.getKnowledgeId())),
convUserLink(systemUrl, activity.getInsertUser(), activity.getUserName()));
} else if (history.getType() == ActivityProcessor.TYPE_COMMENT_LIKED_BY_OHER) {
return resources.getResource("knowledge.activity.type.1032.comment.liked",
convKnowledgeLink(systemUrl, String.valueOf(comment.getKnowledgeId())),
convUserLink(systemUrl, activity.getInsertUser(), activity.getUserName()));
}
}
}
return "";
}
public List<ActivityHistory> getUserPointHistoriese(Integer userId, int limit, int offset, UserConfigs userConfigs) {
List<PointUserHistoriesEntity> histories = PointUserHistoriesDao.get().selectOnUser(userId, limit, offset, Order.DESC);
List<Long> activityNos = new ArrayList<>();
for (PointUserHistoriesEntity history : histories) {
activityNos.add(history.getActivityNo());
}
List<ActivitiesEntity> activityList = ActivitiesDao.get().selectOnNos(activityNos);
Map<Long, ActivitiesEntity> activities = new HashMap<>();
for (ActivitiesEntity activitiesEntity : activityList) {
activities.put(activitiesEntity.getActivityNo(), activitiesEntity);
}
SystemConfigsDao dao = SystemConfigsDao.get();
SystemConfigsEntity config = dao.selectOnKey(SystemConfig.SYSTEM_URL, AppConfig.get().getSystemName());
StringBuilder builder = new StringBuilder();
if (config != null) {
builder.append(config.getConfigValue());
if (!config.getConfigValue().endsWith("/")) {
builder.append("/");
}
}
List<ActivityHistory> list = new ArrayList<>();
for (PointUserHistoriesEntity history : histories) {
String msg = getActivityMsg(history, activities, userConfigs, builder.toString());
if (StringUtils.isNotEmpty(msg)) {
ActivityHistory activity = new ActivityHistory();
activity.setDate(history.getInsertDatetime());
activity.setDispDate(getDisplayDate(history.getInsertDatetime(), userConfigs));
activity.setMsg(msg);
list.add(activity);
}
}
return list;
}
}
| 6,386 |
1,056 |
<gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.maven.grammar;
import java.awt.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JList;
import org.netbeans.modules.maven.api.MavenConfiguration;
import org.netbeans.modules.maven.spi.customizer.TextToValueConversions;
import org.netbeans.spi.project.ProjectConfiguration;
import org.netbeans.spi.project.ProjectConfigurationProvider;
/**
*
* @author mkleint
*/
class ShowEffPomDiffPanel extends javax.swing.JPanel {
/**
* Creates new form ShowEffPomDiffPanel
*/
public ShowEffPomDiffPanel(ProjectConfigurationProvider<MavenConfiguration> configs) {
initComponents();
ComboBoxModel<MavenConfiguration> model = new DefaultComboBoxModel<MavenConfiguration>(configs.getConfigurations().toArray(new MavenConfiguration[0]));
comConfiguration.setModel(model);
comConfiguration.setEditable(false);
comConfiguration.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
return super.getListCellRendererComponent(list, ((ProjectConfiguration)value).getDisplayName(), index, isSelected, cellHasFocus);
}
});
comConfiguration.setSelectedItem(configs.getActiveConfiguration());
enableFields();
epProperties.setContentType("text/x-properties");
}
MavenConfiguration getSelectedConfig() {
return (MavenConfiguration) comConfiguration.getSelectedItem();
}
boolean isConfigurationSelected() {
return rbConfiguration.isSelected();
}
List<String> getSelectedProfiles() {
StringTokenizer tok = new StringTokenizer(txtProfiles.getText().trim(), " ,");
ArrayList<String> lst = new ArrayList<String>();
while (tok.hasMoreTokens()) {
lst.add(tok.nextToken());
}
return lst;
}
Map<String, String> getSelectedProperties() {
return TextToValueConversions.convertStringToActionProperties(epProperties.getText());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
lblConfiguration = new javax.swing.JLabel();
comConfiguration = new javax.swing.JComboBox();
rbConfiguration = new javax.swing.JRadioButton();
rbCustom = new javax.swing.JRadioButton();
lblProfiles = new javax.swing.JLabel();
txtProfiles = new javax.swing.JTextField();
lblProperties = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
epProperties = new javax.swing.JEditorPane();
lblConfiguration.setLabelFor(comConfiguration);
org.openide.awt.Mnemonics.setLocalizedText(lblConfiguration, org.openide.util.NbBundle.getMessage(ShowEffPomDiffPanel.class, "ShowEffPomDiffPanel.lblConfiguration.text")); // NOI18N
buttonGroup1.add(rbConfiguration);
rbConfiguration.setSelected(true);
org.openide.awt.Mnemonics.setLocalizedText(rbConfiguration, org.openide.util.NbBundle.getMessage(ShowEffPomDiffPanel.class, "ShowEffPomDiffPanel.rbConfiguration.text")); // NOI18N
rbConfiguration.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rbConfigurationActionPerformed(evt);
}
});
buttonGroup1.add(rbCustom);
org.openide.awt.Mnemonics.setLocalizedText(rbCustom, org.openide.util.NbBundle.getMessage(ShowEffPomDiffPanel.class, "ShowEffPomDiffPanel.rbCustom.text")); // NOI18N
rbCustom.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rbCustomActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(lblProfiles, org.openide.util.NbBundle.getMessage(ShowEffPomDiffPanel.class, "ShowEffPomDiffPanel.lblProfiles.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(lblProperties, org.openide.util.NbBundle.getMessage(ShowEffPomDiffPanel.class, "ShowEffPomDiffPanel.lblProperties.text")); // NOI18N
jScrollPane1.setViewportView(epProperties);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(rbConfiguration)
.addComponent(rbCustom))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(lblProfiles)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtProfiles))
.addGroup(layout.createSequentialGroup()
.addComponent(lblConfiguration)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(comConfiguration, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(lblProperties)
.addGap(0, 0, Short.MAX_VALUE)))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(rbConfiguration)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblConfiguration)
.addComponent(comConfiguration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(rbCustom)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblProfiles)
.addComponent(txtProfiles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblProperties)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void rbConfigurationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbConfigurationActionPerformed
enableFields();
}//GEN-LAST:event_rbConfigurationActionPerformed
private void rbCustomActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbCustomActionPerformed
enableFields();
}//GEN-LAST:event_rbCustomActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JComboBox comConfiguration;
private javax.swing.JEditorPane epProperties;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lblConfiguration;
private javax.swing.JLabel lblProfiles;
private javax.swing.JLabel lblProperties;
private javax.swing.JRadioButton rbConfiguration;
private javax.swing.JRadioButton rbCustom;
private javax.swing.JTextField txtProfiles;
// End of variables declaration//GEN-END:variables
private void enableFields() {
comConfiguration.setEnabled(rbConfiguration.isSelected());
epProperties.setEnabled(rbCustom.isSelected());
txtProfiles.setEnabled(rbCustom.isSelected());
}
}
| 4,363 |
337 |
package a;
import kotlin.jvm.functions.Function0;
public class X {
private A outer;
public X(A outer, Function0<String> f) {
this.outer = outer;
System.out.println(f.invoke());
}
}
| 91 |
836 |
package com.logpresso.scanner;
public class Version {
private int major;
private int minor;
private int patch;
private int patch2;
public static Version parse(String version) {
String ver = version;
int p = version.indexOf('-');
if (p > 0)
ver = version.substring(0, p);
String[] tokens = ver.split("\\.");
int major = Integer.parseInt(tokens[0]);
int minor = Integer.parseInt(tokens[1]);
int patch = 0;
int patch2 = 0;
// e.g. version 2.0 has only 2 tokens
if (tokens.length > 2)
patch = Integer.parseInt(tokens[2]);
// added for reload4j version scheme
if (tokens.length > 3)
patch2 = Integer.parseInt(tokens[3]);
return new Version(major, minor, patch, patch2);
}
public Version(int major, int minor, int patch, int patch2) {
this.major = major;
this.minor = minor;
this.patch = patch;
this.patch2 = patch2;
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int getPatch() {
return patch;
}
public int getPatch2() {
return patch2;
}
}
| 403 |
1,174 |
package com.github.devnied.emvnfccard.utils;
/*
* Copyright 2010 sasc
*
* 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 com.github.devnied.emvnfccard.enums.SwEnum;
import com.github.devnied.emvnfccard.enums.TagValueTypeEnum;
import com.github.devnied.emvnfccard.exception.TlvException;
import com.github.devnied.emvnfccard.iso7816emv.EmvTags;
import com.github.devnied.emvnfccard.iso7816emv.ITag;
import com.github.devnied.emvnfccard.iso7816emv.TLV;
import com.github.devnied.emvnfccard.iso7816emv.TagAndLength;
import fr.devnied.bitlib.BytesUtils;
import net.sf.scuba.tlv.TLVInputStream;
import net.sf.scuba.tlv.TLVUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* List of utils methods to manipulate TLV
*
* @author <NAME>ien
*
*/
public final class TlvUtil {
// Class logger
private static final Logger LOGGER = LoggerFactory.getLogger(TlvUtil.class);
/**
* Method used to find Tag with ID
*
* @param tagIdBytes
* the tag to find
* @return the tag found
*/
private static ITag searchTagById(final int tagId) {
return EmvTags.getNotNull(TLVUtil.getTagAsBytes(tagId));
}
// This is just a list of Tag And Lengths (eg DOLs)
public static String getFormattedTagAndLength(final byte[] data, final int indentLength) {
StringBuilder buf = new StringBuilder();
String indent = getSpaces(indentLength);
TLVInputStream stream = new TLVInputStream(new ByteArrayInputStream(data));
boolean firstLine = true;
try {
while (stream.available() > 0) {
if (firstLine) {
firstLine = false;
} else {
buf.append("\n");
}
buf.append(indent);
ITag tag = searchTagById(stream.readTag());
int length = stream.readLength();
buf.append(prettyPrintHex(tag.getTagBytes()));
buf.append(" ");
buf.append(String.format("%02x", length));
buf.append(" -- ");
buf.append(tag.getName());
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(stream);
}
return buf.toString();
}
public static TLV getNextTLV(final TLVInputStream stream) {
TLV tlv = null;
try {
int left = stream.available();
if (left <= 2) {
return tlv;
}
ITag tag = searchTagById(stream.readTag());
int length = stream.readLength();
if (stream.available() >= length) {
tlv = new TLV(tag, length, TLVUtil.getLengthAsBytes(length), stream.readValue());
}
} catch (EOFException eof) {
LOGGER.debug(eof.getMessage(), eof);
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(stream);
}
return tlv;
}
/**
* Method used get Tag value as String
*
* @param tag
* tag type
* @param value
* tag value
* @return
*/
private static String getTagValueAsString(final ITag tag, final byte[] value) {
StringBuilder buf = new StringBuilder();
switch (tag.getTagValueType()) {
case TEXT:
buf.append("=");
buf.append(new String(value));
break;
case NUMERIC:
buf.append("NUMERIC");
break;
case BINARY:
buf.append("BINARY");
break;
case MIXED:
buf.append("=");
buf.append(getSafePrintChars(value));
break;
case DOL:
buf.append("");
break;
default:
break;
}
return buf.toString();
}
/**
* Method used to parser Tag and length
*
* @param data
* data to parse
* @return tag and length
*/
public static List<TagAndLength> parseTagAndLength(final byte[] data) {
List<TagAndLength> tagAndLengthList = new ArrayList<TagAndLength>();
if (data != null) {
TLVInputStream stream = new TLVInputStream(new ByteArrayInputStream(data));
try {
while (stream.available() > 0) {
if (stream.available() < 2) {
throw new TlvException("Data length < 2 : " + stream.available());
}
ITag tag = searchTagById(stream.readTag());
int tagValueLength = stream.readLength();
tagAndLengthList.add(new TagAndLength(tag, tagValueLength));
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(stream);
}
}
return tagAndLengthList;
}
public static String prettyPrintAPDUResponse(final byte[] data) {
return prettyPrintAPDUResponse(data, 0);
}
/**
* Method used to get the list of TLV inside the parameter tag specified in parameter
*
* @param pData
* data to parse
* @param pTag
* tag to find
* @param pAdd
* boolean to indicate if we nned to add the tlv to the return list
* @return the list of TLV tag inside
*/
public static List<TLV> getlistTLV(final byte[] pData, final ITag pTag, final boolean pAdd) {
List<TLV> list = new ArrayList<TLV>();
TLVInputStream stream = new TLVInputStream(new ByteArrayInputStream(pData));
try {
while (stream.available() > 0) {
TLV tlv = TlvUtil.getNextTLV(stream);
if (tlv == null) {
break;
}
if (pAdd) {
list.add(tlv);
} else if (tlv.getTag().isConstructed()) {
list.addAll(TlvUtil.getlistTLV(tlv.getValueBytes(), pTag, tlv.getTag() == pTag));
}
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(stream);
}
return list;
}
/**
* Method used to get the list of TLV corresponding to tags specified in parameters
*
* @param pData
* data to parse
* @param pTag
* tags to find
* @return the list of TLV
*/
public static List<TLV> getlistTLV(final byte[] pData, final ITag... pTag) {
List<TLV> list = new ArrayList<TLV>();
TLVInputStream stream = new TLVInputStream(new ByteArrayInputStream(pData));
try {
while (stream.available() > 0) {
TLV tlv = TlvUtil.getNextTLV(stream);
if (tlv == null) {
break;
}
if (ArrayUtils.contains(pTag, tlv.getTag())) {
list.add(tlv);
} else if (tlv.getTag().isConstructed()) {
list.addAll(TlvUtil.getlistTLV(tlv.getValueBytes(), pTag));
}
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(stream);
}
return list;
}
/**
* Method used to get Tag value
*
* @param pData
* data
* @param pTag
* tag to find
* @return tag value or null
*/
public static byte[] getValue(final byte[] pData, final ITag... pTag) {
byte[] ret = null;
if (pData != null) {
TLVInputStream stream = new TLVInputStream(new ByteArrayInputStream(pData));
try {
while (stream.available() > 0) {
TLV tlv = TlvUtil.getNextTLV(stream);
if (tlv == null) {
break;
}
if (ArrayUtils.contains(pTag, tlv.getTag())) {
return tlv.getValueBytes();
} else if (tlv.getTag().isConstructed()) {
ret = TlvUtil.getValue(tlv.getValueBytes(), pTag);
if (ret != null) {
break;
}
}
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(stream);
}
}
return ret;
}
public static String prettyPrintAPDUResponse(final byte[] data, final int indentLength) {
StringBuilder buf = new StringBuilder();
TLVInputStream stream = new TLVInputStream(new ByteArrayInputStream(data));
try {
while (stream.available() > 0) {
buf.append("\n");
if (stream.available() == 2) {
stream.mark(0);
byte[] value = new byte[2];
try {
stream.read(value);
} catch (IOException e) {
}
SwEnum sw = SwEnum.getSW(value);
if (sw != null) {
buf.append(getSpaces(0));
buf.append(BytesUtils.bytesToString(value)).append(" -- ");
buf.append(sw.getDetail());
continue;
}
stream.reset();
}
buf.append(getSpaces(indentLength));
TLV tlv = TlvUtil.getNextTLV(stream);
if (tlv == null) {
buf.setLength(0);
LOGGER.debug("TLV format error");
break;
}
byte[] tagBytes = tlv.getTagBytes();
byte[] lengthBytes = tlv.getRawEncodedLengthBytes();
byte[] valueBytes = tlv.getValueBytes();
ITag tag = tlv.getTag();
buf.append(prettyPrintHex(tagBytes));
buf.append(" ");
buf.append(prettyPrintHex(lengthBytes));
buf.append(" -- ");
buf.append(tag.getName());
int extraIndent = (lengthBytes.length + tagBytes.length) * 3;
if (tag.isConstructed()) {
// indentLength += extraIndent; //TODO check this
// Recursion
buf.append(prettyPrintAPDUResponse(valueBytes, indentLength + extraIndent));
} else {
buf.append("\n");
if (tag.getTagValueType() == TagValueTypeEnum.DOL) {
buf.append(TlvUtil.getFormattedTagAndLength(valueBytes, indentLength + extraIndent));
} else {
buf.append(getSpaces(indentLength + extraIndent));
buf.append(prettyPrintHex(BytesUtils.bytesToStringNoSpace(valueBytes), indentLength + extraIndent));
buf.append(" (");
buf.append(TlvUtil.getTagValueAsString(tag, valueBytes));
buf.append(")");
}
}
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} catch (TlvException exce) {
buf.setLength(0);
LOGGER.debug(exce.getMessage(), exce);
} finally {
IOUtils.closeQuietly(stream);
}
return buf.toString();
}
public static String getSpaces(final int length) {
return StringUtils.leftPad(StringUtils.EMPTY, length);
}
public static String prettyPrintHex(final String in, final int indent) {
return prettyPrintHex(in, indent, true);
}
public static String prettyPrintHex(final byte[] data) {
return prettyPrintHex(BytesUtils.bytesToStringNoSpace(data), 0, true);
}
public static String prettyPrintHex(final String in, final int indent, final boolean wrapLines) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < in.length(); i++) {
char c = in.charAt(i);
buf.append(c);
int nextPos = i + 1;
if (wrapLines && nextPos % 32 == 0 && nextPos != in.length()) {
buf.append("\n").append(getSpaces(indent));
} else if (nextPos % 2 == 0 && nextPos != in.length()) {
buf.append(" ");
}
}
return buf.toString();
}
public static String getSafePrintChars(final byte[] byteArray) {
if (byteArray == null) {
return "";
}
return getSafePrintChars(byteArray, 0, byteArray.length);
}
public static String getSafePrintChars(final byte[] byteArray, final int startPos, final int length) {
if (byteArray == null) {
return "";
}
if (byteArray.length < startPos + length) {
throw new IllegalArgumentException("startPos(" + startPos + ")+length(" + length + ") > byteArray.length("
+ byteArray.length + ")");
}
StringBuilder buf = new StringBuilder();
for (int i = startPos; i < startPos + length; i++) {
if (byteArray[i] >= (byte) 0x20 && byteArray[i] < (byte) 0x7F) {
buf.append((char) byteArray[i]);
} else {
buf.append(".");
}
}
return buf.toString();
}
/**
* Method used to get length of all Tags
*
* @param pList
* tag length list
* @return the sum of tag length
*/
public static int getLength(final List<TagAndLength> pList) {
int ret = 0;
if (pList != null) {
for (TagAndLength tl : pList) {
ret += tl.getLength();
}
}
return ret;
}
/**
* Private constructor
*/
private TlvUtil() {
}
}
| 4,902 |
1,570 |
<reponame>Neelaksh-Singh/ceph-ansible
import pytest
import json
class TestRGWs(object):
@pytest.mark.no_docker
def test_rgw_is_installed(self, node, host):
result = host.package("radosgw").is_installed
if not result:
result = host.package("ceph-radosgw").is_installed
assert result
def test_rgw_service_enabled_and_running(self, node, host):
for i in range(int(node["radosgw_num_instances"])):
service_name = "ceph-radosgw@rgw.{hostname}.rgw{seq}".format(
hostname=node["vars"]["inventory_hostname"],
seq=i
)
s = host.service(service_name)
assert s.is_enabled
assert s.is_running
def test_rgw_is_up(self, node, host, setup):
hostname = node["vars"]["inventory_hostname"]
cluster = setup["cluster_name"]
container_binary = setup["container_binary"]
if node['docker']:
container_exec_cmd = '{container_binary} exec ceph-rgw-{hostname}-rgw0'.format( # noqa E501
hostname=hostname, container_binary=container_binary)
else:
container_exec_cmd = ''
cmd = "sudo {container_exec_cmd} ceph --name client.bootstrap-rgw --keyring /var/lib/ceph/bootstrap-rgw/{cluster}.keyring --cluster={cluster} --connect-timeout 5 -f json -s".format( # noqa E501
container_exec_cmd=container_exec_cmd,
hostname=hostname,
cluster=cluster
)
output = host.check_output(cmd)
keys = list(json.loads(
output)["servicemap"]["services"]["rgw"]["daemons"].keys())
keys.remove('summary')
daemons = json.loads(output)["servicemap"]["services"]["rgw"]["daemons"]
hostnames = []
for key in keys:
hostnames.append(daemons[key]['metadata']['hostname'])
@pytest.mark.no_docker
def test_rgw_http_endpoint(self, node, host, setup):
# rgw frontends ip_addr is configured on public_interface
ip_addr = host.interface(setup['public_interface']).addresses[0]
for i in range(int(node["radosgw_num_instances"])):
assert host.socket(
"tcp://{ip_addr}:{port}".format(ip_addr=ip_addr,
port=(8080+i))
).is_listening # noqa E501
| 1,134 |
831 |
<gh_stars>100-1000
/*
* Copyright (C) 2017 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.tools.idea.navigator.nodes.ndk.includes.view;
import com.android.tools.idea.navigator.nodes.ndk.includes.utils.LexicalIncludePaths;
import com.android.tools.idea.util.VirtualFiles;
import com.google.common.collect.ImmutableList;
import com.intellij.ide.projectView.ViewSettings;
import com.intellij.ide.projectView.impl.nodes.PsiFileNode;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.*;
/**
* Methods for creating and dealing with visual representation nodes for include folders.
*/
public class IncludeViewNodes {
/**
* Method that produces a collection of folders and files that represents a set of includes in order.
*
* @param includes The ordered set of include folders.
* @param excludesVirtualFiles The set of folders to be excluded.
* @param folderParentIsObvious Whether or not the parent folder of these files and folders is visibly obvious.
* If not, then show a hint path next to them.
* @param project The project
* @param settings The view settings
* @return A collection of tree nodes for the folders and files.
*/
@NotNull
public static Collection<AbstractTreeNode<?>> getIncludeFolderNodesWithShadowing(@NotNull Collection<File> includes,
@NotNull ImmutableList<VirtualFile> excludesVirtualFiles,
boolean folderParentIsObvious,
@NotNull Project project,
@NotNull ViewSettings settings) {
List<AbstractTreeNode<?>> result = new ArrayList<>();
Set<String> baseNameSeenAlready = new HashSet<>();
PsiManager psiManager = PsiManager.getInstance(project);
LocalFileSystem fileSystem = LocalFileSystem.getInstance();
for (File include : includes) {
VirtualFile folder = fileSystem.findFileByIoFile(include);
if (folder == null) {
continue;
}
PsiDirectory psiDirectory = psiManager.findDirectory(folder);
if (psiDirectory != null) {
psiDirectory.processChildren(element -> {
if (VirtualFiles.isElementAncestorOfExclude(element, excludesVirtualFiles)) {
// This file or folder is in the set to be excluded.
return true;
}
if (baseNameSeenAlready.contains(element.getName())) {
// These are files and folders that have been shadowed by prior include folders.
// Could accumulate these and show them in a separated node.
return true;
}
baseNameSeenAlready.add(element.getName());
if (element instanceof PsiDirectory) {
PsiDirectory concrete = (PsiDirectory)element;
PsiIncludeDirectoryView node =
new PsiIncludeDirectoryView(project, excludesVirtualFiles, folderParentIsObvious, concrete, settings);
if (!node.getChildren().isEmpty()) {
result.add(node);
}
return true;
}
if (element instanceof PsiFile) {
PsiFile concrete = (PsiFile)element;
if (!LexicalIncludePaths.hasHeaderExtension(concrete.getName())) {
return true;
}
result.add(new PsiFileNode(project, concrete, settings));
return true;
}
return true;
});
}
}
return result;
}
}
| 1,861 |
711 |
<filename>service-api/src/main/java/com/java110/api/listener/user/AddStaffServiceListener.java
package com.java110.api.listener.user;
import com.alibaba.fastjson.JSONObject;
import com.java110.api.bmo.user.IUserBMO;
import com.java110.api.listener.AbstractServiceApiPlusListener;
import com.java110.core.annotation.Java110Listener;
import com.java110.core.context.DataFlowContext;
import com.java110.core.event.service.api.ServiceDataFlowEvent;
import com.java110.core.factory.DataFlowFactory;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.intf.common.IFileInnerServiceSMO;
import com.java110.dto.file.FileDto;
import com.java110.entity.center.AppService;
import com.java110.po.file.FileRelPo;
import com.java110.utils.constant.BusinessTypeConstant;
import com.java110.utils.constant.CommonConstant;
import com.java110.utils.constant.ServiceCodeConstant;
import com.java110.utils.constant.StoreUserRelConstant;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* 添加员工 2018年12月6日
* Created by wuxw on 2018/5/18.
*/
@Java110Listener("addStaffServiceListener")
public class AddStaffServiceListener extends AbstractServiceApiPlusListener {
private final static Logger logger = LoggerFactory.getLogger(AddStaffServiceListener.class);
@Autowired
private IUserBMO userBMOImpl;
@Autowired
private IFileInnerServiceSMO fileInnerServiceSMOImpl;
@Override
public String getServiceCode() {
return ServiceCodeConstant.SERVICE_CODE_USER_STAFF_ADD;
}
@Override
public HttpMethod getHttpMethod() {
return HttpMethod.POST;
}
@Override
public int getOrder() {
return 0;
}
@Override
protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) {
}
@Override
protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {
//获取数据上下文对象
Assert.jsonObjectHaveKey(reqJson, "storeId", "请求参数中未包含storeId 节点,请确认");
Assert.jsonObjectHaveKey(reqJson, "storeTypeCd", "请求参数中未包含storeTypeCd 节点,请确认");
//判断请求报文中包含 userId 并且 不为-1时 将已有用户添加为员工,反之,则添加用户再将用户添加为员工
String userId = "";
String oldUserId = "";
String relCd = reqJson.getString("relCd");//员工 组织 岗位
if (!reqJson.containsKey("userId") || "-1".equals(reqJson.getString("userId"))) {
//将userId 强制写成-1
oldUserId = "-1";
userId = GenerateCodeFactory.getUserId();
reqJson.put("userId", userId);
//添加用户
userBMOImpl.addUser(reqJson, context);
}
reqJson.put("userId", userId);
reqJson.put("relCd", "-1".equals(oldUserId) ? StoreUserRelConstant.REL_COMMON : StoreUserRelConstant.REL_ADMIN);
userBMOImpl.addStaff(reqJson, context);
//重写 员工岗位
reqJson.put("relCd", relCd);
userBMOImpl.addStaffOrg(reqJson, context);
if (reqJson.containsKey("photo") && !StringUtils.isEmpty(reqJson.getString("photo"))) {
FileDto fileDto = new FileDto();
fileDto.setFileId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_file_id));
fileDto.setFileName(fileDto.getFileId());
fileDto.setContext(reqJson.getString("photo"));
fileDto.setSuffix("jpeg");
fileDto.setCommunityId(reqJson.getString("communityId"));
String fileName = fileInnerServiceSMOImpl.saveFile(fileDto);
reqJson.put("photoId", fileDto.getFileId());
reqJson.put("fileSaveName", fileName);
JSONObject businessUnit = new JSONObject();
businessUnit.put("fileRelId", "-1");
businessUnit.put("relTypeCd", "12000");
businessUnit.put("saveWay", "table");
businessUnit.put("objId", userId);
businessUnit.put("fileRealName", fileDto.getFileId());
businessUnit.put("fileSaveName", fileName);
FileRelPo fileRelPo = BeanConvertUtil.covertBean(businessUnit, FileRelPo.class);
super.insert(context, fileRelPo, BusinessTypeConstant.BUSINESS_TYPE_SAVE_FILE_REL);
}
commit(context);
//如果不成功直接返回
if (context.getResponseEntity().getStatusCode() != HttpStatus.OK) {
return;
}
}
/**
* 用户赋权
*
* @return
*/
private void privilegeUserDefault(DataFlowContext dataFlowContext, JSONObject paramObj) {
ResponseEntity responseEntity = null;
AppService appService = DataFlowFactory.getService(dataFlowContext.getAppId(), ServiceCodeConstant.SERVICE_CODE_SAVE_USER_DEFAULT_PRIVILEGE);
if (appService == null) {
responseEntity = new ResponseEntity<String>("当前没有权限访问" + ServiceCodeConstant.SERVICE_CODE_SAVE_USER_DEFAULT_PRIVILEGE, HttpStatus.UNAUTHORIZED);
dataFlowContext.setResponseEntity(responseEntity);
return;
}
String requestUrl = appService.getUrl();
HttpHeaders header = new HttpHeaders();
header.add(CommonConstant.HTTP_SERVICE.toLowerCase(), ServiceCodeConstant.SERVICE_CODE_SAVE_USER_DEFAULT_PRIVILEGE);
userBMOImpl.freshHttpHeader(header, dataFlowContext.getRequestCurrentHeaders());
JSONObject paramInObj = new JSONObject();
paramInObj.put("userId", paramObj.getString("userId"));
paramInObj.put("storeTypeCd", paramObj.getString("storeTypeCd"));
paramInObj.put("storeId", paramObj.getString("storeId"));
paramInObj.put("userFlag", "staff");
HttpEntity<String> httpEntity = new HttpEntity<String>(paramInObj.toJSONString(), header);
doRequest(dataFlowContext, appService, httpEntity);
responseEntity = dataFlowContext.getResponseEntity();
if (responseEntity.getStatusCode() != HttpStatus.OK) {
dataFlowContext.setResponseEntity(responseEntity);
}
}
}
| 2,783 |
506 |
<filename>examples/Touch/TouchGoal/Goals.h<gh_stars>100-1000
#pragma once
#define TEXT_TOP 25
#define TEXT_CENTER 160
#define TEXT_HEIGHT 32
#define TEXT_FONT 4
#define TEST_DURRATION 8000
class Goal {
public:
Goal();
bool test();
bool passed();
const char* getName();
virtual void event_handler(Event& evt) = 0;
protected:
String name;
uint32_t start_time;
bool success;
};
class TapAGoal : public Goal { public: TapAGoal(); void event_handler(Event& e); };
class TapBGoal : public Goal { public: TapBGoal(); void event_handler(Event& e); };
class LongPressAGoal : public Goal { public: LongPressAGoal(); void event_handler(Event& e); };
class LongPressBGoal : public Goal { public: LongPressBGoal(); void event_handler(Event& e); };
class LongPressBackgroundGoal : public Goal { public: LongPressBackgroundGoal(); void event_handler(Event& e); };
class DoubleTapAGoal : public Goal { public: DoubleTapAGoal(); void event_handler(Event& e); };
class DoubleTapBGoal : public Goal { public: DoubleTapBGoal(); void event_handler(Event& e); };
class TapBackgroundGoal : public Goal { public: TapBackgroundGoal(); void event_handler(Event& e); };
class DoubleTapBackgroundGoal : public Goal { public: DoubleTapBackgroundGoal(); void event_handler(Event& e); };
class DragFromAtoBGoal : public Goal { public: DragFromAtoBGoal(); void event_handler(Event& e); };
class DragFromBtoAGoal : public Goal { public: DragFromBtoAGoal(); void event_handler(Event& e); };
class DragFromAtoBackgroundGoal : public Goal { public: DragFromAtoBackgroundGoal(); void event_handler(Event& e); };
class DragFromBtoBackgroundGoal : public Goal { public: DragFromBtoBackgroundGoal(); void event_handler(Event& e); };
class DragFromBackgroundtoAGoal : public Goal { public: DragFromBackgroundtoAGoal(); void event_handler(Event& e); private: bool can_succeed; };
class DragFromBackgroundtoBGoal : public Goal { public: DragFromBackgroundtoBGoal(); void event_handler(Event& e); private: bool can_succeed; };
class SwipeUpGoal : public Goal { public: SwipeUpGoal(); void event_handler(Event& e); };
class SwipeDownGoal : public Goal { public: SwipeDownGoal(); void event_handler(Event& e); };
class SwipeLeftGoal : public Goal { public: SwipeLeftGoal(); void event_handler(Event& e); };
class SwipeRightGoal : public Goal { public: SwipeRightGoal(); void event_handler(Event& e); };
| 1,099 |
14,668 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdio.h>
#include <map>
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "build/chromeos_buildflags.h"
#include "net/disk_cache/cache_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
namespace disk_cache {
class CacheUtilTest : public PlatformTest {
public:
void SetUp() override {
PlatformTest::SetUp();
ASSERT_TRUE(tmp_dir_.CreateUniqueTempDir());
cache_dir_ = tmp_dir_.GetPath().Append(FILE_PATH_LITERAL("Cache"));
file1_ = base::FilePath(cache_dir_.Append(FILE_PATH_LITERAL("file01")));
file2_ = base::FilePath(cache_dir_.Append(FILE_PATH_LITERAL(".file02")));
dir1_ = base::FilePath(cache_dir_.Append(FILE_PATH_LITERAL("dir01")));
file3_ = base::FilePath(dir1_.Append(FILE_PATH_LITERAL("file03")));
ASSERT_TRUE(base::CreateDirectory(cache_dir_));
FILE *fp = base::OpenFile(file1_, "w");
ASSERT_TRUE(fp != nullptr);
base::CloseFile(fp);
fp = base::OpenFile(file2_, "w");
ASSERT_TRUE(fp != nullptr);
base::CloseFile(fp);
ASSERT_TRUE(base::CreateDirectory(dir1_));
fp = base::OpenFile(file3_, "w");
ASSERT_TRUE(fp != nullptr);
base::CloseFile(fp);
dest_dir_ = tmp_dir_.GetPath().Append(FILE_PATH_LITERAL("old_Cache_001"));
dest_file1_ = base::FilePath(dest_dir_.Append(FILE_PATH_LITERAL("file01")));
dest_file2_ =
base::FilePath(dest_dir_.Append(FILE_PATH_LITERAL(".file02")));
dest_dir1_ = base::FilePath(dest_dir_.Append(FILE_PATH_LITERAL("dir01")));
}
protected:
base::ScopedTempDir tmp_dir_;
base::FilePath cache_dir_;
base::FilePath file1_;
base::FilePath file2_;
base::FilePath dir1_;
base::FilePath file3_;
base::FilePath dest_dir_;
base::FilePath dest_file1_;
base::FilePath dest_file2_;
base::FilePath dest_dir1_;
};
TEST_F(CacheUtilTest, MoveCache) {
EXPECT_TRUE(disk_cache::MoveCache(cache_dir_, dest_dir_));
EXPECT_TRUE(base::PathExists(dest_dir_));
EXPECT_TRUE(base::PathExists(dest_file1_));
EXPECT_TRUE(base::PathExists(dest_file2_));
EXPECT_TRUE(base::PathExists(dest_dir1_));
#if BUILDFLAG(IS_CHROMEOS_ASH)
EXPECT_TRUE(base::PathExists(cache_dir_)); // old cache dir stays
#else
EXPECT_FALSE(base::PathExists(cache_dir_)); // old cache is gone
#endif
EXPECT_FALSE(base::PathExists(file1_));
EXPECT_FALSE(base::PathExists(file2_));
EXPECT_FALSE(base::PathExists(dir1_));
}
TEST_F(CacheUtilTest, DeleteCache) {
disk_cache::DeleteCache(cache_dir_, false);
EXPECT_TRUE(base::PathExists(cache_dir_)); // cache dir stays
EXPECT_FALSE(base::PathExists(dir1_));
EXPECT_FALSE(base::PathExists(file1_));
EXPECT_FALSE(base::PathExists(file2_));
EXPECT_FALSE(base::PathExists(file3_));
}
TEST_F(CacheUtilTest, DeleteCacheAndDir) {
disk_cache::DeleteCache(cache_dir_, true);
EXPECT_FALSE(base::PathExists(cache_dir_)); // cache dir is gone
EXPECT_FALSE(base::PathExists(dir1_));
EXPECT_FALSE(base::PathExists(file1_));
EXPECT_FALSE(base::PathExists(file2_));
EXPECT_FALSE(base::PathExists(file3_));
}
TEST_F(CacheUtilTest, DeleteCacheFile) {
EXPECT_TRUE(disk_cache::DeleteCacheFile(file1_));
EXPECT_FALSE(base::PathExists(file1_));
EXPECT_TRUE(base::PathExists(cache_dir_)); // cache dir stays
EXPECT_TRUE(base::PathExists(dir1_));
EXPECT_TRUE(base::PathExists(file3_));
}
TEST_F(CacheUtilTest, PreferredCacheSize) {
const struct TestCase {
int64_t available;
int expected_without_trial;
int expected_with_200_trial;
int expected_with_250_trial;
int expected_with_300_trial;
} kTestCases[] = {
// Weird negative value for available --- return the "default"
{-1000LL, 80 * 1024 * 1024, 160 * 1024 * 1024, 200 * 1024 * 1024,
240 * 1024 * 1024},
{-1LL, 80 * 1024 * 1024, 160 * 1024 * 1024, 200 * 1024 * 1024,
240 * 1024 * 1024},
// 0 produces 0.
{0LL, 0, 0, 0, 0},
// Cache is 80% of available space, when default cache size is larger than
// 80% of available space..
{50 * 1024 * 1024LL, 40 * 1024 * 1024, 40 * 1024 * 1024, 40 * 1024 * 1024,
40 * 1024 * 1024},
// Cache is default size, when default size is 10% to 80% of available
// space.
{100 * 1024 * 1024LL, 80 * 1024 * 1024, 80 * 1024 * 1024,
80 * 1024 * 1024, 80 * 1024 * 1024},
{200 * 1024 * 1024LL, 80 * 1024 * 1024, 80 * 1024 * 1024,
80 * 1024 * 1024, 80 * 1024 * 1024},
// Cache is 10% of available space if 2.5 * default size is more than 10%
// of available space.
{1000 * 1024 * 1024LL, 100 * 1024 * 1024, 200 * 1024 * 1024,
200 * 1024 * 1024, 200 * 1024 * 1024},
{2000 * 1024 * 1024LL, 200 * 1024 * 1024, 400 * 1024 * 1024,
400 * 1024 * 1024, 400 * 1024 * 1024},
// Cache is 2.5 * kDefaultCacheSize if 2.5 * kDefaultCacheSize uses from
// 1% to 10% of available space.
{10000 * 1024 * 1024LL, 200 * 1024 * 1024, 400 * 1024 * 1024,
500 * 1024 * 1024, 600 * 1024 * 1024},
// Otherwise, cache is 1% of available space.
{20000 * 1024 * 1024LL, 200 * 1024 * 1024, 400 * 1024 * 1024,
500 * 1024 * 1024, 600 * 1024 * 1024},
// Until it runs into the cache size cap.
{32000 * 1024 * 1024LL, 320 * 1024 * 1024, 640 * 1024 * 1024,
800 * 1024 * 1024, 960 * 1024 * 1024},
{50000 * 1024 * 1024LL, 320 * 1024 * 1024, 640 * 1024 * 1024,
800 * 1024 * 1024, 960 * 1024 * 1024},
};
for (const auto& test_case : kTestCases) {
EXPECT_EQ(test_case.expected_without_trial,
PreferredCacheSize(test_case.available))
<< test_case.available;
// Preferred size for WebUI code cache matches expected_without_trial but
// should never be more than 5 MB.
int expected_webui_code_cache_size =
std::min(5 * 1024 * 1024, test_case.expected_without_trial);
EXPECT_EQ(expected_webui_code_cache_size,
PreferredCacheSize(test_case.available,
net::GENERATED_WEBUI_BYTE_CODE_CACHE))
<< test_case.available;
}
// Check that the cache size cap is 50% higher for native code caches.
EXPECT_EQ(((320 * 1024 * 1024) / 2) * 3,
PreferredCacheSize(50000 * 1024 * 1024LL,
net::GENERATED_NATIVE_CODE_CACHE));
for (int cache_size_exeriment : {100, 200, 250, 300}) {
base::test::ScopedFeatureList scoped_feature_list;
std::map<std::string, std::string> field_trial_params;
field_trial_params["percent_relative_size"] =
base::NumberToString(cache_size_exeriment);
scoped_feature_list.InitAndEnableFeatureWithParameters(
disk_cache::kChangeDiskCacheSizeExperiment, field_trial_params);
for (const auto& test_case : kTestCases) {
int expected = 0;
switch (cache_size_exeriment) {
case 100:
expected = test_case.expected_without_trial;
break;
case 200:
expected = test_case.expected_with_200_trial;
break;
case 250:
expected = test_case.expected_with_250_trial;
break;
case 300:
expected = test_case.expected_with_300_trial;
break;
}
EXPECT_EQ(expected, PreferredCacheSize(test_case.available));
// For caches other than disk cache, the size is not scaled.
EXPECT_EQ(test_case.expected_without_trial,
PreferredCacheSize(test_case.available,
net::GENERATED_BYTE_CODE_CACHE));
// Preferred size for WebUI code cache is not scaled by the trial, and
// should never be more than 5 MB.
int expected_webui_code_cache_size =
std::min(5 * 1024 * 1024, test_case.expected_without_trial);
EXPECT_EQ(expected_webui_code_cache_size,
PreferredCacheSize(test_case.available,
net::GENERATED_WEBUI_BYTE_CODE_CACHE))
<< test_case.available;
}
// Check that the cache size cap is 50% higher for native code caches but is
// not scaled for the experiment.
EXPECT_EQ(((320 * 1024 * 1024) / 2) * 3,
PreferredCacheSize(50000 * 1024 * 1024LL,
net::GENERATED_NATIVE_CODE_CACHE));
}
// Check no "percent_relative_size" matches default behavior.
{
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(
disk_cache::kChangeDiskCacheSizeExperiment);
for (const auto& test_case : kTestCases) {
EXPECT_EQ(test_case.expected_without_trial,
PreferredCacheSize(test_case.available));
}
// Check that the cache size cap is 50% higher for native code caches.
EXPECT_EQ(((320 * 1024 * 1024) / 2) * 3,
PreferredCacheSize(50000 * 1024 * 1024LL,
net::GENERATED_NATIVE_CODE_CACHE));
}
}
} // namespace disk_cache
| 3,814 |
14,755 |
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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 luigi
from luigi.contrib.s3 import S3Target
from luigi.contrib.spark import SparkSubmitTask, PySparkTask
class InlinePySparkWordCount(PySparkTask):
"""
This task runs a :py:class:`luigi.contrib.spark.PySparkTask` task
over the target data in :py:meth:`wordcount.input` (a file in S3) and
writes the result into its :py:meth:`wordcount.output` target (a file in S3).
This class uses :py:meth:`luigi.contrib.spark.PySparkTask.main`.
Example luigi configuration::
[spark]
spark-submit: /usr/local/spark/bin/spark-submit
master: spark://spark.example.org:7077
# py-packages: numpy, pandas
"""
driver_memory = '2g'
executor_memory = '3g'
def input(self):
return S3Target("s3n://bucket.example.org/wordcount.input")
def output(self):
return S3Target('s3n://bucket.example.org/wordcount.output')
def main(self, sc, *args):
sc.textFile(self.input().path) \
.flatMap(lambda line: line.split()) \
.map(lambda word: (word, 1)) \
.reduceByKey(lambda a, b: a + b) \
.saveAsTextFile(self.output().path)
class PySparkWordCount(SparkSubmitTask):
"""
This task is the same as :py:class:`InlinePySparkWordCount` above but uses
an external python driver file specified in :py:meth:`app`
It runs a :py:class:`luigi.contrib.spark.SparkSubmitTask` task
over the target data in :py:meth:`wordcount.input` (a file in S3) and
writes the result into its :py:meth:`wordcount.output` target (a file in S3).
This class uses :py:meth:`luigi.contrib.spark.SparkSubmitTask.run`.
Example luigi configuration::
[spark]
spark-submit: /usr/local/spark/bin/spark-submit
master: spark://spark.example.org:7077
deploy-mode: client
"""
driver_memory = '2g'
executor_memory = '3g'
total_executor_cores = luigi.IntParameter(default=100, significant=False)
name = "PySpark Word Count"
app = 'wordcount.py'
def app_options(self):
# These are passed to the Spark main args in the defined order.
return [self.input().path, self.output().path]
def input(self):
return S3Target("s3n://bucket.example.org/wordcount.input")
def output(self):
return S3Target('s3n://bucket.example.org/wordcount.output')
'''
// Corresponding example Spark Job, running Word count with Spark's Python API
// This file would have to be saved into wordcount.py
import sys
from pyspark import SparkContext
if __name__ == "__main__":
sc = SparkContext()
sc.textFile(sys.argv[1]) \
.flatMap(lambda line: line.split()) \
.map(lambda word: (word, 1)) \
.reduceByKey(lambda a, b: a + b) \
.saveAsTextFile(sys.argv[2])
'''
| 1,302 |
495 |
<reponame>Musyue/py-apple-quadruped-robot
import _thread
import padog
import time
from machine import Timer
from machine import UART
from padog import g,m
#
from machine import time_pulse_us
from machine import Pin
#run_mode=0:web遥控模式
#run_mode=1:OpenMV 巡线模式
#run_mode=2:OpenMV 颜色识别模式
#run_mode=3:调试模式
run_mode=0
uart6=UART(2,115200)
t = Timer(1)
def OpenMV_Run(t):
command=""
if uart6.any():
read = uart6.read(1).decode('gbk')
while read != '/':
command = command + read
read = uart6.read(1).decode('gbk')
if(command != "1/" ) and command!="":
try:
exec(command)
print("exec:",command)
except:
print("execerr:",command)
command = ""
def app_1():
exec(open('web_c.py').read())
def app_2():
try:
exec(open('my_code.py').read())
except:
print('积木编程代码执行出错,跳过...')
def serial_run_loop():
while True:
padog.mainloop()
def loop(t):
padog.mainloop()
#模式判定
if run_mode==0:
_thread.start_new_thread(app_1, ())
t.init(period=10,mode=Timer.PERIODIC,callback=loop)
elif run_mode==1:
t.init(period=50,mode=Timer.PERIODIC,callback=OpenMV_Run)
padog.gesture(padog.in_pit,padog.in_rol,padog.in_y)
padog.speed=0.045
serial_run_loop()
elif run_mode==2:
t.init(period=10,mode=Timer.PERIODIC,callback=OpenMV_Run)
padog.gesture(padog.in_pit,padog.in_rol,padog.in_y)
padog.speed=0.045
serial_run_loop()
elif run_mode==3:
_thread.start_new_thread(app_1, ())
serial_run_loop()
| 762 |
1,008 |
/*
* Copyright (C) 2019 The Turms Project
* https://github.com/turms-im/turms
*
* 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.
*/
// Generated Code - Do NOT edit manually
package im.turms.plugin.antispam.character.data;
public final class U87 {
public static final char[][] DATA = {
Common.$736875, // '蜀'(8700) -> "shu"
Common.$7875616E, // '蜁'(8701) -> "xuan"
Common.$66656E67, // '蜂'(8702) -> "feng"
Common.$7368656E, // '蜃'(8703) -> "shen"
Common.$7368656E, // '蜄'(8704) -> "shen"
Common.$6675, // '蜅'(8705) -> "fu"
Common.$7869616E, // '蜆'(8706) -> "xian"
Common.$7A6865, // '蜇'(8707) -> "zhe"
Common.$7775, // '蜈'(8708) -> "wu"
Common.$6675, // '蜉'(8709) -> "fu"
Common.$6C69, // '蜊'(870A) -> "li"
Common.$6C616E67, // '蜋'(870B) -> "lang"
Common.$6269, // '蜌'(870C) -> "bi"
Common.$636875, // '蜍'(870D) -> "chu"
Common.$7975616E, // '蜎'(870E) -> "yuan"
Common.$796F75, // '蜏'(870F) -> "you"
Common.$6A6965, // '蜐'(8710) -> "jie"
Common.$64616E, // '蜑'(8711) -> "dan"
Common.$79616E, // '蜒'(8712) -> "yan"
Common.$74696E67, // '蜓'(8713) -> "ting"
Common.$6469616E, // '蜔'(8714) -> "dian"
Common.$747569, // '蜕'(8715) -> "tui"
Common.$687569, // '蜖'(8716) -> "hui"
Common.$776F, // '蜗'(8717) -> "wo"
Common.$7A6869, // '蜘'(8718) -> "zhi"
Common.$736F6E67, // '蜙'(8719) -> "song"
Common.$666569, // '蜚'(871A) -> "fei"
Common.$6A75, // '蜛'(871B) -> "ju"
Common.$6D69, // '蜜'(871C) -> "mi"
Common.$7169, // '蜝'(871D) -> "qi"
Common.$7169, // '蜞'(871E) -> "qi"
Common.$7975, // '蜟'(871F) -> "yu"
Common.$6A756E, // '蜠'(8720) -> "jun"
Common.$6C61, // '蜡'(8721) -> "la"
Common.$6D656E67, // '蜢'(8722) -> "meng"
Common.$7169616E67, // '蜣'(8723) -> "qiang"
Common.$7369, // '蜤'(8724) -> "si"
Common.$7869, // '蜥'(8725) -> "xi"
Common.$6C756E, // '蜦'(8726) -> "lun"
Common.$6C69, // '蜧'(8727) -> "li"
Common.$646965, // '蜨'(8728) -> "die"
Common.$7469616F, // '蜩'(8729) -> "tiao"
Common.$74616F, // '蜪'(872A) -> "tao"
Common.$6B756E, // '蜫'(872B) -> "kun"
Common.$68616E, // '蜬'(872C) -> "han"
Common.$68616E, // '蜭'(872D) -> "han"
Common.$7975, // '蜮'(872E) -> "yu"
Common.$62616E67, // '蜯'(872F) -> "bang"
Common.$666569, // '蜰'(8730) -> "fei"
Common.$7069, // '蜱'(8731) -> "pi"
Common.$776569, // '蜲'(8732) -> "wei"
Common.$64756E, // '蜳'(8733) -> "dun"
Common.$7969, // '蜴'(8734) -> "yi"
Common.$7975616E, // '蜵'(8735) -> "yuan"
Common.$73756F, // '蜶'(8736) -> "suo"
Common.$7175616E, // '蜷'(8737) -> "quan"
Common.$7169616E, // '蜸'(8738) -> "qian"
Common.$727569, // '蜹'(8739) -> "rui"
Common.$6E69, // '蜺'(873A) -> "ni"
Common.$71696E67, // '蜻'(873B) -> "qing"
Common.$776569, // '蜼'(873C) -> "wei"
Common.$6C69616E67, // '蜽'(873D) -> "liang"
Common.$67756F, // '蜾'(873E) -> "guo"
Common.$77616E, // '蜿'(873F) -> "wan"
Common.$646F6E67, // '蝀'(8740) -> "dong"
Common.$65, // '蝁'(8741) -> "e"
Common.$62616E, // '蝂'(8742) -> "ban"
Common.$6469, // '蝃'(8743) -> "di"
Common.$77616E67, // '蝄'(8744) -> "wang"
Common.$63616E, // '蝅'(8745) -> "can"
Common.$79616E67, // '蝆'(8746) -> "yang"
Common.$79696E67, // '蝇'(8747) -> "ying"
Common.$67756F, // '蝈'(8748) -> "guo"
Common.$6368616E, // '蝉'(8749) -> "chan"
Common.$64696E67, // '蝊'(874A) -> "ding"
Common.$6C61, // '蝋'(874B) -> "la"
Common.$6B65, // '蝌'(874C) -> "ke"
Common.$6A6965, // '蝍'(874D) -> "jie"
Common.$786965, // '蝎'(874E) -> "xie"
Common.$74696E67, // '蝏'(874F) -> "ting"
Common.$6D616F, // '蝐'(8750) -> "mao"
Common.$7875, // '蝑'(8751) -> "xu"
Common.$6D69616E, // '蝒'(8752) -> "mian"
Common.$7975, // '蝓'(8753) -> "yu"
Common.$6A6965, // '蝔'(8754) -> "jie"
Common.$736869, // '蝕'(8755) -> "shi"
Common.$7875616E, // '蝖'(8756) -> "xuan"
Common.$6875616E67, // '蝗'(8757) -> "huang"
Common.$79616E, // '蝘'(8758) -> "yan"
Common.$6269616E, // '蝙'(8759) -> "bian"
Common.$726F75, // '蝚'(875A) -> "rou"
Common.$776569, // '蝛'(875B) -> "wei"
Common.$6675, // '蝜'(875C) -> "fu"
Common.$7975616E, // '蝝'(875D) -> "yuan"
Common.$6D6569, // '蝞'(875E) -> "mei"
Common.$776569, // '蝟'(875F) -> "wei"
Common.$6675, // '蝠'(8760) -> "fu"
Common.$7275, // '蝡'(8761) -> "ru"
Common.$786965, // '蝢'(8762) -> "xie"
Common.$796F75, // '蝣'(8763) -> "you"
Common.$716975, // '蝤'(8764) -> "qiu"
Common.$6D616F, // '蝥'(8765) -> "mao"
Common.$786961, // '蝦'(8766) -> "xia"
Common.$79696E67, // '蝧'(8767) -> "ying"
Common.$736869, // '蝨'(8768) -> "shi"
Common.$63686F6E67, // '蝩'(8769) -> "chong"
Common.$74616E67, // '蝪'(876A) -> "tang"
Common.$7A6875, // '蝫'(876B) -> "zhu"
Common.$7A6F6E67, // '蝬'(876C) -> "zong"
Common.$7469, // '蝭'(876D) -> "ti"
Common.$6675, // '蝮'(876E) -> "fu"
Common.$7975616E, // '蝯'(876F) -> "yuan"
Common.$6B7569, // '蝰'(8770) -> "kui"
Common.$6D656E67, // '蝱'(8771) -> "meng"
Common.$6C61, // '蝲'(8772) -> "la"
Common.$6475, // '蝳'(8773) -> "du"
Common.$6875, // '蝴'(8774) -> "hu"
Common.$716975, // '蝵'(8775) -> "qiu"
Common.$646965, // '蝶'(8776) -> "die"
Common.$6C69, // '蝷'(8777) -> "li"
Common.$776F, // '蝸'(8778) -> "wo"
Common.$79756E, // '蝹'(8779) -> "yun"
Common.$7175, // '蝺'(877A) -> "qu"
Common.$6E616E, // '蝻'(877B) -> "nan"
Common.$6C6F75, // '蝼'(877C) -> "lou"
Common.$6368756E, // '蝽'(877D) -> "chun"
Common.$726F6E67, // '蝾'(877E) -> "rong"
Common.$79696E67, // '蝿'(877F) -> "ying"
Common.$6A69616E67, // '螀'(8780) -> "jiang"
Common.$62616E, // '螁'(8781) -> "ban"
Common.$6C616E67, // '螂'(8782) -> "lang"
Common.$70616E67, // '螃'(8783) -> "pang"
Common.$7369, // '螄'(8784) -> "si"
Common.$7869, // '螅'(8785) -> "xi"
Common.$6369, // '螆'(8786) -> "ci"
Common.$7869, // '螇'(8787) -> "xi"
Common.$7975616E, // '螈'(8788) -> "yuan"
Common.$77656E67, // '螉'(8789) -> "weng"
Common.$6C69616E, // '螊'(878A) -> "lian"
Common.$736F75, // '螋'(878B) -> "sou"
Common.$62616E, // '螌'(878C) -> "ban"
Common.$726F6E67, // '融'(878D) -> "rong"
Common.$726F6E67, // '螎'(878E) -> "rong"
Common.$6A69, // '螏'(878F) -> "ji"
Common.$7775, // '螐'(8790) -> "wu"
Common.$786975, // '螑'(8791) -> "xiu"
Common.$68616E, // '螒'(8792) -> "han"
Common.$71696E, // '螓'(8793) -> "qin"
Common.$7969, // '螔'(8794) -> "yi"
Common.$6269, // '螕'(8795) -> "bi"
Common.$687561, // '螖'(8796) -> "hua"
Common.$74616E67, // '螗'(8797) -> "tang"
Common.$7969, // '螘'(8798) -> "yi"
Common.$6475, // '螙'(8799) -> "du"
Common.$6E6169, // '螚'(879A) -> "nai"
Common.$6865, // '螛'(879B) -> "he"
Common.$6875, // '螜'(879C) -> "hu"
Common.$677569, // '螝'(879D) -> "gui"
Common.$6D61, // '螞'(879E) -> "ma"
Common.$6D696E67, // '螟'(879F) -> "ming"
Common.$7969, // '螠'(87A0) -> "yi"
Common.$77656E, // '螡'(87A1) -> "wen"
Common.$79696E67, // '螢'(87A2) -> "ying"
Common.$7465, // '螣'(87A3) -> "te"
Common.$7A686F6E67, // '螤'(87A4) -> "zhong"
Common.$63616E67, // '螥'(87A5) -> "cang"
Common.$73616F, // '螦'(87A6) -> "sao"
Common.$7169, // '螧'(87A7) -> "qi"
Common.$6D616E, // '螨'(87A8) -> "man"
Common.$7469616F, // '螩'(87A9) -> "tiao"
Common.$7368616E67, // '螪'(87AA) -> "shang"
Common.$736869, // '螫'(87AB) -> "shi"
Common.$63616F, // '螬'(87AC) -> "cao"
Common.$636869, // '螭'(87AD) -> "chi"
Common.$6469, // '螮'(87AE) -> "di"
Common.$616F, // '螯'(87AF) -> "ao"
Common.$6C75, // '螰'(87B0) -> "lu"
Common.$776569, // '螱'(87B1) -> "wei"
Common.$7A6869, // '螲'(87B2) -> "zhi"
Common.$74616E67, // '螳'(87B3) -> "tang"
Common.$6368656E, // '螴'(87B4) -> "chen"
Common.$7069616F, // '螵'(87B5) -> "piao"
Common.$7175, // '螶'(87B6) -> "qu"
Common.$7069, // '螷'(87B7) -> "pi"
Common.$7975, // '螸'(87B8) -> "yu"
Common.$6A69616E, // '螹'(87B9) -> "jian"
Common.$6C756F, // '螺'(87BA) -> "luo"
Common.$6C6F75, // '螻'(87BB) -> "lou"
Common.$71696E, // '螼'(87BC) -> "qin"
Common.$7A686F6E67, // '螽'(87BD) -> "zhong"
Common.$79696E, // '螾'(87BE) -> "yin"
Common.$6A69616E67, // '螿'(87BF) -> "jiang"
Common.$7368756169, // '蟀'(87C0) -> "shuai"
Common.$77656E, // '蟁'(87C1) -> "wen"
Common.$7869616F, // '蟂'(87C2) -> "xiao"
Common.$77616E, // '蟃'(87C3) -> "wan"
Common.$7A6865, // '蟄'(87C4) -> "zhe"
Common.$7A6865, // '蟅'(87C5) -> "zhe"
Common.$6D61, // '蟆'(87C6) -> "ma"
Common.$6D61, // '蟇'(87C7) -> "ma"
Common.$67756F, // '蟈'(87C8) -> "guo"
Common.$6C6975, // '蟉'(87C9) -> "liu"
Common.$6D616F, // '蟊'(87CA) -> "mao"
Common.$7869, // '蟋'(87CB) -> "xi"
Common.$636F6E67, // '蟌'(87CC) -> "cong"
Common.$6C69, // '蟍'(87CD) -> "li"
Common.$6D616E, // '蟎'(87CE) -> "man"
Common.$7869616F, // '蟏'(87CF) -> "xiao"
Common.$6368616E67, // '蟐'(87D0) -> "chang"
Common.$7A68616E67, // '蟑'(87D1) -> "zhang"
Common.$6D616E67, // '蟒'(87D2) -> "mang"
Common.$7869616E67, // '蟓'(87D3) -> "xiang"
Common.$6D6F, // '蟔'(87D4) -> "mo"
Common.$7A7569, // '蟕'(87D5) -> "zui"
Common.$7369, // '蟖'(87D6) -> "si"
Common.$716975, // '蟗'(87D7) -> "qiu"
Common.$7465, // '蟘'(87D8) -> "te"
Common.$7A6869, // '蟙'(87D9) -> "zhi"
Common.$70656E67, // '蟚'(87DA) -> "peng"
Common.$70656E67, // '蟛'(87DB) -> "peng"
Common.$6A69616F, // '蟜'(87DC) -> "jiao"
Common.$7175, // '蟝'(87DD) -> "qu"
Common.$626965, // '蟞'(87DE) -> "bie"
Common.$6C69616F, // '蟟'(87DF) -> "liao"
Common.$70616E, // '蟠'(87E0) -> "pan"
Common.$677569, // '蟡'(87E1) -> "gui"
Common.$7869, // '蟢'(87E2) -> "xi"
Common.$6A69, // '蟣'(87E3) -> "ji"
Common.$7A6875616E, // '蟤'(87E4) -> "zhuan"
Common.$6875616E67, // '蟥'(87E5) -> "huang"
Common.$666569, // '蟦'(87E6) -> "fei"
Common.$6C616F, // '蟧'(87E7) -> "lao"
Common.$6A7565, // '蟨'(87E8) -> "jue"
Common.$6A7565, // '蟩'(87E9) -> "jue"
Common.$687569, // '蟪'(87EA) -> "hui"
Common.$79696E, // '蟫'(87EB) -> "yin"
Common.$6368616E, // '蟬'(87EC) -> "chan"
Common.$6A69616F, // '蟭'(87ED) -> "jiao"
Common.$7368616E, // '蟮'(87EE) -> "shan"
Common.$6E616F, // '蟯'(87EF) -> "nao"
Common.$7869616F, // '蟰'(87F0) -> "xiao"
Common.$7775, // '蟱'(87F1) -> "wu"
Common.$63686F6E67, // '蟲'(87F2) -> "chong"
Common.$78756E, // '蟳'(87F3) -> "xun"
Common.$7369, // '蟴'(87F4) -> "si"
Common.$636875, // '蟵'(87F5) -> "chu"
Common.$6368656E67, // '蟶'(87F6) -> "cheng"
Common.$64616E67, // '蟷'(87F7) -> "dang"
Common.$6C69, // '蟸'(87F8) -> "li"
Common.$786965, // '蟹'(87F9) -> "xie"
Common.$7368616E, // '蟺'(87FA) -> "shan"
Common.$7969, // '蟻'(87FB) -> "yi"
Common.$6A696E67, // '蟼'(87FC) -> "jing"
Common.$6461, // '蟽'(87FD) -> "da"
Common.$6368616E, // '蟾'(87FE) -> "chan"
Common.$7169, // '蟿'(87FF) -> "qi"
};
private U87() {}
}
| 8,792 |
14,668 |
<reponame>zealoussnow/chromium
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_AUTOFILL_IOS_FORM_UTIL_AUTOFILL_TEST_WITH_WEB_STATE_H_
#define COMPONENTS_AUTOFILL_IOS_FORM_UTIL_AUTOFILL_TEST_WITH_WEB_STATE_H_
#import "ios/web/public/test/web_test_with_web_state.h"
namespace web {
class WebClient;
class WebFrame;
} // namespace web
// A fixture to set up testing of Autofill methods.
class AutofillTestWithWebState : public web::WebTestWithWebState {
protected:
AutofillTestWithWebState(std::unique_ptr<web::WebClient> web_client);
// Injects initial renderer is value into the |frame| and waits for
// completion.
void SetUpForUniqueIds(web::WebFrame* frame);
// Toggles tracking form mutations in a |frame| and waits for completion.
void TrackFormMutations(web::WebFrame* frame);
};
#endif // COMPONENTS_AUTOFILL_IOS_FORM_UTIL_AUTOFILL_TEST_WITH_WEB_STATE_H_
| 353 |
1,056 |
<reponame>arusinha/incubator-netbeans
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.versioning.core.spi.testvcs;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import org.netbeans.modules.versioning.core.api.VCSFileProxy;
import org.netbeans.modules.versioning.core.spi.*;
import org.netbeans.spi.queries.CollocationQueryImplementation2;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
/**
* Test versioning system.
*
* @author <NAME>
*/
@VersioningSystem.Registration(
actionsCategory="TestVCS",
displayName="TestVCSDisplay",
menuLabel="TestVCSMenu",
metadataFolderNames={
TestVCS.TEST_VCS_METADATA,
"set:getenv:PATH:notnull",
"notset:getenv:SOMENOTSETVARIABLE:notnull",
"null:getenv:whatever:null"}
)
public class TestVCS extends VersioningSystem {
private static TestVCS instance;
private VCSInterceptor interceptor;
private VCSAnnotator annotator;
private VCSHistoryProvider historyProvider;
private VCSVisibilityQuery vq;
private TestVCSCollocationQuery vcq;
public static final String TEST_VCS_METADATA = ".testvcs";
public static final String VERSIONED_FOLDER_SUFFIX = "-test-versioned";
public static String ALWAYS_WRITABLE_PREFIX = "alwayswritable-";
public static TestVCS getInstance() {
return instance;
}
public static void resetInstance() {
instance = null;
}
public TestVCS() {
instance = this;
interceptor = new TestVCSInterceptor();
annotator = new TestVCSAnnotator();
historyProvider = new TestVCSHistoryProvider();
vq = new TestVCSVisibilityQuery();
vcq = new TestVCSCollocationQuery();
}
public VCSFileProxy getTopmostManagedAncestor(VCSFileProxy file) {
VCSFileProxy topmost = null;
for (; file != null; file = file.getParentFile()) {
if (file.getName().endsWith(VERSIONED_FOLDER_SUFFIX)) {
topmost = file;
}
}
return topmost;
}
public VCSInterceptor getVCSInterceptor() {
return interceptor;
}
public VCSAnnotator getVCSAnnotator() {
return annotator;
}
@Override
public VCSVisibilityQuery getVisibilityQuery() {
return vq;
}
@Override
public CollocationQueryImplementation2 getCollocationQueryImplementation() {
return vcq;
}
public void fire() {
// do not fire a null here. Some tests may fail because:
// java.lang.NullPointerException
// at org.netbeans.modules.versioning.core.VersioningAnnotationProvider.refreshAnnotations(VersioningAnnotationProvider.java:345)
// at org.netbeans.modules.versioning.core.VersioningAnnotationProvider.refreshAnnotations(VersioningAnnotationProvider.java:325)
// at org.netbeans.modules.versioning.core.VersioningManager.propertyChange(VersioningManager.java:560)
// at java.beans.PropertyChangeSupport.fire(PropertyChangeSupport.java:335)
// at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:327)
// at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:263)
// at org.netbeans.modules.versioning.core.spi.VersioningSystem.fireStatusChanged(VersioningSystem.java:193)
// at org.netbeans.modules.versioning.core.spi.VersioningSystem.fireStatusChanged(VersioningSystem.java:211)
// at org.netbeans.modules.versioning.core.spi.testvcs.TestVCS.fire(TestVCS.java:133)
// at org.netbeans.modules.versioning.core.DelegatingVCSTest.testListeners(DelegatingVCSTest.java:161)
VCSFileProxy file = VCSFileProxy.createFileProxy(new File("dummy"));
super.fireStatusChanged(file);
}
public void setVCSInterceptor(VCSInterceptor externalyMovedInterceptor) {
interceptor = externalyMovedInterceptor;
}
@ActionID(id = "vcs.delegatetest.init", category = "TestVCS")
@ActionRegistration(displayName = "InitAction", popupText="InitActionPopup", menuText="InitActionMenu")
@ActionReferences({@ActionReference(path="Versioning/TestVCS/Actions/Unversioned")})
public static class InitAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) { }
}
@ActionID(id = "vcs.delegatetest.global", category = "TestVCS")
@ActionRegistration(displayName = "GobalAction", popupText="GlobalActionPopup", menuText="GlobalActionMenu")
@ActionReferences({@ActionReference(path="Versioning/TestVCS/Actions/Global")})
public static class GlobalAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) { }
}
@Override
public VCSHistoryProvider getVCSHistoryProvider() {
return historyProvider;
}
}
| 2,073 |
5,921 |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the MIT-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <fstream>
#include <map>
#include <string>
#include <unordered_map>
#include <flashlight/flashlight.h>
#include "criterion/criterion.h"
#include "recipes/models/local_prior_match/src/runtime/Defines.h"
#include "runtime/Logger.h"
namespace w2l {
struct SSLDatasetMeters {
std::map<std::string, fl::EditDistanceMeter> edits;
std::map<std::string, fl::AverageValueMeter> values;
SSLDatasetMeters()
: edits(
{{kTarget, fl::EditDistanceMeter()},
{kWord, fl::EditDistanceMeter()}}),
values({{kASRLoss, fl::AverageValueMeter()}}) {}
};
struct SSLTrainMeters {
std::map<std::string, fl::TimeMeter> timer;
std::map<std::string, fl::AverageValueMeter> values;
SSLDatasetMeters train;
std::map<std::string, SSLDatasetMeters> valid;
SpeechStatMeter stats;
SSLTrainMeters()
: timer(
{{kRuntime, fl::TimeMeter(false)},
{kTimer, fl::TimeMeter(true)},
{kSampleTimer, fl::TimeMeter(true)},
{kFwdTimer, fl::TimeMeter(true)},
{kCritFwdTimer, fl::TimeMeter(true)},
{kBeamTimer, fl::TimeMeter(true)},
{kBeamFwdTimer, fl::TimeMeter(true)},
{kLMFwdTimer, fl::TimeMeter(true)},
{kBwdTimer, fl::TimeMeter(true)},
{kOptimTimer, fl::TimeMeter(true)}}),
values(
{{kLPMLoss, fl::AverageValueMeter()},
{kFullLoss, fl::AverageValueMeter()},
{kNumHypos, fl::AverageValueMeter()},
{kLMEnt, fl::AverageValueMeter()},
{kLMScore, fl::AverageValueMeter()},
{kLen, fl::AverageValueMeter()}}) {}
};
class LogHelper {
public:
LogHelper(int runIdx, std::string runPath, bool isMaster, bool logOnEpoch);
void saveConfig(const std::unordered_map<std::string, std::string>& config);
void writeHeader(SSLTrainMeters& meters);
void logStatus(
SSLTrainMeters& mtrs,
int64_t epoch,
const std::unordered_map<std::string, double>& logFields);
std::string saveModel(
const std::string& filename,
const std::unordered_map<std::string, std::string>& config,
std::shared_ptr<fl::Module> network,
std::shared_ptr<SequenceCriterion> criterion,
std::shared_ptr<fl::FirstOrderOptimizer> netoptim = nullptr,
bool workerSave = false);
void logAndSaveModel(
SSLTrainMeters& meters,
const std::unordered_map<std::string, std::string>& config,
std::shared_ptr<fl::Module> network,
std::shared_ptr<SequenceCriterion> criterion,
std::shared_ptr<fl::FirstOrderOptimizer> netoptim,
const std::unordered_map<std::string, double>& logFields);
std::string formatStatus(
SSLTrainMeters& meters,
int64_t epoch,
const std::unordered_map<std::string, double>& logFields,
bool verbose = false,
bool date = false,
const std::string& separator = " ",
bool headerOnly = false);
private:
int runIdx_;
std::string runPath_;
bool isMaster_, logOnEpoch_;
std::string logFileName_, perfFileName_;
// best perf so far on valid datasets
std::unordered_map<std::string, double> validminerrs_;
LogHelper() {}
};
template <>
void syncMeter<SSLTrainMeters>(SSLTrainMeters& meters);
template <>
void syncMeter<SSLDatasetMeters>(SSLDatasetMeters& meters);
void resetTrainMeters(SSLTrainMeters& meters);
void stopTimeMeters(SSLTrainMeters& meters);
void resetDatasetMeters(SSLDatasetMeters& meters);
double avgValidErr(SSLTrainMeters& meters);
} // namespace w2l
| 1,561 |
340 |
<reponame>gajubadge11/HackerRank-1<filename>interview-preparation-kit/repeated-string.py<gh_stars>100-1000
#!/bin/python3
import sys
def repeatedString(s, n):
return s.count('a') * (n//len(s)) + s[:n%len(s)].count('a')
if __name__ == "__main__":
s = input().strip()
n = int(input().strip())
result = repeatedString(s, n)
print(result)
| 153 |
418 |
/**
Modified MIT License
Copyright 2019 OneSignal
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:
1. The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
2. All copies of substantial portions of the Software may only be used in connection
with services provided by OneSignal.
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.
*/
#ifndef OSInfluenceDataDefines_h
#define OSInfluenceDataDefines_h
// Influence param keys
static NSString* const OUTCOMES_PARAM = @"outcomes";
static NSString* const DIRECT_PARAM = @"direct";
static NSString* const INDIRECT_PARAM = @"indirect";
static NSString* const UNATTRIBUTED_PARAM = @"unattributed";
static NSString* const ENABLED_PARAM = @"enabled";
static NSString* const NOTIFICATION_ATTRIBUTION_PARAM = @"notification_attribution";
static NSString* const IAM_ATTRIBUTION_PARAM = @"in_app_message_attribution";
static NSString* const MINUTES_SINCE_DISPLAYED_PARAM = @"minutes_since_displayed";
static NSString* const LIMIT_PARAM = @"limit";
// Influence default param values
static int DEFAULT_INDIRECT_NOTIFICATION_LIMIT = 10;
static int DEFAULT_INDIRECT_ATTRIBUTION_WINDOW = 24 * 60;
#endif /* OSInfluenceDataDefines_h */
| 589 |
1,125 |
<filename>client/rest-high-level/src/test/java/org/elasticsearch/client/ml/job/process/DataCountsTests.java
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.client.ml.job.process;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.test.AbstractXContentTestCase;
import org.joda.time.DateTime;
import java.util.Date;
import static org.hamcrest.Matchers.greaterThan;
public class DataCountsTests extends AbstractXContentTestCase<DataCounts> {
public static DataCounts createTestInstance(String jobId) {
return new DataCounts(jobId, randomIntBetween(1, 1_000_000),
randomIntBetween(1, 1_000_000), randomIntBetween(1, 1_000_000), randomIntBetween(1, 1_000_000),
randomIntBetween(1, 1_000_000), randomIntBetween(1, 1_000_000), randomIntBetween(1, 1_000_000),
randomIntBetween(1, 1_000_000), randomIntBetween(1, 1_000_000), randomIntBetween(1, 1_000_000),
new DateTime(randomDateTimeZone()).toDate(), new DateTime(randomDateTimeZone()).toDate(),
new DateTime(randomDateTimeZone()).toDate(), new DateTime(randomDateTimeZone()).toDate(),
new DateTime(randomDateTimeZone()).toDate());
}
@Override
public DataCounts createTestInstance() {
return createTestInstance(randomAlphaOfLength(10));
}
@Override
protected DataCounts doParseInstance(XContentParser parser) {
return DataCounts.PARSER.apply(parser, null);
}
@Override
protected boolean supportsUnknownFields() {
return true;
}
public void testCountsEquals_GivenEqualCounts() {
DataCounts counts1 = createCounts(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
DataCounts counts2 = createCounts(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
assertTrue(counts1.equals(counts2));
assertTrue(counts2.equals(counts1));
}
public void testCountsHashCode_GivenEqualCounts() {
DataCounts counts1 = createCounts(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
DataCounts counts2 = createCounts(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
assertEquals(counts1.hashCode(), counts2.hashCode());
}
public void testCountsCopyConstructor() {
DataCounts counts1 = createCounts(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
DataCounts counts2 = new DataCounts(counts1);
assertEquals(counts1.hashCode(), counts2.hashCode());
}
public void testCountCreatedZero() throws Exception {
DataCounts counts = new DataCounts(randomAlphaOfLength(16));
assertAllFieldsEqualZero(counts);
}
public void testCountCopyCreatedFieldsNotZero() throws Exception {
DataCounts counts1 = createCounts(1, 200, 400, 3, 4, 5, 6, 7, 8, 9, 1479211200000L, 1479384000000L, 13, 14, 15);
assertAllFieldsGreaterThanZero(counts1);
DataCounts counts2 = new DataCounts(counts1);
assertAllFieldsGreaterThanZero(counts2);
}
private void assertAllFieldsEqualZero(DataCounts stats) throws Exception {
assertEquals(0L, stats.getProcessedRecordCount());
assertEquals(0L, stats.getProcessedFieldCount());
assertEquals(0L, stats.getInputBytes());
assertEquals(0L, stats.getInputFieldCount());
assertEquals(0L, stats.getInputRecordCount());
assertEquals(0L, stats.getInvalidDateCount());
assertEquals(0L, stats.getMissingFieldCount());
assertEquals(0L, stats.getOutOfOrderTimeStampCount());
}
private void assertAllFieldsGreaterThanZero(DataCounts stats) throws Exception {
assertThat(stats.getProcessedRecordCount(), greaterThan(0L));
assertThat(stats.getProcessedFieldCount(), greaterThan(0L));
assertThat(stats.getInputBytes(), greaterThan(0L));
assertThat(stats.getInputFieldCount(), greaterThan(0L));
assertThat(stats.getInputRecordCount(), greaterThan(0L));
assertThat(stats.getInputRecordCount(), greaterThan(0L));
assertThat(stats.getInvalidDateCount(), greaterThan(0L));
assertThat(stats.getMissingFieldCount(), greaterThan(0L));
assertThat(stats.getOutOfOrderTimeStampCount(), greaterThan(0L));
assertThat(stats.getLatestRecordTimeStamp().getTime(), greaterThan(0L));
}
private static DataCounts createCounts(
long processedRecordCount, long processedFieldCount, long inputBytes, long inputFieldCount,
long invalidDateCount, long missingFieldCount, long outOfOrderTimeStampCount,
long emptyBucketCount, long sparseBucketCount, long bucketCount,
long earliestRecordTime, long latestRecordTime, long lastDataTimeStamp, long latestEmptyBucketTimeStamp,
long latestSparseBucketTimeStamp) {
DataCounts counts = new DataCounts("foo", processedRecordCount, processedFieldCount, inputBytes,
inputFieldCount, invalidDateCount, missingFieldCount, outOfOrderTimeStampCount,
emptyBucketCount, sparseBucketCount, bucketCount,
new Date(earliestRecordTime), new Date(latestRecordTime),
new Date(lastDataTimeStamp), new Date(latestEmptyBucketTimeStamp), new Date(latestSparseBucketTimeStamp));
return counts;
}
}
| 2,276 |
304 |
<reponame>fduguet-nv/cunumeric
/* Copyright 2022 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#pragma once
namespace cunumeric {
void cub_local_sort(const bool* values_in,
bool* values_out,
const int64_t* indices_in,
int64_t* indices_out,
const size_t volume,
const size_t sort_dim_size,
cudaStream_t stream);
void cub_local_sort(const int8_t* values_in,
int8_t* values_out,
const int64_t* indices_in,
int64_t* indices_out,
const size_t volume,
const size_t sort_dim_size,
cudaStream_t stream);
void cub_local_sort(const int16_t* values_in,
int16_t* values_out,
const int64_t* indices_in,
int64_t* indices_out,
const size_t volume,
const size_t sort_dim_size,
cudaStream_t stream);
void cub_local_sort(const int32_t* values_in,
int32_t* values_out,
const int64_t* indices_in,
int64_t* indices_out,
const size_t volume,
const size_t sort_dim_size,
cudaStream_t stream);
void cub_local_sort(const int64_t* values_in,
int64_t* values_out,
const int64_t* indices_in,
int64_t* indices_out,
const size_t volume,
const size_t sort_dim_size,
cudaStream_t stream);
void cub_local_sort(const uint8_t* values_in,
uint8_t* values_out,
const int64_t* indices_in,
int64_t* indices_out,
const size_t volume,
const size_t sort_dim_size,
cudaStream_t stream);
void cub_local_sort(const uint16_t* values_in,
uint16_t* values_out,
const int64_t* indices_in,
int64_t* indices_out,
const size_t volume,
const size_t sort_dim_size,
cudaStream_t stream);
void cub_local_sort(const uint32_t* values_in,
uint32_t* values_out,
const int64_t* indices_in,
int64_t* indices_out,
const size_t volume,
const size_t sort_dim_size,
cudaStream_t stream);
void cub_local_sort(const uint64_t* values_in,
uint64_t* values_out,
const int64_t* indices_in,
int64_t* indices_out,
const size_t volume,
const size_t sort_dim_size,
cudaStream_t stream);
void cub_local_sort(const __half* values_in,
__half* values_out,
const int64_t* indices_in,
int64_t* indices_out,
const size_t volume,
const size_t sort_dim_size,
cudaStream_t stream);
void cub_local_sort(const float* values_in,
float* values_out,
const int64_t* indices_in,
int64_t* indices_out,
const size_t volume,
const size_t sort_dim_size,
cudaStream_t stream);
void cub_local_sort(const double* values_in,
double* values_out,
const int64_t* indices_in,
int64_t* indices_out,
const size_t volume,
const size_t sort_dim_size,
cudaStream_t stream);
} // namespace cunumeric
| 2,450 |
563 |
<reponame>kant/Sharpmake
#include "src/pch.h"
#include "util_static_lib1.h"
#include <ios>
#include <external.h>
namespace static_lib1_utils
{
std::streampos GetRandomPosition()
{
PrintBuildString("StaticLib1");
return 1;
}
}
| 114 |
2,542 |
<filename>src/prod/src/Reliability/Failover/ra/ClearWarningErrorHealthReportDescriptor.cpp
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "Ra.Stdafx.h"
using namespace std;
using namespace Common;
using namespace Reliability;
using namespace ReconfigurationAgentComponent;
using namespace Health;
ClearWarningErrorHealthReportDescriptor::ClearWarningErrorHealthReportDescriptor()
{
}
std::wstring ClearWarningErrorHealthReportDescriptor::GenerateReportDescriptionInternal(HealthContext const & ) const
{
return L"";
}
| 184 |
1,306 |
/*
* Copyright (C) 2007 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.
*/
/**
* Test math exceptions
*/
public class Main {
public static void main(String args[]) {
int expectedThrows = 2;
int i;
long j;
float f = 0.0f;
double d = 0.0;
try { i = 10 / 0; }
catch (ArithmeticException ae) {
expectedThrows--;
}
try { j = 10L / 0L; }
catch (ArithmeticException ae) {
expectedThrows--;
}
/*
* Floating point divide by zero doesn't throw an exception -- the
* result is just NaN.
*/
try { f = 10.0f / f; }
catch (ArithmeticException ae) {
expectedThrows--;
}
try { d = 10.0 / d; }
catch (ArithmeticException ae) {
expectedThrows--;
}
if (expectedThrows != 0)
System.out.println("HEY: expected throws is " + expectedThrows);
else
System.out.println("testMath3 success");
}
}
| 645 |
335 |
{
"word": "Hatch",
"definitions": [
"A door in an aircraft, spacecraft, or submarine.",
"The rear door of a hatchback car."
],
"parts-of-speech": "Noun"
}
| 81 |
3,055 |
/*
Fontname: streamline_interface_essential_search
Copyright: <EMAIL>
Glyphs: 4/4
BBX Build Mode: 0
*/
const uint8_t u8g2_font_streamline_interface_essential_search_t[270] U8G2_FONT_SECTION("u8g2_font_streamline_interface_essential_search_t") =
"\4\0\4\3\5\5\2\3\6\25\25\0\0\25\0\25\0\0\0\0\0\0\361\60\70\263\316\232\16\310de"
"B\16H\42\42\16\16\42$\16\16\42d\16h\244\256\344A\42\342\1b\242\243b\343\42\323\305FE"
"\307\204\307\204\307\204\307\204\307\204\207\304CH\2\61\67\265\312\372\350\1\204d\5\5\203\343\302\204\302\42"
"e\242bC\202\202cR\207\304D\207\304\304C\4\205G\205\207\5\213\5\217\11\332\11\35\10\322\334\3"
"\324\203\314\3\305\0\62JU\352\232j\352\242\42\242\302\242\42\242\302\242\246\322\3\4\205\215\5EU\305"
"\304\315\205D\320Q\204\10\205$\22\211\240PA\221\215D\66\22\22!\23\231LHDPdA!a"
"\221\302\42\5EL\4ELPTP\24\35\15\0\63\66\224\332\332\252\245D#\3c\303\242\243BC"
"\202BGb\42g\62\32\212\11Y\25\23c\26\24C\26\25$\27\26;\26Y&U!WB!N"
"\21\17P\17\61\1\0\0\0\4\377\377\0";
| 581 |
2,692 |
#!/usr/bin/env python
#
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import logging
import sys
import unittest
from uuid import UUID
from onefuzztypes.enums import JobState
from onefuzztypes.models import Job, JobConfig
from onefuzztypes.primitives import Directory, File
from onefuzz.api import Onefuzz
from onefuzz.templates import JobHelper
class TestHelper(unittest.TestCase):
def test_path_resolution(self) -> None:
helper = JobHelper(
Onefuzz(),
logging.getLogger(),
"a",
"b",
"c",
False,
target_exe=File("README.md"),
job=Job(
job_id=UUID("0" * 32),
state=JobState.init,
config=JobConfig(project="a", name="a", build="a", duration=1),
),
)
values = {
(File("filename.txt"), None): "filename.txt",
(File("dir/filename.txt"), None): "filename.txt",
(File("./filename.txt"), None): "filename.txt",
(File("./filename.txt"), Directory(".")): "filename.txt",
(File("dir/filename.txt"), Directory("dir")): "filename.txt",
(File("dir/filename.txt"), Directory("dir/")): "filename.txt",
(File("dir/filename.txt"), Directory("./dir")): "filename.txt",
(File("./dir/filename.txt"), Directory("./dir/")): "filename.txt",
}
expected = "filename.txt"
if sys.platform == "linux":
filename = File("/unused/filename.txt")
values[(filename, None)] = expected
values[(filename, Directory("/unused"))] = expected
values[(filename, Directory("/unused/"))] = expected
if sys.platform == "windows":
for filename in [
File("c:/unused/filename.txt"),
File("c:\\unused/filename.txt"),
File("c:\\unused\\filename.txt"),
]:
values[(filename, None)] = expected
values[(filename, Directory("c:/unused"))] = expected
values[(filename, Directory("c:/unused/"))] = expected
values[(filename, Directory("c:\\unused\\"))] = expected
values[(filename, Directory("c:\\unused\\"))] = expected
for (args, expected) in values.items():
self.assertEqual(helper.setup_relative_blob_name(*args), expected)
with self.assertRaises(ValueError):
helper.setup_relative_blob_name(
File("dir/filename.txt"), Directory("other_dir")
)
if __name__ == "__main__":
unittest.main()
| 1,228 |
835 |
# -*- coding: utf-8 -*-
from verta.registry import _constants
class TestContainerizedModels:
def test_log(self, registered_model, docker_image):
model_ver = registered_model.create_containerized_model(docker_image)
assert model_ver.get_docker() == docker_image
attrs = model_ver.get_attributes()
assert (
attrs[_constants.MODEL_LANGUAGE_ATTR_KEY]
== _constants.ModelLanguage.UNKNOWN
)
assert (
attrs[_constants.MODEL_TYPE_ATTR_KEY]
== _constants.ModelType.USER_CONTAINERIZED_MODEL
)
| 271 |
597 |
<reponame>ElectricImp-CSE/ElectricImp-Sublime<filename>modules/Sublime_AdvancedNewFile_1_0_0/advanced_new_file/commands/helper_commands.py
import sublime
import sublime_plugin
class AnfReplaceCommand(sublime_plugin.TextCommand):
def run(self, edit, content):
self.view.replace(edit, sublime.Region(0, self.view.size()), content)
class AdvancedNewFileCommand(sublime_plugin.WindowCommand):
def run(self, is_python=False, initial_path=None,
rename=False, rename_file=None):
args = {}
if rename:
args["is_python"] = is_python
args["initial_path"] = initial_path
args["rename_file"] = rename_file
self.window.run_command("advanced_new_file_move", args)
else:
args["is_python"] = is_python
args["initial_path"] = initial_path
self.window.run_command("advanced_new_file_new", args)
class AnfRemoveRegionContentAndRegionCommand(sublime_plugin.TextCommand):
def run(self, edit, region_key):
regions = self.view.get_regions(region_key)
for region in regions:
self.view.erase(edit, region)
self.view.erase_regions(region_key)
| 501 |
809 |
<filename>src/arch/x86/include/asm/multiboot.h
/**
* @file
* @brief the header for Multiboot
*
* @date 10.11.10
* @author <NAME>
*/
#ifndef X86_MULTIBOOT_H_
#define X86_MULTIBOOT_H_
/* The magic number for the Multiboot header. */
#define MULTIBOOT_HEADER_MAGIC 0x1BADB002
/* The magic number passed by a Multiboot-compliant boot loader. It's placed into EBX register by loader */
#define MULTIBOOT_BOOTLOADER_MAGIC 0x2BADB002
/* The flags for the Multiboot header. */
#define MULTIBOOT_MUSTKNOW 0x0000ffff
/* Align all boot modules on page (4KB) boundaries. */
#define MULTIBOOT_PAGE_ALIGN 0x00000001
/* Must be provided memory information in multiboot_info structure */
#define MULTIBOOT_MEMORY_INFO 0x00000002
/* Must be provided information about the video mode table */
#define MULTIBOOT_VIDEO_INFO 0x00000004
/* If bit 16 in the ‘flags’ word is set, then the fields at offsets 12-28 in the Multiboot header are valid.
* his information does not need to be provided if the kernel image is in elf format,
* but it must be provided if the images is in a.out format or in some other format
*/
#define MULTIBOOT_AOUT_KLUDGE 0x00010000
#define MULTIBOOT_HEADER_FLAGS MULTIBOOT_MEMORY_INFO | MULTIBOOT_PAGE_ALIGN
/* is there basic lower/upper memory information? */
#define MULTIBOOT_INFO_MEMORY 0x00000001
/* is there a boot device set? */
#define MULTIBOOT_INFO_BOOTDEV 0x00000002
/* is the command-line defined? */
#define MULTIBOOT_INFO_CMDLINE 0x00000004
/* are there modules to do something with? */
#define MULTIBOOT_INFO_MODS 0x00000008
/* These next two are mutually exclusive */
/* is there a symbol table loaded? */
#define MULTIBOOT_INFO_AOUT_SYMS 0x00000010
/* is there an ELF section header table? */
#define MULTIBOOT_INFO_ELF_SHDR 0X00000020
/* is there a full memory map? */
#define MULTIBOOT_INFO_MEM_MAP 0x00000040
/* Is there drive info? */
#define MULTIBOOT_INFO_DRIVE_INFO 0x00000080
/* Is there a config table? */
#define MULTIBOOT_INFO_CONFIG_TABLE 0x00000100
/* Is there a boot loader name? */
#define MULTIBOOT_INFO_BOOT_LOADER_NAME 0x00000200
/* Is there a APM table? */
#define MULTIBOOT_INFO_APM_TABLE 0x00000400
/* Is there video information? */
#define MULTIBOOT_INFO_VIDEO_INFO 0x00000800
#ifndef __ASSEMBLER__
#include <stdint.h>
/* The Multiboot header. */
typedef struct multiboot_header {
/* Must be MULTIBOOT_MAGIC */
uint32_t magic;
/* Feature flags */
uint32_t flags;
uint32_t checksum;
/* These are only valid if MULTIBOOT_AOUT_KLUDGE is set. */
uint32_t header_addr;
uint32_t load_addr;
uint32_t load_end_addr;
uint32_t bss_end_addr;
uint32_t entry_addr;
/* These are only valid if MULTIBOOT_VIDEO_INFO is set */
uint32_t mode_type; /* 32 */
uint32_t width; /* 36 */
uint32_t height; /* 40 */
uint32_t depth; /* 44 */
} multiboot_header_t;
/* The symbol table for a.out. */
typedef struct aout_symbol_table {
unsigned long tabsize;
unsigned long strsize;
unsigned long addr;
unsigned long reserved;
} aout_symbol_table_t;
/* The section header table for ELF. */
typedef struct elf_section_header_table {
unsigned long num;
unsigned long size;
unsigned long addr;
unsigned long shndx;
} elf_section_header_table_t;
/* The Multiboot information.
The boot loader passes this data structure to the embox in
register EBX on entry. */
typedef struct multiboot_info {
/* These flags indicate which parts of the multiboot_info are valid */
uint32_t flags;
/* Lower/Upper memory installed in the machine. */
uint32_t mem_lower;
uint32_t mem_upper;
/* BIOS disk device the kernel was loaded from. */
uint32_t boot_device;
/* Command-line for the OS kernel: a null-terminated ASCII string. */
uint32_t cmdline;
/* List of boot modules loaded with the kernel. */
uint32_t mods_count;
uint32_t mods_addr;
/* Symbol information for a.out or ELF executables. */
union {
aout_symbol_table_t aout_sym;
elf_section_header_table_t elf_sec;
} u;
/* Memory map buffer. */
uint32_t mmap_length;
uint32_t mmap_addr;
/* Drive Info buffer */
uint32_t drives_length;
uint32_t drives_addr;
/* ROM configuration table */
uint32_t config_table;
/* Boot Loader Name */
uint32_t boot_loader_name;
/* APM table */
uint32_t apm_table;
/* Video */
uint32_t vbe_control_info;
uint32_t vbe_mode_info;
uint16_t vbe_mode;
uint16_t vbe_interface_seg;
uint16_t vbe_interface_off;
uint16_t vbe_interface_len;
} multiboot_info_t;
/* The module structure. */
typedef struct multiboot_module {
unsigned long mod_start;
unsigned long mod_end;
unsigned long string;
unsigned long reserved;
} multiboot_module_t;
/* The memory map. Be careful that the offset 0 is base_addr_low
but no size. */
typedef struct multiboot_memory_map {
unsigned long size;
unsigned long base_addr_low;
unsigned long base_addr_high;
unsigned long length_low;
unsigned long length_high;
unsigned long type;
} memory_map_t;
#endif /* __ASSEMBLER__ */
#endif /* X86_MULTIBOOT_H_ */
| 2,031 |
5,133 |
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.ap.test.java8stream.base;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
/**
* @author <NAME>
*/
@Mapper
public interface StreamMapper {
StreamMapper INSTANCE = Mappers.getMapper( StreamMapper.class );
@Mappings( {
@Mapping(target = "targetStream", source = "stream"),
@Mapping(target = "targetElements", source = "sourceElements")
} )
Target map(Source source);
@InheritInverseConfiguration
Source map(Target target);
SourceElement mapElement(TargetElement targetElement) throws MyCustomException;
@InheritInverseConfiguration
TargetElement mapElement(SourceElement sourceElement);
@InheritInverseConfiguration
Source updateSource(Target target, @MappingTarget Source source) throws MyCustomException;
}
| 352 |
3,084 |
/*++
Copyright (c) Microsoft Corporation. All rights reserved.
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
PURPOSE.
Module Name:
WdfMultiComp.c
Abstract:
This module implements a KMDF sample driver for a multi-component device.
The driver uses the power framework to manage the power state of the
components of its device.
The device used in this sample is a root-enumerated device whose components
are simulated entirely in software. The simulation of the components is
implemented in HwSim.h and HwSim.c.
The driver's interaction with the power framework is encapsulated in a
separate library named WdfPoFx.lib. The driver statically links to this
library.
Environment:
Kernel mode
--*/
#include "WdfMultiComp.h"
#include "HwSim.h"
#include "WdfMultiComp.tmh"
#ifdef ALLOC_PRAGMA
#pragma alloc_text (INIT, DriverEntry)
#pragma alloc_text (PAGE, MCompEvtDriverCleanup)
#pragma alloc_text (PAGE, MCompEvtDeviceAdd)
#pragma alloc_text (PAGE, MCompEvtDeviceD0Exit)
#endif
NTSTATUS
DriverEntry(
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
)
/*++
Routine Description:
Driver initialization entry point. This entry point is called directly by
the I/O system.
Arguments:
DriverObject - pointer to the driver object
RegistryPath - pointer to a unicode string representing the path to the
driver-specific key in the registry.
Return Value:
An NTSTATUS value representing success or failure of the function.
--*/
{
WDF_DRIVER_CONFIG config;
WDF_OBJECT_ATTRIBUTES attributes;
NTSTATUS status;
WDFDRIVER hDriver;
WPP_INIT_TRACING(DriverObject, RegistryPath);
//
// Create a framework driver object to represent our driver.
//
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
attributes.EvtCleanupCallback = MCompEvtDriverCleanup;
WDF_DRIVER_CONFIG_INIT(
&config,
MCompEvtDeviceAdd
);
status = WdfDriverCreate(DriverObject,
RegistryPath,
&attributes,
&config,
&hDriver);
if (FALSE == NT_SUCCESS(status)) {
Trace(TRACE_LEVEL_ERROR,
"%!FUNC! - WdfDriverCreate failed with %!status!",
status);
WPP_CLEANUP(DriverObject);
}
return status;
}
VOID
MCompEvtDriverCleanup(
_In_ WDFOBJECT Driver
)
/*++
Routine Description:
This routine is invoked when the framework driver object that was created in
DriverEntry is about to be deleted.
Arguments:
Driver - Handle to the framework driver object created in DriverEntry
Return Value:
None
--*/
{
PAGED_CODE();
WPP_CLEANUP(WdfDriverWdmGetDriverObject((WDFDRIVER) Driver));
}
NTSTATUS
InitializePowerFrameworkSettings(
_In_ WDFDEVICE Device
)
/*++
Routine Description:
This routine initializes the power framework helper.
Arguments:
Device - Handle to the framework device object
Return Value:
An NTSTATUS value representing success or failure of the function.
--*/
{
NTSTATUS status;
PO_FX_DEVICE_MCOMP_EXT poFxDevice;
PPO_FX_DEVICE poFxDevicePtr;
PO_FX_COMPONENT_IDLE_STATE idleState[2]; // F0 and F1 only
ULONG i;
RtlZeroMemory(&poFxDevice, sizeof(poFxDevice));
RtlZeroMemory(idleState, sizeof(idleState));
//
// Specify callbacks and context
//
poFxDevicePtr = (PPO_FX_DEVICE) &poFxDevice;
poFxDevicePtr->Version = PO_FX_VERSION_V1;
poFxDevicePtr->ComponentIdleStateCallback =
MCompComponentIdleStateCallback;
poFxDevicePtr->ComponentActiveConditionCallback = NULL;
poFxDevicePtr->ComponentIdleConditionCallback = NULL;
poFxDevicePtr->DevicePowerRequiredCallback = NULL;
poFxDevicePtr->DevicePowerNotRequiredCallback = NULL;
poFxDevicePtr->DeviceContext = Device;
poFxDevicePtr->ComponentCount = COMPONENT_COUNT;
//
// Initialize F-state-related information
// NOTE: We're making the F1 specification be the same for all components,
// but it does not have to be that way.
//
//
// Transition latency should be 0 for F0
//
idleState[0].TransitionLatency = 0;
//
// Residency requirement should be 0 for F0
//
idleState[0].ResidencyRequirement = 0;
//
// Nominal power for F0
//
idleState[0].NominalPower = PO_FX_UNKNOWN_POWER;
//
// Transition latency for F1
//
idleState[1].TransitionLatency = TRANSITION_LATENCY_F1;
//
// Residency requirement for F1
//
idleState[1].ResidencyRequirement = RESIDENCY_REQUIREMENT_F1;
//
// Nominal power for F1
//
idleState[1].NominalPower = PO_FX_UNKNOWN_POWER;
for (i=0; i < COMPONENT_COUNT; i++) {
//
// We're declaring that each of components support only F0 and F1
//
poFxDevicePtr->Components[i].IdleStateCount = 2;
//
// Specify the F-state information
//
poFxDevicePtr->Components[i].IdleStates = idleState;
}
//
// Provide the power framework settings to the power framework helper
//
status = PfhInitializePowerFrameworkSettings(Device, poFxDevicePtr);
if (FALSE == NT_SUCCESS(status)) {
goto exit;
}
status = STATUS_SUCCESS;
exit:
return status;
}
NTSTATUS
CreateDevice(
_In_ WDFOBJECT PfhInitializer,
_In_ PWDFDEVICE_INIT DeviceInit,
_Out_ WDFDEVICE * Device
)
/*++
Routine Description:
This routine creates the KMDF device object and also initializes the power
framework helper's settings for this device object.
Arguments:
PfhInitializer - Handle to the initializer object for initializing the power
framework helper.
DeviceInit - Pointer to a framework-allocated WDFDEVICE_INIT structure.
Device - Handle to the KMDF device object created by this routine.
Return Value:
An NTSTATUS value representing success or failure of the function.
--*/
{
NTSTATUS status;
WDF_OBJECT_ATTRIBUTES objectAttributes;
WDFDEVICE device = NULL;
WDF_PNPPOWER_EVENT_CALLBACKS pnpCallbacks;
WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS s0IdleSettings;
//
// Register the PNP/power callbacks
//
// Note: This is the function driver for the device, so the framework
// automatically enables power policy ownership.
//
WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&pnpCallbacks);
pnpCallbacks.EvtDeviceD0Entry = MCompEvtDeviceD0Entry;
pnpCallbacks.EvtDeviceD0Exit = MCompEvtDeviceD0Exit;
//
// Get the power framework helper to override our PNP/power callbacks
//
PfhInterceptWdfPnpPowerEventCallbacks(PfhInitializer, &pnpCallbacks);
WdfDeviceInitSetPnpPowerEventCallbacks(DeviceInit, &pnpCallbacks);
//
// Give the power framework helper an opportunity to register WDM IRP
// preprocess callbacks for power IRPs
//
status = PfhAssignWdmPowerIrpPreProcessCallback(
PfhInitializer,
DeviceInit,
NULL, // EvtDeviceWdmPowerIrpPreprocess
NULL, // MinorFunctions
0 // NumMinorFunctions
);
if (FALSE == NT_SUCCESS(status)) {
goto exit;
}
//
// Specify the context for the device
//
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&objectAttributes,
DEVICE_EXTENSION);
//
// Create a framework device object
//
status = WdfDeviceCreate(&DeviceInit, &objectAttributes, &device);
if (FALSE == NT_SUCCESS(status)) {
Trace(TRACE_LEVEL_ERROR,
"%!FUNC! - WdfDeviceCreate failed with %!status!",
status);
goto exit;
}
//
// Specify the POHANDLE availability callbacks
//
PfhSetPoHandleAvailabilityCallbacks(PfhInitializer,
MCompPoHandleAvailable,
MCompPoHandleUnavailable);
//
// Enable S0-idle power management
//
// Note:
// * We set IdleTimeoutType = DriverManagedIdleTimeout to make sure KMDF
// doesn't register with the power framework on our behalf, because we
// will be directly registering with the power framework ourselves.
// * We set PowerUpIdleDeviceOnSystemWake = TRUE because when we register
// with power framework, we'd like to return to D0 immediately after the
// system returns to S0. It is a power framework requirement that once
// the system returns to S0, then device must return to D0 and the
// driver must invoke PoFxReportDevicePoweredOn (the power framework
// helper library does this on our behalf).
// * We pick a really small idle timeout value so that KMDF can power down
// the device almost immediately after the power framework allows it to
// do so.
//
// If S0-idle power management support is not required, then the following
// modifications should be made:
// 1. Recompile the power framework helper library with the value of the
// WDFPOFX_S0IDLE_SUPPORTED compiler switch set to 0. This omits the
// code that is specific to S0-idle power management, thereby reducing
// the size of the library.
// 2. Remove the calls to PfhSetS0IdleConfiguration and
// WdfDeviceAssignS0IdleSettings below.
//
PfhSetS0IdleConfiguration(PfhInitializer, PfhS0IdleSupportedPowerPageable);
WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS_INIT(&s0IdleSettings,
IdleCannotWakeFromS0);
s0IdleSettings.IdleTimeoutType = DriverManagedIdleTimeout;
s0IdleSettings.PowerUpIdleDeviceOnSystemWake = WdfTrue;
s0IdleSettings.IdleTimeout = 1; // 1 millisecond
status = WdfDeviceAssignS0IdleSettings(device, &s0IdleSettings);
if (FALSE == NT_SUCCESS(status)) {
Trace(TRACE_LEVEL_ERROR,
"%!FUNC! - WdfDeviceAssignS0IdleSettings failed with %!status!",
status);
goto exit;
}
//
// Get the power framework helper to initialize its settings for this device
//
status = PfhInitializeDeviceSettings(device, PfhInitializer);
if (FALSE == NT_SUCCESS(status)) {
goto exit;
}
*Device = device;
status = STATUS_SUCCESS;
exit:
return status;
}
NTSTATUS
CreateComponentQueues(
_In_ WDFOBJECT PfhInitializer,
_In_ WDFDEVICE Device
)
/*++
Routine Description:
This routine creates the component queues and also initializes the power
framework helper's settings for each of them.
Arguments:
PfhInitializer - Handle to the initializer object for initializing the power
framework helper.
Device - Handle to the framework device object
Return Value:
An NTSTATUS value representing success or failure of the function.
--*/
{
NTSTATUS status;
PDEVICE_EXTENSION devExt;
ULONG i;
WDF_IO_QUEUE_CONFIG ioQueueConfig;
//
// Get the device extension
//
devExt = DeviceGetData(Device);
for (i=0; i < COMPONENT_COUNT; i++) {
//
// Create the component-specific queues
//
WDF_IO_QUEUE_CONFIG_INIT(&ioQueueConfig, WdfIoQueueDispatchParallel);
ioQueueConfig.EvtIoDeviceControl = MCompEvtIoDeviceControlSecondary;
//
// Get the power framework helper to override the configuration for our
// component-specific queue
//
PfhInterceptComponentQueueConfig(PfhInitializer, &ioQueueConfig);
//
// Associate the queue with a component
//
PfhSetComponentForComponentQueue(PfhInitializer, i);
//
// Create the queue
//
//
// By default, Static Driver Verifier (SDV) displays a warning if it
// doesn't find the EvtIoStop callback on a power-managed queue.
// The 'assume' below causes SDV to suppress this warning. If the driver
// has not explicitly set PowerManaged to WdfFalse, the framework creates
// power-managed queues when the device is not a filter driver. Normally
// the EvtIoStop is required for power-managed queues, but for this driver
// it is not needed b/c the driver doesn't hold on to the requests or
// forward them to other drivers. This driver completes the requests
// directly in the queue's handlers. If the EvtIoStop callback is not
// implemented, the framework waits for all driver-owned requests to be
// done before moving in the Dx/sleep states or before removing the
// device, which is the correct behavior for this type of driver.
// If the requests were taking an indeterminate amount of time to complete,
// or if the driver forwarded the requests to a lower driver/another stack,
// the queue should have an EvtIoStop/EvtIoResume.
//
__analysis_assume(ioQueueConfig.EvtIoStop != 0);
status = WdfIoQueueCreate(Device,
&ioQueueConfig,
WDF_NO_OBJECT_ATTRIBUTES,
&(devExt->Queue[i]));
__analysis_assume(ioQueueConfig.EvtIoStop == 0);
if (FALSE == NT_SUCCESS(status)) {
Trace(TRACE_LEVEL_ERROR,
"%!FUNC! - WdfIoQueueCreate failed with %!status! when "
"creating queue for component %d",
status,
i);
goto exit;
}
//
// Get the power framework helper to initialize its settings for this
// component-specific queue
//
status = PfhInitializeComponentQueueSettings(devExt->Queue[i],
PfhInitializer);
if (FALSE == NT_SUCCESS(status)) {
goto exit;
}
}
status = STATUS_SUCCESS;
exit:
return status;
}
NTSTATUS
MCompEvtDeviceAdd(
_In_ WDFDRIVER Driver,
_Inout_ PWDFDEVICE_INIT DeviceInit
)
/*++
Routine Description:
EvtDeviceAdd is called by the framework in response to AddDevice call from
the PnP manager.
Arguments:
Driver - Handle to the framework driver object created in DriverEntry
DeviceInit - Pointer to a framework-allocated WDFDEVICE_INIT structure.
Return Value:
An NTSTATUS value representing success or failure of the function.
--*/
{
NTSTATUS status;
WDFOBJECT pfhInitializer = NULL;
WDFDEVICE device = NULL;
WDF_IO_QUEUE_CONFIG ioQueueConfig;
WDFQUEUE sourceQueue = NULL;
PAGED_CODE();
UNREFERENCED_PARAMETER(Driver);
//
// Create an initializer object for the power framework helper
//
status = PfhInitializerCreate(&pfhInitializer);
if (FALSE == NT_SUCCESS(status)) {
goto exit;
}
//
// Create the device object
//
status = CreateDevice(pfhInitializer, DeviceInit, &device);
if (FALSE == NT_SUCCESS(status)) {
goto exit;
}
//
// Create the source queue.
//
WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&ioQueueConfig,
WdfIoQueueDispatchParallel);
ioQueueConfig.EvtIoDeviceControl = MCompEvtIoDeviceControlPrimary;
//
// By default, Static Driver Verifier (SDV) displays a warning if it
// doesn't find the EvtIoStop callback on a power-managed queue.
// The 'assume' below causes SDV to suppress this warning. If the driver
// has not explicitly set PowerManaged to WdfFalse, the framework creates
// power-managed queues when the device is not a filter driver. Normally
// the EvtIoStop is required for power-managed queues, but for this driver
// it is not needed b/c the driver doesn't hold on to the requests or
// forward them to other drivers. This driver completes the requests
// directly in the queue's handlers. If the EvtIoStop callback is not
// implemented, the framework waits for all driver-owned requests to be
// done before moving in the Dx/sleep states or before removing the
// device, which is the correct behavior for this type of driver.
// If the requests were taking an indeterminate amount of time to complete,
// or if the driver forwarded the requests to a lower driver/another stack,
// the queue should have an EvtIoStop/EvtIoResume.
//
__analysis_assume(ioQueueConfig.EvtIoStop != 0);
status = WdfIoQueueCreate(device,
&ioQueueConfig,
WDF_NO_OBJECT_ATTRIBUTES,
&sourceQueue);
__analysis_assume(ioQueueConfig.EvtIoStop == 0);
if (FALSE == NT_SUCCESS(status)) {
Trace(TRACE_LEVEL_ERROR,
"%!FUNC! - WdfIoQueueCreate failed with %!status! when creating "
"source queue.",
status);
goto exit;
}
//
// Initialize power framework settings
//
status = InitializePowerFrameworkSettings(device);
if (FALSE == NT_SUCCESS(status)) {
goto exit;
}
//
// Create the component queues
//
status = CreateComponentQueues(pfhInitializer, device);
if (FALSE == NT_SUCCESS(status)) {
goto exit;
}
//
// Create a device interface so that applications can open a handle to this
// device.
//
status = WdfDeviceCreateDeviceInterface(device,
&GUID_DEVINTERFACE_POWERFX,
NULL /* ReferenceString */);
if (FALSE == NT_SUCCESS(status)) {
Trace(TRACE_LEVEL_ERROR,
"%!FUNC! - WdfDeviceCreateDeviceInterface failed with %!status!.",
status);
goto exit;
}
//
// Initialize the hardware simulator
//
status = HwSimInitialize(device);
if (FALSE == NT_SUCCESS(status)) {
goto exit;
}
status = STATUS_SUCCESS;
exit:
if (NULL != pfhInitializer) {
WdfObjectDelete(pfhInitializer);
}
return status;
}
NTSTATUS
MCompPoHandleAvailable(
_In_ WDFDEVICE Device,
_In_ POHANDLE PoHandle
)
{
PDEVICE_EXTENSION devExt = NULL;
ULONG i;
//
// Get the device extension
//
devExt = DeviceGetData(Device);
//
// Save the POHANDLE
//
devExt->PoHandle = PoHandle;
//
// Provide latency and residency hints to enable the power framework to
// select lower-powered F-states when we are idle.
//
for (i=0; i < COMPONENT_COUNT; i++) {
PoFxSetComponentLatency(
PoHandle,
i,
(TRANSITION_LATENCY_F1 + 1)
);
PoFxSetComponentResidency(
PoHandle,
i,
(RESIDENCY_REQUIREMENT_F1 + 1)
);
}
return STATUS_SUCCESS;
}
VOID
MCompPoHandleUnavailable(
_In_ WDFDEVICE Device,
_In_ POHANDLE PoHandle
)
{
PDEVICE_EXTENSION devExt = NULL;
//
// Get the device extension
//
devExt = DeviceGetData(Device);
//
// Clear the POHANDLE. It is not guaranteed to remain valid after we return
// from this callback.
//
devExt->PoHandle = PoHandle;
return;
}
NTSTATUS
MCompEvtDeviceD0Entry(
_In_ WDFDEVICE Device,
_In_ WDF_POWER_DEVICE_STATE PreviousState
)
/*++
Routine Description:
In this routine the driver enters D0
Arguments:
Device - Handle to the framework device object
PreviousState - Previous device power state
Return Value:
An NTSTATUS value representing success or failure of the function.
--*/
{
UNREFERENCED_PARAMETER(PreviousState);
HwSimD0Entry(Device);
return STATUS_SUCCESS;
}
NTSTATUS
MCompEvtDeviceD0Exit(
_In_ WDFDEVICE Device,
_In_ WDF_POWER_DEVICE_STATE TargetState
)
/*++
Routine Description:
In this routine the driver leaves D0
Arguments:
Device - Handle to the framework device object
TargetState - Device power state that the device is about to enter
Return Value:
An NTSTATUS value representing success or failure of the function.
--*/
{
PAGED_CODE();
UNREFERENCED_PARAMETER(TargetState);
HwSimD0Exit(Device);
return STATUS_SUCCESS;
}
VOID
MCompComponentIdleStateCallback(
_In_ PVOID Context,
_In_ ULONG Component,
_In_ ULONG State
)
/*++
Routine Description:
The power framework helper invokes this routine to change the F-state of one
of our components.
Arguments:
Context - Context that we passed in to our power framework helper module
when we asked it to register with the power framework helper on our behalf
Component - Index of component for which the F-state change is to be made
State - The new F-state to transition the component to
Return Value:
None
--*/
{
PDEVICE_EXTENSION devExt = NULL;
WDFDEVICE device = NULL;
//
// Get the device object handle
//
device = (WDFDEVICE) Context;
//
// Get the device extension
//
devExt = DeviceGetData(device);
//
// Change the F-state of the component
// This includes hardware-specific operations such as:
// * disabling/enabling DMA capabilities associated with the component
// * disabling/enabling interrupts associated with the component
// * saving/restoring component state
//
HwSimFStateChange(device, Component, State);
//
// F-state transition complete
//
PoFxCompleteIdleState(devExt->PoHandle, Component);
return;
}
VOID
MCompEvtIoDeviceControlPrimary(
_In_ WDFQUEUE Queue,
_In_ WDFREQUEST Request,
_In_ size_t OutputBufferLength,
_In_ size_t InputBufferLength,
_In_ ULONG IoControlCode
)
/*++
Routine Description:
This routine is the IOCTL handler for the device's primary queue
Arguments:
Queue - Handle to the framework queue object for the primary queue
Request - Handle to the framework request object for IOCTL being dispatched
OutputBufferLength - Output buffer length for IOCTL
InputBufferLength - Input buffer length for IOCTL
IoControlCode - IOCTL code
Return Value:
None
--*/
{
NTSTATUS status;
PPOWERFX_READ_COMPONENT_INPUT inputBuffer = NULL;
WDFDEVICE device = NULL;
PDEVICE_EXTENSION devExt = NULL;
WDFQUEUE componentQueue = NULL;
ULONG component;
UNREFERENCED_PARAMETER(OutputBufferLength);
switch (IoControlCode) {
case IOCTL_POWERFX_READ_COMPONENT:
{
//
// Validate input buffer length
//
if (InputBufferLength != sizeof(*inputBuffer)) {
status = STATUS_INVALID_PARAMETER;
Trace(TRACE_LEVEL_ERROR,
"%!FUNC! -Invalid input buffer size. Expected: %d. "
"Actual: %I64u. %!status!.",
sizeof(*inputBuffer),
InputBufferLength,
status);
goto exit;
}
//
// Identify the component that we need to read in order to satisfy
// this request
//
status = WdfRequestRetrieveInputBuffer(Request,
sizeof(*inputBuffer),
(PVOID*) &inputBuffer,
NULL // Length
);
if (FALSE == NT_SUCCESS(status)) {
Trace(TRACE_LEVEL_ERROR,
"%!FUNC! - WdfRequestRetrieveInputBuffer failed with "
"%!status!.",
status);
goto exit;
}
component = inputBuffer->ComponentNumber;
//
// Identify the queue corresponding to the above component
//
device = WdfIoQueueGetDevice(Queue);
devExt = DeviceGetData(device);
componentQueue = devExt->Queue[component];
}
break;
default:
{
status = STATUS_INVALID_PARAMETER;
Trace(TRACE_LEVEL_ERROR,
"%!FUNC! - Unexpected IOCTL code %d. %!status!.",
IoControlCode,
status);
goto exit;
}
}
//
// Forward the request to the appropriate queue. We do this via the power
// framework helper so that it can take a power reference on behalf of the
// request.
//
PfhForwardRequestToQueue(Request, componentQueue);
status = STATUS_SUCCESS;
exit:
if (FALSE == NT_SUCCESS(status)) {
//
// Complete the request in case of failure. In case of success, we would
// have dispatched the request to the component-specific queue, so we
// don't need to complete it here.
//
PfhCompleteRequest(Request, status, 0 /* Information */);
}
return;
}
VOID
MCompEvtIoDeviceControlSecondary(
_In_ WDFQUEUE Queue,
_In_ WDFREQUEST Request,
_In_ size_t OutputBufferLength,
_In_ size_t InputBufferLength,
_In_ ULONG IoControlCode
)
/*++
Routine Description:
This routine is the IOCTL handler for the device's secondary queue (i.e.
component-specific queue).
Arguments:
Queue - Handle to the framework queue object for the secondary queue
Request - Handle to the framework request object for IOCTL being dispatched
OutputBufferLength - Output buffer length for IOCTL
InputBufferLength - Input buffer length for IOCTL
IoControlCode - IOCTL code
Return Value:
None
--*/
{
NTSTATUS status;
PPOWERFX_READ_COMPONENT_INPUT inputBuffer = NULL;
PPOWERFX_READ_COMPONENT_OUTPUT outputBuffer = NULL;
WDFDEVICE device = NULL;
ULONG component;
ULONG componentData;
ULONG_PTR information = 0;
//
// When we complete the request, make sure we don't get the I/O manager to
// copy any more data to the client address space than what we write to the
// output buffer. The only data that we write to the output buffer is the
// component data and the C_ASSERT below ensures that the output buffer does
// not have room to contain anything other than that.
//
C_ASSERT(sizeof(componentData) == sizeof(*outputBuffer));
UNREFERENCED_PARAMETER(InputBufferLength);
UNREFERENCED_PARAMETER(IoControlCode);
//
// The following ASSERTMSG checks should have already been made by the IOCTL
// dispatch routine for the primary queue. That routine should have
// completed the request with failure if the checks had failed. Therefore we
// only use ASSERTMSG here.
//
ASSERTMSG("Unexpected IOCTL code\n",
IOCTL_POWERFX_READ_COMPONENT == IoControlCode);
ASSERTMSG("Invalid input buffer size",
InputBufferLength == sizeof(*inputBuffer));
//
// Validate output buffer length
//
if (OutputBufferLength != sizeof(*outputBuffer)) {
status = STATUS_INVALID_PARAMETER;
Trace(TRACE_LEVEL_ERROR,
"%!FUNC! -Invalid input buffer size. Expected: %d. Actual: %I64u."
" %!status!.",
sizeof(*outputBuffer),
OutputBufferLength,
status);
goto exit;
}
//
// Identify the component that we need to read in order to satisfy
// this request.
//
status = WdfRequestRetrieveInputBuffer(Request,
sizeof(*inputBuffer),
(PVOID*) &inputBuffer,
NULL // Length
);
if (FALSE == NT_SUCCESS(status)) {
Trace(TRACE_LEVEL_ERROR,
"%!FUNC! - WdfRequestRetrieveInputBuffer failed with %!status!.",
status);
goto exit;
}
component = inputBuffer->ComponentNumber;
//
// Get the output buffer
//
status = WdfRequestRetrieveOutputBuffer(Request,
sizeof(*outputBuffer),
(PVOID*) &outputBuffer,
NULL // Length
);
if (FALSE == NT_SUCCESS(status)) {
Trace(TRACE_LEVEL_ERROR,
"%!FUNC! - WdfRequestRetrieveOutputBuffer failed with %!status!.",
status);
goto exit;
}
//
// Read the data from the component
//
device = WdfIoQueueGetDevice(Queue);
componentData = HwSimReadComponent(device, component);
outputBuffer->ComponentData = componentData;
information = sizeof(*outputBuffer);
status = STATUS_SUCCESS;
exit:
//
// Complete the request
//
PfhCompleteRequest(Request, status, information);
return;
}
| 13,779 |
816 |
<filename>src/main/java/org/mybatis/dynamic/sql/Callback.java
/*
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.dynamic.sql;
import java.util.function.Function;
@FunctionalInterface
public interface Callback {
void call();
static Callback exceptionThrowingCallback(String message) {
return exceptionThrowingCallback(message, RuntimeException::new);
}
static Callback exceptionThrowingCallback(String message,
Function<String, ? extends RuntimeException> exceptionBuilder) {
return () -> {
throw exceptionBuilder.apply(message);
};
}
}
| 384 |
348 |
{"nom":"Lieuron","circ":"4ème circonscription","dpt":"Ille-et-Vilaine","inscrits":585,"abs":309,"votants":276,"blancs":1,"nuls":0,"exp":275,"res":[{"nuance":"SOC","nom":"<NAME>","voix":106},{"nuance":"REM","nom":"<NAME>","voix":70},{"nuance":"FI","nom":"<NAME>","voix":42},{"nuance":"FN","nom":"<NAME>","voix":29},{"nuance":"LR","nom":"<NAME>","voix":13},{"nuance":"DLF","nom":"Mme <NAME>","voix":5},{"nuance":"ECO","nom":"Mme <NAME>","voix":4},{"nuance":"EXG","nom":"Mme <NAME>","voix":2},{"nuance":"EXD","nom":"Mme <NAME>","voix":2},{"nuance":"ECO","nom":"Mme <NAME>","voix":1},{"nuance":"DVG","nom":"<NAME>","voix":1},{"nuance":"DIV","nom":"Mme <NAME>","voix":0}]}
| 272 |
488 |
<filename>projects/RTC2/tests/unsorted/seq_examples/pointer_example_class3_trans.cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdint.h>
#define PTR_SIZE 100
#define PTR2_SIZE 10
#define PTR3_SIZE 10
#define OUT_OF_BOUNDS_EXCESS 1
struct VoidStruct
{
void *L;
void *H;
uint64_t* lock_loc;
uint64_t key;
}
;
class User_structed
{
public:
struct VoidStruct tracking_struct;
public: struct VoidStruct user_ptr1_structed;
}
;
struct User{
float* user_ptr1;
};
class Base_structed
{
public:
struct VoidStruct tracking_struct;
public: struct VoidStruct *ptr1_structed;
struct VoidStruct *ptr2_structed;
struct VoidStruct *ptr3_structed;
struct VoidStruct *ptr4_structed;
class User_structed *str_ptr1_structed;
#if 0
virtual void print() {
int* print_ptr1;
printf("This is base class\n");
}
#endif
}
;
class Base{
unsigned int *ptr1;
unsigned int *ptr2;
unsigned int var1;
char var2;
float var3;
float* ptr3;
unsigned int *ptr4;
struct User *str_ptr1;
public:
virtual void print() {
int* print_ptr1;
printf("This is base class\n");
}
};
class Derived1_structed : public Base_structed
{
public:
struct VoidStruct tracking_struct;
public: struct VoidStruct *der1_ptr1_structed;
struct VoidStruct *der1_ptr2_structed;
}
;
class Derived1 : public Base {
unsigned int* der1_ptr1;
float* der1_ptr2;
public:
void print() {
int* print_ptr1;
printf("This is Derived1 class\n");
}
};
class Derived2_structed : public Derived1_structed
{
public:
struct VoidStruct tracking_struct;
public: struct VoidStruct *der2_ptr1_structed;
struct VoidStruct *der2_ptr2_structed;
class Base_structed *der2_base_ptr1_structed;
class Derived1 der2_der1_obj_structed;
}
;
class Derived2 : public Derived1 {
unsigned int* der2_ptr1;
float* der2_ptr2;
class Base* der2_base_ptr1;
class Derived1 der2_der1_obj;
public:
void print() {
int* print_ptr1;
printf("This is Derived2 class\n");
}
};
struct BasePtr_Struct {
class Base* obj;
class Base_structed* tracker;
};
struct Base_Struct {
class Base obj;
class Base_structed tracker;
};
struct Derived1Ptr_Struct {
class Derived1* obj;
class Derived1_structed *tracker;
};
struct Derived1_Struct {
class Derived1 obj;
class Derived1_structed tracker;
};
struct Derived2Ptr_Struct {
class Derived2* obj;
class Derived2_structed* tracker;
};
struct Derived2_Struct {
class Derived2_structed obj;
class Derived2_structed tracker;
};
struct VoidPtr_Struct {
void* obj;
struct VoidStruct* tracker;
};
struct BasePtr_Struct fn1(struct VoidPtr_Struct input1_structed, char input4, struct VoidPtr_Struct input2_structed,
struct Derived2Ptr_Struct input3_structed, struct Base_Struct input5_structed) {
struct BasePtr_Struct baseptr_structed = {dynamic_cast<class Base*>(input3_structed.obj),
dynamic_cast<class Base_structed*>(input3_structed.tracker)};
return baseptr_structed;
}
#if 0
struct ArgStruct fn1(struct ArgStruct input1_structed, char input4, struct ArgStruct input2_structed,
struct ArgStruct input3_structed, struct ArgStruct input5_structed) {
return input3_structed;
}
class Base* fn1(int* input1, char input4, float* input2, class Derived2* input3, class Base input5) {
return dynamic_cast<class Base*>(input3);
}
#endif
void Check_Deref(void* ptr) {}
int main() {
int *ptr = (int*)malloc(PTR_SIZE*sizeof(int));
struct VoidStruct* ptr_structed;
int *ptr2 = (int*)malloc(PTR2_SIZE*sizeof(int));
struct VoidStruct* ptr2_structed;
class Base base_obj;
class Base_structed base_obj_structed;
class Base* base_ptr = new class Base;
class Base_structed* base_ptr_structed = new class Base_structed;
Check_Deref(base_ptr_structed);
base_ptr->print();
class Base* base_ptr2 = base_ptr;
class Base_structed* base_ptr2_structed = base_ptr_structed;
Check_Deref(base_ptr_structed);
base_ptr->print();
class Derived1 der1_obj;
class Derived1_structed der1_obj_structed;
base_ptr = &der1_obj;
base_ptr_structed = &der1_obj_structed;
Check_Deref((static_cast<class Derived1_structed*>(base_ptr_structed)));
// Check_Deref((dynamic_cast<class Derived1_structed*>(base_ptr_structed)));
(dynamic_cast<class Derived1*>(base_ptr))->print();
class Derived2* der2_ptr = new class Derived2;
class Derived2_structed* der2_ptr_structed = new class Derived2_structed;
base_ptr = der2_ptr;
base_ptr_structed = der2_ptr_structed;
Check_Deref(static_cast<class Derived2_structed*>(base_ptr_structed));
// Check_Deref(dynamic_cast<class Derived2_structed*>(base_ptr_structed));
(dynamic_cast<class Derived2*>(base_ptr))->print();
//der2_ptr = dynamic_cast<class Derived2*>(fn1(ptr, 'a', (float*)ptr2, der2_ptr, base_obj));
// int*
struct VoidPtr_Struct input1;
input1.obj = ptr;
input1.tracker = ptr_structed;
// float*
struct VoidPtr_Struct input2;
input2.obj = (float*)ptr2;
input2.tracker = ptr2_structed;
// Derived2 arg
struct Derived2Ptr_Struct der2Arg;
der2Arg.obj = der2_ptr;
der2Arg.tracker = der2_ptr_structed;
// Base arg
struct Base_Struct baseArg;
baseArg.obj = base_obj;
baseArg.tracker = base_obj_structed;
struct BasePtr_Struct basePtr_Str;
basePtr_Str = fn1(input1, 'a', input2, der2Arg, baseArg);
der2_ptr = dynamic_cast<class Derived2*>(basePtr_Str.obj);
der2_ptr_structed = dynamic_cast<class Derived2_structed*>(basePtr_Str.tracker);
int* start_ptr = ptr;
int* start_ptr2 = ptr2;
// Crossing the boundary of ptr. The condition should
// be less than, not less than or equal to
// ptr[PTR_SIZE] is an out-of-bounds access
for(int index = 0; index <= (PTR_SIZE + OUT_OF_BOUNDS_EXCESS); index++) {
*ptr = index;
ptr++;
}
// Resetting ptr to start_ptr, so that it points to the beginning
// of the allocation
ptr = start_ptr;
// Printing what we wrote above
for(int index = 0; index <= (PTR_SIZE + OUT_OF_BOUNDS_EXCESS); index++) {
printf("ptr[%d]=%d\n", index, *ptr);
ptr++;
}
return 1;
}
| 2,605 |
473 |
<gh_stars>100-1000
/*
Author: <NAME> <<EMAIL>>
Copyright (c) 2014 Cromulence LLC
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.
*/
#include "cgc_service.h"
#include "cgc_stdlib.h"
int cgc_dive_statistics(logbook_type *Info) {
char buf[1024];
int rcv_cnt;
int dive_count = 0;
int sum_max_depths = 0;
int max_depth_count = 0;
int sum_dive_lengths = 0;
int dive_lengths_count = 0;
dive_log_type *next_dive;
cgc_printf("\n");
if (Info->dives == 0) {
cgc_printf("No dives are logged\n");
return -1;
}
next_dive = Info->dives;
while (next_dive != 0) {
++dive_count;
if (next_dive->max_depth > 0) {
sum_max_depths+= next_dive->max_depth;
++max_depth_count;
}
if (next_dive->dive_length > 0) {
sum_dive_lengths+= next_dive->dive_length;
++dive_lengths_count;
}
next_dive = next_dive->next;
} // while
cgc_printf("Dives logged: @d\n", dive_count);
if (max_depth_count > 0)
cgc_printf("Average Max Depth: @d\n", sum_max_depths/max_depth_count);
else
cgc_printf("Average Max Depth: 0\n");
if (dive_lengths_count > 0)
cgc_printf("Average Dive Length: @d\n", sum_dive_lengths/dive_lengths_count);
else
cgc_printf("Average Dive Length: 0\n");
return 0;
}
| 796 |
1,442 |
#include "calculator.h"
#include <shared/drivers/serial_number.h>
#include <ion.h>
#include <ion/usb.h>
#include <shared/drivers/usb.h>
namespace Ion {
namespace Device {
namespace USB {
void Calculator::PollAndReset() {
/* Don't use Ion::serialNumber to avoid any data section in the relocatable
* dfu. */
char serialNumber[Ion::k_serialNumberLength+1];
SerialNumber::copy(serialNumber);
Calculator c(serialNumber, USB::stringDescriptor());
while (Ion::USB::isPlugged() && !c.isSoftDisconnected() && !(USB::shouldInterruptDFU() && !c.isErasingAndWriting())) {
c.poll();
}
if (!c.isSoftDisconnected()) {
c.detach();
}
if (c.resetOnDisconnect()) {
c.leave(c.addressPointer());
}
}
Descriptor * Calculator::descriptor(uint8_t type, uint8_t index) {
/* Special case: Microsoft OS String Descriptor should be returned when
* searching for string descriptor at index 0xEE. */
if (type == m_microsoftOSStringDescriptor.type() && index == 0xEE) {
return &m_microsoftOSStringDescriptor;
}
int typeCount = 0;
for (size_t i=0; i<sizeof(m_descriptors)/sizeof(m_descriptors[0]); i++) {
Descriptor * descriptor = m_descriptors[i];
if (descriptor->type() != type) {
continue;
}
if (typeCount == index) {
return descriptor;
} else {
typeCount++;
}
}
return nullptr;
}
bool Calculator::processSetupInRequest(SetupPacket * request, uint8_t * transferBuffer, uint16_t * transferBufferLength, uint16_t transferBufferMaxLength) {
if (Device::processSetupInRequest(request, transferBuffer, transferBufferLength, transferBufferMaxLength)) {
return true;
}
if (request->requestType() == SetupPacket::RequestType::Vendor) {
if (request->bRequest() == k_webUSBVendorCode && request->wIndex() == 2) {
// This is a WebUSB, GET_URL request
assert(request->wValue() == k_webUSBLandingPageIndex);
return getURLCommand(transferBuffer, transferBufferLength, transferBufferMaxLength);
}
if (request->bRequest() == k_microsoftOSVendorCode && request->wIndex() == 0x0004) {
// This is a Microsoft OS descriptor, Extended Compat ID request
assert(request->wValue() == 0);
return getExtendedCompatIDCommand(transferBuffer, transferBufferLength, transferBufferMaxLength);
}
}
return false;
}
bool Calculator::getURLCommand(uint8_t * transferBuffer, uint16_t * transferBufferLength, uint16_t transferBufferMaxLength) {
*transferBufferLength = m_workshopURLDescriptor.copy(transferBuffer, transferBufferMaxLength);
return true;
}
bool Calculator::getExtendedCompatIDCommand(uint8_t * transferBuffer, uint16_t * transferBufferLength, uint16_t transferBufferMaxLength) {
*transferBufferLength = m_extendedCompatIdDescriptor.copy(transferBuffer, transferBufferMaxLength);
return true;
}
}
}
}
| 963 |
438 |
import numpy as np
from .base import BaseMetric
from .registry import METRICS
class Compose:
def __init__(self, metrics):
self.metrics = metrics
def reset(self):
for m in self.metrics:
m.reset()
def accumulate(self):
res = dict()
for m in self.metrics:
mtc = m.accumulate()
res.update(mtc)
return res
def __call__(self, pred, target):
for m in self.metrics:
m(pred, target)
class ConfusionMatrix(BaseMetric):
"""
Calculate confusion matrix for segmentation
Args:
num_classes (int): number of classes.
"""
def __init__(self, num_classes):
self.num_classes = num_classes
super().__init__()
def reset(self):
self.cfsmtx = np.zeros((self.num_classes,) * 2)
def compute(self, pred, target):
mask = (target >= 0) & (target < self.num_classes)
self.current_state = np.bincount(
self.num_classes * target[mask].astype('int') + pred[mask],
minlength=self.num_classes ** 2
).reshape(self.num_classes, self.num_classes)
return self.current_state
def update(self, n=1):
self.cfsmtx += self.current_state
def accumulate(self):
accumulate_state = {
'confusion matrix': self.cfsmtx
}
return accumulate_state
class MultiLabelConfusionMatrix(BaseMetric):
"""
Calculate confusion matrix for multi label segmentation
Args:
num_classes (int): number of classes.
"""
def __init__(self, num_classes):
self.num_classes = num_classes
self.binary = 2
self.current_state = np.zeros(
(self.num_classes, self.binary, self.binary))
super().__init__()
@staticmethod
def _check_match(pred, target):
assert pred.shape == target.shape, \
"pred should habe same shape with target"
def reset(self):
self.cfsmtx = np.zeros((self.num_classes, self.binary, self.binary))
def compute(self, pred, target):
mask = (target >= 0) & (target < self.binary)
for i in range(self.num_classes):
pred_index_sub = pred[:, i, :, :]
target_sub = target[:, i, :, :]
mask_sub = mask[:, i, :, :]
self.current_state[i, :, :] = np.bincount(
self.binary * target_sub[mask_sub].astype('int') +
pred_index_sub[mask_sub], minlength=self.binary ** 2
).reshape(self.binary, self.binary)
return self.current_state
def update(self, n=1):
self.cfsmtx += self.current_state
def accumulate(self):
accumulate_state = {
'confusion matrix': self.cfsmtx
}
return accumulate_state
@METRICS.register_module
class Accuracy(ConfusionMatrix):
"""
Calculate accuracy based on confusion matrix for segmentation
Args:
num_classes (int): number of classes.
average (str): {'pixel', 'class'}
'pixel':
calculate pixel wise average accuracy
'class':
calculate class wise average accuracy
"""
def __init__(self, num_classes, average='pixel'):
self.num_classes = num_classes
self.average = average
super().__init__(num_classes=self.num_classes)
def accumulate(self):
assert self.average in ('pixel', 'class'), \
'Accuracy only support "pixel" & "class" wise average'
if self.average == 'pixel':
accuracy = self.cfsmtx.diagonal().sum() / (
self.cfsmtx.sum() + 1e-15)
elif self.average == 'class':
accuracy_class = self.cfsmtx.diagonal() / self.cfsmtx.sum(axis=1)
accuracy = np.nanmean(accuracy_class)
accumulate_state = {
'accuracy': accuracy
}
return accumulate_state
@METRICS.register_module
class MultiLabelIoU(MultiLabelConfusionMatrix):
def __init__(self, num_classes):
super().__init__(num_classes)
def accumulate(self):
ious = self.cfsmtx.diagonal(axis1=1, axis2=2) / (
self.cfsmtx.sum(axis=1) + self.cfsmtx.sum(axis=2) -
self.cfsmtx.diagonal(axis1=1, axis2=2) + np.finfo(
np.float32).eps)
accumulate_state = {
'IoUs': ious[:, 1]
}
return accumulate_state
@METRICS.register_module
class MultiLabelMIoU(MultiLabelIoU):
def __init__(self, num_classes):
super().__init__(num_classes)
def accumulate(self):
ious = (super().accumulate())['IoUs']
accumulate_state = {
'mIoU': np.nanmean(ious)
}
return accumulate_state
@METRICS.register_module
class IoU(ConfusionMatrix):
"""
Calculate IoU for each class based on confusion matrix for segmentation
Args:
num_classes (int): number of classes.
"""
def __init__(self, num_classes):
self.num_classes = num_classes
super().__init__(num_classes=self.num_classes)
def accumulate(self):
ious = self.cfsmtx.diagonal() / (
self.cfsmtx.sum(axis=0) + self.cfsmtx.sum(axis=1) -
self.cfsmtx.diagonal() + np.finfo(np.float32).eps)
accumulate_state = {
'IoUs': ious
}
return accumulate_state
@METRICS.register_module
class MIoU(IoU):
"""
Calculate mIoU based on confusion matrix for segmentation
Args:
num_classes (int): number of classes.
average (str): {'equal', 'frequency_weighted'}
'equal':
calculate mIoU in an equal class wise average manner
'frequency_weighted':
calculate mIoU in an frequency weighted class wise average manner
"""
def __init__(self, num_classes, average='equal'):
self.num_classes = num_classes
self.average = average
super().__init__(num_classes=self.num_classes)
def accumulate(self):
assert self.average in ('equal', 'frequency_weighted'), \
'mIoU only support "equal" & "frequency_weighted" average'
ious = (super().accumulate())['IoUs']
if self.average == 'equal':
miou = np.nanmean(ious)
elif self.average == 'frequency_weighted':
pos_freq = self.cfsmtx.sum(axis=1) / self.cfsmtx.sum()
miou = (pos_freq[pos_freq > 0] * ious[pos_freq > 0]).sum()
accumulate_state = {
'mIoU': miou
}
return accumulate_state
class DiceScore(ConfusionMatrix):
"""
Calculate dice score based on confusion matrix for segmentation
Args:
num_classes (int): number of classes.
"""
def __init__(self, num_classes):
self.num_classes = num_classes
super().__init__(self.num_classes)
def accumulate(self):
dice_score = 2.0 * self.cfsmtx.diagonal() / (self.cfsmtx.sum(axis=1) +
self.cfsmtx.sum(axis=0) +
np.finfo(np.float32).eps)
accumulate_state = {
'dice_score': dice_score
}
return accumulate_state
| 3,332 |
1,192 |
<gh_stars>1000+
///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaEnumTable.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include <array>
#include "dia2.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include "DxilDia.h"
#include "DxilDiaTable.h"
namespace dxil_dia {
class Session;
class EnumTables : public IDiaEnumTables {
private:
DXC_MICROCOM_TM_REF_FIELDS()
protected:
CComPtr<Session> m_pSession;
unsigned m_next;
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) {
return DoBasicQueryInterface<IDiaEnumTables>(this, iid, ppvObject);
}
EnumTables(IMalloc *pMalloc, Session *pSession)
: m_pMalloc(pMalloc), m_pSession(pSession), m_dwRef(0), m_next(0) {
m_tables.fill(nullptr);
}
STDMETHODIMP get__NewEnum(
/* [retval][out] */ IUnknown **pRetVal) override { return ENotImpl(); }
STDMETHODIMP get_Count(_Out_ LONG *pRetVal) override;
STDMETHODIMP Item(
/* [in] */ VARIANT index,
/* [retval][out] */ IDiaTable **table) override;
STDMETHODIMP Next(
ULONG celt,
IDiaTable **rgelt,
ULONG *pceltFetched) override;
STDMETHODIMP Skip(
/* [in] */ ULONG celt) override { return ENotImpl(); }
STDMETHODIMP Reset(void) override;
STDMETHODIMP Clone(
/* [out] */ IDiaEnumTables **ppenum) override { return ENotImpl(); }
static HRESULT Create(Session *pSession,
IDiaEnumTables **ppEnumTables);
private:
std::array<CComPtr<IDiaTable>, (int)Table::LastKind+1> m_tables;
};
} // namespace dxil_dia
| 1,111 |
5,156 |
<filename>src/test/detach_sigkill_exit.c
/* -*- Mode: C; tab-width: 8; c-basic-offset: 2; indent-tabs-mode: nil; -*- */
#include "util_internal.h"
static int parent_to_child[2];
static int child_to_parent[2];
int main(__attribute__((unused)) int argc,
__attribute__((unused)) char **argv) {
int status;
char ch;
pid_t pid;
siginfo_t sig;
test_assert(0 == pipe(parent_to_child));
test_assert(0 == pipe(child_to_parent));
if (0 == (pid = fork())) {
if (running_under_rr()) {
rr_detach_teleport();
}
// Signal that we are ready
test_assert(1 == read(parent_to_child[0], &ch, 1) && ch == 'y');
exit(24);
}
test_assert(1 == write(parent_to_child[1], "y", 1));
// Give the child a chance to finish exiting
test_assert(0 == waitid(P_PID, pid, &sig, WNOWAIT | WEXITED));
test_assert(sig.si_pid == pid && sig.si_code == CLD_EXITED && sig.si_status == 24);
// Now kill the detach proxy before reaping the child
kill(pid, SIGKILL);
// Let rr listen for the SIGKILL event
usleep(100);
test_assert(pid == waitpid(pid, &status, 0));
test_assert(WIFEXITED(status) && WEXITSTATUS(status) == 24);
atomic_puts("EXIT-SUCCESS");
return 0;
}
| 554 |
1,177 |
/*
* Copyright (c) 2018 jmjatlanta and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <graphene/chain/database.hpp>
#include <graphene/chain/htlc_evaluator.hpp>
#include <graphene/chain/htlc_object.hpp>
#include <graphene/chain/hardfork.hpp>
#include <graphene/chain/is_authorized_asset.hpp>
namespace graphene {
namespace chain {
namespace detail
{
void check_htlc_create_hf_bsip64(const fc::time_point_sec& block_time,
const htlc_create_operation& op, const asset_object& asset_to_transfer)
{
if (block_time < HARDFORK_CORE_BSIP64_TIME)
{
// memo field added at harfork BSIP64
// NOTE: both of these checks can be removed after hardfork time
FC_ASSERT( !op.extensions.value.memo.valid(),
"Memo unavailable until after HARDFORK BSIP64");
// HASH160 added at hardfork BSIP64
FC_ASSERT( !op.preimage_hash.is_type<fc::hash160>(),
"HASH160 unavailable until after HARDFORK BSIP64" );
}
else
{
// this can be moved to the normal non-hf checks after HF_BSIP64
// IF there were no restricted transfers before HF_BSIP64
FC_ASSERT( !asset_to_transfer.is_transfer_restricted()
|| op.from == asset_to_transfer.issuer || op.to == asset_to_transfer.issuer,
"Asset ${asset} cannot be transfered.", ("asset", asset_to_transfer.id) );
}
}
void check_htlc_redeem_hf_bsip64(const fc::time_point_sec& block_time,
const htlc_redeem_operation& op, const htlc_object* htlc_obj)
{
// TODO: The hardfork portion of this check can be removed if no HTLC redemptions are
// attempted on an HTLC with a 0 preimage size before the hardfork date.
if ( htlc_obj->conditions.hash_lock.preimage_size > 0U ||
block_time < HARDFORK_CORE_BSIP64_TIME )
FC_ASSERT(op.preimage.size() == htlc_obj->conditions.hash_lock.preimage_size,
"Preimage size mismatch.");
}
} // end of graphene::chain::details
optional<htlc_options> get_committee_htlc_options(graphene::chain::database& db)
{
return db.get_global_properties().parameters.extensions.value.updatable_htlc_options;
}
void_result htlc_create_evaluator::do_evaluate(const htlc_create_operation& o)
{
graphene::chain::database& d = db();
optional<htlc_options> htlc_options = get_committee_htlc_options(db());
FC_ASSERT(htlc_options, "HTLC Committee options are not set.");
// make sure the expiration is reasonable
FC_ASSERT( o.claim_period_seconds <= htlc_options->max_timeout_secs,
"HTLC Timeout exceeds allowed length" );
// make sure the preimage length is reasonable
FC_ASSERT( o.preimage_size <= htlc_options->max_preimage_size,
"HTLC preimage length exceeds allowed length" );
// make sure the sender has the funds for the HTLC
FC_ASSERT( d.get_balance( o.from, o.amount.asset_id) >= (o.amount), "Insufficient funds") ;
const auto& asset_to_transfer = o.amount.asset_id( d );
const auto& from_account = o.from( d );
const auto& to_account = o.to( d );
detail::check_htlc_create_hf_bsip64(d.head_block_time(), o, asset_to_transfer);
FC_ASSERT( is_authorized_asset( d, from_account, asset_to_transfer ),
"Asset ${asset} is not authorized for account ${acct}.",
( "asset", asset_to_transfer.id )( "acct", from_account.id ) );
FC_ASSERT( is_authorized_asset( d, to_account, asset_to_transfer ),
"Asset ${asset} is not authorized for account ${acct}.",
( "asset", asset_to_transfer.id )( "acct", to_account.id ) );
return void_result();
}
object_id_type htlc_create_evaluator::do_apply(const htlc_create_operation& o)
{
try {
graphene::chain::database& dbase = db();
dbase.adjust_balance( o.from, -o.amount );
const htlc_object& esc = db().create<htlc_object>([&dbase,&o]( htlc_object& esc ) {
esc.transfer.from = o.from;
esc.transfer.to = o.to;
esc.transfer.amount = o.amount.amount;
esc.transfer.asset_id = o.amount.asset_id;
esc.conditions.hash_lock.preimage_hash = o.preimage_hash;
esc.conditions.hash_lock.preimage_size = o.preimage_size;
if ( o.extensions.value.memo.valid() )
esc.memo = o.extensions.value.memo;
esc.conditions.time_lock.expiration = dbase.head_block_time() + o.claim_period_seconds;
});
return esc.id;
} FC_CAPTURE_AND_RETHROW( (o) )
}
class htlc_redeem_visitor
{
//private:
const std::vector<char>& data;
public:
typedef bool result_type;
htlc_redeem_visitor( const std::vector<char>& preimage )
: data( preimage ) {}
template<typename T>
bool operator()( const T& preimage_hash )const
{
return T::hash( (const char*)data.data(), (uint32_t) data.size() ) == preimage_hash;
}
};
void_result htlc_redeem_evaluator::do_evaluate(const htlc_redeem_operation& o)
{
auto& d = db();
htlc_obj = &d.get<htlc_object>(o.htlc_id);
detail::check_htlc_redeem_hf_bsip64(d.head_block_time(), o, htlc_obj);
const htlc_redeem_visitor vtor( o.preimage );
FC_ASSERT( htlc_obj->conditions.hash_lock.preimage_hash.visit( vtor ),
"Provided preimage does not generate correct hash.");
return void_result();
}
void_result htlc_redeem_evaluator::do_apply(const htlc_redeem_operation& o)
{
const auto amount = asset(htlc_obj->transfer.amount, htlc_obj->transfer.asset_id);
db().adjust_balance(htlc_obj->transfer.to, amount);
// notify related parties
htlc_redeemed_operation virt_op( htlc_obj->id, htlc_obj->transfer.from, htlc_obj->transfer.to, o.redeemer,
amount, htlc_obj->conditions.hash_lock.preimage_hash, htlc_obj->conditions.hash_lock.preimage_size,
o.preimage );
db().push_applied_operation( virt_op );
db().remove(*htlc_obj);
return void_result();
}
void_result htlc_extend_evaluator::do_evaluate(const htlc_extend_operation& o)
{
htlc_obj = &db().get<htlc_object>(o.htlc_id);
FC_ASSERT(o.update_issuer == htlc_obj->transfer.from, "HTLC may only be extended by its creator.");
optional<htlc_options> htlc_options = get_committee_htlc_options(db());
FC_ASSERT( htlc_obj->conditions.time_lock.expiration.sec_since_epoch()
+ static_cast<uint64_t>(o.seconds_to_add) < fc::time_point_sec::maximum().sec_since_epoch(),
"Extension would cause an invalid date");
FC_ASSERT( htlc_obj->conditions.time_lock.expiration + o.seconds_to_add
<= db().head_block_time() + htlc_options->max_timeout_secs,
"Extension pushes contract too far into the future" );
return void_result();
}
void_result htlc_extend_evaluator::do_apply(const htlc_extend_operation& o)
{
db().modify(*htlc_obj, [&o](htlc_object& db_obj) {
db_obj.conditions.time_lock.expiration += o.seconds_to_add;
});
return void_result();
}
} // namespace chain
} // namespace graphene
| 4,028 |
669 |
<filename>lib/tensor/tensor_type_registration.cc<gh_stars>100-1000
// Copyright 2020 The TensorFlow Runtime Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This file implements Tensor type and its registration.
#include "tfrt/tensor/tensor_type_registration.h"
#include <limits>
#include <tuple>
#include "llvm/Support/raw_ostream.h"
#include "tfrt/support/ref_count.h"
namespace tfrt {
llvm::raw_ostream& operator<<(llvm::raw_ostream& os,
const TensorType& tensor_type) {
os << "TensorType<name=" << tensor_type.name() << ">";
return os;
}
// Registry that contains all the TensorType registered.
class TensorTypeRegistry {
public:
TensorTypeRegistry(const TensorTypeRegistry&) = delete;
TensorTypeRegistry& operator=(const TensorTypeRegistry&) = delete;
// Each process should only have one TensorTypeRegistry.
static TensorTypeRegistry* GetInstance();
// Registers a new tensor type name. The tensor type name must be unique and
// haven't registered before.
TensorType RegisterTensorType(string_view tensor_type_name);
// Returns the registered tensor type.
TensorType GetRegisteredTensorType(string_view tensor_type_name) const;
string_view GetTensorTypeName(TensorType tensor_type) const;
private:
TensorTypeRegistry() = default;
// TODO(b/165864222): change to reader-write lock instead of mutex.
mutable mutex mu_;
llvm::SmallVector<std::string, 10> name_list_ TFRT_GUARDED_BY(mu_);
llvm::StringMap<int8_t> name_to_id_map_ TFRT_GUARDED_BY(mu_);
};
TensorTypeRegistry* TensorTypeRegistry::GetInstance() {
static TensorTypeRegistry* registry = new TensorTypeRegistry();
return registry;
}
TensorType TensorTypeRegistry::RegisterTensorType(
string_view tensor_type_name) {
mutex_lock l(mu_);
auto result = name_to_id_map_.try_emplace(tensor_type_name);
assert(result.second && "Re-registering existing tensor type name");
result.first->second = name_list_.size();
name_list_.emplace_back(tensor_type_name);
return TensorType(result.first->second);
}
TensorType TensorTypeRegistry::GetRegisteredTensorType(
string_view tensor_type_name) const {
mutex_lock l(mu_);
llvm::StringMap<int8_t>::const_iterator itr =
name_to_id_map_.find(tensor_type_name);
if (itr == name_to_id_map_.end()) {
return TensorType::kUnknownTensorType;
}
return TensorType(itr->second);
}
string_view TensorTypeRegistry::GetTensorTypeName(
TensorType tensor_type) const {
mutex_lock l(mu_);
int8_t id = tensor_type.id();
assert(id < name_list_.size() && "Invalid tensor type id");
return name_list_[id];
}
TensorType RegisterStaticTensorType(string_view tensor_type_name) {
return TensorTypeRegistry::GetInstance()->RegisterTensorType(
tensor_type_name);
}
TensorType GetStaticTensorType(string_view tensor_type_name) {
return TensorTypeRegistry::GetInstance()->GetRegisteredTensorType(
tensor_type_name);
}
string_view TensorType::name() const {
return TensorTypeRegistry::GetInstance()->GetTensorTypeName(*this);
}
const TensorType TensorType::kUnknownTensorType =
RegisterStaticTensorType("Unknown");
} // namespace tfrt
| 1,257 |
3,428 |
<gh_stars>1000+
{"id":"01415","group":"easy-ham-1","checksum":{"type":"MD5","value":"f3a2a0972d0e7c8490bcd79664be7db5"},"text":"From <EMAIL> Wed Sep 4 18:59:06 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy<EMAIL>.spamassassin.taint.org\nReceived: from localhost (jalapeno [1172.16.58.3])\n\tby jmason.org (Postfix) with ESMTP id 66F0116F56\n\tfor <jm@localhost>; Wed, 4 Sep 2002 18:58:55 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Wed, 04 Sep 2002 18:58:55 +0100 (IST)\nReceived: from outgoing.securityfocus.com (outgoing3.securityfocus.com\n [192.168.3.117]) by dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id\n g84HQfZ12414 for <<EMAIL>>; Wed, 4 Sep 2002 18:26:41 +0100\nReceived: from lists.securityfocus.com (lists.securityfocus.com\n [192.168.3.119]) by outgoing.securityfocus.com (Postfix) with QMQP id\n 3D51EA3600; Wed, 4 Sep 2002 10:55:41 -0600 (MDT)\nMailing-List: contact <EMAIL>; run by ezmlm\nPrecedence: bulk\nList-Id: <secprog.list-id.securityfocus.com>\nList-Post: <mailto:<EMAIL>>\nList-Help: <mailto:<EMAIL>>\nList-Unsubscribe: <mailto:<EMAIL>>\nList-Subscribe: <mailto:<EMAIL>>\nDelivered-To: mailing list <EMAIL>@<EMAIL>focus.<EMAIL>\nDelivered-To: moderator for <EMAIL>\nReceived: (qmail 4329 invoked from network); 4 Sep 2002 10:33:26 -0000\nMessage-Id: <<EMAIL>>\nDate: Wed, 04 Sep 2002 11:47:56 +0100\nFrom: <NAME> <<EMAIL>>\nUser-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.0.1)\n Gecko/20020815\nX-Accept-Language: en-us, en\nMIME-Version: 1.0\nTo: <NAME> <<EMAIL>>\nCc: <EMAIL>\nSubject: Re: Secure Sofware Key\nReferences: <<EMAIL>.<EMAIL>>\n <<EMAIL>>\n <<EMAIL>>\nX-Enigmail-Version: 0.63.3.0\nX-Enigmail-Supports: pgp-inline, pgp-mime\nContent-Type: text/plain; charset=ISO-8859-15; format=flowed\nContent-Transfer-Encoding: 7bit\n\n<NAME> wrote:\n> Is the use of \"trusted hardware\" really worth it ? Does it really make it \n> more secure ? Look at the DVDs.\n\nDVDs don't use trusted hardware. As for whether it is worth it, that \ndepends entirely on what its worth to secure your software.\n\nCheers,\n\nBen.\n\n-- \nhttp://www.apache-ssl.org/ben.html http://www.thebunker.net/\n\n\"There is no limit to what a man can do or how far he can go if he\ndoesn't mind who gets the credit.\" - <NAME>\n\n\n"}
| 980 |
33,622 |
from rich.color_triplet import ColorTriplet
def test_hex():
assert ColorTriplet(255, 255, 255).hex == "#ffffff"
assert ColorTriplet(0, 255, 0).hex == "#00ff00"
def test_rgb():
assert ColorTriplet(255, 255, 255).rgb == "rgb(255,255,255)"
assert ColorTriplet(0, 255, 0).rgb == "rgb(0,255,0)"
def test_normalized():
assert ColorTriplet(255, 255, 255).normalized == (1.0, 1.0, 1.0)
assert ColorTriplet(0, 255, 0).normalized == (0.0, 1.0, 0.0)
| 196 |
358 |
<reponame>AirGuanZ/Atrc<filename>src/editor/include/agz/editor/resource/pool/image_text_icon.h
#pragma once
#include <QLabel>
#include <QTimer>
#include <QVBoxLayout>
#include <QWidget>
#include <agz/editor/resource/thumbnail_provider.h>
AGZ_EDITOR_BEGIN
class ImageTextIcon : public QWidget
{
Q_OBJECT
public:
ImageTextIcon(QWidget *parent, const QFont &font, int image_size)
: QWidget(parent), image_size_(image_size)
{
QVBoxLayout *layout = new QVBoxLayout(this);
image_ = new QLabel(this);
text_ = new QLabel(this);
text_->setFont(font);
image_->setAlignment(Qt::AlignCenter);
text_->setAlignment(Qt::AlignCenter);
layout->addWidget(image_);
layout->addWidget(text_);
}
void set_text(const QString &text)
{
QFontMetrics metrix(text_->font());
QString clipped_text = metrix.elidedText(
text, Qt::ElideRight, image_size_);
text_->setText(clipped_text);
if(clipped_text != text)
setToolTip(text);
}
void set_image(Box<ResourceThumbnailProvider> thumbnail_provider)
{
thumbnail_provider_ = std::move(thumbnail_provider);
connect(thumbnail_provider_.get(), &ResourceThumbnailProvider::update_thumbnail,
this, &ImageTextIcon::set_pixmap);
image_->setPixmap(thumbnail_provider_->start());
}
void set_selected(bool selected)
{
is_selected_ = selected;
update_background_color();
}
bool is_selected() const noexcept
{
return is_selected_;
}
signals:
void clicked();
public slots:
void set_pixmap(QPixmap pixmap)
{
image_->setPixmap(pixmap);
}
protected:
void enterEvent(QEvent *event) override
{
is_in_ = true;
update_background_color();
}
void leaveEvent(QEvent *event) override
{
is_in_ = false;
is_pressed_ = false;
update_background_color();
}
void mousePressEvent(QMouseEvent *event) override
{
is_pressed_ = true;
update_background_color();
}
void mouseReleaseEvent(QMouseEvent *event) override
{
AGZ_SCOPE_GUARD({ update_background_color(); });
if(!is_pressed_)
return;
is_pressed_ = false;
emit clicked();
}
private:
void set_background_color(const QColor &color)
{
setAutoFillBackground(true);
QPalette pal = palette();
pal.setColor(QPalette::Window, color);
setPalette(pal);
}
void update_background_color()
{
static const QColor ORDINARY = QColor(Qt::transparent);
static const QColor HOVERED = QColor(75, 75, 75);
static const QColor PRESSED = QColor(100, 100, 100);
static const QColor SELECTED = QColor(100, 100, 100);
static const QColor SELECTED_HOVERED = QColor(125, 125, 125);
static const QColor SELECTED_PRESSED = QColor(75, 75, 75);
if(is_selected_)
{
if(is_in_)
{
if(is_pressed_)
set_background_color(SELECTED_PRESSED);
else
set_background_color(SELECTED_HOVERED);
}
else
set_background_color(SELECTED);
}
else
{
if(is_in_)
{
if(is_pressed_)
set_background_color(PRESSED);
else
set_background_color(HOVERED);
}
else
set_background_color(ORDINARY);
}
}
int image_size_;
QLabel *image_;
QLabel *text_;
bool is_in_ = false;
bool is_pressed_ = false;
bool is_selected_ = false;
Box<ResourceThumbnailProvider> thumbnail_provider_;
};
AGZ_EDITOR_END
| 1,896 |
2,025 |
#pragma once
#include <iostream>
#include <sstream>
#include <iod/utils.hh>
#include <silicon/symbols.hh>
namespace sl
{
using s::_primary_key;
using s::_auto_increment;
using s::_read_only;
namespace sql_orm_internals
{
auto remove_members_with_attribute = [] (const auto& o, const auto& a)
{
typedef std::decay_t<decltype(a)> A;
return foreach2(o) | [&] (auto& m)
{
typedef typename std::decay_t<decltype(m)>::attributes_type attrs;
return ::iod::static_if<!has_symbol<attrs, A>::value>(
[&] () { return m; },
[&] () {});
};
};
auto extract_members_with_attribute = [] (const auto& o, const auto& a)
{
typedef std::decay_t<decltype(a)> A;
return foreach2(o) | [&] (auto& m)
{
typedef typename std::decay_t<decltype(m)>::attributes_type attrs;
return ::iod::static_if<has_symbol<attrs, A>::value>(
[&] () { return m; },
[&] () {});
};
};
template <typename T>
using remove_auto_increment_t = decltype(remove_members_with_attribute(std::declval<T>(), _auto_increment));
template <typename T>
using remove_read_only_fields_t = decltype(remove_members_with_attribute(std::declval<T>(), _read_only));
template <typename T>
using extract_primary_keys_t = decltype(extract_members_with_attribute(std::declval<T>(), _primary_key));
template <typename T>
using remove_primary_keys_t = decltype(remove_members_with_attribute(std::declval<T>(), _primary_key));
}
template <typename C, typename O>
struct sql_orm
{
typedef O object_type;
// O without auto increment for create procedure.
typedef sql_orm_internals::remove_auto_increment_t<O> without_auto_inc_type;
// Object with only the primary keys for the delete and update procedures.
typedef sql_orm_internals::extract_primary_keys_t<O> PKS;
static_assert(!std::is_same<PKS, void>::value, "You must set at least one member of the CRUD object as primary key.");
sql_orm(const std::string& table, C& con) : table_name_(table), con_(con) {}
int find_by_id(int id, O& o)
{
std::stringstream field_ss;
bool first = true;
foreach(o) | [&] (auto& m)
{
if (!first) field_ss << ",";
first = false;
field_ss << m.symbol().name();
};
return con_("SELECT " + field_ss.str() + " from " + table_name_ + " where id = ?")(id) >> o;
}
// save all fields except auto increment.
// The db will automatically fill auto increment keys.
template <typename N>
int insert(const N& o)
{
std::stringstream ss;
std::stringstream vs;
ss << "INSERT into " << table_name_ << "(";
bool first = true;
auto values = foreach(without_auto_inc_type()) | [&] (auto& m) {
if (!first) { ss << ","; vs << ","; }
first = false;
ss << m.symbol().name();
vs << "?";
return m.symbol() = m.symbol().member_access(o);
};
ss << ") VALUES (" << vs.str() << ")";
auto req = con_(ss.str());
apply(values, req);
return req.last_insert_id();
};
// Iterate on all the rows of the table.
template <typename F>
void forall(F f)
{
std::stringstream ss;
ss << "SELECT * from " << table_name_;
con_(ss.str())() | f;
}
// Update N's members except auto increment members.
// N must have at least one primary key.
template <typename N>
int update(const N& o)
{
// check if N has at least one member of PKS.
auto pk = intersect(o, PKS());
static_assert(decltype(pk)::size() > 0, "You must provide at least one primary key to update an object.");
std::stringstream ss;
ss << "UPDATE " << table_name_ << " SET ";
bool first = true;
auto values = foreach(o) | [&] (auto& m) {
if (!first) ss << ",";
first = false;
ss << m.symbol().name() << " = ?";
return m;
};
ss << " WHERE ";
first = true;
auto pks_values = foreach(pk) | [&] (auto& m) {
if (!first) ss << " and ";
first = false;
ss << m.symbol().name() << " = ? ";
return m.symbol() = m.value();
};
auto stmt = con_(ss.str());
apply(values, pks_values, stmt);
return stmt.last_insert_id();
}
template <typename T>
void destroy(const T& o)
{
std::stringstream ss;
ss << "DELETE from " << table_name_ << " WHERE ";
bool first = true;
auto values = foreach(PKS()) | [&] (auto& m) {
if (!first) ss << " and ";
first = false;
ss << m.symbol().name() << " = ? ";
return m.symbol() = o[m.symbol()];
};
apply(values, con_(ss.str()));
}
std::string table_name_;
C con_;
};
struct sqlite_connection;
struct mysql_connection;
template <typename C, typename O>
struct sql_orm_factory
{
typedef O object_type;
typedef sql_orm<C, O> instance_type;
sql_orm_factory(const std::string& table_name) : table_name_(table_name) {}
void initialize(C& c)
{
std::stringstream ss;
ss << "CREATE TABLE if not exists " << table_name_ << " (";
bool first = true;
foreach(O()) | [&] (auto& m)
{
if (!first) ss << ", ";
ss << m.symbol().name() << " " << c.type_to_string(m.value());
if (std::is_same<C, sqlite_connection>::value)
{
if (m.attributes().has(_auto_increment) || m.attributes().has(_primary_key))
ss << " PRIMARY KEY ";
}
if (std::is_same<C, mysql_connection>::value)
{
if (m.attributes().has(_auto_increment))
ss << " AUTO_INCREMENT NOT NULL";
if (m.attributes().has(_primary_key))
ss << " PRIMARY KEY ";
}
// To activate when pgsql_connection is implemented.
// if (std::is_same<C, pgsql_connection>::value and
// m.attributes().has(_auto_increment))
// ss << " SERIAL ";
first = false;
};
ss << ");";
try
{
c(ss.str())();
}
catch (std::exception e)
{
std::cout << "Warning: Silicon could not create the " << table_name_ << " sql table." << std::endl
<< "You can ignore this message if the table already exists."
<< "The sql error is: " << e.what() << std::endl;
}
}
sql_orm<C, O> instantiate(C& con) {
return sql_orm<C, O>(table_name_, con);
};
std::string table_name_;
};
}
| 3,032 |
981 |
<reponame>Alexmitter/box64
/*******************************************************************
* File automatically generated by rebuild_wrappers.py (v2.1.0.16) *
*******************************************************************/
#ifndef __wrappedlibformwDEFS_H_
#define __wrappedlibformwDEFS_H_
#endif // __wrappedlibformwDEFS_H_
| 90 |
363 |
/*
* 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.
*
* Copyright 2012-2021 the original author or authors.
*/
package org.assertj.core.error;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.withinPercentage;
import static org.assertj.core.api.BDDAssertions.then;
import static org.assertj.core.error.OptionalDoubleShouldHaveValueCloseToPercentage.shouldHaveValueCloseToPercentage;
import java.util.OptionalDouble;
import org.junit.jupiter.api.Test;
class OptionalDouble_ShouldHaveValueCloseToPercentage_create_Test {
@Test
void should_create_error_message_when_optionaldouble_is_empty() {
// WHEN
String errorMessage = shouldHaveValueCloseToPercentage(10.0).create();
// THEN
then(errorMessage).isEqualTo(format("%nExpecting an OptionalDouble with value:%n" +
" 10.0%n" +
"but was empty."));
}
@Test
void should_create_error_message_when_optionaldouble_value_is_not_close_enough_to_expected_value() {
// WHEN
String errorMessage = shouldHaveValueCloseToPercentage(OptionalDouble.of(20), 10, withinPercentage(2), 3).create();
// THEN
then(errorMessage).isEqualTo(format("%nExpecting actual:%n OptionalDouble[20.0]%n" +
"to be close to:%n" +
" 10.0%n" +
"by less than 2%% but difference was 30.0%%.%n" +
"(a difference of exactly 2%% being considered valid)"));
}
}
| 807 |
980 |
[
{
"name": "Discussions",
"url": "https://github.com/geist-org/geist-ui/discussions"
},
{
"name": "Example projects",
"url": "https://github.com/geist-org/geist-ui/tree/master/examples"
},
{
"name": "Create issue",
"url": "https://github.com/geist-org/geist-ui/issues/new/choose"
},
{
"name": "Release Note",
"url": "https://github.com/geist-org/geist-ui/releases"
},
{
"name": "Join Slack",
"url": "https://github.com/geist-org/geist-ui/discussions/572"
},
{
"name": "License",
"url": "https://github.com/geist-org/geist-ui/blob/master/LICENSE"
},
{
"name": "Canary Documentation",
"url": "https://rc.geist-ui.dev/"
},
{
"name": "Canary Releases",
"url": "https://github.com/geist-org/geist-ui/releases?q=canary&expanded=true"
}
]
| 360 |
2,863 |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Magic constants used within `dm_control.mjcf`."""
PREFIX_SEPARATOR = '/'
PREFIX_SEPARATOR_ESCAPE = '\\'
# Used to disambiguate namespaces between attachment frames.
NAMESPACE_SEPARATOR = '@'
# Magic attribute names
BASEPATH = 'basepath'
CHILDCLASS = 'childclass'
CLASS = 'class'
DEFAULT = 'default'
DCLASS = 'dclass'
# Magic tags
ACTUATOR = 'actuator'
BODY = 'body'
DEFAULT = 'default'
MESH = 'mesh'
SITE = 'site'
SKIN = 'skin'
TENDON = 'tendon'
WORLDBODY = 'worldbody'
MJDATA_TRIGGERS_DIRTY = [
'qpos', 'qvel', 'act', 'ctrl', 'qfrc_applied', 'xfrc_applied']
MJMODEL_DOESNT_TRIGGER_DIRTY = [
'rgba', 'matid', 'emission', 'specular', 'shininess', 'reflectance']
# When writing into `model.{body,geom,site}_{pos,quat}` we must ensure that the
# corresponding rows in `model.{body,geom,site}_sameframe` are set to zero,
# otherwise MuJoCo will use the body or inertial frame instead of our modified
# pos/quat values. We must do the same for `body_{ipos,iquat}` and
# `body_simple`.
MJMODEL_DISABLE_ON_WRITE = {
# Field name in MjModel: (attribute names of Binding instance to be zeroed)
'body_pos': ('sameframe',),
'body_quat': ('sameframe',),
'geom_pos': ('sameframe',),
'geom_quat': ('sameframe',),
'site_pos': ('sameframe',),
'site_quat': ('sameframe',),
'body_ipos': ('simple', 'sameframe'),
'body_iquat': ('simple', 'sameframe'),
}
# This is the actual upper limit on VFS filename length, despite what it says
# in the header file (100) or the error message (99).
MAX_VFS_FILENAME_LENGTH = 98
# The prefix used in the schema to denote reference_namespace that are defined
# via another attribute.
INDIRECT_REFERENCE_NAMESPACE_PREFIX = 'attrib:'
INDIRECT_REFERENCE_ATTRIB = {
'xbody': 'body',
}
| 831 |
892 |
{
"schema_version": "1.2.0",
"id": "GHSA-rm4p-5c85-7wp5",
"modified": "2022-05-01T18:18:56Z",
"published": "2022-05-01T18:18:56Z",
"aliases": [
"CVE-2007-3955"
],
"details": "Buffer overflow in the IEToolbar.IEContextMenu.1 ActiveX control in LinkedInIEToolbar.dll in the LinkedIn Toolbar 3.0.2.1098 allows remote attackers to execute arbitrary code via a long second argument (varBrowser argument) to the search method. NOTE: some of these details are obtained from third party information.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2007-3955"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/35578"
},
{
"type": "WEB",
"url": "https://www.exploit-db.com/exploits/4217"
},
{
"type": "WEB",
"url": "http://osvdb.org/37696"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/26181"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/25032"
},
{
"type": "WEB",
"url": "http://www.vdalabs.com/tools/linkedin.html"
},
{
"type": "WEB",
"url": "http://www.vupen.com/english/advisories/2007/2620"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "MODERATE",
"github_reviewed": false
}
}
| 666 |
1,144 |
/** Generated Model - DO NOT CHANGE */
package de.metas.procurement.base.model;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.util.Properties;
import org.compiere.util.Env;
/** Generated Model for PMM_PurchaseCandidate_Weekly
* @author Adempiere (generated)
*/
@SuppressWarnings("javadoc")
public class X_PMM_PurchaseCandidate_Weekly extends org.compiere.model.PO implements I_PMM_PurchaseCandidate_Weekly, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = -1731504596L;
/** Standard Constructor */
public X_PMM_PurchaseCandidate_Weekly (Properties ctx, int PMM_PurchaseCandidate_Weekly_ID, String trxName)
{
super (ctx, PMM_PurchaseCandidate_Weekly_ID, trxName);
/** if (PMM_PurchaseCandidate_Weekly_ID == 0)
{
setC_BPartner_ID (0);
setDatePromised (new Timestamp( System.currentTimeMillis() ));
setM_Product_ID (0);
setQtyOrdered (Env.ZERO);
// 0
setQtyPromised (Env.ZERO);
// 0
} */
}
/** Load Constructor */
public X_PMM_PurchaseCandidate_Weekly (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
@Override
public org.compiere.model.I_C_BPartner getC_BPartner() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_BPartner_ID, org.compiere.model.I_C_BPartner.class);
}
@Override
public void setC_BPartner(org.compiere.model.I_C_BPartner C_BPartner)
{
set_ValueFromPO(COLUMNNAME_C_BPartner_ID, org.compiere.model.I_C_BPartner.class, C_BPartner);
}
/** Set Geschäftspartner.
@param C_BPartner_ID
Bezeichnet einen Geschäftspartner
*/
@Override
public void setC_BPartner_ID (int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID));
}
/** Get Geschäftspartner.
@return Bezeichnet einen Geschäftspartner
*/
@Override
public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Zugesagter Termin.
@param DatePromised
Zugesagter Termin für diesen Auftrag
*/
@Override
public void setDatePromised (java.sql.Timestamp DatePromised)
{
set_ValueNoCheck (COLUMNNAME_DatePromised, DatePromised);
}
/** Get Zugesagter Termin.
@return Zugesagter Termin für diesen Auftrag
*/
@Override
public java.sql.Timestamp getDatePromised ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DatePromised);
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Bestellte Menge.
@param QtyOrdered
Bestellte Menge
*/
@Override
public void setQtyOrdered (java.math.BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
/** Get Bestellte Menge.
@return Bestellte Menge
*/
@Override
public java.math.BigDecimal getQtyOrdered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Zusagbar.
@param QtyPromised Zusagbar */
@Override
public void setQtyPromised (java.math.BigDecimal QtyPromised)
{
set_Value (COLUMNNAME_QtyPromised, QtyPromised);
}
/** Get Zusagbar.
@return Zusagbar */
@Override
public java.math.BigDecimal getQtyPromised ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised);
if (bd == null)
return Env.ZERO;
return bd;
}
}
| 1,926 |
344 |
<gh_stars>100-1000
//===============================================================================
// @ IvClipper.h
// ------------------------------------------------------------------------------
// Clipping class
//
// Copyright (C) 2008-2015 by <NAME> and <NAME>.
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
//===============================================================================
#ifndef __IvClipperDefs__
#define __IvClipperDefs__
//-------------------------------------------------------------------------------
//-- Dependencies ---------------------------------------------------------------
//-------------------------------------------------------------------------------
#include <IvVector3.h>
#include <IvPlane.h>
class IvVertexBuffer;
//-------------------------------------------------------------------------------
//-- Classes --------------------------------------------------------------------
//-------------------------------------------------------------------------------
class IvClipper
{
public:
IvClipper();
~IvClipper();
void ClipVertex( const IvVector3& end );
void StartClip();
inline void SetPlane( const IvPlane& plane ) { mPlane = plane; }
void FinishClip();
private:
IvPlane mPlane; // current clipping plane
IvVector3 mStart; // current edge start vertex
float mBCStart; // current edge start boundary condition
bool mStartInside; // whether current start vertex is inside
bool mFirstVertex; // whether expected vertex is start vertex
IvVector3 mClipVertices[6]; // set of currently clipped vertices
unsigned int mNumVertices; // number of clipped vertices
IvVertexBuffer* mBuffer; // output vertices
};
#endif
| 494 |
32,544 |
<filename>hystrix/src/main/java/com/baeldung/hystrix/CommandHelloWorld.java<gh_stars>1000+
package com.baeldung.hystrix;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
class CommandHelloWorld extends HystrixCommand<String> {
private final String name;
CommandHelloWorld(String name) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.name = name;
}
@Override
protected String run() {
return "Hello " + name + "!";
}
}
| 204 |
327 |
from torch.utils.data import Dataset
import numpy as np
import cv2
import os
class PredDataset(Dataset):
''' Reads image and trimap pairs from folder.
'''
def __init__(self, img_dir, trimap_dir):
self.img_dir, self.trimap_dir = img_dir, trimap_dir
self.img_names = [x for x in os.listdir(self.img_dir) if 'png' in x]
def __len__(self):
return len(self.img_names)
def __getitem__(self, idx):
img_name = self.img_names[idx]
image = read_image(os.path.join(self.img_dir, img_name))
trimap = read_trimap(os.path.join(self.trimap_dir, img_name))
pred_dict = {'image': image, 'trimap': trimap, 'name': img_name}
return pred_dict
def read_image(name):
return (cv2.imread(name) / 255.0)[:, :, ::-1]
def read_trimap(name):
trimap_im = cv2.imread(name, 0) / 255.0
h, w = trimap_im.shape
trimap = np.zeros((h, w, 2))
trimap[trimap_im == 1, 1] = 1
trimap[trimap_im == 0, 0] = 1
return trimap
| 467 |
388 |
<filename>honssh/utils/validation.py
import re
def check_valid_ip(prop, value):
match = re.match('^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$',
value)
if match:
return True
else:
print '[VALIDATION] - [' + prop[0] + '][' + prop[1] + '] should be a valid IP address'
return False
def check_valid_port(prop, value):
if check_valid_number(prop, value):
if 1 <= int(value) <= 65535:
return True
else:
print '[VALIDATION] - [' + prop[0] + '][' + prop[1] + '] should be between 1 and 65535'
return False
def check_valid_boolean(prop, value):
if value in ['true', 'false']:
return True
else:
print '[VALIDATION] - [' + prop[0] + '][' + prop[1] + '] must be either true or false (case sensitive)'
return False
def check_valid_number(prop, value):
try:
int(value)
return True
except ValueError:
print '[VALIDATION] - [' + prop[0] + '][' + prop[1] + '] should be number.'
return False
def check_valid_chance(prop, value):
if check_valid_number(prop, value):
if 1 <= int(value):
return True
else:
print '[VALIDATION] - [' + prop[0] + '][' + prop[1] + '] should be greater than 0'
return False
| 661 |
831 |
/*
* Copyright (C) 2020 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.tools.profilers;
import com.android.tools.adtui.TabularLayout;
import com.android.tools.adtui.TooltipComponent;
import com.android.tools.adtui.chart.hchart.HTreeChart;
import com.android.tools.adtui.model.HNode;
import com.google.common.annotations.VisibleForTesting;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import org.jetbrains.annotations.NotNull;
public abstract class ChartTooltipViewBase<T extends HNode<T>> extends MouseAdapter {
@NotNull
private final HTreeChart<T> myChart;
@NotNull
private final TooltipComponent myTooltipComponent;
@NotNull
private final JPanel myContent;
protected ChartTooltipViewBase(@NotNull HTreeChart<T> chart, @NotNull JLayeredPane tooltipRoot) {
myChart = chart;
myContent = new JPanel(new TabularLayout("*", "*"));
myContent.setBorder(ProfilerLayout.TOOLTIP_BORDER);
myContent.setBackground(ProfilerColors.TOOLTIP_BACKGROUND);
myTooltipComponent = new TooltipComponent.Builder(myContent, chart, tooltipRoot).build();
myTooltipComponent.registerListenersOn(chart);
}
@Override
public void mouseMoved(MouseEvent e) {
myTooltipComponent.setVisible(false);
T node = myChart.getNodeAt(e.getPoint());
if (node != null) {
myTooltipComponent.setVisible(true);
showTooltip(node);
}
}
@VisibleForTesting
public TooltipComponent getTooltipComponent() {
return myTooltipComponent;
}
protected JPanel getTooltipContainer() {
return myContent;
}
@VisibleForTesting
abstract public void showTooltip(@NotNull T node);
}
| 723 |
906 |
<filename>VTIL-Compiler/optimizer/stack_propagation_pass.cpp
// Copyright (c) 2020 <NAME> and contributors of the VTIL Project
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of VTIL Project 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include "stack_propagation_pass.hpp"
#include "../common/auxiliaries.hpp"
namespace vtil::optimizer
{
// Wrap cached tracer with a filter rejecting queries of registers and specializing recursive tracer.
//
struct lazy_tracer : cached_tracer
{
cached_tracer* link;
il_const_iterator bypass = {};
lazy_tracer( cached_tracer* p ) : link( p ) {}
tracer* purify() override { return link; }
symbolic::expression::reference trace( const symbolic::variable& lookup ) override
{
// If tracing stack pointer, use normal tracing.
//
if( lookup.is_register() && lookup.reg().is_stack_pointer() )
return link->trace( lookup );
// If instruction accesses memory:
//
if ( !lookup.at.is_end() && lookup.at->base->accesses_memory() )
{
// If query overlaps base, trace normally.
//
if ( lookup.is_register() && lookup.reg().overlaps( lookup.at->memory_location().first ) )
return link->trace( lookup );
}
// Bypass if at the beginning of block//query.
//
if ( !bypass.is_valid() || lookup.at == bypass || lookup.at.is_end() )
return cached_tracer::trace( lookup );
// Return without tracing.
//
return lookup.to_expression();
}
};
// Implement the pass.
//
size_t stack_propagation_pass::pass( basic_block* blk, bool xblock )
{
// Acquire a shared lock.
//
cnd_shared_lock lock( mtx, xblock );
// Create tracers.
//
cached_tracer ctracer = {};
lazy_tracer ltracer = { &ctracer };
// Allocate the swap buffers.
//
std::vector<std::tuple<il_iterator, const instruction_desc*, operand>> ins_swap_buffer;
std::vector<std::tuple<il_iterator, const instruction_desc*, symbolic::variable>> ins_revive_swap_buffer;
// For each instruction:
//
for ( auto it = blk->begin(); !it.is_end(); it++ )
{
// Skip volatile instructions.
//
if ( it->is_volatile() ) continue;
// Filter to LDD instructions referencing stack:
//
if ( it->base == &ins::ldd && it->memory_location().first.is_stack_pointer() )
{
auto resize_and_pack = [ & ] ( symbolic::expression::reference& exp )
{
exp = symbolic::variable::pack_all( exp.resize( it->operands[ 0 ].bit_count() ) );
};
// Lazy-trace the value.
//
symbolic::pointer ptr = { ctracer.trace( { it, REG_SP } ) + it->memory_location().second };
symbolic::variable var = { it, { std::move( ptr ), it->access_size() } };
ltracer.bypass = it;
auto exp = xblock ? ltracer.rtrace( var ) : ltracer.trace( var );
ltracer.bypass = {};
// Resize and pack variables.
//
resize_and_pack( exp );
// Determine the instruction we will use to move the source.
//
auto* new_instruction = &ins::mov;
if ( exp->is_expression() )
{
// If __ucast(V, N):
//
if ( exp->op == math::operator_id::ucast && exp->lhs->is_variable() )
{
exp = exp->lhs;
}
// If __cast(V, N):
//
else if ( exp->op == math::operator_id::cast && exp->lhs->is_variable() )
{
exp = exp->lhs;
new_instruction = &ins::movsx;
}
// Otherwise skip.
//
else
{
continue;
}
}
// If constant, replace with [mov reg, imm].
//
if ( auto imm = exp->get() )
{
// Push to swap buffer.
//
ins_swap_buffer.emplace_back( it, new_instruction, operand{ *imm, exp->size() } );
}
// Otherwise, try to replace with [mov reg, reg].
//
else
{
fassert( exp->is_variable() );
// Skip if not a register or branch dependant.
//
symbolic::variable rvar = exp->uid.get<symbolic::variable>();
if ( rvar.is_branch_dependant || !rvar.is_register() )
continue;
// If value is not alive, try hijacking the value declaration.
//
if ( !aux::is_alive( rvar, it, xblock, nullptr ) )
{
// Must be a valid (and non-end) iterator.
//
if ( rvar.at.is_end() )
{
// If begin (begin&&end == invalid), fail.
//
if ( rvar.at.is_begin() )
continue;
// Try determining the path to current block. If single direction
// possible, replace iterator, otherwise fail.
//
il_const_iterator it_rstr = rvar.at;
it_rstr.restrict_path( it.block, true );
il_const_iterator it_next = {};
it_rstr.enum_paths( true, [ & ] ( const il_const_iterator& iter )
{
if ( it_next.is_valid() )
{
it_next = iter;
return enumerator::ocontinue;
}
else
{
it_next = {};
return enumerator::obreak;
}
} );
// If single direction possible, replace iterator, otherwise fail.
//
if ( it_next.is_valid() )
rvar.bind( it_next );
else
continue;
}
// Push to swap buffer.
//
ins_revive_swap_buffer.emplace_back( it, new_instruction, rvar );
}
else
{
// Push to swap buffer.
//
ins_swap_buffer.emplace_back( it, new_instruction, operand{ rvar.reg() } );
}
}
}
}
// Acquire lock and swap all instructions at once.
//
lock = {};
cnd_unique_lock _g( mtx, xblock );
for ( auto [it, ins, op] : ins_swap_buffer )
{
( +it )->base = ins;
( +it )->operands = { it->operands[ 0 ], op };
it->is_valid( true );
}
for ( auto [it, ins, var] : ins_revive_swap_buffer )
{
( +it )->base = ins;
register_desc rev;
if ( auto i2 = xblock ? revive_list.find( var ) : revive_list.end(); i2 != revive_list.end() )
rev = i2->second;
else
rev = aux::revive_register( var, it );
( +it )->operands = { it->operands[ 0 ], rev };
it->is_valid( true );
}
return ins_swap_buffer.size() + ins_revive_swap_buffer.size();
}
};
| 3,118 |
9,402 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//----------------------------------------------------------
// verbDump.h - verb that Dumps a MC file
//----------------------------------------------------------
#ifndef _verbDump
#define _verbDump
class verbDump
{
public:
static int DoWork(const char* nameofInput, int indexCount, const int* indexes, bool simple);
};
#endif
| 114 |
509 |
from prometeo import *
nm: dims = 10
nx: dims = 2*nm
nu: dims = nm
nxu: dims = nx + nu
N: dims = 5
def main() -> int:
# number of repetitions for timing
nrep : int = 10000
# set up dynamics TODO(needs discretization!)
A: pmat = pmat(nx, nx)
Ac11 : pmat = pmat(nm,nm)
for i in range(nm):
Ac11[i,i] = 1.0
Ac12 : pmat = pmat(nm,nm)
for i in range(nm):
Ac12[i,i] = 1.0
Ac21 : pmat = pmat(nm,nm)
for i in range(nm):
Ac21[i,i] = -2.0
for i in range(nm-1):
Ac21[i+1,i] = 1.0
Ac21[i,i+1] = 1.0
Ac22 : pmat = pmat(nm,nm)
for i in range(nm):
Ac22[i,i] = 1.0
for i in range(nm):
for j in range(nm):
A[i,j] = Ac11[i,j]
for i in range(nm):
for j in range(nm):
A[i,nm+j] = Ac12[i,j]
for i in range(nm):
for j in range(nm):
A[nm+i,j] = Ac21[i,j]
for i in range(nm):
for j in range(nm):
A[nm+i,nm+j] = Ac22[i,j]
tmp : float = 0.0
for i in range(nx):
tmp = A[i,i]
tmp = tmp + 1.0
A[i,i] = tmp
B: pmat = pmat(nx, nu)
for i in range(nu):
B[nm+i,i] = 1.0
Q: pmat = pmat(nx, nx)
for i in range(nx):
Q[i,i] = 1.0
R: pmat = pmat(nu, nu)
for i in range(nu):
R[i,i] = 1.0
RSQ: pmat = pmat(nxu, nxu)
Lxx: pmat = pmat(nx, nx)
M: pmat = pmat(nxu, nxu)
w_nxu_nx: pmat = pmat(nxu, nx)
BAt : pmat = pmat(nxu, nx)
BA : pmat = pmat(nx, nxu)
pmat_hcat(B, A, BA)
pmat_tran(BA, BAt)
RSQ[0:nu,0:nu] = R
RSQ[nu:nu+nx,nu:nu+nx] = Q
# array-type Riccati factorization
for i in range(nrep):
pmt_potrf(Q, Lxx)
M[nu:nu+nx,nu:nu+nx] = Lxx
for i in range(1, N):
pmt_trmm_rlnn(Lxx, BAt, w_nxu_nx)
pmt_syrk_ln(w_nxu_nx, w_nxu_nx, RSQ, M)
pmt_potrf(M, M)
Lxx[0:nx,0:nx] = M[nu:nu+nx,nu:nu+nx]
return 0
| 1,226 |
998 |
// Copyright 2021 Phyronnaz
#pragma once
#include "CoreMinimal.h"
#include "VoxelGeneratedWorldGeneratorsIncludes.h"
#include "VDI_Capsule_Graph.generated.h"
UCLASS(Blueprintable)
class UVDI_Capsule_Graph : public UVoxelGraphGeneratorHelper
{
GENERATED_BODY()
public:
// Relative to the radius
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="", meta=(DisplayName="Noise Amplitude", UIMax="2", UIMin="0"))
float Noise_Amplitude = 1.0;
//
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="", meta=(DisplayName="Seed"))
int32 Seed = 1443;
UVDI_Capsule_Graph();
virtual TVoxelSharedRef<FVoxelTransformableGeneratorInstance> GetTransformableInstance() override;
};
| 271 |
575 |
<filename>src/unix/unix_c/unix_get_cpu.c
/* This file is part of Lwt, released under the MIT license. See LICENSE.md for
details, or visit https://github.com/ocsigen/lwt/blob/master/LICENSE.md. */
#include "lwt_config.h"
#if !defined(LWT_ON_WINDOWS)
#define _GNU_SOURCE
#include <caml/mlvalues.h>
#include <caml/unixsupport.h>
#include <sched.h>
#include "lwt_unix.h"
#if defined(HAVE_GETCPU)
CAMLprim value lwt_unix_get_cpu(value Unit)
{
int cpu = sched_getcpu();
if (cpu < 0) uerror("sched_getcpu", Nothing);
return Val_int(cpu);
}
#else
LWT_NOT_AVAILABLE1(unix_get_cpu)
#endif
#endif
| 271 |
6,717 |
<reponame>sillywalk/grazz
/*===-- llvm-c/Object.h - Object Lib C Iface --------------------*- C++ -*-===*/
/* */
/* The LLVM Compiler Infrastructure */
/* */
/* This file is distributed under the University of Illinois Open Source */
/* License. See LICENSE.TXT for details. */
/* */
/*===----------------------------------------------------------------------===*/
/* */
/* This header declares the C interface to libLLVMObject.a, which */
/* implements object file reading and writing. */
/* */
/* Many exotic languages can interoperate with C code but have a harder time */
/* with C++ due to name mangling. So in addition to C, this interface enables */
/* tools written in such languages. */
/* */
/*===----------------------------------------------------------------------===*/
#ifndef LLVM_C_OBJECT_H
#define LLVM_C_OBJECT_H
#include "llvm-c/Types.h"
#include "llvm/Config/llvm-config.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup LLVMCObject Object file reading and writing
* @ingroup LLVMC
*
* @{
*/
// Opaque type wrappers
typedef struct LLVMOpaqueObjectFile *LLVMObjectFileRef;
typedef struct LLVMOpaqueSectionIterator *LLVMSectionIteratorRef;
typedef struct LLVMOpaqueSymbolIterator *LLVMSymbolIteratorRef;
typedef struct LLVMOpaqueRelocationIterator *LLVMRelocationIteratorRef;
// ObjectFile creation
LLVMObjectFileRef LLVMCreateObjectFile(LLVMMemoryBufferRef MemBuf);
void LLVMDisposeObjectFile(LLVMObjectFileRef ObjectFile);
// ObjectFile Section iterators
LLVMSectionIteratorRef LLVMGetSections(LLVMObjectFileRef ObjectFile);
void LLVMDisposeSectionIterator(LLVMSectionIteratorRef SI);
LLVMBool LLVMIsSectionIteratorAtEnd(LLVMObjectFileRef ObjectFile,
LLVMSectionIteratorRef SI);
void LLVMMoveToNextSection(LLVMSectionIteratorRef SI);
void LLVMMoveToContainingSection(LLVMSectionIteratorRef Sect,
LLVMSymbolIteratorRef Sym);
// ObjectFile Symbol iterators
LLVMSymbolIteratorRef LLVMGetSymbols(LLVMObjectFileRef ObjectFile);
void LLVMDisposeSymbolIterator(LLVMSymbolIteratorRef SI);
LLVMBool LLVMIsSymbolIteratorAtEnd(LLVMObjectFileRef ObjectFile,
LLVMSymbolIteratorRef SI);
void LLVMMoveToNextSymbol(LLVMSymbolIteratorRef SI);
// SectionRef accessors
const char *LLVMGetSectionName(LLVMSectionIteratorRef SI);
uint64_t LLVMGetSectionSize(LLVMSectionIteratorRef SI);
const char *LLVMGetSectionContents(LLVMSectionIteratorRef SI);
uint64_t LLVMGetSectionAddress(LLVMSectionIteratorRef SI);
LLVMBool LLVMGetSectionContainsSymbol(LLVMSectionIteratorRef SI,
LLVMSymbolIteratorRef Sym);
// Section Relocation iterators
LLVMRelocationIteratorRef LLVMGetRelocations(LLVMSectionIteratorRef Section);
void LLVMDisposeRelocationIterator(LLVMRelocationIteratorRef RI);
LLVMBool LLVMIsRelocationIteratorAtEnd(LLVMSectionIteratorRef Section,
LLVMRelocationIteratorRef RI);
void LLVMMoveToNextRelocation(LLVMRelocationIteratorRef RI);
// SymbolRef accessors
const char *LLVMGetSymbolName(LLVMSymbolIteratorRef SI);
uint64_t LLVMGetSymbolAddress(LLVMSymbolIteratorRef SI);
uint64_t LLVMGetSymbolSize(LLVMSymbolIteratorRef SI);
// RelocationRef accessors
uint64_t LLVMGetRelocationOffset(LLVMRelocationIteratorRef RI);
LLVMSymbolIteratorRef LLVMGetRelocationSymbol(LLVMRelocationIteratorRef RI);
uint64_t LLVMGetRelocationType(LLVMRelocationIteratorRef RI);
// NOTE: Caller takes ownership of returned string of the two
// following functions.
const char *LLVMGetRelocationTypeName(LLVMRelocationIteratorRef RI);
const char *LLVMGetRelocationValueString(LLVMRelocationIteratorRef RI);
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* defined(__cplusplus) */
#endif
| 1,886 |
1,056 |
<gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.java.j2seproject;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.netbeans.api.java.project.JavaProjectConstants;
import org.netbeans.api.java.queries.SourceForBinaryQuery;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.modules.SpecificationVersion;
import org.netbeans.junit.NbTestCase;
import org.netbeans.api.project.ProjectManager;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectUtils;
import org.netbeans.api.project.SourceGroup;
import org.netbeans.api.project.Sources;
import org.netbeans.api.project.TestUtil;
import org.netbeans.junit.RandomlyFails;
import org.netbeans.modules.java.api.common.SourceRoots;
import org.netbeans.modules.java.api.common.project.ProjectProperties;
import org.netbeans.spi.project.support.ant.AntProjectHelper;
import org.netbeans.spi.project.support.ant.EditableProperties;
import org.netbeans.spi.project.ui.ProjectOpenedHook;
import org.openide.util.test.MockLookup;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Document;
/**
* Tests J2SESources
* Tests if SourceForBinaryQuery works fine on external build folder.
*
* @author <NAME>
*/
public class J2SESourcesTest extends NbTestCase {
public J2SESourcesTest(String testName) {
super(testName);
}
private FileObject scratch;
private FileObject projdir;
private FileObject sources;
private FileObject build;
private FileObject classes;
private ProjectManager pm;
private Project project;
private AntProjectHelper helper;
protected @Override int timeOut() {
return 300000;
}
protected @Override void setUp() throws Exception {
super.setUp();
MockLookup.setLayersAndInstances(
new org.netbeans.modules.projectapi.SimpleFileOwnerQueryImplementation()
);
scratch = TestUtil.makeScratchDir(this);
projdir = scratch.createFolder("proj");
J2SEProjectGenerator.setDefaultSourceLevel(new SpecificationVersion ("1.6")); //NOI18N
helper = J2SEProjectGenerator.createProject(FileUtil.toFile(projdir),"proj",null,null,null, false); //NOI18N
J2SEProjectGenerator.setDefaultSourceLevel(null);
sources = getFileObject(projdir, "src");
build = getFileObject (scratch, "build");
classes = getFileObject(build,"classes");
File f = FileUtil.normalizeFile (FileUtil.toFile(build));
String path = f.getAbsolutePath ();
//#47657: SourcesHelper.remarkExternalRoots () does not work on deleted folders
// To reproduce it uncomment following line
// build.delete();
EditableProperties props = helper.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH);
props.setProperty(ProjectProperties.BUILD_DIR, path);
helper.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, props);
pm = ProjectManager.getDefault();
project = pm.findProject(projdir);
assertTrue("Invalid project type", project instanceof J2SEProject);
}
protected @Override void tearDown() throws Exception {
scratch = null;
projdir = null;
sources = null;
build = null;
classes = null;
pm = null;
project = null;
helper = null;
super.tearDown();
}
public void testSourceRoots () throws Exception {
FileObject[] roots = SourceForBinaryQuery.findSourceRoots(classes.toURL()).getRoots();
assertNotNull (roots);
assertEquals("There should be 1 src root",1,roots.length);
assertTrue ("The source root is not valid", sources.isValid());
assertEquals("Invalid src root", sources, roots[0]);
FileObject src2 = projdir.createFolder("src2");
addSourceRoot (helper, src2, "src2");
roots = SourceForBinaryQuery.findSourceRoots(classes.toURL()).getRoots();
assertNotNull (roots);
assertEquals("There should be 2 src roots", 2, roots.length);
assertTrue ("The source root is not valid", sources.isValid());
assertEquals("Invalid src root", sources, roots[0]);
assertTrue ("The source root 2 is not valid", src2.isValid());
assertEquals("Invalid src2 root", src2, roots[1]);
}
public void testIncludesExcludes() throws Exception {
SourceGroup g = ProjectUtils.getSources(project).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA)[0];
assertEquals(sources, g.getRootFolder());
FileObject objectJava = FileUtil.createData(sources, "java/lang/Object.java");
FileObject jcJava = FileUtil.createData(sources, "javax/swing/JComponent.java");
FileObject doc = FileUtil.createData(sources, "javax/swing/doc-files/index.html");
assertTrue(g.contains(objectJava));
assertTrue(g.contains(jcJava));
assertTrue(g.contains(doc));
Method projectOpened = ProjectOpenedHook.class.getDeclaredMethod("projectOpened");
projectOpened.setAccessible(true);
projectOpened.invoke(project.getLookup().lookup(ProjectOpenedHook.class));
EditableProperties ep = helper.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH);
assertEquals("includes/excludes were initialized to defaults", "**", ep.getProperty(ProjectProperties.INCLUDES));
assertEquals("includes/excludes were initialized to defaults", "", ep.getProperty(ProjectProperties.EXCLUDES));
ep.setProperty(ProjectProperties.INCLUDES, "javax/swing/");
ep.setProperty(ProjectProperties.EXCLUDES, "**/doc-files/");
helper.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, ep);
pm.saveProject(project);
assertFalse(g.contains(objectJava));
assertTrue(g.contains(jcJava));
assertFalse(g.contains(doc));
}
@RandomlyFails // on various builders, and w/o dump despite timeOut
public void testFiring() throws Exception {
final Sources s = project.getLookup().lookup(Sources.class);
final SourceRoots roots = ((J2SEProject)project).getSourceRoots();
SourceGroup[] groups = s.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
assertEquals(2, groups.length);
class EventCounter implements ChangeListener {
final AtomicInteger count = new AtomicInteger();
public @Override void stateChanged(ChangeEvent e) {
count.incrementAndGet();
}
}
final EventCounter counter = new EventCounter();
s.addChangeListener(counter);
final URL[] oldRootUrls = roots.getRootURLs();
final String[] oldRootLabels = roots.getRootNames();
final String[] oldRootProps = roots.getRootProperties();
final FileObject newRoot = projdir.createFolder("new_src"); //NOI18N
//test: adding of src root should fire once
URL[] newRootUrls = new URL[oldRootUrls.length+1];
System.arraycopy(oldRootUrls, 0, newRootUrls, 0, oldRootUrls.length);
newRootUrls[newRootUrls.length-1] = newRoot.toURL();
String[] newRootLabels = new String[oldRootLabels.length+1];
for (int i=0; i< oldRootLabels.length; i++) {
newRootLabels[i] = roots.getRootDisplayName(oldRootLabels[i], oldRootProps[i]);
}
newRootLabels[newRootLabels.length-1] = newRoot.getName();
roots.putRoots(newRootUrls, newRootLabels);
assertEquals(1, counter.count.get());
groups = s.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
assertEquals(3, groups.length);
//test: removing of src root should fire once
counter.count.set(0);
newRootUrls = new URL[oldRootUrls.length];
System.arraycopy(oldRootUrls, 0, newRootUrls, 0, oldRootUrls.length);
newRootLabels = new String[oldRootLabels.length];
for (int i=0; i< oldRootLabels.length; i++) {
newRootLabels[i] = roots.getRootDisplayName(oldRootLabels[i], oldRootProps[i]);
}
roots.putRoots(newRootUrls, newRootLabels);
assertEquals(1, counter.count.get());
groups = s.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
assertEquals(2, groups.length);
}
private static FileObject getFileObject (FileObject parent, String name) throws IOException {
FileObject result = parent.getFileObject(name);
if (result == null) {
result = parent.createFolder(name);
}
return result;
}
private static void addSourceRoot (AntProjectHelper helper, FileObject sourceFolder, String propName) throws Exception {
Element data = helper.getPrimaryConfigurationData(true);
NodeList nl = data.getElementsByTagNameNS(J2SEProject.PROJECT_CONFIGURATION_NAMESPACE,"source-roots");
assert nl.getLength() == 1;
Element roots = (Element) nl.item(0);
Document doc = roots.getOwnerDocument();
Element root = doc.createElementNS(J2SEProject.PROJECT_CONFIGURATION_NAMESPACE,"root");
root.setAttribute("id", propName);
roots.appendChild (root);
helper.putPrimaryConfigurationData (data,true);
EditableProperties props = helper.getProperties (AntProjectHelper.PROJECT_PROPERTIES_PATH);
File f = FileUtil.normalizeFile(FileUtil.toFile(sourceFolder));
props.put (propName, f.getAbsolutePath());
helper.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH,props);
}
}
| 3,993 |
852 |
<reponame>Purva-Chaudhari/cmssw<filename>DQM/HcalTasks/plugins/NoCQTask.cc
#include "DQM/HcalTasks/interface/NoCQTask.h"
using namespace hcaldqm;
using namespace hcaldqm::constants;
NoCQTask::NoCQTask(edm::ParameterSet const& ps)
: DQTask(ps), hcalDbServiceToken_(esConsumes<HcalDbService, HcalDbRecord, edm::Transition::BeginRun>()) {
_tagHBHE = ps.getUntrackedParameter<edm::InputTag>("tagHBHE", edm::InputTag("hcalDigis"));
_tagHO = ps.getUntrackedParameter<edm::InputTag>("tagHO", edm::InputTag("hcalDigis"));
_tagHF = ps.getUntrackedParameter<edm::InputTag>("tagHF", edm::InputTag("hcalDigis"));
_tagReport = ps.getUntrackedParameter<edm::InputTag>("tagReport", edm::InputTag("hcalDigis"));
_tokHBHE = consumes<HBHEDigiCollection>(_tagHBHE);
_tokHO = consumes<HODigiCollection>(_tagHO);
_tokHF = consumes<HFDigiCollection>(_tagHF);
_tokReport = consumes<HcalUnpackerReport>(_tagReport);
_cutSumQ_HBHE = ps.getUntrackedParameter<double>("cutSumQ_HBHE", 20);
_cutSumQ_HO = ps.getUntrackedParameter<double>("cutSumQ_HO", 20);
_cutSumQ_HF = ps.getUntrackedParameter<double>("cutSumQ_HF", 20);
}
/* virtual */ void NoCQTask::bookHistograms(DQMStore::IBooker& ib, edm::Run const& r, edm::EventSetup const& es) {
DQTask::bookHistograms(ib, r, es);
edm::ESHandle<HcalDbService> dbs = es.getHandle(hcalDbServiceToken_);
_emap = dbs->getHcalMapping();
_cTimingCut_depth.initialize(_name,
"TimingCut",
hcaldqm::hashfunctions::fdepth,
new hcaldqm::quantity::DetectorQuantity(hcaldqm::quantity::fieta),
new hcaldqm::quantity::DetectorQuantity(hcaldqm::quantity::fiphi),
new hcaldqm::quantity::ValueQuantity(hcaldqm::quantity::fTiming_TS200),
0);
_cOccupancy_depth.initialize(_name,
"Occupancy",
hcaldqm::hashfunctions::fdepth,
new hcaldqm::quantity::DetectorQuantity(hcaldqm::quantity::fieta),
new hcaldqm::quantity::DetectorQuantity(hcaldqm::quantity::fiphi),
new hcaldqm::quantity::ValueQuantity(hcaldqm::quantity::fN),
0);
_cOccupancyCut_depth.initialize(_name,
"OccupancyCut",
hcaldqm::hashfunctions::fdepth,
new hcaldqm::quantity::DetectorQuantity(hcaldqm::quantity::fieta),
new hcaldqm::quantity::DetectorQuantity(hcaldqm::quantity::fiphi),
new hcaldqm::quantity::ValueQuantity(hcaldqm::quantity::fN),
0);
_cBadQuality_depth.initialize(_name,
"BadQuality",
hcaldqm::hashfunctions::fdepth,
new hcaldqm::quantity::DetectorQuantity(hcaldqm::quantity::fieta),
new hcaldqm::quantity::DetectorQuantity(hcaldqm::quantity::fiphi),
new hcaldqm::quantity::ValueQuantity(hcaldqm::quantity::fN),
0);
_cTimingCut_depth.book(ib, _emap, _subsystem);
_cOccupancy_depth.book(ib, _emap, _subsystem);
_cOccupancyCut_depth.book(ib, _emap, _subsystem);
_cBadQuality_depth.book(ib, _emap, _subsystem);
}
/* virtual */ void NoCQTask::_resetMonitors(hcaldqm::UpdateFreq uf) { DQTask::_resetMonitors(uf); }
/* virtual */ void NoCQTask::_process(edm::Event const& e, edm::EventSetup const&) {
edm::Handle<HBHEDigiCollection> chbhe;
edm::Handle<HODigiCollection> cho;
edm::Handle<HFDigiCollection> chf;
edm::Handle<HcalUnpackerReport> creport;
if (!e.getByToken(_tokHBHE, chbhe))
_logger.dqmthrow("Collection HBHEDigiCollection isn't available" + _tagHBHE.label() + " " + _tagHBHE.instance());
if (!e.getByToken(_tokHO, cho))
_logger.dqmthrow("Collection HODigiCollection isn't available" + _tagHO.label() + " " + _tagHO.instance());
if (!e.getByToken(_tokHF, chf))
_logger.dqmthrow("Collection HFDigiCollection isn't available" + _tagHF.label() + " " + _tagHF.instance());
if (!e.getByToken(_tokReport, creport))
_logger.dqmthrow("Collection HcalUnpackerReport isn't available" + _tagReport.label() + " " +
_tagReport.instance());
// RAW Bad Quality
for (std::vector<DetId>::const_iterator it = creport->bad_quality_begin(); it != creport->bad_quality_end(); ++it) {
if (!HcalGenericDetId(*it).isHcalDetId())
continue;
_cBadQuality_depth.fill(HcalDetId(*it));
}
// DIGI HBH, HO, HF
for (HBHEDigiCollection::const_iterator it = chbhe->begin(); it != chbhe->end(); ++it) {
double sumQ = hcaldqm::utilities::sumQ<HBHEDataFrame>(*it, 2.5, 0, it->size() - 1);
HcalDetId const& did = it->id();
_cOccupancy_depth.fill(did);
if (sumQ > _cutSumQ_HBHE) {
double timing = hcaldqm::utilities::aveTS<HBHEDataFrame>(*it, 2.5, 0, it->size() - 1);
_cOccupancyCut_depth.fill(did);
_cTimingCut_depth.fill(did, timing);
}
}
for (HODigiCollection::const_iterator it = cho->begin(); it != cho->end(); ++it) {
double sumQ = hcaldqm::utilities::sumQ<HODataFrame>(*it, 8.5, 0, it->size() - 1);
HcalDetId const& did = it->id();
_cOccupancy_depth.fill(did);
if (sumQ > _cutSumQ_HO) {
double timing = hcaldqm::utilities::aveTS<HODataFrame>(*it, 8.5, 0, it->size() - 1);
_cOccupancyCut_depth.fill(did);
_cTimingCut_depth.fill(did, timing);
}
}
for (HFDigiCollection::const_iterator it = chf->begin(); it != chf->end(); ++it) {
double sumQ = hcaldqm::utilities::sumQ<HFDataFrame>(*it, 2.5, 0, it->size() - 1);
HcalDetId const& did = it->id();
_cOccupancy_depth.fill(did);
if (sumQ > _cutSumQ_HF) {
double timing = hcaldqm::utilities::aveTS<HFDataFrame>(*it, 2.5, 0, it->size() - 1);
_cOccupancyCut_depth.fill(did);
_cTimingCut_depth.fill(did, timing);
}
}
}
std::shared_ptr<hcaldqm::Cache> NoCQTask::globalBeginLuminosityBlock(edm::LuminosityBlock const& lb,
edm::EventSetup const& es) const {
return DQTask::globalBeginLuminosityBlock(lb, es);
}
/* virtual */ void NoCQTask::globalEndLuminosityBlock(edm::LuminosityBlock const& lb, edm::EventSetup const& es) {
DQTask::globalEndLuminosityBlock(lb, es);
}
DEFINE_FWK_MODULE(NoCQTask);
| 3,201 |
551 |
#ifndef LINUX_INPUT_MANAGER
#define LINUX_INPUT_MANAGER 1
#include <vector>
using namespace std;
#include "Etterna/Globals/global.h"
class InputHandler_Linux_Joystick;
class InputHandler_Linux_Event;
// Enumerates the input devices on the system and dispatches them to
// IH_Linux_Event and IH_Linux_Joystick as appropriate.
class LinuxInputManager
{
public:
LinuxInputManager();
void InitDriver(InputHandler_Linux_Joystick* drv);
void InitDriver(InputHandler_Linux_Event* drv);
~LinuxInputManager();
private:
bool m_bEventEnabled;
InputHandler_Linux_Event* m_EventDriver;
vector<std::string> m_vsPendingEventDevices;
bool m_bJoystickEnabled;
InputHandler_Linux_Joystick* m_JoystickDriver;
vector<std::string> m_vsPendingJoystickDevices;
};
extern LinuxInputManager*
LINUXINPUT; // global and accessible from anywhere in our program
#endif // LINUX_INPUT_MANAGER
| 335 |
432 |
<filename>ballcat-starters/ballcat-spring-boot-starter-web/src/main/java/com/hccake/ballcat/autoconfigure/web/validation/ValidationAutoConfiguration.java
package com.hccake.ballcat.autoconfigure.web.validation;
import com.hccake.ballcat.common.core.validation.EmptyCurlyToDefaultMessageInterpolator;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnResource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import javax.validation.MessageInterpolator;
import javax.validation.Validator;
import javax.validation.executable.ExecutableValidator;
/**
* Validation 自动配置类,扩展支持使用 {} 占位替换默认消息
*
* @author hccake
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ExecutableValidator.class)
@ConditionalOnResource(resources = "classpath:META-INF/services/javax.validation.spi.ValidationProvider")
@AutoConfigureBefore(org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration.class)
public class ValidationAutoConfiguration {
@Bean
@ConditionalOnMissingBean({ Validator.class, MessageInterpolator.class })
public EmptyCurlyToDefaultMessageInterpolator messageInterpolator() {
return new EmptyCurlyToDefaultMessageInterpolator();
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@ConditionalOnMissingBean(Validator.class)
@ConditionalOnBean(MessageInterpolator.class)
public static LocalValidatorFactoryBean defaultValidator(MessageInterpolator messageInterpolator) {
LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
factoryBean.setMessageInterpolator(messageInterpolator);
return factoryBean;
}
}
| 692 |
3,100 |
/******************************************************************************
* $Id$
*
* Project: GDAL Core
* Purpose: Read metadata (mainly the remote sensing imagery) from files of
* different providers like DigitalGlobe, GeoEye etc.
* Author: <NAME>, <EMAIL>
*
******************************************************************************
* Copyright (c) 2014-2015, NextGIS <EMAIL>
*
* 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.
****************************************************************************/
#ifndef GDAL_MDREADER_H_INCLUDED
#define GDAL_MDREADER_H_INCLUDED
#include "cpl_port.h"
#include "gdal_priv.h"
#define MD_DOMAIN_IMD "IMD" /**< image metadata section */
#define MD_DOMAIN_RPC "RPC" /**< rpc metadata section */
#define MD_DOMAIN_IMAGERY "IMAGERY" /**< imagery metadata section */
#define MD_DOMAIN_DEFAULT "" /**< default metadata section */
#define MD_NAME_ACQDATETIME "ACQUISITIONDATETIME" /**< Acquisition Date Time property name. The time should be in UTC */
#define MD_NAME_SATELLITE "SATELLITEID" /**< Satellite identificator property name */
#define MD_NAME_CLOUDCOVER "CLOUDCOVER" /**< Cloud coverage property name. The value between 0 - 100 or 999 if n/a */
#define MD_NAME_MDTYPE "METADATATYPE" /**< Metadata reader type property name. The reader processed this metadata */
#define MD_DATETIMEFORMAT "%Y-%m-%d %H:%M:%S" /**< Date time format */
#define MD_CLOUDCOVER_NA "999" /**< The value if cloud cover is n/a */
/**
* RPC/RPB specific defines
*/
#define RPC_ERR_BIAS "ERR_BIAS"
#define RPC_ERR_RAND "ERR_RAND"
#define RPC_LINE_OFF "LINE_OFF"
#define RPC_SAMP_OFF "SAMP_OFF"
#define RPC_LAT_OFF "LAT_OFF"
#define RPC_LONG_OFF "LONG_OFF"
#define RPC_HEIGHT_OFF "HEIGHT_OFF"
#define RPC_LINE_SCALE "LINE_SCALE"
#define RPC_SAMP_SCALE "SAMP_SCALE"
#define RPC_LAT_SCALE "LAT_SCALE"
#define RPC_LONG_SCALE "LONG_SCALE"
#define RPC_HEIGHT_SCALE "HEIGHT_SCALE"
#define RPC_LINE_NUM_COEFF "LINE_NUM_COEFF"
#define RPC_LINE_DEN_COEFF "LINE_DEN_COEFF"
#define RPC_SAMP_NUM_COEFF "SAMP_NUM_COEFF"
#define RPC_SAMP_DEN_COEFF "SAMP_DEN_COEFF"
/* Optional */
#define RPC_MIN_LONG "MIN_LONG"
#define RPC_MIN_LAT "MIN_LAT"
#define RPC_MAX_LONG "MAX_LONG"
#define RPC_MAX_LAT "MAX_LAT"
/**
* Enumerator of metadata readers
*/
typedef enum {
MDR_None = 0x00000000, /**< no reader */
MDR_DG = 0x00000001, /**< Digital Globe, METADATATYPE=DG */
MDR_GE = 0x00000002, /**< Geo Eye, METADATATYPE=GE */
MDR_OV = 0x00000004, /**< Orb View, METADATATYPE=OV */
MDR_PLEIADES = 0x00000008, /**< Pleiades, METADATATYPE=DIMAP */
MDR_SPOT = 0x00000010, /**< Spot, METADATATYPE=DIMAP */
MDR_RDK1 = 0x00000020, /**< Resurs DK1, METADATATYPE=MSP */
MDR_LS = 0x00000040, /**< Landsat, METADATATYPE=ODL */
MDR_RE = 0x00000080, /**< RapidEye, METADATATYPE=RE */
MDR_KOMPSAT = 0x00000100, /**< Kompsat, METADATATYPE=KARI */
MDR_EROS = 0x00000200, /**< EROS, METADATATYPE=EROS */
MDR_ALOS = 0x00000400, /**< ALOS, METADATATYPE=ALOS */
MDR_ANY = MDR_DG | MDR_GE | MDR_OV | MDR_PLEIADES | MDR_SPOT | MDR_RDK1 |
MDR_LS | MDR_RE | MDR_KOMPSAT | MDR_EROS | MDR_ALOS /**< any reader */
} MDReaders;
/**
* The base class for all metadata readers
*/
class CPL_DLL GDALMDReaderBase{
CPL_DISALLOW_COPY_ASSIGN(GDALMDReaderBase)
public:
GDALMDReaderBase(const char *pszPath, char **papszSiblingFiles);
virtual ~GDALMDReaderBase();
/**
* @brief Get specified metadata domain
* @param pszDomain The metadata domain to return
* @return List of metadata items
*/
virtual char ** GetMetadataDomain(const char *pszDomain);
/**
* @brief Fill provided metadata store class
* @param poMDMD Metadata store class
* @return true on success or false
*/
virtual bool FillMetadata(GDALMultiDomainMetadata* poMDMD);
/**
* @brief Determine whether the input parameter correspond to the particular
* provider of remote sensing data completely
* @return True if all needed sources files found
*/
virtual bool HasRequiredFiles() const = 0;
/**
* @brief Get metadata file names. The caller become owner of returned list
* and have to free it via CSLDestroy.
* @return A file name list
*/
virtual char** GetMetadataFiles() const = 0;
protected:
/**
* @brief Load metadata to the correspondent IMD, RPB, IMAGERY and DEFAULT
* domains
*/
virtual void LoadMetadata();
/**
* @brief Convert string like 2012-02-25T00:25:59.9440000Z to time
* @param pszDateTime String to convert
* @return value in second sinc epoch 1970-01-01 00:00:00
*/
virtual GIntBig GetAcquisitionTimeFromString(const char* pszDateTime);
/**
* @brief ReadXMLToList Transform xml to list of NULL terminated name=value
* strings
* @param psNode A xml node to process
* @param papszList A list to fill with name=value strings
* @param pszName A name of parent node. For root xml node should be empty.
* If name is not empty, the sibling nodes will not proceed
* @return An input list filled with values
*/
virtual char** ReadXMLToList(CPLXMLNode* psNode, char** papszList,
const char* pszName = "");
/**
* @brief AddXMLNameValueToList Execute from ReadXMLToList to add name and
* value to list. One can override this function for special
* processing input values before add to list.
* @param papszList A list to fill with name=value strings
* @param pszName A name to add
* @param pszValue A value to add
* @return An input list filled with values
*/
virtual char** AddXMLNameValueToList(char** papszList, const char *pszName,
const char *pszValue);
protected:
//! @cond Doxygen_Suppress
char **m_papszIMDMD = nullptr;
char **m_papszRPCMD = nullptr;
char **m_papszIMAGERYMD = nullptr;
char **m_papszDEFAULTMD = nullptr;
bool m_bIsMetadataLoad = false;
//! @endcond
};
/**
* The metadata reader main class.
* The main purpose of this class is to provide an correspondent reader
* for provided path.
*/
class CPL_DLL GDALMDReaderManager{
CPL_DISALLOW_COPY_ASSIGN(GDALMDReaderManager)
public:
GDALMDReaderManager();
virtual ~GDALMDReaderManager();
/**
* @brief Try to detect metadata reader correspondent to the provided
* datasource path
* @param pszPath a path to GDALDataset
* @param papszSiblingFiles file list for metadata search purposes
* @param nType a preferable reader type (may be the OR of MDReaders)
* @return an appropriate reader or NULL if no such reader or error.
* The pointer delete by the GDALMDReaderManager, so the user have not
* delete it.
*/
virtual GDALMDReaderBase* GetReader(const char *pszPath,
char **papszSiblingFiles,
GUInt32 nType = MDR_ANY);
protected:
//! @cond Doxygen_Suppress
GDALMDReaderBase *m_pReader = nullptr;
//! @endcond
};
// misc
CPLString CPLStrip(const CPLString& osString, const char cChar);
CPLString CPLStripQuotes(const CPLString& osString);
char** GDALLoadRPBFile( const CPLString& osFilePath );
char** GDALLoadRPCFile( const CPLString& osFilePath );
char** GDALLoadIMDFile( const CPLString& osFilePath );
bool GDALCheckFileHeader(const CPLString& soFilePath,
const char * pszTestString,
int nBufferSize = 256);
CPLErr GDALWriteRPBFile( const char *pszFilename, char **papszMD );
CPLErr GDALWriteRPCTXTFile( const char *pszFilename, char **papszMD );
CPLErr GDALWriteIMDFile( const char *pszFilename, char **papszMD );
#endif //GDAL_MDREADER_H_INCLUDED
| 3,708 |
12,278 |
<filename>boost/libs/spirit/classic/example/fundamental/matching_tags.cpp
/*=============================================================================
Copyright (c) 2002-2003 <NAME>
http://spirit.sourceforge.net/
Use, modification and distribution is subject to the Boost Software
License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
////////////////////////////////////////////////////////////////////////////
//
// HTML/XML like tag matching grammar
// Demonstrates phoenix and closures and parametric parsers
// This is discussed in the "Closures" chapter in the Spirit User's Guide.
//
// [ JDG 6/30/2002 ]
//
////////////////////////////////////////////////////////////////////////////
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_attribute.hpp>
#include <iostream>
#include <string>
////////////////////////////////////////////////////////////////////////////
using namespace std;
using namespace BOOST_SPIRIT_CLASSIC_NS;
using namespace phoenix;
////////////////////////////////////////////////////////////////////////////
//
// HTML/XML like tag matching grammar
//
////////////////////////////////////////////////////////////////////////////
struct tags_closure : BOOST_SPIRIT_CLASSIC_NS::closure<tags_closure, string>
{
member1 tag;
};
struct tags : public grammar<tags>
{
template <typename ScannerT>
struct definition {
definition(tags const& /*self*/)
{
element = start_tag >> *element >> end_tag;
start_tag =
'<'
>> lexeme_d
[
(+alpha_p)
[
// construct string from arg1 and arg2 lazily
// and assign to element.tag
element.tag = construct_<string>(arg1, arg2)
]
]
>> '>';
end_tag = "</" >> f_str_p(element.tag) >> '>';
}
rule<ScannerT, tags_closure::context_t> element;
rule<ScannerT> start_tag, end_tag;
rule<ScannerT, tags_closure::context_t> const&
start() const { return element; }
};
};
////////////////////////////////////////////////////////////////////////////
//
// Main program
//
////////////////////////////////////////////////////////////////////////////
int
main()
{
cout << "/////////////////////////////////////////////////////////\n\n";
cout << "\t\tHTML/XML like tag matching parser demo \n\n";
cout << "/////////////////////////////////////////////////////////\n\n";
cout << "Type an HTML/XML like nested tag input...or [q or Q] to quit\n\n";
cout << "Example: <html><head></head><body></body></html>\n\n";
tags p; // Our parser
string str;
while (getline(cin, str))
{
if (str.empty() || str[0] == 'q' || str[0] == 'Q')
break;
parse_info<> info = parse(str.c_str(), p, space_p);
if (info.full)
{
cout << "-------------------------\n";
cout << "Parsing succeeded\n";
cout << "-------------------------\n";
}
else
{
cout << "-------------------------\n";
cout << "Parsing failed\n";
cout << "stopped at: \": " << info.stop << "\"\n";
cout << "-------------------------\n";
}
}
cout << "Bye... :-) \n\n";
return 0;
}
| 1,387 |
1,418 |
package aima.core.learning.neural;
/**
* @author <NAME>
*
*/
public class PureLinearActivationFunction implements ActivationFunction {
public double activation(double parameter) {
return parameter;
}
public double deriv(double parameter) {
return 1;
}
}
| 81 |
351 |
# Generated by Django 2.1.4 on 2018-12-22 14:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('wagtailcore', '0041_group_collection_permissions_verbose_name_plural'),
]
operations = [
migrations.CreateModel(
name='Configuration',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('default_shipping_rate', models.DecimalField(decimal_places=2, default=3.95, help_text='The default shipping rate for countries which have not been configured', max_digits=12)),
('default_shipping_carrier', models.CharField(default='Royal Mail', help_text='The default shipping carrier', max_length=32)),
('default_shipping_enabled', models.BooleanField(default=False, help_text='Whether to enable default shipping. This essentially means you ship to all countries, not only those with configured shipping rates')),
('currency_html_code', models.CharField(default='£', help_text='The HTML code for the currency symbol. Used for display purposes only', max_length=12)),
('currency', models.CharField(default='GBP', help_text='The iso currency code to use for payments', max_length=6)),
('site', models.OneToOneField(editable=False, on_delete=django.db.models.deletion.CASCADE, to='wagtailcore.Site')),
],
options={
'abstract': False,
},
),
]
| 628 |
2,027 |
<reponame>sullis/atomix<gh_stars>1000+
/*
* Copyright 2016-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.core.multimap;
import com.google.common.collect.Multimap;
import com.google.common.util.concurrent.MoreExecutors;
import io.atomix.core.collection.DistributedCollection;
import io.atomix.core.map.DistributedMap;
import io.atomix.core.multiset.DistributedMultiset;
import io.atomix.core.set.DistributedSet;
import io.atomix.primitive.SyncPrimitive;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.Executor;
/**
* This provides a synchronous version of the functionality provided by
* {@link AsyncAtomicMultimap}. Instead of returning futures this map
* blocks until the future completes then returns the result.
*/
public interface DistributedMultimap<K, V> extends SyncPrimitive, Multimap<K, V> {
/**
* Returns a set of the keys contained in this multimap with one or more
* associated values.
*
* @return the collection of all keys with one or more associated values,
* this may be empty
*/
@Override
DistributedSet<K> keySet();
/**
* Returns a multiset of the keys present in this multimap with one or more
* associated values each. Keys will appear once for each key-value pair
* in which they participate.
*
* @return a multiset of the keys, this may be empty
*/
@Override
DistributedMultiset<K> keys();
/**
* Returns a collection of values in the set with duplicates permitted, the
* size of this collection will equal the size of the map at the time of
* creation.
*
* @return a collection of values, this may be empty
*/
@Override
DistributedMultiset<V> values();
/**
* Returns a collection of each key-value pair in this map.
*
* @return a collection of all entries in the map, this may be empty
*/
@Override
DistributedCollection<Map.Entry<K, V>> entries();
@Override
DistributedMap<K, Collection<V>> asMap();
/**
* Registers the specified listener to be notified whenever the map is updated.
*
* @param listener listener to notify about map events
*/
default void addListener(MultimapEventListener<K, V> listener) {
addListener(listener, MoreExecutors.directExecutor());
}
/**
* Registers the specified listener to be notified whenever the map is updated.
*
* @param listener listener to notify about map events
* @param executor executor to use for handling incoming map events
*/
void addListener(MultimapEventListener<K, V> listener, Executor executor);
/**
* Unregisters the specified listener such that it will no longer
* receive map change notifications.
*
* @param listener listener to unregister
*/
void removeListener(MultimapEventListener<K, V> listener);
@Override
AsyncDistributedMultimap<K, V> async();
}
| 1,001 |
798 |
<gh_stars>100-1000
/*
* The MIT License
*
* Copyright (c) 2014 The Broad Institute
*
* 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 picard.vcf;
import htsjdk.samtools.util.CollectionUtil;
import htsjdk.samtools.util.IOUtil;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.variantcontext.writer.Options;
import htsjdk.variant.variantcontext.writer.VariantContextWriter;
import htsjdk.variant.variantcontext.writer.VariantContextWriterBuilder;
import htsjdk.variant.vcf.VCFFileReader;
import htsjdk.variant.vcf.VCFHeader;
import org.broadinstitute.barclay.argparser.Argument;
import org.broadinstitute.barclay.argparser.CommandLineProgramProperties;
import org.broadinstitute.barclay.help.DocumentedFeature;
import picard.cmdline.CommandLineProgram;
import picard.cmdline.StandardOptionDefinitions;
import picard.cmdline.programgroups.VariantManipulationProgramGroup;
import java.io.File;
import java.util.EnumSet;
/**
* Renames a sample within a VCF or BCF.
*
* <h3> Summary </h3>
* This tool enables the user to rename a sample in either a VCF or BCF file. It is intended to change the name of a
* sample in a VCF prior to merging with VCF files in which one or more samples have similar names. Note that the
* input VCF file must be single-sample VCF and that the NEW_SAMPLE_NAME argument is required.
*
*
* <h3> Inputs</h3>
* <ul>
* <li> Input single-sample VCF or BCF file. </li>
* <li> Output single-sample VCF or BCF file. </li>
* <li> New name to give sample in output VCF. </li>
* <li> [Optional] Existing name of sample in VCF; if provided, asserts that that is the name of the extant sample name. </li>
* </ul>
*
* <h3>Usage example:</h3>
* <pre>
* java -jar picard.jar RenameSampleInVcf \
* INPUT=input_variants.vcf \
* OUTPUT=output_variants.vcf \
* NEW_SAMPLE_NAME=sample
* </pre>
*
* <h3> Notes </h3>
* The input VCF (or BCF) <i>must</i> be single-sample.
*
*/
@CommandLineProgramProperties(
summary = RenameSampleInVcf.USAGE_DETAILS,
oneLineSummary = RenameSampleInVcf.USAGE_SUMMARY,
programGroup = VariantManipulationProgramGroup.class)
@DocumentedFeature
public class RenameSampleInVcf extends CommandLineProgram {
static final String USAGE_SUMMARY = "Renames a sample within a VCF or BCF.";
static final String USAGE_DETAILS = "This tool enables the user to rename a sample in either a VCF or BCF file. " +
"It is intended to change the name of a sample in a VCF prior to merging with VCF files in which one or more samples have " +
"similar names. Note that the input VCF file must be single-sample VCF and that the NEW_SAMPLE_NAME is required." +
"<br /><br />" +
"<h4>Usage example:</h4>" +
"<pre>" +
"java -jar picard.jar RenameSampleInVcf \\<br />" +
" INPUT=input_variants.vcf \\<br />" +
" OUTPUT=output_variants.vcf \\<br />" +
" NEW_SAMPLE_NAME=sample" +
"</pre>" +
"<h4> Notes </h4>" +
"<br />" +
"The input VCF (or BCF) <i>must</i> be single-sample.";
@Argument(shortName=StandardOptionDefinitions.INPUT_SHORT_NAME, doc="Input single sample VCF or BCF file.")
public File INPUT;
@Argument(shortName=StandardOptionDefinitions.OUTPUT_SHORT_NAME, doc="Output single sample VCF.")
public File OUTPUT;
@Argument(doc="Existing name of sample in VCF; if provided, asserts that that is the name of the extant sample name", optional = true)
public String OLD_SAMPLE_NAME = null;
@Argument(doc="New name to give sample in output VCF.")
public String NEW_SAMPLE_NAME;
@Override
protected int doWork() {
IOUtil.assertFileIsReadable(INPUT);
IOUtil.assertFileIsWritable(OUTPUT);
final VCFFileReader in = new VCFFileReader(INPUT, false);
final VCFHeader header = in.getFileHeader();
if (header.getGenotypeSamples().size() > 1) {
throw new IllegalArgumentException("Input VCF must be single-sample.");
}
if (OLD_SAMPLE_NAME != null && !OLD_SAMPLE_NAME.equals(header.getGenotypeSamples().get(0))) {
throw new IllegalArgumentException("Input VCF did not contain expected sample. Contained: " + header.getGenotypeSamples().get(0));
}
final EnumSet<Options> options = EnumSet.copyOf(VariantContextWriterBuilder.DEFAULT_OPTIONS);
if (CREATE_INDEX) options.add(Options.INDEX_ON_THE_FLY); else options.remove(Options.INDEX_ON_THE_FLY);
final VCFHeader outHeader = new VCFHeader(header.getMetaDataInInputOrder(), CollectionUtil.makeList(NEW_SAMPLE_NAME));
final VariantContextWriter out = new VariantContextWriterBuilder()
.setOptions(options)
.setOutputFile(OUTPUT).setReferenceDictionary(outHeader.getSequenceDictionary()).build();
out.writeHeader(outHeader);
for (final VariantContext ctx : in) {
out.add(ctx);
}
out.close();
in.close();
return 0;
}
}
| 2,242 |
4,537 |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "slave/containerizer/mesos/isolators/network/ports.hpp"
#include <dirent.h>
#include <sys/types.h>
#include <process/after.hpp>
#include <process/async.hpp>
#include <process/defer.hpp>
#include <process/id.hpp>
#include <process/loop.hpp>
#include <stout/lambda.hpp>
#include <stout/numify.hpp>
#include <stout/path.hpp>
#include <stout/proc.hpp>
#include "common/protobuf_utils.hpp"
#include "common/values.hpp"
#include "linux/cgroups.hpp"
#include "slave/constants.hpp"
#include "slave/containerizer/mesos/paths.hpp"
using std::list;
using std::set;
using std::string;
using std::vector;
using process::Continue;
using process::ControlFlow;
using process::Failure;
using process::Future;
using process::Owned;
using process::defer;
using mesos::slave::ContainerConfig;
using mesos::slave::ContainerLaunchInfo;
using mesos::slave::ContainerLimitation;
using mesos::slave::ContainerState;
using mesos::slave::Isolator;
using mesos::internal::values::intervalSetToRanges;
using mesos::internal::values::rangesToIntervalSet;
using namespace routing::diagnosis;
namespace mesos {
namespace internal {
namespace slave {
// Given a cgroup hierarchy and a set of container IDs, collect
// the ports of all the listening sockets open in each cgroup,
// indexed by container ID.
static hashmap<ContainerID, IntervalSet<uint16_t>>
collectContainerListeners(
const string& cgroupsRoot,
const string& freezerHierarchy,
const Option<IntervalSet<uint16_t>>& isolatedPorts,
const hashset<ContainerID>& containerIds)
{
hashmap<ContainerID, IntervalSet<uint16_t>> listeners;
Try<hashmap<uint32_t, socket::Info>> listenInfos =
NetworkPortsIsolatorProcess::getListeningSockets();
if (listenInfos.isError()) {
LOG(ERROR) << "Failed to query listening sockets: "
<< listenInfos.error();
return listeners;
}
if (listenInfos->empty()) {
return listeners;
}
foreach (const ContainerID& containerId, containerIds) {
// Reconstruct the cgroup path from the container ID.
string cgroup =
containerizer::paths::getCgroupPath(cgroupsRoot, containerId);
VLOG(1) << "Checking processes for container " << containerId
<< " in cgroup " << cgroup;
Try<set<pid_t>> pids = cgroups::processes(freezerHierarchy, cgroup);
if (pids.isError()) {
LOG(ERROR) << "Failed to list processes for container "
<< containerId << ": " << pids.error();
continue;
}
// For each process in this container, check whether any of its open
// sockets matches something in the listening set.
foreach (pid_t pid, pids.get()) {
Try<vector<uint32_t>> sockets =
NetworkPortsIsolatorProcess::getProcessSockets(pid);
// The PID might have exited since we sampled the cgroup tasks, so
// don't worry too much if this fails.
if (sockets.isError()) {
VLOG(1) << "Failed to list sockets for PID "
<< stringify(pid) << ": " << sockets.error();
continue;
}
if (sockets->empty()) {
continue;
}
foreach (uint32_t inode, sockets.get()) {
if (!listenInfos->contains(inode)) {
continue;
}
const auto& socketInfo = listenInfos->at(inode);
process::network::inet::Address address(
socketInfo.sourceIP.get(),
ntohs(socketInfo.sourcePort.get()));
if (VLOG_IS_ON(1)) {
Result<string> cmd = proc::cmdline(pid);
if (cmd.isSome()) {
VLOG(1) << "PID " << pid << " in container " << containerId
<< " (" << cmd.get() << ")"
<< " is listening on port " << address.port;
} else {
VLOG(1) << "PID " << pid << " in container " << containerId
<< " is listening on port " << address.port;
}
}
// Only collect this listen socket if it falls within the
// isolated range.
if (isolatedPorts.isNone() || isolatedPorts->contains(address.port)) {
listeners[containerId].add(address.port);
}
}
}
}
return listeners;
}
// Return a hashmap of routing::diagnosis::socket::Info structures
// for all listening sockets, indexed by the socket inode.
Try<hashmap<uint32_t, socket::Info>>
NetworkPortsIsolatorProcess::getListeningSockets()
{
Try<vector<socket::Info>> socketInfos = socket::infos(
AF_INET,
socket::state::LISTEN);
if (socketInfos.isError()) {
return Error(socketInfos.error());
}
hashmap<uint32_t, socket::Info> inodes;
foreach (const socket::Info& info, socketInfos.get()) {
// The inode should never be 0. This would only happen if the kernel
// didn't return the inode in the sockdiag response, which would imply
// a very old kernel or a problem between the kernel and libnl.
if (info.inode != 0) {
inodes.emplace(info.inode, info);
}
}
return inodes;
}
// Extract the inode field from a /proc/$PID/fd entry. The format of
// the socket entry is "socket:[nnnn]" where nnnn is the numberic inode
// number of the socket.
static uint32_t extractSocketInode(const string& sock)
{
const size_t s = sizeof("socket:[]") - 1;
const string val = sock.substr(s - 1, sock.size() - s);
Try<uint32_t> value = numify<uint32_t>(val);
CHECK_SOME(value);
return value.get();
}
// Return the inodes of all the sockets open in the the given process.
Try<vector<uint32_t>> NetworkPortsIsolatorProcess::getProcessSockets(pid_t pid)
{
const string fdPath = path::join("/proc", stringify(pid), "fd");
DIR* dir = opendir(fdPath.c_str());
if (dir == nullptr) {
return ErrnoError("Failed to open directory '" + fdPath + "'");
}
vector<uint32_t> inodes;
struct dirent* entry;
char target[NAME_MAX];
while (true) {
errno = 0;
if ((entry = readdir(dir)) == nullptr) {
// If errno is non-zero, readdir failed.
if (errno != 0) {
Error error = ErrnoError("Failed to read directory '" + fdPath + "'");
CHECK_EQ(closedir(dir), 0) << os::strerror(errno);
return error;
}
// Otherwise we just reached the end of the directory and we are done.
CHECK_EQ(closedir(dir), 0) << os::strerror(errno);
return inodes;
}
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
ssize_t nbytes = readlinkat(
dirfd(dir), entry->d_name, target, sizeof(target) - 1);
if (nbytes == -1) {
Error error = ErrnoError(
"Failed to read symbolic link '" +
path::join(fdPath, entry->d_name) + "'");
CHECK_EQ(closedir(dir), 0) << os::strerror(errno);
return error;
}
target[nbytes] = '\0';
if (strings::startsWith(target, "socket:[")) {
inodes.push_back(extractSocketInode(target));
}
}
}
// Return true if any "ports" resources are specified in the flags. This
// is later used to distinguish between empty an unspecified ports.
static bool havePortsResource(const Flags& flags)
{
vector<Resource> resourceList = Resources::fromString(
flags.resources.getOrElse(""), flags.default_role).get();
foreach(const auto& resource, resourceList) {
if (resource.name() == "ports") {
return true;
}
}
return false;
}
Try<Isolator*> NetworkPortsIsolatorProcess::create(const Flags& flags)
{
if (flags.launcher != "linux") {
return Error("The 'network/ports' isolator requires the 'linux' launcher");
}
if (flags.check_agent_port_range_only &&
flags.container_ports_isolated_range.isSome()) {
return Error(
"Only one of `--check_agent_port_range_only` or "
"'--container_ports_isolated_range` should be specified");
}
Try<string> freezerHierarchy = cgroups::prepare(
flags.cgroups_hierarchy,
"freezer",
flags.cgroups_root);
if (freezerHierarchy.isError()) {
return Error(
"Failed to prepare the freezer cgroup: " +
freezerHierarchy.error());
}
// Set None as the default of isolated ports range.
Option<IntervalSet<uint16_t>> isolatedPorts = None();
// If we are only watching the ports in the agent resources, figure
// out what the agent ports will be by checking the resources flag
// and falling back to the default.
if (flags.check_agent_port_range_only) {
Try<Resources> resources = Resources::parse(
flags.resources.getOrElse(""),
flags.default_role);
if (resources.isError()) {
return Error(
"Failed to parse agent resources: " + resources.error());
}
// Mirroring the logic in Containerizer::resources(), we need
// to distinguish between an empty ports resource and a missing
// ports resource.
if (!havePortsResource(flags)) {
// Apply the defaults, if no ports were specified.
resources = Resources(
Resources::parse(
"ports",
stringify(DEFAULT_PORTS),
flags.default_role).get());
isolatedPorts =
rangesToIntervalSet<uint16_t>(resources->ports().get()).get();
} else if (resources->ports().isSome()) {
// Use the given non-empty ports resource.
Try<IntervalSet<uint16_t>> ports =
rangesToIntervalSet<uint16_t>(resources->ports().get());
if (ports.isError()) {
return Error(
"Invalid ports resource '" +
stringify(resources->ports().get()) +
"': " + ports.error());
}
isolatedPorts = ports.get();
} else {
// An empty ports resource was specified.
isolatedPorts = IntervalSet<uint16_t>{};
}
}
// Use the given isolated ports range if specified.
if (flags.container_ports_isolated_range.isSome()) {
Try<Resource> portRange =
Resources::parse(
"ports",
flags.container_ports_isolated_range.get(),
"*");
if (portRange.isError()) {
return Error(
"Failed to parse isolated ports range '" +
flags.container_ports_isolated_range.get() + "'");
}
if (portRange->type() != Value::RANGES) {
return Error(
"Invalid port range resource type " +
mesos::Value_Type_Name(portRange->type()) +
", expecting " +
mesos::Value_Type_Name(Value::RANGES));
}
Try<IntervalSet<uint16_t>> ports =
rangesToIntervalSet<uint16_t>(portRange->ranges());
if (ports.isError()) {
return Error(ports.error());
}
isolatedPorts = ports.get();
}
if (isolatedPorts.isSome()) {
LOG(INFO) << "Isolating port range " << stringify(isolatedPorts.get());
}
return new MesosIsolator(process::Owned<MesosIsolatorProcess>(
new NetworkPortsIsolatorProcess(
strings::contains(flags.isolation, "network/cni"),
flags.container_ports_watch_interval,
flags.enforce_container_ports,
flags.cgroups_root,
freezerHierarchy.get(),
isolatedPorts)));
}
NetworkPortsIsolatorProcess::NetworkPortsIsolatorProcess(
bool _cniIsolatorEnabled,
const Duration& _watchInterval,
const bool& _enforceContainerPorts,
const string& _cgroupsRoot,
const string& _freezerHierarchy,
const Option<IntervalSet<uint16_t>>& _isolatedPorts)
: ProcessBase(process::ID::generate("network-ports-isolator")),
cniIsolatorEnabled(_cniIsolatorEnabled),
watchInterval(_watchInterval),
enforceContainerPorts(_enforceContainerPorts),
cgroupsRoot(_cgroupsRoot),
freezerHierarchy(_freezerHierarchy),
isolatedPorts(_isolatedPorts)
{
}
bool NetworkPortsIsolatorProcess::supportsNesting()
{
return true;
}
// Return whether this ContainerInfo has a NetworkInfo with a name. This
// is our signal that the container is (or will be) joined to a CNI network.
static bool hasNamedNetwork(const ContainerInfo& container_info)
{
foreach (const auto& networkInfo, container_info.network_infos()) {
if (networkInfo.has_name()) {
return true;
}
}
return false;
}
// Recover the given list of containers. Note that we don't look at
// the executor resources from the ContainerState because from the
// perspective of the container, they are incomplete. That is, the
// resources here are only the resources for the executor, not the
// resources for the whole container. At this point, we don't know
// whether any of the tasks in the container have been allocated ports,
// so we must not start isolating it until we receive the resources
// update.
Future<Nothing> NetworkPortsIsolatorProcess::recover(
const vector<ContainerState>& states,
const hashset<ContainerID>& orphans)
{
// First, recover all the root level containers.
foreach (const auto& state, states) {
if (state.container_id().has_parent()) {
continue;
}
CHECK(!infos.contains(state.container_id()))
<< "Duplicate ContainerID " << state.container_id();
// A root level container ought to always have an executor_info.
CHECK(state.has_executor_info());
if (!cniIsolatorEnabled) {
infos.emplace(state.container_id(), Owned<Info>(new Info()));
continue;
}
// Ignore containers that will be network isolated by the
// `network/cni` isolator on the rationale that they ought
// to be getting a per-container IP address.
if (!state.executor_info().has_container() ||
!hasNamedNetwork(state.executor_info().container())) {
infos.emplace(state.container_id(), Owned<Info>(new Info()));
}
}
// Now that we know which root level containers we are isolating, we can
// decide which child containers we also want.
foreach (const auto& state, states) {
if (!state.container_id().has_parent()) {
continue;
}
CHECK(!infos.contains(state.container_id()))
<< "Duplicate ContainerID " << state.container_id();
if (infos.contains(protobuf::getRootContainerId(state.container_id()))) {
infos.emplace(state.container_id(), Owned<Info>(new Info()));
}
}
// We don't need to worry about any orphans since we don't have any state
// to clean up and we know the containerizer will destroy them soon.
return Nothing();
}
Future<Option<ContainerLaunchInfo>> NetworkPortsIsolatorProcess::prepare(
const ContainerID& containerId,
const ContainerConfig& containerConfig)
{
if (infos.contains(containerId)) {
return Failure("Container has already been prepared");
}
if (cniIsolatorEnabled) {
// A nested container implicitly joins a parent CNI network. The
// network configuration is always set from the top of the tree of
// nested containers, so we know that we should only isolate the
// child if we already have the root of the container tree.
if (containerId.has_parent()) {
if (!infos.contains(protobuf::getRootContainerId(containerId))) {
return None();
}
} else {
// Ignore containers that will be network isolated by the
// `network/cni` isolator on the rationale that they ought
// to be getting a per-container IP address.
if (containerConfig.has_container_info() &&
hasNamedNetwork(containerConfig.container_info())) {
return None();
}
}
}
infos.emplace(containerId, Owned<Info>(new Info()));
return update(containerId, containerConfig.resources())
.then([]() -> Future<Option<ContainerLaunchInfo>> {
return None();
});
}
Future<ContainerLimitation> NetworkPortsIsolatorProcess::watch(
const ContainerID& containerId)
{
if (!infos.contains(containerId)) {
return Failure(
"Failed to watch ports for unknown container " +
stringify(containerId));
}
return infos.at(containerId)->limitation.future();
}
Future<Nothing> NetworkPortsIsolatorProcess::update(
const ContainerID& containerId,
const Resources& resourceRequests,
const google::protobuf::Map<string, Value::Scalar>& resourceLimits)
{
if (!infos.contains(containerId)) {
LOG(INFO) << "Ignoring update for unknown container " << containerId;
return Nothing();
}
const Owned<Info>& info = infos.at(containerId);
// The resources are attached to the root container. For child
// containers, just track its existence so that we can scan
// processes in the corresponding cgroup.
if (containerId.has_parent()) {
// Child containers don't get resources, only the parents do.
CHECK(resourceRequests.empty());
// Verify that we know about the root for this container.
CHECK(infos.contains(protobuf::getRootContainerId(containerId)));
return Nothing();
}
Option<Value::Ranges> ports = resourceRequests.ports();
if (ports.isSome()) {
const Owned<Info>& info = infos.at(containerId);
info->allocatedPorts = rangesToIntervalSet<uint16_t>(ports.get()).get();
} else {
info->allocatedPorts = IntervalSet<uint16_t>();
}
LOG(INFO) << "Updated ports to "
<< intervalSetToRanges(info->allocatedPorts.get())
<< " for container " << containerId;
return Nothing();
}
Future<Nothing> NetworkPortsIsolatorProcess::cleanup(
const ContainerID& containerId)
{
if (!infos.contains(containerId)) {
LOG(INFO) << "Ignoring cleanup for unknown container " << containerId;
return Nothing();
}
infos.erase(containerId);
return Nothing();
}
// Given a map of containers to the ports they are listening on,
// verify that each container is only listening on ports that we
// have recorded as being allocated to it.
Future<Nothing> NetworkPortsIsolatorProcess::check(
const hashmap<ContainerID, IntervalSet<uint16_t>>& listeners)
{
foreachpair (const ContainerID& containerId,
const IntervalSet<uint16_t>& ports,
listeners) {
if (!infos.contains(containerId)) {
continue;
}
ContainerID rootContainerId = protobuf::getRootContainerId(containerId);
CHECK(infos.contains(rootContainerId));
// Find the corresponding root container that holds the resources
// for this container.
const Owned<Info>& info = infos.at(rootContainerId);
if (info->allocatedPorts.isSome() &&
!info->allocatedPorts->contains(ports)) {
const IntervalSet<uint16_t> unallocatedPorts =
ports - info->allocatedPorts.get();
// Only log unallocated ports once to prevent excessive logging
// for the same unallocated ports while port enforcement is disabled.
if (info->activePorts.isSome() && info->activePorts == ports) {
continue;
}
// Cache the last listeners port sample so that we will
// only log new ports resource violations.
info->activePorts = ports;
Resource resource;
resource.set_name("ports");
resource.set_type(Value::RANGES);
resource.mutable_ranges()->CopyFrom(
intervalSetToRanges(unallocatedPorts));
const string message =
"Container " + stringify(containerId) +
" is listening on unallocated port(s): " +
stringify(resource.ranges());
LOG(INFO) << message;
if (enforceContainerPorts) {
info->limitation.set(
protobuf::slave::createContainerLimitation(
Resources(resource),
message,
TaskStatus::REASON_CONTAINER_LIMITATION));
}
}
}
return Nothing();
}
void NetworkPortsIsolatorProcess::initialize()
{
process::PID<NetworkPortsIsolatorProcess> self(this);
// Start a loop to periodically reconcile listening ports against allocated
// resources. Note that we have to do this after the process we want the
// loop to schedule against (the ports isolator process) has been spawned.
process::loop(
self,
[=]() {
return process::after(watchInterval);
},
[=](const Nothing&) {
return process::async(
&collectContainerListeners,
cgroupsRoot,
freezerHierarchy,
isolatedPorts,
infos.keys())
.then(defer(self, &NetworkPortsIsolatorProcess::check, lambda::_1))
.then([]() -> ControlFlow<Nothing> { return Continue(); });
});
}
} // namespace slave {
} // namespace internal {
} // namespace mesos {
| 7,663 |
3,459 |
//============================================================================
//
// SSSS tt lll lll
// SS SS tt ll ll
// SS tttttt eeee ll ll aaaa
// SSSS tt ee ee ll ll aa
// SS tt eeeeee ll ll aaaaa -- "An Atari 2600 VCS Emulator"
// SS SS tt ee ll ll aa aa
// SSSS ttt eeeee llll llll aaaaa
//
// Copyright (c) 1995-2011 by <NAME>, <NAME>
// and the Stella Team
//
// See the file "License.txt" for information on usage and redistribution of
// this file, and for a DISCLAIMER OF ALL WARRANTIES.
//
// $Id: TIATables.hxx 2199 2011-01-01 16:04:32Z stephena $
//============================================================================
#ifndef TIA_TABLES_HXX
#define TIA_TABLES_HXX
#include "bspf.hxx"
enum TIABit {
P0Bit = 0x01, // Bit for Player 0
M0Bit = 0x02, // Bit for Missle 0
P1Bit = 0x04, // Bit for Player 1
M1Bit = 0x08, // Bit for Missle 1
BLBit = 0x10, // Bit for Ball
PFBit = 0x20, // Bit for Playfield
ScoreBit = 0x40, // Bit for Playfield score mode
PriorityBit = 0x80 // Bit for Playfield priority
};
enum CollisionBit
{
Cx_M0P1 = 1 << 0, // Missle0 - Player1 collision
Cx_M0P0 = 1 << 1, // Missle0 - Player0 collision
Cx_M1P0 = 1 << 2, // Missle1 - Player0 collision
Cx_M1P1 = 1 << 3, // Missle1 - Player1 collision
Cx_P0PF = 1 << 4, // Player0 - Playfield collision
Cx_P0BL = 1 << 5, // Player0 - Ball collision
Cx_P1PF = 1 << 6, // Player1 - Playfield collision
Cx_P1BL = 1 << 7, // Player1 - Ball collision
Cx_M0PF = 1 << 8, // Missle0 - Playfield collision
Cx_M0BL = 1 << 9, // Missle0 - Ball collision
Cx_M1PF = 1 << 10, // Missle1 - Playfield collision
Cx_M1BL = 1 << 11, // Missle1 - Ball collision
Cx_BLPF = 1 << 12, // Ball - Playfield collision
Cx_P0P1 = 1 << 13, // Player0 - Player1 collision
Cx_M0M1 = 1 << 14 // Missle0 - Missle1 collision
};
// TIA Write/Read register names
enum TIARegister {
VSYNC = 0x00, // Write: vertical sync set-clear (D1)
VBLANK = 0x01, // Write: vertical blank set-clear (D7-6,D1)
WSYNC = 0x02, // Write: wait for leading edge of hrz. blank (strobe)
RSYNC = 0x03, // Write: reset hrz. sync counter (strobe)
NUSIZ0 = 0x04, // Write: number-size player-missle 0 (D5-0)
NUSIZ1 = 0x05, // Write: number-size player-missle 1 (D5-0)
COLUP0 = 0x06, // Write: color-lum player 0 (D7-1)
COLUP1 = 0x07, // Write: color-lum player 1 (D7-1)
COLUPF = 0x08, // Write: color-lum playfield (D7-1)
COLUBK = 0x09, // Write: color-lum background (D7-1)
CTRLPF = 0x0a, // Write: cntrl playfield ballsize & coll. (D5-4,D2-0)
REFP0 = 0x0b, // Write: reflect player 0 (D3)
REFP1 = 0x0c, // Write: reflect player 1 (D3)
PF0 = 0x0d, // Write: playfield register byte 0 (D7-4)
PF1 = 0x0e, // Write: playfield register byte 1 (D7-0)
PF2 = 0x0f, // Write: playfield register byte 2 (D7-0)
RESP0 = 0x10, // Write: reset player 0 (strobe)
RESP1 = 0x11, // Write: reset player 1 (strobe)
RESM0 = 0x12, // Write: reset missle 0 (strobe)
RESM1 = 0x13, // Write: reset missle 1 (strobe)
RESBL = 0x14, // Write: reset ball (strobe)
AUDC0 = 0x15, // Write: audio control 0 (D3-0)
AUDC1 = 0x16, // Write: audio control 1 (D4-0)
AUDF0 = 0x17, // Write: audio frequency 0 (D4-0)
AUDF1 = 0x18, // Write: audio frequency 1 (D3-0)
AUDV0 = 0x19, // Write: audio volume 0 (D3-0)
AUDV1 = 0x1a, // Write: audio volume 1 (D3-0)
GRP0 = 0x1b, // Write: graphics player 0 (D7-0)
GRP1 = 0x1c, // Write: graphics player 1 (D7-0)
ENAM0 = 0x1d, // Write: graphics (enable) missle 0 (D1)
ENAM1 = 0x1e, // Write: graphics (enable) missle 1 (D1)
ENABL = 0x1f, // Write: graphics (enable) ball (D1)
HMP0 = 0x20, // Write: horizontal motion player 0 (D7-4)
HMP1 = 0x21, // Write: horizontal motion player 1 (D7-4)
HMM0 = 0x22, // Write: horizontal motion missle 0 (D7-4)
HMM1 = 0x23, // Write: horizontal motion missle 1 (D7-4)
HMBL = 0x24, // Write: horizontal motion ball (D7-4)
VDELP0 = 0x25, // Write: vertical delay player 0 (D0)
VDELP1 = 0x26, // Write: vertical delay player 1 (D0)
VDELBL = 0x27, // Write: vertical delay ball (D0)
RESMP0 = 0x28, // Write: reset missle 0 to player 0 (D1)
RESMP1 = 0x29, // Write: reset missle 1 to player 1 (D1)
HMOVE = 0x2a, // Write: apply horizontal motion (strobe)
HMCLR = 0x2b, // Write: clear horizontal motion registers (strobe)
CXCLR = 0x2c, // Write: clear collision latches (strobe)
CXM0P = 0x00, // Read collision: D7=(M0,P1); D6=(M0,P0)
CXM1P = 0x01, // Read collision: D7=(M1,P0); D6=(M1,P1)
CXP0FB = 0x02, // Read collision: D7=(P0,PF); D6=(P0,BL)
CXP1FB = 0x03, // Read collision: D7=(P1,PF); D6=(P1,BL)
CXM0FB = 0x04, // Read collision: D7=(M0,PF); D6=(M0,BL)
CXM1FB = 0x05, // Read collision: D7=(M1,PF); D6=(M1,BL)
CXBLPF = 0x06, // Read collision: D7=(BL,PF); D6=(unused)
CXPPMM = 0x07, // Read collision: D7=(P0,P1); D6=(M0,M1)
INPT0 = 0x08, // Read pot port: D7
INPT1 = 0x09, // Read pot port: D7
INPT2 = 0x0a, // Read pot port: D7
INPT3 = 0x0b, // Read pot port: D7
INPT4 = 0x0c, // Read P1 joystick trigger: D7
INPT5 = 0x0d // Read P2 joystick trigger: D7
};
/**
The TIA class uses some static tables that aren't dependent on the actual
TIA state. For code organization, it's better to place that functionality
here.
@author <NAME>
@version $Id: TIATables.hxx 2199 2011-01-01 16:04:32Z stephena $
*/
class TIATables
{
public:
/**
Compute all static tables used by the TIA
*/
static void computeAllTables();
// Used to set the collision register to the correct value
static uInt16 CollisionMask[64];
// A mask table which can be used when an object is disabled
static uInt8 DisabledMask[640];
// Indicates the update delay associated with poking at a TIA address
static const Int16 PokeDelay[64];
#if 0
// Used to convert value written in a motion register into
// its internal representation
static const Int32 CompleteMotion[76][16];
#endif
// Indicates if HMOVE blanks should occur for the corresponding cycle
static const bool HMOVEBlankEnableCycles[76];
// Player mask table
// [alignment][suppress mode][nusiz][pixel]
static uInt8 PxMask[4][2][8][320];
// Missle mask table (entries are true or false)
// [alignment][number][size][pixel]
// There are actually only 4 possible size combinations on a real system
// The fifth size is used for simulating the starfield effect in
// Cosmic Ark and Stay Frosty
static uInt8 MxMask[4][8][5][320];
// Ball mask table (entries are true or false)
// [alignment][size][pixel]
static uInt8 BLMask[4][4][320];
// Playfield mask table for reflected and non-reflected playfields
// [reflect, pixel]
static uInt32 PFMask[2][160];
// Used to reflect a players graphics
static uInt8 GRPReflect[256];
// Indicates if player is being reset during delay, display or other times
// [nusiz][old pixel][new pixel]
static Int8 PxPosResetWhen[8][160][160];
private:
// Compute the collision decode table
static void buildCollisionMaskTable();
// Compute the player mask table
static void buildPxMaskTable();
// Compute the missle mask table
static void buildMxMaskTable();
// Compute the ball mask table
static void buildBLMaskTable();
// Compute playfield mask table
static void buildPFMaskTable();
// Compute the player reflect table
static void buildGRPReflectTable();
// Compute the player position reset when table
static void buildPxPosResetWhenTable();
};
#endif
| 3,303 |
348 |
<gh_stars>100-1000
{"nom":"Lalevade-d'Ardèche","circ":"3ème circonscription","dpt":"Ardèche","inscrits":819,"abs":452,"votants":367,"blancs":32,"nuls":24,"exp":311,"res":[{"nuance":"LR","nom":"<NAME>","voix":178},{"nuance":"REM","nom":"M. <NAME>","voix":133}]}
| 110 |
435 |
<reponame>cirnoftw/android-openslmediaplayer<filename>test/src/androidTest/java/com/h6ah4i/android/media/openslmediaplayer/classtest/PresetReverbTestCase.java
/*
* Copyright (C) 2014 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.h6ah4i.android.media.openslmediaplayer.classtest;
import com.h6ah4i.android.media.IBasicMediaPlayer;
import com.h6ah4i.android.media.IMediaPlayerFactory;
import com.h6ah4i.android.media.audiofx.IAudioEffect;
import com.h6ah4i.android.media.audiofx.IPresetReverb;
import com.h6ah4i.android.media.openslmediaplayer.base.BasicMediaPlayerTestCaseBase;
import com.h6ah4i.android.media.openslmediaplayer.testing.ParameterizedTestArgs;
import com.h6ah4i.android.media.openslmediaplayer.testing.ParameterizedTestSuiteBuilder;
import junit.framework.TestSuite;
import java.util.ArrayList;
import java.util.List;
public class PresetReverbTestCase
extends BasicMediaPlayerTestCaseBase {
private static final class TestParams extends BasicTestParams {
private final boolean mEnabled;
public TestParams(
Class<? extends IMediaPlayerFactory> factoryClass,
boolean enabled) {
super(factoryClass);
mEnabled = enabled;
}
public boolean getPreconditionEnabled() {
return mEnabled;
}
@Override
public String toString() {
return super.toString() + ", " + mEnabled;
}
}
public static TestSuite buildTestSuite(
Class<? extends IMediaPlayerFactory> factoryClazz) {
TestSuite suite = new TestSuite();
String[] testsWithoutPreconditionEnabled = new String[] {
"testSetAndGetEnabled",
"testHasControl",
"testMultiInstanceBehavior",
"testAfterReleased",
};
// use TestParam.getPreconditionEnabled()
{
ParameterizedTestSuiteBuilder.Filter filter =
ParameterizedTestSuiteBuilder.notMatches(
testsWithoutPreconditionEnabled);
List<TestParams> params = new ArrayList<TestParams>();
params.add(new TestParams(factoryClazz, false));
params.add(new TestParams(factoryClazz, true));
suite.addTest(ParameterizedTestSuiteBuilder.buildDetail(
PresetReverbTestCase.class, params, filter, false));
}
// don't use TestParam.getPreconditionEnabled()
{
ParameterizedTestSuiteBuilder.Filter filter =
ParameterizedTestSuiteBuilder.matches(
testsWithoutPreconditionEnabled);
List<TestParams> params = new ArrayList<TestParams>();
params.add(new TestParams(factoryClazz, false));
suite.addTest(ParameterizedTestSuiteBuilder.buildDetail(
PresetReverbTestCase.class, params, filter, false));
}
return suite;
}
public PresetReverbTestCase(ParameterizedTestArgs args) {
super(args);
}
private static final short[] PRESETS = new short[] {
IPresetReverb.PRESET_NONE,
IPresetReverb.PRESET_SMALLROOM,
IPresetReverb.PRESET_MEDIUMROOM,
IPresetReverb.PRESET_LARGEROOM,
IPresetReverb.PRESET_MEDIUMHALL,
IPresetReverb.PRESET_LARGEHALL,
IPresetReverb.PRESET_PLATE,
};
//
// Exposed test cases
//
public void testSetAndGetEnabled() {
IPresetReverb reverb = null;
try {
reverb = getFactory().createPresetReverb();
assertFalse(reverb.getEnabled());
assertEquals(IAudioEffect.SUCCESS, reverb.setEnabled(true));
assertTrue(reverb.getEnabled());
assertEquals(IAudioEffect.SUCCESS, reverb.setEnabled(false));
assertFalse(reverb.getEnabled());
} finally {
releaseQuietly(reverb);
}
}
public void testDefaultPreset() {
TestParams params = (TestParams) getTestParams();
IPresetReverb reverb = null;
try {
reverb = getFactory().createPresetReverb();
reverb.setEnabled(params.getPreconditionEnabled());
assertEquals(IPresetReverb.PRESET_NONE, reverb.getPreset());
assertEquals(IPresetReverb.PRESET_NONE, reverb.getProperties().preset);
} finally {
releaseQuietly(reverb);
}
}
public void testSetAndGetPreset() {
TestParams params = (TestParams) getTestParams();
IPresetReverb reverb = null;
try {
reverb = getFactory().createPresetReverb();
reverb.setEnabled(params.getPreconditionEnabled());
for (short preset : PRESETS) {
reverb.setPreset(preset);
assertEquals(preset, reverb.getPreset());
assertEquals(preset, reverb.getProperties().preset);
}
} finally {
releaseQuietly(reverb);
}
}
public void testSetInvalidPreset() {
TestParams params = (TestParams) getTestParams();
short[] INVALID_PRESETS = new short[] {
(short) -1,
(short) (IPresetReverb.PRESET_PLATE + 1),
};
IPresetReverb reverb = null;
try {
reverb = getFactory().createPresetReverb();
reverb.setEnabled(params.getPreconditionEnabled());
for (short preset : INVALID_PRESETS) {
try {
reverb.setPreset(preset);
fail();
} catch (IllegalArgumentException e) {
// expected
}
}
} finally {
releaseQuietly(reverb);
}
}
public void testSetAndGetPropertiesCompat() {
TestParams params = (TestParams) getTestParams();
IPresetReverb reverb = null;
try {
reverb = getFactory().createPresetReverb();
reverb.setEnabled(params.getPreconditionEnabled());
for (short preset : PRESETS) {
IPresetReverb.Settings settings = new IPresetReverb.Settings();
settings.preset = preset;
reverb.setProperties(settings);
assertEquals(preset, reverb.getPreset());
assertEquals(preset, reverb.getProperties().preset);
}
} finally {
releaseQuietly(reverb);
}
}
public void testGetId() {
TestParams params = (TestParams) getTestParams();
IPresetReverb reverb = null;
try {
reverb = getFactory().createPresetReverb();
reverb.setEnabled(params.getPreconditionEnabled());
assertNotEquals(0, reverb.getId());
} finally {
releaseQuietly(reverb);
}
}
public void testHasControl() {
IPresetReverb reverb1 = null, reverb2 = null, reverb3 = null;
try {
// create instance 1
// NOTE: [1]: has control, [2] not created, [3] not created
reverb1 = getFactory().createPresetReverb();
assertTrue(reverb1.hasControl());
// create instance 2
// NOTE: [1]: lost control, [2] has control, [3] not created
reverb2 = getFactory().createPresetReverb();
assertFalse(reverb1.hasControl());
assertTrue(reverb2.hasControl());
// create instance 3
// NOTE: [1]: lost control, [2] lost control, [3] not created
reverb3 = getFactory().createPresetReverb();
assertFalse(reverb1.hasControl());
assertFalse(reverb2.hasControl());
assertTrue(reverb3.hasControl());
// release instance 3
// NOTE: [1]: lost control, [2] has control, [3] released
reverb3.release();
reverb3 = null;
assertFalse(reverb1.hasControl());
assertTrue(reverb2.hasControl());
// release instance 2
// NOTE: [1]: lost control, [2] released, [3] released
reverb2.release();
reverb2 = null;
assertTrue(reverb1.hasControl());
} finally {
releaseQuietly(reverb1);
releaseQuietly(reverb2);
releaseQuietly(reverb3);
}
}
public void testMultiInstanceBehavior() {
IPresetReverb reverb1 = null, reverb2 = null;
try {
reverb1 = getFactory().createPresetReverb();
reverb2 = getFactory().createPresetReverb();
// check pre. conditions
assertFalse(reverb1.hasControl());
assertTrue(reverb2.hasControl());
assertFalse(reverb1.getEnabled());
assertFalse(reverb2.getEnabled());
assertEquals(IPresetReverb.PRESET_NONE, reverb1.getPreset());
assertEquals(IPresetReverb.PRESET_NONE, reverb2.getPreset());
// change states
assertEquals(IAudioEffect.SUCCESS, reverb2.setEnabled(true));
reverb2.setPreset(IPresetReverb.PRESET_SMALLROOM);
// check post conditions
assertFalse(reverb1.hasControl());
assertTrue(reverb2.hasControl());
assertTrue(reverb1.getEnabled());
assertTrue(reverb2.getEnabled());
assertEquals(IPresetReverb.PRESET_SMALLROOM, reverb1.getPreset());
assertEquals(IPresetReverb.PRESET_SMALLROOM, reverb2.getPreset());
// release effect 2
reverb2.release();
reverb2 = null;
// check effect 1 gains control
assertTrue(reverb1.hasControl());
assertEquals(IAudioEffect.SUCCESS, reverb1.setEnabled(false));
} finally {
releaseQuietly(reverb1);
releaseQuietly(reverb2);
}
}
public void testAfterReleased() {
try {
createReleasedPresetReverb().hasControl();
fail();
} catch (IllegalStateException e) {
// expected
}
try {
createReleasedPresetReverb().getEnabled();
fail();
} catch (IllegalStateException e) {
// expected
}
try {
createReleasedPresetReverb().setEnabled(false);
fail();
} catch (IllegalStateException e) {
// expected
}
try {
createReleasedPresetReverb().getId();
fail();
} catch (IllegalStateException e) {
// expected
}
try {
createReleasedPresetReverb().getPreset();
fail();
} catch (IllegalStateException e) {
// expected
}
try {
createReleasedPresetReverb().setPreset(IPresetReverb.PRESET_NONE);
fail();
} catch (IllegalStateException e) {
// expected
}
try {
createReleasedPresetReverb().getProperties();
fail();
} catch (IllegalStateException e) {
// expected
}
try {
IPresetReverb.Settings settings = new IPresetReverb.Settings();
settings.preset = IPresetReverb.PRESET_NONE;
createReleasedPresetReverb().setProperties(settings);
fail();
} catch (IllegalStateException e) {
// expected
}
}
public void testReleaseAfterAttachedPlayerReleased() throws Exception {
TestParams params = (TestParams) getTestParams();
IBasicMediaPlayer player = null;
IPresetReverb reverb = null;
try {
player = createWrappedPlayerInstance();
reverb = getFactory().createPresetReverb();
reverb.setEnabled(params.getPreconditionEnabled());
transitStateToPrepared(player, null);
// attach the effect
int effectId = reverb.getId();
assertNotEquals(0, effectId);
player.attachAuxEffect(effectId);
// release player
player.release();
// release reverb
reverb.release();
} finally {
releaseQuietly(player);
releaseQuietly(reverb);
}
}
public void testReleaseBeforeAttachedPlayerReleased() throws Exception {
TestParams params = (TestParams) getTestParams();
IBasicMediaPlayer player = null;
IPresetReverb reverb = null;
try {
player = createWrappedPlayerInstance();
reverb = getFactory().createPresetReverb();
reverb.setEnabled(params.getPreconditionEnabled());
transitStateToPrepared(player, null);
// attach the effect
int effectId = reverb.getId();
assertNotEquals(0, effectId);
player.attachAuxEffect(effectId);
// release reverb
reverb.release();
// release player
player.release();
} finally {
releaseQuietly(player);
releaseQuietly(reverb);
}
}
public void testReleaseAfterFactoryReleased() throws Exception {
IPresetReverb reverb = null;
try {
reverb = getFactory().createPresetReverb();
IPresetReverb.Settings origSettings = reverb.getProperties();
getFactory().release();
// NOTE: The reverb object is still usable
assertTrue(reverb.hasControl());
assertFalse(reverb.getEnabled());
assertNotEquals(0, reverb.getId());
reverb.getPreset();
reverb.setPreset(IPresetReverb.PRESET_NONE);
reverb.getProperties();
reverb.setProperties(origSettings);
reverb.release();
reverb = null;
} finally {
releaseQuietly(reverb);
}
}
//
// Utilities
//
static void assertEquals(IPresetReverb.Settings expected, IPresetReverb.Settings actual) {
assertEquals(expected.toString(), actual.toString());
}
IPresetReverb createReleasedPresetReverb() {
IPresetReverb reverb = getFactory().createPresetReverb();
reverb.release();
return reverb;
}
}
| 6,948 |
409 |
// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2018, <NAME>, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: <NAME> <<EMAIL>>
// ==========================================================================
#ifndef TESTS_MODIFIER_MODIFIER_STRING_PADDING_H_
#define TESTS_MODIFIER_MODIFIER_STRING_PADDING_H_
SEQAN_DEFINE_TEST(test_modified_string_padding_construction)
{
using namespace seqan;
DnaString seq = "ACGTGGATAGCATCG";
ModifiedString<DnaString, ModPadding> modString(seq);
SEQAN_ASSERT(modString._host == &seq);
SEQAN_ASSERT(modString._cargo._paddedValue == 'A');
SEQAN_ASSERT(modString._cargo._numPaddedChar == 0u);
SEQAN_ASSERT(modString._cargo._remainingSteps == 0u);
}
SEQAN_DEFINE_TEST(test_modified_string_padding_expand)
{
using namespace seqan;
DnaString seq = "ACGTGGATAGCATCG";
ModifiedString<DnaString, ModPadding> modString(seq);
ModifiedString<DnaString, ModPadding> modString2(seq);
expand(modString, 5);
expand(modString2, 5, 'C');
for (unsigned i = 0; i < 5; ++i)
{
SEQAN_ASSERT(modString[length(seq) + i] == 'A');
SEQAN_ASSERT(modString2[length(seq) + i] == 'C');
}
}
SEQAN_DEFINE_TEST(test_modified_string_padding_length)
{
using namespace seqan;
DnaString seq = "ACGTGGATAGCATCG";
ModifiedString<DnaString, ModPadding> modString(seq);
SEQAN_ASSERT(length(modString) == length(seq));
expand(modString, 5);
SEQAN_ASSERT(length(modString) == length(seq) + 5);
}
SEQAN_DEFINE_TEST(test_modified_string_padding_begin)
{
using namespace seqan;
DnaString seq = "ACGTGGATAGCATCG";
ModifiedString<DnaString, ModPadding> modString(seq);
auto it = begin(modString, Standard());
SEQAN_ASSERT(host(it) == begin(seq, Rooted()));
SEQAN_ASSERT_EQ(cargo(it)._remainingSteps, 0u);
SEQAN_ASSERT_EQ(cargo(it)._numPaddedChar, 0u);
expand(modString, 5);
it = begin(modString, Standard());
SEQAN_ASSERT(host(it) == begin(seq, Rooted()));
SEQAN_ASSERT_EQ(cargo(it)._remainingSteps, 5u);
SEQAN_ASSERT_EQ(cargo(it)._numPaddedChar, 5u);
}
SEQAN_DEFINE_TEST(test_modified_string_padding_end)
{
using namespace seqan;
DnaString seq = "ACGTGGATAGCATCG";
ModifiedString<DnaString, ModPadding> modString(seq);
auto itEnd = end(modString, Standard());
SEQAN_ASSERT(host(itEnd) == end(seq, Rooted()));
SEQAN_ASSERT_EQ(cargo(itEnd)._remainingSteps, 0u);
SEQAN_ASSERT_EQ(cargo(itEnd)._numPaddedChar, 0u);
expand(modString, 5);
itEnd = end(modString, Standard());
SEQAN_ASSERT(host(itEnd) == end(seq, Rooted()));
SEQAN_ASSERT_EQ(cargo(itEnd)._remainingSteps, 0u);
SEQAN_ASSERT_EQ(cargo(itEnd)._numPaddedChar, 5u);
}
SEQAN_DEFINE_TEST(test_modified_string_padding_difference)
{
using namespace seqan;
DnaString seq = "ACGTGGATAGCATCG";
ModifiedString<DnaString, ModPadding> modString(seq);
expand(modString, 5);
auto itB = begin(modString, Standard());
auto itE = end(modString, Standard());
auto pos = 0;
for (auto it = itB; it != itE; ++it, ++pos)
SEQAN_ASSERT(it - itB == pos);
}
SEQAN_DEFINE_TEST(test_modified_string_padding_iterator)
{
using namespace seqan;
DnaString seq = "ACGTGGATAGCATCG";
ModifiedString<DnaString, ModPadding> modString(seq);
expand(modString, 5, static_cast<Dna>('T'));
// Test begin, end, increment, decrement and dereference
auto itSeq = begin(seq, Standard());
auto it = begin(modString, Standard());
for (; it != end(modString, Standard()); ++it)
{
if (itSeq < end(seq, Standard()))
SEQAN_ASSERT_EQ(*it, *(itSeq++));
else
SEQAN_ASSERT_EQ(*it, static_cast<Dna>('T'));
}
while (it != begin(modString, Standard()))
{
--it;
if (it - begin(modString, Standard()) < static_cast<typename Difference<decltype(it)>::Type>(length(seq)))
SEQAN_ASSERT_EQ(*it, *(--itSeq));
else
SEQAN_ASSERT_EQ(*it, static_cast<Dna>('T'));
}
// Test advance.
SEQAN_ASSERT(it == begin(modString, Standard()));
it += 4;
SEQAN_ASSERT_EQ(*it, seq[4]);
it -= 2;
SEQAN_ASSERT_EQ(*it, seq[2]);
it += 13;
SEQAN_ASSERT_EQ(*it, static_cast<Dna>('T'));
it -= 15;
SEQAN_ASSERT_EQ(*it, seq[0]);
it = it + 17;
SEQAN_ASSERT_EQ(*it, static_cast<Dna>('T'));
it += 3;
SEQAN_ASSERT(it == end(modString, Standard()));
it -= 5;
SEQAN_ASSERT_EQ(*it, static_cast<Dna>('T'));
SEQAN_ASSERT_EQ(*(it - 3), seq[12]);
}
SEQAN_DEFINE_TEST(test_modified_string_padding_defect_2190)
{
using namespace seqan;
DnaString seq = "ACGTGGATAGCATCG";
auto seqInf = infix(seq, 0, length(seq));
auto test_const = [](auto const & modifier)
{
// using TRef = typename Reference<decltype(modifier)>::Type;
auto x = value(modifier, 1);
SEQAN_ASSERT_EQ(x, 'C');
};
{ // Test working case, when reference of const modifier gives back a const reference to the value
ModifiedString<decltype(seq), ModPadding> modString(seq);
test_const(modString);
}
{ // Test defect, when reference of const modifier gives back a non-const reference to the value
ModifiedString<decltype(seqInf), ModPadding> modString(seqInf);
test_const(modString);
}
}
#endif // #ifndef TESTS_MODIFIER_MODIFIER_STRING_PADDING_H_
| 2,841 |
5,023 |
# Copyright 2019 Google LLC
#
# 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.
"""Tests for build_setup."""
import os
import unittest
from clusterfuzz._internal.bot.untrusted_runner import build_setup
from clusterfuzz._internal.protos import untrusted_runner_pb2
from clusterfuzz._internal.tests.test_libs import helpers as test_helpers
def _failed_setup(*_):
return False
def _mock_regular_build_setup(*_):
os.environ['APP_PATH'] = '/release/bin/app'
os.environ['APP_PATH_DEBUG'] = ''
os.environ['APP_DIR'] = '/release/bin'
os.environ['BUILD_DIR'] = '/release'
os.environ['BUILD_URL'] = 'https://build/url.zip'
return True
class BuildSetupTest(unittest.TestCase):
"""Tests for build setup (untrusted side)."""
def setUp(self):
test_helpers.patch(self, [
('regular_build_setup',
'clusterfuzz._internal.build_management.build_manager.RegularBuild.setup'
),
])
test_helpers.patch_environ(self)
def test_setup_regular_build(self):
"""Test setup_regular_build."""
request = untrusted_runner_pb2.SetupRegularBuildRequest(
base_build_dir='/base',
revision=1337,
build_url='https://build/url.zip',
target_weights={
'bad_target': 0.1,
'normal_target': 1.0
})
self.mock.regular_build_setup.side_effect = _mock_regular_build_setup
response = build_setup.setup_regular_build(request)
self.assertTrue(response.result)
self.assertEqual(response.app_path, '/release/bin/app')
self.assertEqual(response.app_path_debug, '')
self.assertEqual(response.app_dir, '/release/bin')
self.assertEqual(response.build_dir, '/release')
self.assertEqual(response.build_url, 'https://build/url.zip')
self.mock.regular_build_setup.side_effect = _failed_setup
response = build_setup.setup_regular_build(request)
self.assertFalse(response.result)
self.assertFalse(response.HasField('app_path'))
self.assertFalse(response.HasField('app_path_debug'))
self.assertFalse(response.HasField('app_dir'))
self.assertFalse(response.HasField('build_dir'))
self.assertFalse(response.HasField('build_url'))
| 952 |
1,056 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.javascript2.editor;
import org.netbeans.modules.csl.api.Formatter;
// XXX note this also tests indenter
public class JsonTypedBreakInterceptorTest extends JsonTestBase {
public JsonTypedBreakInterceptorTest(String testName) {
super(testName);
}
@Override
protected Formatter getFormatter(IndentPrefs preferences) {
return null;
}
public void testInsertNewLine1() throws Exception {
insertBreak("x^", "x\n^");
}
public void testInsertNewLine2() throws Exception {
insertBreak("{^", "{\n ^\n}");
}
public void testInsertNewLine3() throws Exception {
insertBreak("{^\n}", "{\n ^\n}");
}
public void testInsertNewLine4() throws Exception {
insertBreak("{\n"
+ " \"x\": {^\n"
+ "}\n",
"{\n"
+ " \"x\": {\n"
+ " ^\n"
+ " }\n"
+ "}\n");
}
public void testNoContComment1() throws Exception {
if (JsTypedBreakInterceptor.CONTINUE_COMMENTS) {
insertBreak("// ^", "// \n^");
} else {
insertBreak("// ^", "// \n^");
}
}
public void testNoContComment2() throws Exception {
insertBreak("/*^\n*/", "/*\n^\n*/");
}
public void testNoMultilineString() throws Exception {
insertBreak("{ \"a\" : \"abc^def\" }", "{ \"a\" : \"abc\n ^def\" }");
}
}
| 866 |
826 |
<reponame>dartartem/eventuate-tram-sagas
package io.eventuate.tram.sagas.reactive.orchestration;
import io.eventuate.tram.sagas.orchestration.SagaInstance;
import reactor.core.publisher.Mono;
import java.util.Optional;
public interface ReactiveSagaManager<Data> {
Mono<SagaInstance> create(Data sagaData);
void subscribeToReplyChannel();
Mono<SagaInstance> create(Data sagaData, Optional<String> lockTarget);
Mono<SagaInstance> create(Data data, Class targetClass, Object targetId);
}
| 164 |
1,398 |
#ifndef CONFLUO_STORAGE_MEMPOOL_STAT_H_
#define CONFLUO_STORAGE_MEMPOOL_STAT_H_
#include "atomic.h"
#include <cstdlib>
#include <cstdint>
namespace confluo {
namespace storage {
/**
* The memory stat class. Contains functionality for modifying the amount
* of memory used.
*/
class memory_stat {
public:
/**
* Initializes memory statistics.
*/
memory_stat();
/**
* Increments the memory used by the specified size
*
* @param size The size to increment by in bytes
*/
void increment(size_t size);
/**
* Decrements the memory used by the specified size
*
* @param size The size to increment by in bytes
*/
void decrement(size_t size);
/**
* Loads the amount of memory used
*
* @return The amount of memory used
*/
size_t get();
private:
atomic::type<size_t> memory_used_;
};
}
}
#endif /* CONFLUO_STORAGE_MEMPOOL_STAT_H_ */
| 324 |
1,056 |
<reponame>timfel/netbeans<filename>java/jshell.support/src/org/netbeans/modules/jshell/launch/ShellLaunchEvent.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.netbeans.modules.jshell.launch;
import java.util.EventObject;
/**
* Event informing on Shell launch events.
*
* @author sdedic
*/
public final class ShellLaunchEvent extends EventObject {
private JShellConnection connection;
private ShellAgent agent;
private boolean remoteClose;
/*
Enable after refactoring
ShellLaunchEvent(ShellLaunchManager mgr, JShellConnection source) {
this(mgr, source, false);
}
*/
ShellLaunchEvent(ShellLaunchManager mgr, JShellConnection source, boolean remoteClose) {
super(mgr);
this.connection = source;
this.remoteClose = remoteClose;
}
ShellLaunchEvent(ShellLaunchManager mgr, ShellAgent agent) {
super(mgr);
this.agent = agent;
}
/**
* True, if the connection was shut down remotely.
* @return true for remote-initiated close.
*/
public boolean isRemoteClose() {
return remoteClose;
}
public ShellAgent getAgent() {
return agent;
}
public JShellConnection getSource() {
return (JShellConnection)super.getSource();
}
public JShellConnection getConnection() {
return connection;
}
}
| 716 |
432 |
<gh_stars>100-1000
import setuptools
from pkg_resources import parse_requirements
import pathlib
import os
def write_version_py():
with open(os.path.join("indicnlp", "version.txt")) as f:
version = f.read().strip()
# write version info to fairseq/version.py
with open(os.path.join("indicnlp", "version.py"), "w") as f:
f.write('__version__ = "{}"\n'.format(version))
return version
with open("README.md", "r") as fh:
long_description = fh.read()
version=write_version_py()
setuptools.setup(
name="indic_nlp_library", # Replace with your own username
version=version,
author="<NAME>",
author_email="<EMAIL>",
description="The goal of the Indic NLP Library is to build Python based libraries for common"\
' text processing and Natural Language Processing in Indian languages.',
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/anoopkunchukuttan/indic_nlp_library",
# project_urls={
# "Bug Tracker": "https://bugs.example.com/HelloWorld/",
# "Documentation": "https://docs.example.com/HelloWorld/",
# "Source Code": "https://code.example.com/HelloWorld/",
# },
packages=setuptools.find_packages(),
license='MIT',
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.5',
download_url='https://github.com/anoopkunchukuttan/indic_nlp_library/archive/master.zip',
install_requires=[
str(requirement) for requirement
in parse_requirements(pathlib.Path('requirements.txt').open())
]
)
| 653 |
312 |
<gh_stars>100-1000
#if OCCA_GL_ENABLED
# ifndef OCCA_VISUALIZER_HEADER
# define OCCA_VISUALIZER_HEADER
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <ctime>
#include <occa.hpp>
#if (OCCA_OS == OCCA_LINUX_OS)
# include <GL/glew.h>
# include <GL/gl.h>
# include <GL/glut.h>
#elif (OCCA_OS == OCCA_MACOS_OS)
# include <OpenGL/gl.h>
# include <GLUT/glut.h>
#elif (OCCA_OS == OCCA_WINDOWS_OS)
# include <gl/glut.h>
#endif
using std::string;
class visualizer;
class viewport;
typedef void(visualizer::*eventFunction)(int, int);
typedef void(*functionPointer)();
#define OCCA_PI_H 1.570796326794896619231321
#define OCCA_PI 3.141592653589793238462643
#define OCCA_PI_2 6.283185307179586476925286
class viewport {
public:
int width, height;
int vpWOffset, vpHOffset;
int vpWidth, vpHeight;
GLfloat fov, aspect, znear, zfar;
GLfloat eye[3], aim[3], up[3], right[2];
GLfloat eyeOffset[3], oldEyeOffset[3];
GLfloat camRadius, minCamRadius;
GLfloat camTheta, camPhi;
GLfloat oldCamTheta, oldCamPhi;
int dragX, dragY, drag_f;
GLfloat zoomSpeed;
GLfloat panSpeed;
GLfloat rotateSpeed;
GLfloat bgColor[3];
GLfloat lightPos[4];
char light_f;
char wireframe_f;
viewport();
~viewport();
void place();
void drawBackground();
void setAspectInformation(GLfloat, GLfloat, GLfloat);
void resize(GLfloat, GLfloat, GLfloat, GLfloat);
void resize(int, int, GLfloat, GLfloat, GLfloat, GLfloat);
void placeCamera();
void updateCamera();
void phaseAngles();
void setCamera(GLfloat, GLfloat, GLfloat);
void setLight(char);
void toggleLight();
void toggleWireframeMode();
GLint getPolyMode();
void setBackground(GLfloat, GLfloat, GLfloat);
void setBackground(int, int, int);
void leftClick(int x, int y);
void rightClick(int x, int y);
void move(int x, int y);
void updateSpeed();
void moveForward();
void moveBackward();
void moveLeft();
void moveRight();
void rotateUp();
void rotateDown();
void rotateLeft();
void rotateRight();
void setRotateSpeed(GLfloat);
};
class visualizer {
public:
//--[ SETTINGS ]--------------------------------
string appName;
eventFunction pressFunction[256];
eventFunction releaseFunction[256];
eventFunction mouseFunction[7][2];
char keyState[256];
char mouseState[7];
GLfloat moveSpeed, moveSpeed_d;
GLfloat rotateSpeed;
char pause_f;
char drag_f;
char external_f;
char lastKey_f;
//==============================================
//--[ DATA ]-----------------------------------
GLfloat mx, my;
//==============================================
//--[ EXTERNAL DATA ]---------------------------
float fps, fpsInv;
functionPointer externalFunction;
//==============================================
//--[ COLORS ]----------------------------------
static int colorCount;
static GLfloat *palette;
//==============================================
//--[ CAMERA ]----------------------------------
int rowVP, colVP;
int vpRowCount, vpColCount;
int *vpWidth;
int *vpHeight;
int oldVPWidth, oldVPHeight;
int vpRowDrag, vpColDrag;
int vpPadding;
GLfloat vpOutlineColor[4];
int vpOutlineSize;
char vpOutline_f;
viewport** viewports;
GLfloat oldCamTheta, oldCamPhi;
//==============================================
//--[ VIEWPORTS ]----------------------------------
int width, height;
GLfloat fov, znear, zfar;
int screenWidth, screenHeight;
GLfloat viewX, viewY;
//==============================================
static visualizer *staticVisualizer;
visualizer();
visualizer(string);
visualizer(string, int&, char**);
~visualizer();
void setup(string);
void setup(string, int&, char**);
void init(int&, char**);
void initFunctions();
void start();
void render();
static void render_s() {
staticVisualizer->render();
}
void resize(int, int);
static void resize_s(int w, int h) {
staticVisualizer->resize(w, h);
};
//--[ EXTERNAL DATA ]----------------------------------------------------
void setFPS(float);
void setExternalFunction(functionPointer);
//=========================================================================
//--[ EVENT FUNCTIONS ]----------------------------------------------------
void keyPress(unsigned char, int, int);
static void keyPress_s(unsigned char k, int x, int y) {
staticVisualizer->keyPress(k, x, y);
};
void keyRelease(unsigned char, int, int);
static void keyRelease_s(unsigned char k, int x, int y) {
staticVisualizer->keyRelease(k, x, y);
};
void keyPressUpdate();
void mousePress(int, int, int, int);
static void mousePress_s(int button, int state, int x, int y) {
staticVisualizer->mousePress(button, state, x, y);
};
void mouseDrag(int, int);
static void mouseDrag_s(int x, int y) {
staticVisualizer->mouseDrag(x, y);
};
void mouseMove(int, int);
static void mouseMove_s(int x, int y) {
staticVisualizer->mouseMove(x, y);
};
void setVPDrag(int*, int, int, int, int&, int&, int, int);
int getVP();
//=======================================================================
//--[ CAMERA FUNCTIONS ]-------------------------------------------------
void createViewports(int, int);
void placeViewport(int, int);
void fitBox(int, int, GLfloat, GLfloat, GLfloat, GLfloat);
void fitBox(int, int, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
void setCamera(int, int, GLfloat, GLfloat, GLfloat);
void setLight(int, int, char);
void toggleLight(int, int);
void setBackground(int, int, GLfloat, GLfloat, GLfloat);
void setBackground(int, int, int, int, int);
void drawBackground(int, int);
void placeCamera(int, int);
void updateCamera(int, int);
void drawBackground();
void setOutlineColor(GLfloat, GLfloat, GLfloat);
void setOutlineColor(GLfloat, GLfloat, GLfloat, GLfloat);
void drawViewportOutlines();
void startHUD();
void endHUD();
//=======================================================================
//--[ MOUSE FUNCTIONS ]--------------------------------------------------
void getRayNormal(int, int, GLfloat*, GLfloat*);
void leftClickDown(int, int);
void leftClickUp(int, int);
void rightClickDown(int, int);
void rightClickUp(int, int);
//=======================================================================
//--[ KEY FUNCTIONS ]----------------------------------------------------
void voidEventFunction(int x, int y) {};
void voidExternalFunction() {};
char keyIsPressed(char);
char lastKeyPressed();
void toggleWireframeMode(int, int);
void exitFunction(int, int);
void pause(int, int);
char isPaused();
void moveForward(int, int);
void moveBackward(int, int);
void moveLeft(int, int);
void moveRight(int, int);
void rotateUp(int, int);
void rotateDown(int, int);
void rotateLeft(int, int);
void rotateRight(int, int);
void slowDown(int, int);
void speedUp(int, int);
//=======================================================================
void setupColors();
static void paletteColor(int, GLfloat);
};
# endif
#endif
| 2,314 |
1,762 |
<reponame>ra-app/Broadway
/*
* Copyright (C) 2007-2008 ARM Limited
*
* 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.
*
*/
/* ----------------------------------------------------------------
*
*
* File Name: omxVCM4P10_PredictIntra_4x4.c
* OpenMAX DL: v1.0.2
* Revision: 9641
* Date: Thursday, February 7, 2008
*
*
*
*
* H.264 4x4 intra prediction module
*
*/
#include "omxtypes.h"
#include "armOMX.h"
#include "omxVC.h"
#include "armCOMM.h"
#include "armVC.h"
/**
* Function: omxVCM4P10_PredictIntra_4x4 (6.3.3.1.1)
*
* Description:
* Perform Intra_4x4 prediction for luma samples. If the upper-right block is
* not available, then duplication work should be handled inside the function.
* Users need not define them outside.
*
* Input Arguments:
*
* pSrcLeft - Pointer to the buffer of 4 left pixels:
* p[x, y] (x = -1, y = 0..3)
* pSrcAbove - Pointer to the buffer of 8 above pixels:
* p[x,y] (x = 0..7, y =-1);
* must be aligned on a 4-byte boundary.
* pSrcAboveLeft - Pointer to the above left pixels: p[x,y] (x = -1, y = -1)
* leftStep - Step of left pixel buffer; must be a multiple of 4.
* dstStep - Step of the destination buffer; must be a multiple of 4.
* predMode - Intra_4x4 prediction mode.
* availability - Neighboring 4x4 block availability flag, refer to
* "Neighboring Macroblock Availability" .
*
* Output Arguments:
*
* pDst - Pointer to the destination buffer; must be aligned on a 4-byte
* boundary.
*
* Return Value:
* If the function runs without error, it returns OMX_Sts_NoErr.
* If one of the following cases occurs, the function returns
* OMX_Sts_BadArgErr:
* pDst is NULL.
* dstStep < 4, or dstStep is not a multiple of 4.
* leftStep is not a multiple of 4.
* predMode is not in the valid range of enumeration
* OMXVCM4P10Intra4x4PredMode.
* predMode is OMX_VC_4x4_VERT, but availability doesn't set OMX_VC_UPPER
* indicating p[x,-1] (x = 0..3) is not available.
* predMode is OMX_VC_4x4_HOR, but availability doesn't set OMX_VC_LEFT
* indicating p[-1,y] (y = 0..3) is not available.
* predMode is OMX_VC_4x4_DIAG_DL, but availability doesn't set
* OMX_VC_UPPER indicating p[x, 1] (x = 0..3) is not available.
* predMode is OMX_VC_4x4_DIAG_DR, but availability doesn't set
* OMX_VC_UPPER_LEFT or OMX_VC_UPPER or OMX_VC_LEFT indicating
* p[x,-1] (x = 0..3), or p[-1,y] (y = 0..3) or p[-1,-1] is not
* available.
* predMode is OMX_VC_4x4_VR, but availability doesn't set
* OMX_VC_UPPER_LEFT or OMX_VC_UPPER or OMX_VC_LEFT indicating
* p[x,-1] (x = 0..3), or p[-1,y] (y = 0..3) or p[-1,-1] is not
* available.
* predMode is OMX_VC_4x4_HD, but availability doesn't set
* OMX_VC_UPPER_LEFT or OMX_VC_UPPER or OMX_VC_LEFT indicating
* p[x,-1] (x = 0..3), or p[-1,y] (y = 0..3) or p[-1,-1] is not
* available.
* predMode is OMX_VC_4x4_VL, but availability doesn't set OMX_VC_UPPER
* indicating p[x,-1] (x = 0..3) is not available.
* predMode is OMX_VC_4x4_HU, but availability doesn't set OMX_VC_LEFT
* indicating p[-1,y] (y = 0..3) is not available.
* availability sets OMX_VC_UPPER, but pSrcAbove is NULL.
* availability sets OMX_VC_LEFT, but pSrcLeft is NULL.
* availability sets OMX_VC_UPPER_LEFT, but pSrcAboveLeft is NULL.
* either pSrcAbove or pDst is not aligned on a 4-byte boundary.
*
* Note:
* pSrcAbove, pSrcAbove, pSrcAboveLeft may be invalid pointers if
* they are not used by intra prediction as implied in predMode.
*
*/
OMXResult omxVCM4P10_PredictIntra_4x4(
const OMX_U8* pSrcLeft,
const OMX_U8 *pSrcAbove,
const OMX_U8 *pSrcAboveLeft,
OMX_U8* pDst,
OMX_INT leftStep,
OMX_INT dstStep,
OMXVCM4P10Intra4x4PredMode predMode,
OMX_S32 availability
)
{
int x, y;
OMX_U8 pTmp[10];
armRetArgErrIf(pDst == NULL, OMX_Sts_BadArgErr);
armRetArgErrIf((leftStep % 4) != 0, OMX_Sts_BadArgErr);
armRetArgErrIf((dstStep % 4) != 0, OMX_Sts_BadArgErr);
armRetArgErrIf((dstStep < 4), OMX_Sts_BadArgErr);
armRetArgErrIf(armNot4ByteAligned(pSrcAbove), OMX_Sts_BadArgErr);
armRetArgErrIf(armNot4ByteAligned(pDst), OMX_Sts_BadArgErr);
armRetArgErrIf((availability & OMX_VC_UPPER) && pSrcAbove == NULL, OMX_Sts_BadArgErr);
armRetArgErrIf((availability & OMX_VC_LEFT ) && pSrcLeft == NULL, OMX_Sts_BadArgErr);
armRetArgErrIf((availability & OMX_VC_UPPER_LEFT) && pSrcAboveLeft == NULL, OMX_Sts_BadArgErr);
armRetArgErrIf(predMode==OMX_VC_4X4_VERT && !(availability & OMX_VC_UPPER), OMX_Sts_BadArgErr);
armRetArgErrIf(predMode==OMX_VC_4X4_HOR && !(availability & OMX_VC_LEFT), OMX_Sts_BadArgErr);
armRetArgErrIf(predMode==OMX_VC_4X4_DIAG_DL && !(availability & OMX_VC_UPPER), OMX_Sts_BadArgErr);
armRetArgErrIf(predMode==OMX_VC_4X4_DIAG_DR && !(availability & OMX_VC_UPPER), OMX_Sts_BadArgErr);
armRetArgErrIf(predMode==OMX_VC_4X4_DIAG_DR && !(availability & OMX_VC_UPPER_LEFT), OMX_Sts_BadArgErr);
armRetArgErrIf(predMode==OMX_VC_4X4_DIAG_DR && !(availability & OMX_VC_LEFT), OMX_Sts_BadArgErr);
armRetArgErrIf(predMode==OMX_VC_4X4_VR && !(availability & OMX_VC_UPPER), OMX_Sts_BadArgErr);
armRetArgErrIf(predMode==OMX_VC_4X4_VR && !(availability & OMX_VC_UPPER_LEFT), OMX_Sts_BadArgErr);
armRetArgErrIf(predMode==OMX_VC_4X4_VR && !(availability & OMX_VC_LEFT), OMX_Sts_BadArgErr);
armRetArgErrIf(predMode==OMX_VC_4X4_HD && !(availability & OMX_VC_UPPER), OMX_Sts_BadArgErr);
armRetArgErrIf(predMode==OMX_VC_4X4_HD && !(availability & OMX_VC_UPPER_LEFT), OMX_Sts_BadArgErr);
armRetArgErrIf(predMode==OMX_VC_4X4_HD && !(availability & OMX_VC_LEFT), OMX_Sts_BadArgErr);
armRetArgErrIf(predMode==OMX_VC_4X4_VL && !(availability & OMX_VC_UPPER), OMX_Sts_BadArgErr);
armRetArgErrIf(predMode==OMX_VC_4X4_HU && !(availability & OMX_VC_LEFT), OMX_Sts_BadArgErr);
armRetArgErrIf((unsigned)predMode > OMX_VC_4X4_HU, OMX_Sts_BadArgErr);
/* Note: This code must not read the pSrc arrays unless the corresponding
* block is marked as available. If the block is not avaibable then pSrc
* may not be a valid pointer.
*
* Note: To make the code more readable we refer to the neighbouring pixels
* in variables named as below:
*
* UL U0 U1 U2 U3 U4 U5 U6 U7
* L0 xx xx xx xx
* L1 xx xx xx xx
* L2 xx xx xx xx
* L3 xx xx xx xx
*/
#define UL pSrcAboveLeft[0]
#define U0 pSrcAbove[0]
#define U1 pSrcAbove[1]
#define U2 pSrcAbove[2]
#define U3 pSrcAbove[3]
#define U4 pSrcAbove[4]
#define U5 pSrcAbove[5]
#define U6 pSrcAbove[6]
#define U7 pSrcAbove[7]
#define L0 pSrcLeft[0*leftStep]
#define L1 pSrcLeft[1*leftStep]
#define L2 pSrcLeft[2*leftStep]
#define L3 pSrcLeft[3*leftStep]
switch (predMode)
{
case OMX_VC_4X4_VERT:
for (y=0; y<4; y++)
{
pDst[y*dstStep+0] = U0;
pDst[y*dstStep+1] = U1;
pDst[y*dstStep+2] = U2;
pDst[y*dstStep+3] = U3;
}
break;
case OMX_VC_4X4_HOR:
for (x=0; x<4; x++)
{
pDst[0*dstStep+x] = L0;
pDst[1*dstStep+x] = L1;
pDst[2*dstStep+x] = L2;
pDst[3*dstStep+x] = L3;
}
break;
case OMX_VC_4X4_DC:
/* This can always be used even if no blocks available */
armVCM4P10_PredictIntraDC4x4(pSrcLeft, pSrcAbove, pDst, leftStep, dstStep, availability);
break;
case OMX_VC_4X4_DIAG_DL:
pTmp[0] = (OMX_U8)((U0 + 2*U1 + U2 + 2)>>2);
pTmp[1] = (OMX_U8)((U1 + 2*U2 + U3 + 2)>>2);
if (availability & OMX_VC_UPPER_RIGHT)
{
pTmp[2] = (OMX_U8)((U2 + 2*U3 + U4 + 2)>>2);
pTmp[3] = (OMX_U8)((U3 + 2*U4 + U5 + 2)>>2);
pTmp[4] = (OMX_U8)((U4 + 2*U5 + U6 + 2)>>2);
pTmp[5] = (OMX_U8)((U5 + 2*U6 + U7 + 2)>>2);
pTmp[6] = (OMX_U8)((U6 + 3*U7 + 2)>>2);
}
else
{
pTmp[2] = (OMX_U8)((U2 + 3*U3 + 2)>>2);
pTmp[3] = U3;
pTmp[4] = U3;
pTmp[5] = U3;
pTmp[6] = U3;
}
for (y=0; y<4; y++)
{
for (x=0; x<4; x++)
{
pDst[y*dstStep+x] = pTmp[x+y];
}
}
break;
case OMX_VC_4X4_DIAG_DR:
/* x-y = -3, -2, -1, 0, 1, 2, 3 */
pTmp[0] = (OMX_U8)((L1 + 2*L2 + L3 + 2)>>2);
pTmp[1] = (OMX_U8)((L0 + 2*L1 + L2 + 2)>>2);
pTmp[2] = (OMX_U8)((UL + 2*L0 + L1 + 2)>>2);
pTmp[3] = (OMX_U8)((U0 + 2*UL + L0 + 2)>>2);
pTmp[4] = (OMX_U8)((U1 + 2*U0 + UL + 2)>>2);
pTmp[5] = (OMX_U8)((U2 + 2*U1 + U0 + 2)>>2);
pTmp[6] = (OMX_U8)((U3 + 2*U2 + U1 + 2)>>2);
for (y=0; y<4; y++)
{
for (x=0; x<4; x++)
{
pDst[y*dstStep+x] = pTmp[3+x-y];
}
}
break;
case OMX_VC_4X4_VR:
/* zVR=2x-y = -3, -2, -1, 0, 1, 2, 3, 4, 5, 6
* x-(y>>1) = -1, -1, 0, 0, 1, 1, 2, 2, 3, 3
* y = 3, 2, ?, ?, ?, ?, ?, ?, 1, 0
*/
pTmp[0] = (OMX_U8)((L2 + 2*L1 + L0 + 2)>>2);
pTmp[1] = (OMX_U8)((L1 + 2*L0 + UL + 2)>>2);
pTmp[2] = (OMX_U8)((L0 + 2*UL + U0 + 2)>>2);
pTmp[3] = (OMX_U8)((UL + U0 + 1)>>1);
pTmp[4] = (OMX_U8)((UL + 2*U0 + U1 + 2)>>2);
pTmp[5] = (OMX_U8)((U0 + U1 + 1)>>1);
pTmp[6] = (OMX_U8)((U0 + 2*U1 + U2 + 2)>>2);
pTmp[7] = (OMX_U8)((U1 + U2 + 1)>>1);
pTmp[8] = (OMX_U8)((U1 + 2*U2 + U3 + 2)>>2);
pTmp[9] = (OMX_U8)((U2 + U3 + 1)>>1);
for (y=0; y<4; y++)
{
for (x=0; x<4; x++)
{
pDst[y*dstStep+x] = pTmp[3+2*x-y];
}
}
break;
case OMX_VC_4X4_HD:
/* zHD=2y-x = -3 -2 -1 0 1 2 3 4 5 6
* y-(x>>1) = -1 -1 0 0 1 1 2 2 3 3
* x = 3 2 1 0
*/
pTmp[0] = (OMX_U8)((U2 + 2*U1 + U0 + 2)>>2);
pTmp[1] = (OMX_U8)((U1 + 2*U0 + UL + 2)>>2);
pTmp[2] = (OMX_U8)((U0 + 2*UL + L0 + 2)>>2);
pTmp[3] = (OMX_U8)((UL + L0 + 1)>>1);
pTmp[4] = (OMX_U8)((UL + 2*L0 + L1 + 2)>>2);
pTmp[5] = (OMX_U8)((L0 + L1 + 1)>>1);
pTmp[6] = (OMX_U8)((L0 + 2*L1 + L2 + 2)>>2);
pTmp[7] = (OMX_U8)((L1 + L2 + 1)>>1);
pTmp[8] = (OMX_U8)((L1 + 2*L2 + L3 + 2)>>2);
pTmp[9] = (OMX_U8)((L2 + L3 + 1)>>1);
for (y=0; y<4; y++)
{
for (x=0; x<4; x++)
{
pDst[y*dstStep+x] = pTmp[3+2*y-x];
}
}
break;
case OMX_VC_4X4_VL:
/* Note: x+(y>>1) = (2*x+y)>>1
* 2x+y = 0 1 2 3 4 5 6 7 8 9
*/
pTmp[0] = (OMX_U8)((U0 + U1 + 1)>>1);
pTmp[1] = (OMX_U8)((U0 + 2*U1 + U2 + 2)>>2);
pTmp[2] = (OMX_U8)((U1 + U2 + 1)>>1);
pTmp[3] = (OMX_U8)((U1 + 2*U2 + U3 + 2)>>2);
pTmp[4] = (OMX_U8)((U2 + U3 + 1)>>1);
if (availability & OMX_VC_UPPER_RIGHT)
{
pTmp[5] = (OMX_U8)((U2 + 2*U3 + U4 + 2)>>2);
pTmp[6] = (OMX_U8)((U3 + U4 + 1)>>1);
pTmp[7] = (OMX_U8)((U3 + 2*U4 + U5 + 2)>>2);
pTmp[8] = (OMX_U8)((U4 + U5 + 1)>>1);
pTmp[9] = (OMX_U8)((U4 + 2*U5 + U6 + 2)>>2);
}
else
{
pTmp[5] = (OMX_U8)((U2 + 3*U3 + 2)>>2);
pTmp[6] = U3;
pTmp[7] = U3;
pTmp[8] = U3;
pTmp[9] = U3;
}
for (y=0; y<4; y++)
{
for (x=0; x<4; x++)
{
pDst[y*dstStep+x] = pTmp[2*x+y];
}
}
break;
case OMX_VC_4X4_HU:
/* zHU = x+2*y */
pTmp[0] = (OMX_U8)((L0 + L1 + 1)>>1);
pTmp[1] = (OMX_U8)((L0 + 2*L1 + L2 + 2)>>2);
pTmp[2] = (OMX_U8)((L1 + L2 + 1)>>1);
pTmp[3] = (OMX_U8)((L1 + 2*L2 + L3 + 2)>>2);
pTmp[4] = (OMX_U8)((L2 + L3 + 1)>>1);
pTmp[5] = (OMX_U8)((L2 + 3*L3 + 2)>>2);
pTmp[6] = L3;
pTmp[7] = L3;
pTmp[8] = L3;
pTmp[9] = L3;
for (y=0; y<4; y++)
{
for (x=0; x<4; x++)
{
pDst[y*dstStep+x] = pTmp[x+2*y];
}
}
break;
}
return OMX_Sts_NoErr;
}
| 7,760 |
358 |
/*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//
// JniEvent.h
// XCodePlugin
//
// Created by benwu on 9/11/15.
//
//
#ifndef __XCodePlugin__JniEvent__
#define __XCodePlugin__JniEvent__
#include <stdio.h>
#include "JniDataSnapshot.h"
class JniEvent {
public:
virtual void Process();
};
class ValueChangedEvent : public JniEvent {
public:
ValueChangedEvent(JniDataSnapshot* snapshot);
void Process();
private:
JniDataSnapshot* m_snapshot;
};
class ChildAddedEvent : public JniEvent {
public:
ChildAddedEvent(JniDataSnapshot* snapshot);
void Process();
private:
JniDataSnapshot* m_snapshot;
};
class ChildRemovedEvent : public JniEvent {
public:
ChildRemovedEvent(JniDataSnapshot* snapshot);
void Process();
private:
JniDataSnapshot* m_snapshot;
};
class ChildChangedEvent : public JniEvent {
public:
ChildChangedEvent(JniDataSnapshot* snapshot);
void Process();
private:
JniDataSnapshot* m_snapshot;
};
class ChildMovedEvent : public JniEvent {
public:
ChildMovedEvent(JniDataSnapshot* snapshot);
void Process();
private:
JniDataSnapshot* m_snapshot;
};
class AuthSuccessEvent : public JniEvent {
public:
AuthSuccessEvent(uint64_t cookie, const char* token, const char*uid, uint64_t expiration);
void Process();
private:
uint64_t m_cookie;
const char* m_token;
const char* m_uid;
uint64_t m_expiration;
};
class AuthFailureEvent : public JniEvent {
public:
AuthFailureEvent(uint64_t cookie, int code, const char* message, const char* detail);
void Process();
private:
uint64_t m_cookie;
int m_code;
const char* m_message;
const char* m_detail;
};
class ErrorEvent : public JniEvent {
public:
ErrorEvent(void* cookie, int code, const char* message, const char* detail);
void Process();
private:
void* m_cookie;
int m_code;
const char* m_message;
const char* m_detail;
};
#endif /* defined(__XCodePlugin__JniEvent__) */
| 848 |
348 |
{"nom":"Lannes","circ":"1ère circonscription","dpt":"Lot-et-Garonne","inscrits":330,"abs":166,"votants":164,"blancs":5,"nuls":7,"exp":152,"res":[{"nuance":"REM","nom":"M. <NAME>","voix":82},{"nuance":"UDI","nom":"<NAME>","voix":70}]}
| 95 |
2,260 |
<reponame>ecameracci/GamePlay<gh_stars>1000+
// Autogenerated by gameplay-luagen
#ifndef LUA_TEXTURESAMPLER_H_
#define LUA_TEXTURESAMPLER_H_
namespace gameplay
{
void luaRegister_TextureSampler();
}
#endif
| 85 |
3,508 |
<filename>src/main/java/com/fishercoder/solutions/_796.java<gh_stars>1000+
package com.fishercoder.solutions;
public class _796 {
public static class Solution1 {
public boolean rotateString(String A, String B) {
if (A.length() != B.length()) {
return false;
}
for (int i = 0; i < A.length(); i++) {
if ((A.substring(i) + A.substring(0, i)).equals(B)) {
return true;
}
}
return false;
}
}
}
| 288 |
702 |
<gh_stars>100-1000
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.core;
import org.hyperledger.besu.ethereum.privacy.storage.LegacyPrivateStateKeyValueStorage;
import org.hyperledger.besu.ethereum.privacy.storage.LegacyPrivateStateStorage;
import org.hyperledger.besu.ethereum.privacy.storage.PrivacyStorageProvider;
import org.hyperledger.besu.ethereum.privacy.storage.PrivateStateKeyValueStorage;
import org.hyperledger.besu.ethereum.privacy.storage.PrivateStateStorage;
import org.hyperledger.besu.ethereum.storage.keyvalue.WorldStateKeyValueStorage;
import org.hyperledger.besu.ethereum.storage.keyvalue.WorldStatePreimageKeyValueStorage;
import org.hyperledger.besu.ethereum.worldstate.DefaultMutableWorldState;
import org.hyperledger.besu.ethereum.worldstate.DefaultWorldStateArchive;
import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive;
import org.hyperledger.besu.ethereum.worldstate.WorldStatePreimageStorage;
import org.hyperledger.besu.ethereum.worldstate.WorldStateStorage;
import org.hyperledger.besu.services.kvstore.InMemoryKeyValueStorage;
public class InMemoryPrivacyStorageProvider implements PrivacyStorageProvider {
public static WorldStateArchive createInMemoryWorldStateArchive() {
return new DefaultWorldStateArchive(
new WorldStateKeyValueStorage(new InMemoryKeyValueStorage()),
new WorldStatePreimageKeyValueStorage(new InMemoryKeyValueStorage()));
}
public static MutableWorldState createInMemoryWorldState() {
final InMemoryPrivacyStorageProvider provider = new InMemoryPrivacyStorageProvider();
return new DefaultMutableWorldState(
provider.createWorldStateStorage(), provider.createWorldStatePreimageStorage());
}
@Override
public WorldStateStorage createWorldStateStorage() {
return new WorldStateKeyValueStorage(new InMemoryKeyValueStorage());
}
@Override
public WorldStatePreimageStorage createWorldStatePreimageStorage() {
return new WorldStatePreimageKeyValueStorage(new InMemoryKeyValueStorage());
}
@Override
public PrivateStateStorage createPrivateStateStorage() {
return new PrivateStateKeyValueStorage(new InMemoryKeyValueStorage());
}
@Override
public LegacyPrivateStateStorage createLegacyPrivateStateStorage() {
return new LegacyPrivateStateKeyValueStorage(new InMemoryKeyValueStorage());
}
@Override
public int getFactoryVersion() {
return 1;
}
@Override
public void close() {}
}
| 875 |
2,826 |
/*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* 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 <gst/gst.h>
#include "ServerMethods.hpp"
#include <MediaSet.hpp>
#include <memory>
#include <string>
#include <EventHandler.hpp>
#include <KurentoException.hpp>
#include <jsonrpc/JsonRpcException.hpp>
#include <jsonrpc/JsonRpcUtils.hpp>
#include <jsonrpc/JsonRpcConstants.hpp>
#include <jsonrpc/JsonFixes.hpp>
#include <sstream>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "modules.hpp"
#include <version.hpp>
#include <ServerManagerImpl.hpp>
#include <ServerInfo.hpp>
#include <ModuleInfo.hpp>
#include <ServerType.hpp>
#include <UUIDGenerator.hpp>
#include <ResourceManager.hpp>
#define GST_CAT_DEFAULT kurento_server_methods
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoServerMethods"
#define SESSION_ID "sessionId"
#define VALUE "value"
#define OBJECT "object"
#define SUBSCRIPTION "subscription"
#define TYPE "type"
#define QUALIFIED_TYPE "qualifiedType"
#define HIERARCHY "hierarchy"
#define REQUEST_TIMEOUT 20000 /* 20 seconds */
static const std::string KURENTO_MODULES_PATH = "KURENTO_MODULES_PATH";
static const std::string NEW_REF = "newref:";
namespace kurento
{
ServerMethods::ServerMethods (const boost::property_tree::ptree &config) :
config (config), moduleManager (getModuleManager() )
{
std::string version (get_version() );
std::vector<std::shared_ptr<ModuleInfo>> modules;
std::shared_ptr<ServerType> type (new ServerType (ServerType::KMS) );
std::vector<std::string> capabilities;
std::shared_ptr <ServerInfo> serverInfo;
std::shared_ptr<MediaObjectImpl> serverManager;
std::chrono::seconds collectorInterval{};
bool disableRequestCache;
collectorInterval = std::chrono::seconds (
config.get<long> ("mediaServer.resources.garbageCollectorPeriod",
MediaSet::getCollectorInterval().count() ) );
MediaSet::setCollectorInterval (collectorInterval);
disableRequestCache = config.get<bool> ("mediaServer.resources.disableRequestCache",
false);
resourceLimitPercent =
config.get<float> ("mediaServer.resources.exceptionLimit",
DEFAULT_RESOURCE_LIMIT_PERCENT);
GST_INFO ("Using above %.0f%% of system limits will throw NOT_ENOUGH_RESOURCES exception",
resourceLimitPercent * 100.0f);
std::string maxThreadsStr;
const rlim_t maxThreads = getMaxThreads ();
if (maxThreads == RLIM_INFINITY) {
maxThreadsStr = "unlimited";
} else {
maxThreadsStr = std::to_string(maxThreads);
}
std::string maxOpenFilesStr;
const rlim_t maxOpenFiles = getMaxOpenFiles ();
if (maxOpenFiles == RLIM_INFINITY) {
maxOpenFilesStr = "unlimited";
} else {
maxOpenFilesStr = std::to_string(maxOpenFiles);
}
GST_INFO ("System limits: %s threads, %s files",
maxThreadsStr.c_str(), maxOpenFilesStr.c_str());
instanceId = generateUUID();
for (auto moduleIt : moduleManager.getModules () ) {
std::vector<std::string> factories;
for (auto factIt : moduleIt.second->getFactories() ) {
factories.push_back (factIt.first);
}
modules.push_back(std::make_shared<ModuleInfo>(
moduleIt.second->getVersion(), moduleIt.second->getName(),
moduleIt.second->getGenerationTime(), factories));
}
capabilities.emplace_back("transactions");
serverInfo =
std::make_shared<ServerInfo>(version, modules, type, capabilities);
serverManager = MediaSet::getMediaSet ()->ref (new ServerManagerImpl (
serverInfo, config, moduleManager) );
MediaSet::getMediaSet ()->setServerManager (std::dynamic_pointer_cast
<ServerManagerImpl> (serverManager) );
cache = std::make_shared<RequestCache>(REQUEST_TIMEOUT);
if (!disableRequestCache) {
handler.setPreProcess (std::bind (&ServerMethods::preProcess, this,
std::placeholders::_1,
std::placeholders::_2) );
handler.setPostProcess (std::bind (&ServerMethods::postProcess, this,
std::placeholders::_1,
std::placeholders::_2) );
GST_INFO ("RPC Request Cache is ENABLED");
} else {
GST_INFO ("RPC Request Cache is DISABLED");
}
handler.addMethod ("connect", std::bind (&ServerMethods::connect, this,
std::placeholders::_1,
std::placeholders::_2) );
handler.addMethod ("create", std::bind (&ServerMethods::create, this,
std::placeholders::_1,
std::placeholders::_2) );
handler.addMethod ("invoke", std::bind (&ServerMethods::invoke, this,
std::placeholders::_1,
std::placeholders::_2) );
handler.addMethod ("subscribe", std::bind (&ServerMethods::subscribe, this,
std::placeholders::_1,
std::placeholders::_2) );
handler.addMethod ("unsubscribe", std::bind (&ServerMethods::unsubscribe,
this, std::placeholders::_1,
std::placeholders::_2) );
handler.addMethod ("release", std::bind (&ServerMethods::release,
this, std::placeholders::_1,
std::placeholders::_2) );
handler.addMethod ("ref", std::bind (&ServerMethods::ref,
this, std::placeholders::_1,
std::placeholders::_2) );
handler.addMethod ("unref", std::bind (&ServerMethods::unref,
this, std::placeholders::_1,
std::placeholders::_2) );
handler.addMethod ("keepAlive", std::bind (&ServerMethods::keepAlive,
this, std::placeholders::_1,
std::placeholders::_2) );
handler.addMethod ("describe", std::bind (&ServerMethods::describe,
this, std::placeholders::_1,
std::placeholders::_2) );
handler.addMethod ("transaction", std::bind (&ServerMethods::transaction,
this, std::placeholders::_1, std::placeholders::_2) );
handler.addMethod ("ping", std::bind (&ServerMethods::ping, this,
std::placeholders::_1, std::placeholders::_2) );
handler.addMethod ("closeSession", std::bind (&ServerMethods::closeSession,
this,
std::placeholders::_1, std::placeholders::_2) );
}
ServerMethods::~ServerMethods() = default;
static void
requireParams (const Json::Value ¶ms)
{
if (params == Json::Value::null) {
Json::Value data;
data[TYPE] = "INVALID_PARAMS";
throw JsonRpc::CallException (JsonRpc::ErrorCode::INVALID_PARAMS,
"'params' is requiered", data);
}
}
static bool
getOrCreateSessionId (std::string &_sessionId, const Json::Value ¶ms)
{
try {
JsonRpc::getValue (params, SESSION_ID, _sessionId);
return true;
} catch (JsonRpc::CallException e) {
_sessionId = generateUUID ();
return false;
}
}
static std::string
getSessionId (const Json::Value &resp)
{
std::string sessionId;
Json::Value result;
if (resp.isMember (JSON_RPC_ERROR) ) {
/* If response is an error do not return a sessionId */
return sessionId;
}
JsonRpc::getValue (resp, JSON_RPC_RESULT, result);
JsonRpc::getValue (result, SESSION_ID, sessionId);
return sessionId;
}
static void
injectSessionId (Json::Value &req, const std::string &sessionId)
{
try {
Json::Value params;
params = req[JSON_RPC_PARAMS];
try {
std::string oldSessionId;
JsonRpc::getValue (params, SESSION_ID, oldSessionId);
} catch (JsonRpc::CallException &e) {
// There is no sessionId, inject it
GST_TRACE ("Injecting sessionId %s", sessionId.c_str() );
params[SESSION_ID] = sessionId;
req[JSON_RPC_PARAMS] = params;
}
} catch (JsonRpc::CallException &ex) {
}
}
std::string
ServerMethods::process (const std::string &requestStr, std::string &responseStr,
std::string &sessionId)
{
Json::Value response;
Json::Value request;
bool parse = false;
Json::Reader reader;
std::string newSessionId;
parse = reader.parse (requestStr, request);
if (!parse) {
throw JsonRpc::CallException (JsonRpc::ErrorCode::PARSE_ERROR, "Parse error.");
}
if (!sessionId.empty() ) {
injectSessionId (request, sessionId);
}
handler.process (request, response);
try {
newSessionId = getSessionId (response);
} catch (JsonRpc::CallException &ex) {
/* We could not get some of the required parameters. Ignore */
newSessionId = sessionId;
}
if (response != Json::Value::null) {
Json::StreamWriterBuilder writerFactory;
writerFactory["indentation"] = "";
responseStr = Json::writeString (writerFactory, response);
}
return newSessionId;
}
void
ServerMethods::keepAliveSession (const std::string &sessionId)
{
MediaSet::getMediaSet()->keepAliveSession (sessionId);
}
bool
ServerMethods::preProcess (const Json::Value &request, Json::Value &response)
{
std::string sessionId;// std::string resp;
std::string requestId;
try {
Json::Value params;
JsonRpc::getValue (request, JSON_RPC_ID, requestId);
JsonRpc::getValue (request, JSON_RPC_PARAMS, params);
JsonRpc::getValue (params, SESSION_ID, sessionId);
response = cache->getCachedResponse (sessionId, requestId);
GST_DEBUG ("Cached response");
return false;
} catch (...) {
/* continue processing */
return true;
}
}
void
ServerMethods::postProcess (const Json::Value &request, Json::Value &response)
{
std::string sessionId;
std::string requestId;
try {
JsonRpc::getValue (request, JSON_RPC_ID, requestId);
try {
Json::Value result;
JsonRpc::getValue (response, JSON_RPC_RESULT, result);
JsonRpc::getValue (result, SESSION_ID, sessionId);
} catch (JsonRpc::CallException &ex) {
Json::Value params;
JsonRpc::getValue (request, JSON_RPC_PARAMS, params);
JsonRpc::getValue (params, SESSION_ID, sessionId);
}
/* CacheException will be triggered if this response is not cached */
cache->getCachedResponse (sessionId, requestId);
} catch (JsonRpc::CallException &e) {
/* We could not get some of the required parameters. Ignore */
} catch (CacheException &e) {
GST_LOG ("Caching: %s", response.toStyledString().c_str() );
cache->addResponse (sessionId, requestId, response);
}
}
void
ServerMethods::describe (const Json::Value ¶ms, Json::Value &response)
{
std::shared_ptr<MediaObjectImpl> obj;
std::string sessionId;
std::string objectId;
requireParams (params);
getOrCreateSessionId (sessionId, params);
JsonRpc::getValue (params, OBJECT, objectId);
try {
obj = MediaSet::getMediaSet()->getMediaObject (sessionId, objectId);
} catch (KurentoException &ex) {
Json::Value data;
data[TYPE] = ex.getType();
throw JsonRpc::CallException (ex.getCode (), ex.getMessage (), data);
}
response[SESSION_ID] = sessionId;
response[TYPE] = obj->getType ();
response[QUALIFIED_TYPE] = obj->getQualifiedType();
JsonSerializer serializer (true);
std::vector <std::string> array = obj->getHierarchy();
serializer.Serialize ("array", array);
response[HIERARCHY] = serializer.JsonValue["array"];
}
void
ServerMethods::keepAlive (const Json::Value ¶ms, Json::Value &response)
{
std::string sessionId;
requireParams (params);
JsonRpc::getValue (params, SESSION_ID, sessionId);
try {
MediaSet::getMediaSet()->keepAliveSession (sessionId);
} catch (KurentoException &ex) {
Json::Value data;
data[TYPE] = ex.getType();
throw JsonRpc::CallException (ex.getCode (), ex.getMessage (), data);
}
response[SESSION_ID] = sessionId;
}
void
ServerMethods::release (const Json::Value ¶ms, Json::Value &response)
{
std::string objectId;
std::string sessionId;
requireParams (params);
JsonRpc::getValue (params, OBJECT, objectId);
getOrCreateSessionId (sessionId, params);
try {
MediaSet::getMediaSet()->release (objectId);
} catch (KurentoException &ex) {
Json::Value data;
data[TYPE] = ex.getType();
throw JsonRpc::CallException (ex.getCode (), ex.getMessage (), data);
}
response[SESSION_ID] = sessionId;
}
void
ServerMethods::ref (const Json::Value ¶ms, Json::Value &response)
{
std::string objectId;
std::string sessionId;
requireParams (params);
JsonRpc::getValue (params, OBJECT, objectId);
JsonRpc::getValue (params, SESSION_ID, sessionId);
try {
MediaSet::getMediaSet()->ref (sessionId, objectId);
} catch (KurentoException &ex) {
Json::Value data;
data[TYPE] = ex.getType();
throw JsonRpc::CallException (ex.getCode (), ex.getMessage (), data);
}
response[SESSION_ID] = sessionId;
}
void
ServerMethods::unref (const Json::Value ¶ms, Json::Value &response)
{
std::string objectId;
std::string sessionId;
requireParams (params);
JsonRpc::getValue (params, OBJECT, objectId);
JsonRpc::getValue (params, SESSION_ID, sessionId);
try {
MediaSet::getMediaSet()->unref (sessionId, objectId);
} catch (KurentoException &ex) {
Json::Value data;
data[TYPE] = ex.getType();
throw JsonRpc::CallException (ex.getCode (), ex.getMessage (), data);
}
response[SESSION_ID] = sessionId;
}
void
ServerMethods::unsubscribe (const Json::Value ¶ms, Json::Value &response)
{
std::string subscription;
std::string sessionId;
std::string objectId;
requireParams (params);
JsonRpc::getValue (params, OBJECT, objectId);
JsonRpc::getValue (params, SUBSCRIPTION, subscription);
JsonRpc::getValue (params, SESSION_ID, sessionId);
MediaSet::getMediaSet()->removeEventHandler (sessionId, objectId, subscription);
response[SESSION_ID] = sessionId;
}
void
ServerMethods::registerEventHandler (std::shared_ptr<MediaObjectImpl> obj,
const std::string &sessionId,
const std::string &subscriptionId,
std::shared_ptr<EventHandler> handler)
{
MediaSet::getMediaSet()->addEventHandler (sessionId, obj->getId(),
subscriptionId, handler);
}
std::string
ServerMethods::connectEventHandler (std::shared_ptr<MediaObjectImpl> obj,
const std::string &sessionId, const std::string &eventType,
std::shared_ptr<EventHandler> handler)
{
std::string subscriptionId;
if (!obj->connect (eventType, handler) ) {
throw KurentoException (MEDIA_OBJECT_EVENT_NOT_SUPPORTED, "Event not found");
}
subscriptionId = generateUUID();
registerEventHandler (obj, sessionId, subscriptionId, handler);
return subscriptionId;
}
void
ServerMethods::subscribe (const Json::Value ¶ms, Json::Value &response)
{
std::shared_ptr<MediaObjectImpl> obj;
std::string eventType;
std::string handlerId;
std::string sessionId;
std::string objectId;
requireParams (params);
JsonRpc::getValue (params, TYPE, eventType);
JsonRpc::getValue (params, OBJECT, objectId);
getOrCreateSessionId (sessionId, params);
try {
obj = MediaSet::getMediaSet()->getMediaObject (sessionId, objectId);
try {
handlerId = eventSubscriptionHandler (obj, sessionId, eventType, params);
} catch (std::bad_function_call &e) {
throw KurentoException (NOT_IMPLEMENTED,
"Current transport does not support events");
}
if (handlerId == "") {
throw KurentoException (MEDIA_OBJECT_EVENT_NOT_SUPPORTED, "Event not found");
}
} catch (KurentoException &ex) {
Json::Value data;
data[TYPE] = ex.getType();
throw JsonRpc::CallException (ex.getCode (), ex.getMessage (), data);
}
response[SESSION_ID] = sessionId;
response[VALUE] = handlerId;
}
void
ServerMethods::invoke (const Json::Value ¶ms, Json::Value &response)
{
std::shared_ptr<MediaObjectImpl> obj;
std::string sessionId;
std::string operation;
Json::Value operationParams;
std::string objectId;
requireParams (params);
JsonRpc::getValue (params, "operation", operation);
JsonRpc::getValue (params, OBJECT, objectId);
try {
JsonRpc::getValue (params, "operationParams", operationParams);
} catch (JsonRpc::CallException e) {
/* operationParams is optional at this point */
}
getOrCreateSessionId (sessionId, params);
try {
Json::Value value;
obj = MediaSet::getMediaSet()->getMediaObject (sessionId, objectId);
if (!obj) {
throw KurentoException (MEDIA_OBJECT_NOT_FOUND, "Object not found");
}
obj->invoke (obj, operation, operationParams, value);
response[VALUE] = value;
response[SESSION_ID] = sessionId;
} catch (KurentoException &ex) {
Json::Value data;
data[TYPE] = ex.getType();
throw JsonRpc::CallException (ex.getCode (), ex.getMessage (), data);
}
}
void
ServerMethods::connect (const Json::Value ¶ms, Json::Value &response)
{
std::string sessionId;
if (params == Json::Value::null) {
sessionId = generateUUID ();
} else {
bool doKeepAlive = false;
doKeepAlive = getOrCreateSessionId (sessionId, params);
if (doKeepAlive) {
try {
keepAliveSession (sessionId);
} catch (KurentoException &ex) {
Json::Value data;
data[TYPE] = ex.getType();
throw JsonRpc::CallException (ex.getCode (), ex.getMessage (), data);
}
}
}
response[SESSION_ID] = sessionId;
response["serverId"] = instanceId;
}
void
ServerMethods::create (const Json::Value ¶ms,
Json::Value &response)
{
std::string type;
std::shared_ptr<Factory> factory;
std::string sessionId;
requireParams (params);
JsonRpc::getValue (params, TYPE, type);
try {
JsonRpc::getValue (params, SESSION_ID, sessionId);
} catch (JsonRpc::CallException e) {
sessionId = generateUUID ();
}
try {
factory = moduleManager.getFactory (type);
checkResources (resourceLimitPercent);
std::shared_ptr <MediaObjectImpl> object;
object = std::dynamic_pointer_cast<MediaObjectImpl> (
factory->createObject (config, sessionId, params["constructorParams"]) );
response[VALUE] = object->getId();
response[SESSION_ID] = sessionId;
} catch (KurentoException &ex) {
Json::Value data;
data[TYPE] = ex.getType();
throw JsonRpc::CallException (ex.getCode (), ex.getMessage (), data);
}
}
void
insertResult (Json::Value &value, Json::Value &responses, const int index)
{
try {
Json::Value result;
JsonRpc::getValue (responses[index], JSON_RPC_RESULT, result);
value = result[VALUE];
} catch (JsonRpc::CallException e) {
Json::Value data;
KurentoException ke (MALFORMED_TRANSACTION,
"Result not found on request " +
std::to_string (index) );
data[TYPE] = ke.getType();
GST_ERROR ("Error while inserting new ref value: %s",
e.getMessage ().c_str () );
throw JsonRpc::CallException (ke.getCode (), ke.getMessage (), data);
}
}
void
injectRefs (Json::Value ¶ms, Json::Value &responses)
{
if (params.isObject () || params.isArray () ) {
for (auto ¶m : params) {
injectRefs(param, responses);
}
} else if (params.isConvertibleTo (Json::ValueType::stringValue) ) {
std::string param = JsonFixes::getString (params);
if (param.size() > NEW_REF.size()
&& param.substr (0, NEW_REF.size() ) == NEW_REF) {
std::string ref = param.substr (NEW_REF.size() );
try {
int index = stoi (ref);
insertResult (params, responses, index);
} catch (std::invalid_argument &e) {
Json::Value data;
KurentoException ke (MALFORMED_TRANSACTION,
"Invalid index of newref '" + ref + "'");
data[TYPE] = ke.getType();
throw JsonRpc::CallException (ke.getCode (), ke.getMessage (), data);
}
}
}
}
void
ServerMethods::transaction (const Json::Value ¶ms, Json::Value &response)
{
std::string sessionId;
Json::Value operations;
std::string uniqueId = generateUUID();
requireParams (params);
getOrCreateSessionId (sessionId, params);
JsonRpc::getArray (params, "operations", operations);
Json::Value responses;
for (uint i = 0; i < operations.size(); i++) {
bool ret;
Json::Value &reqParams = operations[i][JSON_RPC_PARAMS];
reqParams[SESSION_ID] = sessionId;
if (!operations[i][JSON_RPC_ID].isConvertibleTo (Json::ValueType::uintValue)
|| operations[i][JSON_RPC_ID].asUInt() != i) {
Json::Value data;
KurentoException ke (MALFORMED_TRANSACTION,
"Id of request '" + std::to_string (i) +
"' should be '" + std::to_string (i) + "'");
data[TYPE] = ke.getType();
throw JsonRpc::CallException (ke.getCode (), ke.getMessage (), data);
}
try {
operations[i][JSON_RPC_ID] = uniqueId + "_" + std::to_string (
operations[i][JSON_RPC_ID].asUInt() );
} catch (...) {
GST_ERROR ("Error setting id");
}
injectRefs (reqParams, responses);
ret = handler.process (operations[i], responses[i]);
responses[i][JSON_RPC_ID] = i;
if (!ret) {
break;
}
}
if (responses.isNull () ) {
responses.resize (0);
}
response[VALUE] = responses;
response[SESSION_ID] = sessionId;
}
void
ServerMethods::ping (const Json::Value ¶ms, Json::Value &response)
{
std::string sessionId;
try {
JsonRpc::getValue (params, SESSION_ID, sessionId);
response [SESSION_ID] = sessionId;
} catch (JsonRpc::CallException e) {
}
if (sessionId.empty()) {
GST_DEBUG ("WebSocket Ping/Pong");
}
else {
GST_DEBUG ("WebSocket Ping/Pong with sessionId %s", sessionId.c_str());
}
response[VALUE] = "pong";
}
void
ServerMethods::closeSession (const Json::Value ¶ms,
Json::Value &response)
{
std::string sessionId;
bool release = false;
requireParams (params);
try {
JsonRpc::getValue (params, "release", release);
} catch (JsonRpc::CallException e) {
/* release param is optional*/
}
JsonRpc::getValue (params, SESSION_ID, sessionId);
if (release) {
MediaSet::getMediaSet()->releaseSession (sessionId);
} else {
MediaSet::getMediaSet()->unrefSession (sessionId);
}
}
ServerMethods::StaticConstructor ServerMethods::staticConstructor;
ServerMethods::StaticConstructor::StaticConstructor()
{
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
}
} /* kurento */
| 9,380 |
890 |
/*
*
* Copyright 2018 Asylo authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef ASYLO_PLATFORM_POSIX_INCLUDE_SYS_INOTIFY_H_
#define ASYLO_PLATFORM_POSIX_INCLUDE_SYS_INOTIFY_H_
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
// Flags for inotify_init1(2).
#define IN_NONBLOCK 0x01
#define IN_CLOEXEC 0x02
// Bitmask flags for inotify events.
#define IN_ACCESS 0x001
#define IN_ATTRIB 0x002
#define IN_CLOSE_WRITE 0x004
#define IN_CLOSE_NOWRITE 0x008
#define IN_CREATE 0x010
#define IN_DELETE 0x020
#define IN_DELETE_SELF 0x040
#define IN_MODIFY 0x080
#define IN_MOVE_SELF 0x100
#define IN_MOVED_FROM 0x200
#define IN_MOVED_TO 0x400
#define IN_OPEN 0x800
// Combination flags
#define IN_ALL_EVENTS \
(IN_ACCESS | IN_ATTRIB | IN_CLOSE_WRITE | IN_CLOSE_NOWRITE | IN_CREATE | \
IN_DELETE | IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | \
IN_MOVED_TO | IN_OPEN)
#define IN_MOVE (IN_MOVED_FROM | IN_MOVED_TO)
#define IN_CLOSE (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE)
// Further flags for inotify_add_watch(2).
#define IN_DONT_FOLLOW 0x01000
#define IN_EXCL_UNLINK 0x02000
#define IN_MASK_ADD 0x04000
#define IN_ONESHOT 0x08000
#define IN_ONLYDIR 0x10000
// Additional flags that may be set in the buffer modified by read(2).
#define IN_IGNORED 0x020000
#define IN_ISDIR 0x040000
#define IN_Q_OVERFLOW 0x080000
#define IN_UNMOUNT 0x100000
// API functions for interacting with an inotify object.
int inotify_init(void);
int inotify_init1(int flags);
int inotify_add_watch(int fd, const char *pathname, uint32_t mask);
int inotify_rm_watch(int fd, int wd);
// Struct definition from inotify(7) man page.
struct inotify_event {
int wd; // Watch descriptor
uint32_t mask; // Mask describing event
uint32_t cookie; // Unique cookie associating related events (for rename(2))
uint32_t len; // Size of name field
char name[]; // Optional null-terminated name
};
#ifdef __cplusplus
} // extern "C"
#endif
#endif // ASYLO_PLATFORM_POSIX_INCLUDE_SYS_INOTIFY_H_
| 1,044 |
460 |
package de.saxsys.mvvmfx.examples.contacts.events;
/**
* CDI event class that is used to indicate that a contact was
* updated/added/removed.
*/
public class ContactsUpdatedEvent {
}
| 61 |
3,857 |
<filename>dev.skidfuscator.obfuscator/src/main/java/dev/skidfuscator/obf/yggdrasil/app/MapleEntryPoint.java<gh_stars>1000+
package dev.skidfuscator.obf.yggdrasil.app;
import dev.skidfuscator.obf.init.SkidSession;
import dev.skidfuscator.obf.yggdrasil.EntryPoint;
import dev.skidfuscator.obf.yggdrasil.method.MethodInvokerResolver;
import org.mapleir.app.service.ApplicationClassSource;
import org.mapleir.app.service.InvocationResolver;
import org.mapleir.asm.MethodNode;
import org.mapleir.context.AnalysisContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @author Ghast
* @since 21/01/2021
* SkidfuscatorV2 © 2021
*/
public class MapleEntryPoint implements EntryPoint {
public List<MethodNode> getEntryPoints(final SkidSession context, final ApplicationClassSource contents) {
final AnalysisContext cxt = context.getCxt();
final Set<MethodNode> free = context.getCxt().getApplicationContext().getEntryPoints();
return new ArrayList<>(free);
}
}
| 365 |
476 |
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.spi.snapshot;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Help to clarify snapshot support of the annotated class:
* - unsupported: controls whether the class is expeccted to be involved in snapshot. Default is false.
* - stateClassName: name of state class, the result of capturing the annotated class. Default is class name with State suffix.
* The state class can also be omitted if there are 0 or 1 fields to capture.
* - baseClassStateName: name of field in stateClass that corresponds to result of "super.capture()". Default is "baseState".
* - uncapturedFields: which fields don't need to be captured.
* <p>
* A special case is for anonymous classes, where it's not easy to attach this annotation.
* new @RestorableConfig(...) SomeInterface {
* int a;
* ...
* }
* This works syntactically, but a Java issue sometimes causes the field "a" to not be accessible by methods in the class.
* To work around it, for anonymous classes, instead of annotating the class, we allow:
* new SomeInterface {
*
* @RestorableConfig(...) private final RestorableConfig restorableConfig = null;
* int a;
* ...
* }
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})
public @interface RestorableConfig
{
boolean unsupported() default false;
String stateClassName() default "";
String baseClassStateName() default "baseState";
String[] uncapturedFields() default {};
}
| 595 |
821 |
/*
* Copyright (C) 2018 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.
*/
package com.google.caliper.runner.worker.dryrun;
import com.google.caliper.runner.experiment.Experiment;
import com.google.caliper.runner.worker.WorkerRunner;
import com.google.caliper.runner.worker.WorkerScoped;
import com.google.common.collect.ImmutableSet;
import dagger.BindsInstance;
import dagger.Subcomponent;
import java.util.Set;
/**
* Component for dry-running experiments on a worker and getting the results.
*
* <p>Dry-runs for all experiments that are to be run on a single target are done in a single worker
* process so as to avoid the overhead of creating potentially hundreds of worker processes.
*/
@WorkerScoped
@Subcomponent(modules = DryRunModule.class)
public interface DryRunComponent {
WorkerRunner<ImmutableSet<Experiment>> workerRunner();
/** Builder for {@link DryRunComponent}. */
@Subcomponent.Builder
interface Builder {
/** Binds the set of experiments to be dry-run. */
@BindsInstance
Builder experiments(Set<Experiment> experiment);
/** Builds a new {@link DryRunComponent}. */
DryRunComponent build();
}
}
| 467 |
1,749 |
// Copyright 2015, <NAME> and the FunctionalPlus contributors.
// https://github.com/Dobiasd/FunctionalPlus
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <doctest/doctest.h>
#include <fplus/fplus.hpp>
#include <vector>
namespace {
auto sqrtToResult = [](auto x)
{
return x < 0.0f ? fplus::error<float>(std::string("no sqrt of negative numbers")) :
fplus::ok<float, std::string>(static_cast<float>(sqrt(static_cast<float>(x))));
};
auto sqrtToResultInt = [](auto x)
{
return x < 0 ? fplus::error<int>(std::string("no sqrt of negative numbers")) :
fplus::ok<int, std::string>(fplus::round(sqrt(static_cast<float>(x))));
};
float IntToFloat(const int& x)
{
return static_cast<float>(x);
}
typedef std::vector<fplus::result<int, std::string>> IntResults;
typedef std::vector<int> Ints;
typedef std::vector<std::string> Strings;
}
class resultTestState {
public:
explicit resultTestState(int x) : x_(x) {}
void Add(int y) { x_ += y; }
int Get() const { return x_; }
private:
int x_;
};
TEST_CASE("result_test - ok_with_default")
{
using namespace fplus;
auto x = ok<int, std::string>(2);
auto y = error<int, std::string>("an error");
auto Or42 = bind_1st_of_2(ok_with_default<int, std::string>, 42);
REQUIRE_EQ(Or42(x), 2);
REQUIRE_EQ(Or42(y), 42);
}
TEST_CASE("maybe_test - join_result")
{
using namespace fplus;
using Ok = int;
using Err = std::string;
using Res = result<Ok, Err>;
REQUIRE_EQ(join_result(ok<Res, Err>(ok<Ok, Err>(2))), (ok<Ok, Err>(2)));
REQUIRE_EQ(join_result(ok<Res, Err>(error<Ok, Err>("e"))), (error<Ok, Err>("e")));
REQUIRE_EQ(join_result(error<Res, Err>("e")), (error<Ok, Err>("e")));
}
TEST_CASE("result_test - and_then_result")
{
using namespace fplus;
auto ok_4 = ok<int, std::string>(4);
auto ok_2 = ok<int, std::string>(2);
auto an_error = error<int, std::string>("an error");
REQUIRE_EQ(and_then_result(sqrtToResultInt, ok_4), ok_2);
REQUIRE_EQ(and_then_result(sqrtToResultInt, an_error), an_error);
const auto string_to_result_int_string = [](const auto& str) {
if (str == "42")
return ok<int, std::string>(42);
else
return error<int, std::string>("not 42");
};
REQUIRE_EQ(and_then_result(string_to_result_int_string, (ok<std::string, std::string>("3"))), (error<int, std::string>("not 42")));
REQUIRE_EQ(and_then_result(string_to_result_int_string, (ok<std::string, std::string>("42"))), (ok<int, std::string>(42)));
REQUIRE_EQ(and_then_result(string_to_result_int_string, (error<std::string, std::string>("error"))), (error<int, std::string>("error")));
}
TEST_CASE("result_test - compose_result")
{
using namespace fplus;
auto x = ok<int, std::string>(2);
auto y = error<int, std::string>("an error");
auto sqrtAndSqrt = compose_result(sqrtToResult, sqrtToResult);
REQUIRE_EQ(lift_result(square<int>, x), (ok<int, std::string>(4)));
REQUIRE_EQ(lift_result(square<int>, y), (error<int>(std::string("an error"))));
auto sqrtIntAndSqrtIntAndSqrtInt = compose_result(sqrtToResultInt, sqrtToResultInt, sqrtToResultInt);
REQUIRE_EQ(sqrtIntAndSqrtIntAndSqrtInt(256), (ok<int, std::string>(2)));
auto sqrtIntAndSqrtIntAndSqrtIntAndSqrtInt = compose_result(sqrtToResultInt, sqrtToResultInt, sqrtToResultInt, sqrtToResultInt);
REQUIRE_EQ(sqrtIntAndSqrtIntAndSqrtIntAndSqrtInt(65536), (ok<int, std::string>(2)));
const auto LiftedIntToFloat =
[](const result<int, std::string>& r) -> result<float, std::string>
{
return lift_result(IntToFloat, r);
};
auto OkInt = ok<int, std::string>;
auto IntToResultFloat = compose(OkInt, LiftedIntToFloat);
auto IntToFloatAndSqrtAndSqrt = compose_result(IntToResultFloat, sqrtAndSqrt);
REQUIRE(is_in_interval(1.41f, 1.42f, unsafe_get_ok<float>
(IntToFloatAndSqrtAndSqrt(4))));
// first callable can take a variadic number of arguments
auto sumToResult = [](auto a, auto b) {
return ok<decltype(a + b), std::string>(a + b);
};
auto squareSumResult = compose_result(sumToResult, [](auto sum) {
return ok<decltype(sum * sum), std::string>(sum * sum);
});
REQUIRE_EQ(squareSumResult(5, 5), (ok<int, std::string>(100)));
}
TEST_CASE("result_test - lift")
{
using namespace fplus;
auto x = ok<int, std::string>(2);
auto y = error<int, std::string>("an error");
auto SquareAndSquare = compose(square<int>, square<int>);
REQUIRE_EQ((lift_result(SquareAndSquare, x)), (ok<int, std::string>(16)));
REQUIRE_EQ((lift_result([](auto n) { return square(n) * square(n); }, x)),
(ok<int, std::string>(16)));
}
TEST_CASE("result_test - lift_both")
{
using namespace fplus;
const auto x = ok<int, std::string>(2);
const auto y = error<int, std::string>("an error");
REQUIRE_EQ(lift_result_both(square<int>, to_upper_case<std::string>, x), (ok<int, std::string>(4)));
REQUIRE_EQ(lift_result_both(square<int>, to_upper_case<std::string>, y), (error<int, std::string>("AN ERROR")));
REQUIRE_EQ(lift_result_both([](auto z) { return z * z; },
[](auto z) { return to_upper_case(z); },
y),
(error<int, std::string>("AN ERROR")));
}
TEST_CASE("result_test - unify_result")
{
using namespace fplus;
const auto x = ok<int, std::string>(2);
const auto y = error<int, std::string>("an error");
const auto unify = [](const result<int, std::string>& r) -> std::string
{
return unify_result(show<int>, to_upper_case<std::string>, r);
};
REQUIRE_EQ(unify(x), "2");
REQUIRE_EQ(unify(y), "AN ERROR");
const auto unifyGeneric = [](auto r) {
return unify_result(show<typename decltype(r)::ok_t>,
to_upper_case<typename decltype(r)::error_t>,
r);
};
REQUIRE_EQ(unifyGeneric(x), "2");
REQUIRE_EQ(unifyGeneric(y), "AN ERROR");
}
TEST_CASE("result_test - equality")
{
using namespace fplus;
IntResults results = {ok<int, std::string>(1), error<int>(std::string("no sqrt of negative numbers")), ok<int, std::string>(2)};
REQUIRE(oks(results) == Ints({ 1,2 }));
REQUIRE(errors(results) == Strings({std::string("no sqrt of negative numbers")}));
REQUIRE((ok<int, std::string>(1)) == (ok<int, std::string>(1)));
REQUIRE((ok<int, std::string>(1)) != (ok<int, std::string>(2)));
REQUIRE((ok<int, std::string>(1)) != (error<int, std::string>(std::string("fail"))));
REQUIRE(error<int>(std::string("fail")) == (error<int>(std::string("fail"))));
REQUIRE(error<int>(std::string("fail 1")) != (error<int>(std::string("fail 2"))));
}
TEST_CASE("result_test - transform_and_keep_oks")
{
using namespace fplus;
Ints wholeNumbers = { -3, 4, 16, -1 };
REQUIRE_EQ(transform_and_keep_oks(sqrtToResultInt, wholeNumbers)
, Ints({2,4}));
REQUIRE_EQ(transform_and_concat(
bind_1st_of_2(replicate<int>, std::size_t(3)), Ints{ 1,2 })
, Ints({ 1,1,1,2,2,2 }));
}
TEST_CASE("result_test - show_result")
{
using namespace fplus;
REQUIRE_EQ(show_result(ok<int, std::string>(42)), std::string("Ok 42"));
REQUIRE_EQ(show_result(error<int, std::string>("fail")), std::string("Error fail"));
auto x = ok<int, std::string>(2);
REQUIRE_EQ((to_maybe<int, std::string>(x)), just(2));
REQUIRE_EQ((from_maybe<std::string, int>(std::string("no error"), just(2))), x);
}
TEST_CASE("result_test - exceptions")
{
using namespace fplus;
std::string thrown_str;
try
{
throw_on_error(std::invalid_argument("exception string"), error<int, std::string>("failed"));
}
catch (const std::exception& e)
{
thrown_str = e.what();
}
REQUIRE_EQ(thrown_str, std::string("exception string"));
thrown_str.clear();
try
{
throw_type_on_error<std::invalid_argument>(error<int, std::string>("failed"));
}
catch (const std::exception& e)
{
thrown_str = e.what();
}
REQUIRE_EQ(thrown_str, std::string("failed"));
thrown_str.clear();
}
TEST_CASE("result_test - copy")
{
using namespace fplus;
result<int, std::string> result_4 = ok<int, std::string>(4);
result<int, std::string> result_4_copy(result_4);
result<int, std::string> result_4_copy_2 = error<int, std::string>("dummy");
result_4_copy_2 = result_4_copy;
REQUIRE_EQ(result_4_copy_2, (ok<int, std::string>(4)));
result<int, std::string> result_int_string_error = error<int, std::string>("error");
result<int, std::string> result_int_string_error_copy(result_int_string_error);
result<int, std::string> result_int_string_error_copy_2 = ok<int, std::string>(9999);
result_int_string_error_copy_2 = result_int_string_error_copy;
REQUIRE_EQ(result_int_string_error_copy_2, (error<int, std::string>("error")));
}
| 3,941 |
4,551 |
<reponame>quipper/robolectric
package org.robolectric.testing;
import org.robolectric.annotation.internal.Instrument;
@SuppressWarnings("UnusedDeclaration")
@Instrument
public class AClassThatCallsAMethodReturningAForgettableClass {
public void callSomeMethod() {
AClassToForget forgettableClass = getAForgettableClass();
}
public AClassToForget getAForgettableClass() {
throw new RuntimeException("should never be called!");
}
}
| 144 |
5,169 |
<filename>Specs/b/2/6/KKHttp/1.0.0/KKHttp.podspec.json
{
"name": "KKHttp",
"version": "1.0.0",
"summary": "HTTP",
"description": "HTTP, 支持 JavascriptCore",
"homepage": "https://github.com/hailongz/KKHttp",
"license": "MIT",
"authors": {
"<NAME>": "<EMAIL>"
},
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/hailongz/KKHttp.git",
"tag": "1.0.0"
},
"vendored_frameworks": "KKhttp.framework",
"requires_arc": true
}
| 222 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.