Change specific pixels
I'd like to change the color of specific pixels from array data that could look like this:
var pixel_array = [ [100,201, "#d3d3d3"], [140,211, "#ffffff"], ...]
The 0. index symbolizes the x  positions of the pixel that should be changed
The 1.index symbolizes the y  positions of the pixel that should be changed
The 2.index is the HEXvalue of the color the pixel should get
I'm a bloody beginner in Swift  so I really got no idea how to accomplish this task to get a working solution for changing the pixels of an Image.
This is what I've got so far.
func changeColorByArray(_ array: [[Any]], _ image: UIImage) > UIImage {
let img: CGImage = image.cgImage!
let data: CFData = img.dataProvider!.data!
let binary = vImage_Buffer(data: UnsafeMutableRawPointer(mutating: CFDataGetBytePtr(data)), height: vImagePixelCount(img.height), width: vImagePixelCount(img.width), rowBytes: img.bytesPerRow)
for i in 0..<img.height {
for j in 0..<img.width {
let rgb = binary.data.load(fromByteOffset: (i * img.width + j) * 4, as: UInt32.self)
// (!) if array includes positions ?
// set pixel to hexStringToUIColor(array[k][2])
// else nothing
}
}
return UIImage(data: binary) // error
}
func hexStringToUIColor (hex:String) > UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
I've added comments where I got stuck so any help would be very appreciated :)
See also questions close to this topic

Swift DateFormatter to unix seconds
I'm using JSONEncoder/Codable to easily serialize an object. The object contains a Date value.
I wish to convert the Date value to unix seconds without a decimal. With any Encoder you can set the dateEncodingStrategy, however .secondsSince1970 provides a decimal, where as I'm looking for only secondsprecision. There is the option of using a custom DateFormatter, however I cannot find a dateFormat value that outputs unix seconds.
Note I know the backup option would be to completely override the encode method of the Codable struct, however I was hoping not to.
Example:
struct SomethingCodable: Codable { let date: Date } let encoder = JSONEncoder() // Will encode to this format: 1521744936.301688 encoder.dateEncodingStrategy = .secondsSince1970 // Could use a custom DateFormatter?? Wish for: 1521744936 encoder.formatted(aDateFormatter)

How should I be using the WKWebView failure/error delegate methods
I have two scenarios I've encountered that are not caught by the WKWebView delegate failure methods
 (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
 (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
1) When I attempt to load a webpage and have no internet connection*
2) When I attempt to load a webpage and get a response other than 200's or 300's I have seen this post, but it doesn't not explain why the failure methods don't fire, only how to get the response codes.**
*I am trying to guard against the loss of internet connectivity. If I load a webpage, then put the phone in airplane mode and click on a link within the page I am not seeing the start or failure WKWebView delegate methods firing (
(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
). Assuming it cannot start because of a lack of connectivity I would still expect the failure method to fire as a conclusion to my attempted request. This makes handling the loss of connectivity when a user may click an internal link on a webview incredibly difficult.**Anything other than a 200 or 300 level response is considered an error and I would expect the failure with error to response with the correct error/response code.
I have since implemented Reachability code for connectivity, and
 (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
for abnormal responses, however I'm left wondering how I should be using the failure methods and if my efforts are overkill and I can use the supplied failure delegate methods for a simpler method of solving the problems.

Best way to secure data
I have written an app in swift which uses several files like videos, jpg, and other data which I want to protect from being copied by just opening the .ipa file on a computer and copy them.
The principle by which I want to achieve this is this:
1.encrypt the files using my iMac or pc (some sort of java program which I will write for this) 2.put the encrypted files into the app 3.decrypt the files when the app is launched and load the decrypted files directly into the ram.
What's the best encryption technique for this? how can I save the password for decryption inside my source code securely? It's probably pretty unsafe to just create a string containing it plain ? important is that I don't want to use a third party library. I want to achieve this by only using apple libraries.
Thank you very much!

Using lodash to get the closest next value of a prop
I have an array of objects, each with non correlative ids.
I would like to know if it is possbile, given an integer, to find the next closest id value object.
Example
const array = [{id: 4}, {id: 10}, {id: 15}]
given any value
x
, if10 < x <= 15
, it should return15
given any value
x
, if4 < x <= 10
, it should return10
and so on.
Thank you

error accessing simple array
Have an ArrayList the first element is a simple String[][], the rest are ArrayLists. I need to retrieve and parse that array. I can get the first structure into a list as below
Object o = results.get(0); List l = Arrays.asList(o);
However when I try the following I get the error in the third below
int len = ((String[])l.get(tokenInd)).length; or int len = ((ArrayList)l.get(tokenInd)).size();
I get java.lang.ClassCastException: [[Ljava.lang.String; cannot be cast to [Ljava.lang.String;

Undefined on data.filter or multi if statements with returning array
I've figured out the following code allows me to look up multiple variables, and return them in an array...
function() { var cart_item_1 = document.querySelectorAll("#main>#ViewCartWrapper>form>div>.bordered>tbody>tr>td")[5].innerText; var cart_item_2 = document.querySelectorAll("#main>#ViewCartWrapper>form>div>.bordered>tbody>tr>td")[9].innerText; var cart_item_3 = document.querySelectorAll("#main>#ViewCartWrapper>form>div>.bordered>tbody>tr>td")[13].innerText; return [cart_item_1, cart_item_2, cart_item_3]; }
Everything works fine as long as there are exactly (3) cart items, but the environment that I'm working with varies. There may only be 1 cart item or 7 depending on user input.
Unless there's an exact 3 in this scenario it'll return everything back as undefined.
I've tried using:
if ([cart_item_1] == undefined){ return "_" } else { return [cart_item_1] } if ([cart_item_2] == undefined){ return "_" } else { return [cart_item_2] }
etc...
But it'll stop after the first cart item.
I tried implementing a data.filter from another post "removingundefinedvaluesfromarray" but it returned everything back as undefined.
Can someone help with what I need to look for to return back only variables that exist?
Or looking at the cart code, is there a better way of dynamically pulling any instance of the:
document.querySelectorAll("#main>#ViewCartWrapper>form>div>.bordered>tbody>tr>td")**[5]**.innerText
The only thing that changes is the number bolded. I tried using a wildcard in that field but it returned back undefined.
Since I'm using for GTM as a custom js variable then any recommendation has to of course be js.

How To Store Data Permanently With User Defaults In xCode Swift for toggle button
How can I save the state of my toggle button using userdefaults this is cood please help me
import UIKit
class LawFigure: UIViewController {
//Outlets: @IBOutlet weak var likeButton: UIButton! //Variables:
var isButtonOn = false
override func viewDidLoad() { super.viewDidLoad() customiseUI() }
func customiseUI() {
likeButton.layer.borderWidth = 3.0 likeButton.layer.borderColor = UIColor(red: 0/255, green: 166/255, blue: 221/255, alpha: 1.0).cgColor likeButton.layer.cornerRadius = 20.0 likeButton.clipsToBounds = true } @IBAction func followActionPressed(_ sender: Any) { self.activateButton(bool: !isButtonOn)
}
func activateButton(bool: Bool) { isButtonOn = bool likeButton.backgroundColor = bool ? UIColor(red: 0/255, green: 166/255, blue: 221/255, alpha: 1.0) : .clear likeButton.setTitle(bool ? "unlike": "like", for: .normal) likeButton.setTitleColor(bool ? .white : UIColor(red: 0/255, green: 166/255, blue: 221/255, alpha: 1.0), for: .normal) }
}

Swift: How to validate Social Security Number (SSN)?
How can I validate SSN (Social security number) if it matches pattern
123456789
using Swift? 
How to get children on the first layer from a Firebase reference? (shallow query)
I have a Firebase Database structure that looks like this:
/users  abc001  name: "Harry Watson"  credentials:  email: "h.watson@yahoo.com"  abc002  name: "Jason Polakow"  credentials:  email: "j.polakow_1@gmail.com"  abc003  name: "Madeleine Février"  credentials:  email: "mad_fev@gmail.fr"  ...
I would like to get all children on the first layer, e.g.:
 abc001  abc002  abc003 ...
 I don't know how to do this. As far as I know, a
value
event would also trigger for every child of every child (second and third layer).  A
childAdded
event is also not the right choice, because I only want to receive the data once (I don't want to listen for data changes/child added, ...).  A singleevent of
childAdded
only triggers once and returns the first child (abc001
).
Could you help me out?
Thanks in advance.
 I don't know how to do this. As far as I know, a

Matlab and C++ yield different outcomes when optimizing Schwefel function by an algorithm similar to PSO
This question might be long and I really appreciate your patience. The core problem is I used matlab and c++ to implement an optimization algorithm but they provided me different results(matlab's better).
I am recently studying some evolutionary algorithms and interested in one variant of PSO(Particle Swarm Optimization), which is called Competitive Swarm Optimizer(born in 2015). This is the paper link http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=6819057.
The basic idea of this algorithm is to first generate some random particles in searching space and assign them random velocities. At each iteration, we randomly pair them and let every pair of particles compare their objective function values. Winners(with better objective values) keep status quo while losers update themselves by learning from winners(moving toward winners).
For example, suppose now I want to minimize a 500d Schwefel function(minimize the maximal absolute element) and I use 250 particles, set phi=0.1, searching space is 500d [100, 100]. Matlab could return me something around 35 while C++ got stuck at 85 to 90. I cannot figure out what's the problem.
Let me attach my matlab and c++ code here.
Sch = @(x)max(abs(x)) lb = 100 * ones(1, 500); ub = 100 * ones(1, 500); swarmsize = 250; phi = 0.1; maxiter = 10000; tic cso(Sch, lb, ub, swarmsize, phi, maxiter); toc function [minf, minx] = cso(obj_fun, lb, ub, swarmsize, phi, maxiter) assert(length(lb) == length(ub), 'Not equal length of bounds'); if all(ub  lb <= 0) > 0 error('Error. \n Upper bound must be greater than lower bound.') end vhigh = abs(ub  lb); vlow = vhigh; S = swarmsize; D = length(ub); x = rand(S, D); x = bsxfun(@plus, lb, bsxfun(@times, ublb, x)); % randomly initalize all particles v = zeros([S D]); % set initial velocities to 0 iter = 0; pairnum_1 = floor(S / 2); losers = 1:S; fx = arrayfun(@(K) obj_fun(x(K, :)), 1:S); randperm_index = randperm(S); while iter <= maxiter fx(losers) = arrayfun(@(K) obj_fun(x(K, :)), losers); swarm_center = mean(x); % calculate center all particles randperm_index = randperm(S); % randomly permuate all particle indexes rpairs = [randperm_index(1:pairnum_1); randperm_index(Spairnum_1+1:S)]'; % random pair cmask= (fx(rpairs(:, 1)) > fx(rpairs(:, 2)))'; losers = bsxfun(@times, cmask, rpairs(:, 1)) + bsxfun(@times, ~cmask, rpairs(:, 2)); % losers who with larger values winners = bsxfun(@times, ~cmask, rpairs(:, 1)) + bsxfun(@times, cmask, rpairs(:, 2)); % winners who with smaller values R1 = rand(pairnum_1, D); R2 = rand(pairnum_1, D); R3 = rand(pairnum_1, D); v(losers, :) = bsxfun(@times, R1, v(losers, :)) + bsxfun(@times, R2, x(winners, :)  x(losers, :)) + phi * bsxfun(@times, R3, bsxfun(@minus, swarm_center, x(losers, :))); x(losers, :) = x(losers, :) + v(losers, :); maskl = bsxfun(@lt, x(losers, :), lb); masku = bsxfun(@gt, x(losers, :), ub); mask = bsxfun(@lt, x(losers, :), lb)  bsxfun(@gt, x(losers, :), ub); x(losers, :) = bsxfun(@times, ~mask, x(losers, :)) + bsxfun(@times, lb, maskl) + bsxfun(@times, ub, masku); iter = iter + 1; fprintf('Iter: %d\n', iter); fprintf('Best fitness: %e\n', min(fx)); end fprintf('Best fitness: %e\n', min(fx)); [minf, min_index] = min(fx); minx = x(min_index, :); end
(I didn't write C++ function.)
#include <cstring> #include <iostream> #include <cmath> #include <algorithm> #include <ctime> #include <iomanip> #include <time.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #define rand_01 ((double) rand() / RAND_MAX) // generate 0~1 random numbers #define PI 3.14159265359 const int numofdims = 500; // problem dimension const int numofparticles = 250; // number of particles const int halfswarm = numofparticles / 2; const double phi = 0.1; const int maxiter = 10000; // iteration number double Sch(double X[], int d); // max(abs(x_i)) using namespace std; int main(){ clock_t t1,t2; t1=clock(); srand(time(0)); // random seed double** X = new double*[numofparticles]; // X for storing all particles for(int i=0; i<numofparticles; i++) X[i] = new double[numofdims]; double** V = new double*[numofparticles]; // V for storing velocities for(int i=0; i<numofparticles; i++) V[i] = new double[numofdims]; double Xmin[numofdims] = {0}; // lower bounds double Xmax[numofdims] = {0}; // upper bounds double* fitnesses = new double[numofparticles]; // objective function values for(int j=0; j<numofdims; j++) { Xmin[j] = 100; Xmax[j] = 100; } for(int i=0; i<numofparticles; i++) { for(int j=0; j<numofdims; j++) { X[i][j] = Xmin[j] + rand_01 * (Xmax[j]  Xmin[j]); // initialize X V[i][j] = 0; // initialize V } } for(int i=0; i<numofparticles; i++) { fitnesses[i] = Sch(X[i], numofdims); // } double minfit = fitnesses[0]; // temporary minimal value int minidx = 0; // temporary index of minimal value int* idxofparticles = new int[numofparticles]; for(int i=0; i<numofparticles; i++) idxofparticles[i] = i; double* Xmean = new double[numofdims]; int* losers = new int[halfswarm]; // for saving losers indexes for(int iter=0; iter<maxiter; iter++) { random_shuffle(idxofparticles, idxofparticles+numofparticles); for(int j=0; j<numofdims; j++) { for(int i=0; i<numofparticles; i++) { Xmean[j] += X[i][j]; } Xmean[j] = (double) Xmean[j] / numofparticles; // calculate swarm center } for(int i = 0; i < halfswarm; i++) { // indexes are now random // compare 1st to (halfswarm+1)th, 2nd to (halfswarm+2)th, ... if(fitnesses[idxofparticles[i]] < fitnesses[idxofparticles[i+halfswarm]]) { losers[i] = idxofparticles[i+halfswarm]; for(int j = 0; j < numofdims; j++) { V[idxofparticles[i+halfswarm]][j] = rand_01 * V[idxofparticles[i+halfswarm]][j] + rand_01 * (X[idxofparticles[i]][j]  X[idxofparticles[i+halfswarm]][j]) + rand_01 * phi * (Xmean[j]  X[idxofparticles[i+halfswarm]][j]); X[idxofparticles[i+halfswarm]][j] = min(max((X[idxofparticles[i+halfswarm]][j] + V[idxofparticles[i+halfswarm]][j]), Xmin[j]), Xmax[j]); } } else { losers[i] = idxofparticles[i]; for(int j = 0; j < numofdims; j++) { V[idxofparticles[i]][j] = rand_01 * V[idxofparticles[i]][j] + rand_01 * (X[idxofparticles[i+halfswarm]][j]  X[idxofparticles[i]][j]) + rand_01 * phi * (Xmean[j]  X[idxofparticles[i]][j]); X[idxofparticles[i]][j] = min(max((X[idxofparticles[i]][j] + V[idxofparticles[i]][j]), Xmin[j]), Xmax[j]); } } } // recalculate particles' values for(int i=0; i<numofparticles; i++) { fitnesses[i] = Sch(X[i], numofdims); if(fitnesses[i] < minfit) { minfit = fitnesses[i]; // update minimum minidx = i; // update index } } if(iter % 1000 == 0) { cout << scientific << endl; cout << minfit << endl; } } cout << scientific << endl; cout << minfit << endl; t2=clock(); delete [] X; delete [] V; delete [] fitnesses; delete [] idxofparticles; delete [] Xmean; delete [] losers; float diff ((float)t2(float)t1); float seconds = diff / CLOCKS_PER_SEC; cout << "runtime: " << seconds << "s" <<endl; return 0; } double Sch(double X[], int d) { double result=abs(X[0]); for(int j=0; j<d; j++) { if(abs(X[j]) > result) result = abs(X[j]); } return result; }
So, finally, why can't my c++ code reproduce matlab's outcome? Thank you very much.

How to assign value type byte array in java to a button
I’m trying to develop a system that will ask the user to enter a text in JTextBox (plainText) then it will click on key JButton (key_128) then it will encrypt the user text and show the output in another JTextButton. But when I try to assign the value to the Key it gives error where. BinaryCodec() saying cannot find symbol. The code is this error in line 2
byte[] plain = plaintext.getText().getBytes(); byte[] K = new BinaryCodec().toByteArray(“0011000100110011100000001010”); byte[] encrypted = encrypt(plain, K); String a = new String(encrypted); encryptedtext.setText(a);

How to divide an array into two groups having most appropriate sum
You are given an array of integers. You can divide this array into two distinct groups and that groups must have most approapiate sum( the difference beetween the sum of that two groups needs to be as low as possible in modul). The output need to contain the sum of each of two groups. For example: if n = 5 and the array is {2,8,10,1,3} the output needs to be 12 and 12 (12 = 2 + 10 and 12 = 8 + 1 + 3). Is there any faster solution than backtracking?

I am trying to calculate sine of an angle without using the Math.sin() in java
I am trying to calculate sine of an angle without using the Math.sin(). I got stuck in it's equation as I keep getting the wrong results
note I have a method that changes the angle from degrees to radians
public static double sin(double x, int precision) { //this method is simply the sine function double answer = 1, power = 1; int n = 2,factorial = 1; while (n<=precision) { power = (power * x * x *1) +1 ; factorial = (factorial * (n +1))* (n1); answer = answer + ((power/factorial )); n = n + 2; } return answer; }

Scale/Rotate a triangle into an equilateral in one loop
I have a set of triangles that can have any sort of shape. They made of pixels from an image.
I would like to find a simple and efficient way to transpose them into an equilateral triangle of size N.
I can't really use a library as I want to do this in golang and no such library exists + I don't want to use c bindings.
I tried to play around with barycenters+rotation+scale and such but I am really not the best math person and therefore achieved mediocre results...
 Show following equation use LaTex synax