Perform the L_2 attack on the given instance for the given targets.

    If self.targeted is true, then the targets represents the target labels
    If self.targeted is false, then targets are the original class labels
514566
def attack(self, imgs, targets):
    

    r = []
    for i in range(0, len(imgs), self.batch_size):
      _logger.debug(
          ("Running CWL2 attack on instance %s of %s", i, len(imgs)))
      r.extend(
          self.attack_batch(imgs[i:i + self.batch_size],
                            targets[i:i + self.batch_size]))
    return np.array(r)
627778
def play_actions(self, target):
        
        for method_name, args, kwargs in self.actions:
            method = getattr(target, method_name)
            method(*args, **kwargs)
1083879
def markPairs(self, labeled_pairs):
        '''
        
        '''
        self._checkTrainingPairs(labeled_pairs)

        for label, examples in labeled_pairs.items():
            self.training_pairs[label].extend(examples)

        if self.active_learner:
            examples, y = flatten_training(labeled_pairs)
            self.active_learner.mark(examples, y)
613555
public static void verifyTargets(
			ITargetHandlerResolver targetHandlerResolver,
			ManagedApplication ma,
			ITargetsMngr targetsMngr ) {

		Logger logger = Logger.getLogger( TargetHelpers.class.getName());
		for( Instance inst : InstanceHelpers.getAllInstances( ma.getApplication())) {
			if( ! InstanceHelpers.isTarget( inst ))
				continue;

			try {
				String path = InstanceHelpers.computeInstancePath( inst );
				Map<String,String> targetProperties = targetsMngr.findTargetProperties( ma.getApplication(), path ).asMap();
				targetHandlerResolver.findTargetHandler( targetProperties );

			} catch( TargetException e ) {
				logger.warning( e.getMessage());
			}
		}
	}
616082
private void setTargets(TrellisNode[][] trellis, double[] scaling, int[] label) {
        TrellisNode[] t0 = trellis[0];

        // Finding the normalizer for our first 'column' in the matrix
        double normalizer = 0.0;
        for (int i = 0; i < numClasses; i++) {
            normalizer += t0[i].expScores[0] * t0[i].beta;
        }

        for (int i = 0; i < numClasses; i++) {
            if (label[0] == i) {
                t0[i].target[0] = 1 - t0[i].expScores[0] * t0[i].beta / normalizer;
            } else {
                t0[i].target[0] = -t0[i].expScores[0] * t0[i].beta / normalizer;
            }
        }

        for (int t = 1; t < label.length; t++) {
            normalizer = 0.0;
            TrellisNode[] tt = trellis[t];
            TrellisNode[] tt1 = trellis[t-1];
            for (int i = 0; i < numClasses; i++) {
                normalizer += tt[i].alpha * tt[i].beta;
            }
            normalizer *= scaling[t];

            for (int i = 0; i < numClasses; i++) {
                TrellisNode tti = tt[i];
                for (int j = 0; j < numClasses; j++) {
                    if (label[t] == i && label[t - 1] == j) {
                        tti.target[j] = 1 - tti.expScores[j] * tt1[j].alpha * tti.beta / normalizer;
                    } else {
                        tti.target[j] = -tti.expScores[j] * tt1[j].alpha * tti.beta / normalizer;
                    }
                }
            }
        }
    }
1069421
@Override
	protected void applyAction(final SubordinateTarget target, final Object value) {
		if (value instanceof Boolean) {
			boolean visible = ((Boolean) value);
			target.setValidate(visible);
			((AbstractWComponent) target).setHidden(!visible);
		}
	}
832964
protected void setTargetClass(Class targetClass) {
		this.targetClass = targetClass;
		this.readAccessors.clear();
		this.writeAccessors.clear();
		introspectMethods(targetClass, new HashSet());
		if (isFieldAccessEnabled()) {
			introspectFields(targetClass, new HashSet());
		}
	}
1331897
def _validate_target(self, y):
        
        # Ignore None values
        if y is None:
            return

        y_type = type_of_target(y)
        if y_type not in ("binary", "multiclass"):
            raise YellowbrickValueError((
                "'{}' target type not supported, only binary and multiclass"
            ).format(y_type))
1233988
protected void checkTarget(final File target) throws IOException {
        if (target == null) {
            throw new IOException("You must provide a target directory or file");
        }
        if (!target.exists()) {
            String extension = FilenameUtils.getExtension(target.getName());
            if (extension.length() == 0) {
                throw new IOException("Target folder " + target + " not found");
            }
        }
    }
314639
public void targetAppears( TargetHandler targetItf ) {
		this.defaultTargetHandlerResolver.addTargetHandler( targetItf );

		// When a target is deployed, we may also have to update instance states.
		// Consider as an example when the DM restarts. Targets may be injected
		// before and after the pojo was started by iPojo.

		// See #519 for more details.
		// Notice we restore instances only when the DM was started (the messaging
		// must be ready). If it is not started, do nothing. The "start" method
		// will trigger the restoration.

		// We consider the DM is started if the timer is not null.
		if( this.timer != null )
			restoreInstancesFrom( targetItf );
	}
518611
def generate(self, x, **kwargs):
    
    assert self.sess is not None, \
        'Cannot use `generate` when no `sess` was provided'
    self.parse_params(**kwargs)

    if self.y_target is None:
      self.y_target, nb_classes = self.get_or_guess_labels(x, kwargs)
      self.targeted_attack = False
    else:
      _, nb_classes = self.get_or_guess_labels(x, kwargs)
      self.targeted_attack = True

    attack = LBFGS_impl(
        self.sess, x, self.model.get_logits(x),
        self.y_target, self.targeted_attack,
        self.binary_search_steps, self.max_iterations, self.initial_const,
        self.clip_min, self.clip_max, nb_classes, self.batch_size)

    def lbfgs_wrap(x_val, y_val):
      """
      Wrapper creating TensorFlow interface for use with py_func
      """
      return np.array(attack.attack(x_val, y_val), dtype=self.np_dtype)

    wrap = tf.py_func(lbfgs_wrap, [x, self.y_target], self.tf_dtype)
    wrap.set_shape(x.get_shape())

    return wrap
976810
public void setTargets(java.util.Collection<TargetDescription> targets) {
        if (targets == null) {
            this.targets = null;
            return;
        }

        this.targets = new java.util.ArrayList<TargetDescription>(targets);
    }
180114
def attack(self, x, true_y):
    
    adv_x_cls = []
    prob_cls = []
    m = tf.shape(x)[0]
    true_y_idx = tf.argmax(true_y, axis=1)

    expanded_x = tf.concat([x] * self.nb_classes, axis=0)
    target_ys = [tf.to_float(tf.one_hot(tf.ones(m, dtype=tf.int32) * cls,
                                        self.nb_classes))
                 for cls in range(self.nb_classes)]
    target_y = tf.concat(target_ys, axis=0)
    adv_x_cls = self.attack_class(expanded_x, target_y)
    expanded_all_probs = self.model.get_probs(adv_x_cls)

    adv_x_list = tf.split(adv_x_cls, self.nb_classes)
    all_probs_list = tf.split(expanded_all_probs, self.nb_classes)

    for cls in range(self.nb_classes):
      target_y = target_ys[cls]
      all_probs = all_probs_list[cls]
      # We don't actually care whether we hit the target class.
      # We care about the probability of the most likely wrong class
      cur_prob_cls = tf.reduce_max(all_probs - true_y, axis=1)
      # Knock out examples that are correctly classified.
      # This is not needed to be optimal for t >= 0.5, but may as well do it
      # to get better failure rate at lower thresholds.
      chosen_cls = tf.argmax(all_probs, axis=1)
      eligible = tf.to_float(tf.not_equal(true_y_idx, chosen_cls))
      cur_prob_cls = cur_prob_cls * eligible
      prob_cls.append(cur_prob_cls)

    probs = tf.concat([tf.expand_dims(e, 1) for e in prob_cls], axis=1)
    # Don't need to censor here because we knocked out the true class above
    # probs = probs - true_y
    most_confident = tf.argmax(probs, axis=1)
    fused_mask = tf.one_hot(most_confident, self.nb_classes)
    masks = tf.split(fused_mask, num_or_size_splits=self.nb_classes, axis=1)
    shape = [m] + [1] * (len(x.get_shape()) - 1)
    reshaped_masks = [tf.reshape(mask, shape) for mask in masks]
    out = sum(adv_x * rmask for adv_x,
              rmask in zip(adv_x_list, reshaped_masks))
    return out
1158787
def find_label(self, label: Label):
        
        for index, action in enumerate(self.program):
            if isinstance(action, JumpTarget):
                if label == action.label:
                    return index

        raise RuntimeError("Improper program - Jump Target not found in the "
                           "input program!")
903963
def clip_and_copy_attack_outputs(self, attack_name, is_targeted):
    
    if is_targeted:
      self._targeted_attack_names.add(attack_name)
    else:
      self._attack_names.add(attack_name)
    attack_dir = os.path.join(self.targeted_attacks_output_dir
                              if is_targeted
                              else self.attacks_output_dir,
                              attack_name)
    for fname in os.listdir(attack_dir):
      if not (fname.endswith('.png') or fname.endswith('.jpg')):
        continue
      image_id = fname[:-4]
      if image_id not in self.dataset_max_clip:
        continue
      image_max_clip = self.dataset_max_clip[image_id]
      image_min_clip = self.dataset_min_clip[image_id]
      adversarial_image = np.array(
          Image.open(os.path.join(attack_dir, fname)).convert('RGB'))
      clipped_adv_image = np.clip(adversarial_image,
                                  image_min_clip,
                                  image_max_clip)
      output_basename = '{0:08d}'.format(self._output_image_idx)
      self._output_image_idx += 1
      self._output_to_attack_mapping[output_basename] = (attack_name,
                                                         is_targeted,
                                                         image_id)
      if is_targeted:
        self._targeted_attack_image_count += 1
      else:
        self._attack_image_count += 1
      Image.fromarray(clipped_adv_image).save(
          os.path.join(self.all_adv_examples_dir, output_basename + '.png'))
1181349
public void setProtectedTargets(String... targets) {
        handler.setProtectedTargets(Arrays.copyOf(targets, targets.length));
    }
759935
function SeeAddKnightAttacks(target, us, attacks) {
    var pieceIdx = (us | pieceKnight) << 4;
    var attackerSq = g_pieceList[pieceIdx++];

    while (attackerSq != 0) {
        if (IsSquareOnPieceLine(target, attackerSq)) {
            attacks[attacks.length] = attackerSq;
        }
        attackerSq = g_pieceList[pieceIdx++];
    }
}