Concatenate two images in the channel dimension?
I have to concatenate two images in the channel dimension in either MATLAB or Python.
Let's say we take two grayscale input images, where each has for example the dimension [1, 1, 28, 28]
(i.e. 1 image, 1 channel, 28x28 resolution). How can we concatenate them to be one image of size [1, 2, 28, 28]
?
3 answers

I'm not sure what you want to do with your fist dimension but this works for your example:
img1 = randi(255,1,1,28,28); % first image img2 = randi(255,1,1,28,28); % second image img1(1,end+1,:,:) = img2; % stack second image on top of first image size(img1) % [ 1 2 28 28]

In MATLAB you would usually use the
cat
command for this:bigMat = cat(dimNo, matA, matB); % dimNo can be 1, 2, ...
But in the case of concatenating along the 2^{nd} dimension, you can also simply use
[... ; ...]
:bigMat = [matA; matB];
(which is equivalent to the
vertcat
function).If you know in advance how many matrices you'd like to concatenate (i.e. the final size of the result), you should preallocate your matrix using e.g.
bigMat = zeros(1, N, 28, 28)
, then put each image in its correct position similarly to the previous answer img1(:,n,:,:) = img2; % where n is 1..N, and not anything like end+1
We don't want to use
end+1
as this incurs performance losses related to constant reallocation of larger and larger arrays and copying all contents of the array each time. 
Python: Use numpy for this operation:
import numpy as np img1, img2 = np.random.rand(1,1,28,28), np.random.rand(1,1,28,28) img = np.concatenate([img1, img2], axis=1)
The argument
axis=1
defines the axis along which the operation is executed.
See also questions close to this topic

Worikng on assignment in python for password cracking with md5 hashes
Problem 3 * is the issue I'm having not sure how to add the extra digit to eachword to find the right combination.
The variables hash4 and hash5 contain two mystery hashes. I'll give you a hint: they are constructed by taking a word from the rockyou list and appending a single digit. For example, morgan3 or shadow7. This is a common thing people to do choose "good" passwords. But they are easy to crack because it's such a predictable pattern.
Write a function to solve this problem for you. Paste your solutions into the word4 and word5 variables, respectively. You can name the function whatever you want; the function itself won't be checked.
from hashlib import md5 from random import sample
The first 300 entries from the rockyou.txt file. This is a single string, which will be split into an array further down.
rockyou_str = """123456 12345 123456789 password iloveyou princess 1234567 rockyou 12345678 abc123 nicole daniel babygirl monkey lovely Jessica 654321 michael ashley qwerty 111111 iloveu 000000 michelle tigger sunshine chocolate password1 soccer anthony friends butterfly purple angel jordan liverpool justin loveme 123123 football secret andrea carlos jennifer joshua bubbles 1234567890 superman hannah Amanda loveyou pretty basketball andrew angels tweety flower playboy hello elizabeth hottie tinkerbell charlie samantha barbie chelsea lovers teamo jasmine brandon 666666 shadow melissa eminem matthew Robert danielle forever family jonathan 987654321 computer whatever dragon vanessa cookie naruto summer sweety spongebob joseph junior softball taylor yellow daniela lauren mickey princesa alexandra alexis jesus estrella miguel william thomas beautiful mylove angela poohbear patrick iloveme sakura adrian alexander destiny christian 121212 sayang america dancer monica richard 112233 princess1 555555 diamond carolina steven rangers louise orange 789456 999999 shorty 11111 nathan snoopy gabriel hunter cherry killer sandra alejandro buster george brittany alejandra patricia rachel tequiero 7777777 cheese 159753 arsenal dolphin antonio heather david ginger stephanie peanut blink182 sweetie 222222 beauty 987654 victoria honey 00000 Fernando pokemon maggie corazon chicken pepper cristina rainbow kisses manuel myspace rebelde angel1 ricardo babygurl heaven 55555 baseball martin greenday november alyssa madison mother 123321 123abc mahalkita batman september december morgan mariposa maria gabriela iloveyou2 bailey jeremy pamela kimberly gemini shannon pictures sophie jessie hellokitty claudia babygirl1 angelica austin mahalko victor horses tiffany mariana eduardo andres courtney kissme harley Ronaldo iloveyou1 precious october inuyasha peaches veronica chris 888888 adriana cutie james banana prince friend jesus1 crystal celtic zxcvbnm edward oliver diana samsung freedom angelo kenneth master scooby carmen 456789 sebastian rebecca jackie spiderman christopher karina johnny hotmail 0123456789 school barcelona august orlando Samuel cameron slipknot cutiepie monkey1 50cent bonita kevin maganda Babyboy casper brenda adidas kitten karen mustang isabel natalie cuteako javier 789456123 123654 sarah bowwow portugal laura 777777 marvin"""
Split and convert rockyou to array of byte strings.
This is the array you should use for cracking the hashes.
rockyou = [ bytes(i, 'utf8') for i in rockyou_str.split() ]
Hashes of a few of the passwords. Can you figure out which ones they are? hash0 = 'df53ca268240ca76670c8566ee54568a'
hash1 = 'fe546279a62683de8ca334b673420696' hash2 = '5ebe2294ecd0e0f08eab7690d2a6ee69' hash3 = 'c8837b23ff8aaa8a2dde915473ce0991'
Problem 1: crack a single hash
`def crack_one(target):` for word in rockyou: if md5(word).hexdigest() == target: return word
Paste your solutions here word0 = b'computer'
word1 = b'samsung' word2 = b'secret' word3 = b'123321'
Select 10 random passwords and hash them into a list. There are two sets of random hashes here. rand_hashes1 = [ md5(p).hexdigest() for p in sample(rockyou, 10) ] rand_hashes2 = [ md5(p).hexdigest() for p in sample(rockyou, 10) ]
Problem 2: crack the lists of random hashes
`def crack_list(target):` cracked = [crack_one(target) for target in target] return cracked
Problem 3: what are these passwords?
hash4 = '610c23407eb63d963c73cdda8703b506' hash5 = '82f1742b8fef8c2379698be495c29c3d'
You may need this to help solve the problem digits = [b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9']
`def crack_password(target):` for word in rockyou: for digit in digits: words = word + digit crunch = [crack_one(target) for target in words] if md5(words).hexdigest() == target: return words
Paste your solutions here these are the correct answers
word4 = b'purple4' word5 = b'softball8'
Problem 3 * is the issue I'm having not sure how to add the extra digit to eachword to find the right combination.
The variables hash4 and hash5 contain two mystery hashes. I'll give you a hint: they are constructed by taking a word from the rockyou list and appending a single digit. For example, morgan3 or shadow7. This is a common thing people to do choose "good" passwords. But they are easy to crack because it's such a predictable pattern.
Write a function to solve this problem for you. Paste your solutions into the word4 and word5 variables, respectively. You can name the function whatever you want; the function itself won't be checked. Any help is appreciated. Thank you.

Update DynamoDB for a counter with dual key values
I am trying to add a counter which will update itself for a specific type of keys in DynamoDB. My question is similar to or based on the following question: DynamoDB update a counter (or insert a key) However, my code fails and gives out errors. I am going wrong with the syntax.
My Code snippet based on the linked question is:
dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('Lambda_Call_Table') dynamodb.update_item( TableName=table, # I need to update for 'Invoke' and 'InvokeExpression' values. Key={'eventName': {'S': 'Invoke'}}, UpdateExpression="ADD #counter :increment", ExpressionAttributeNames={'#counter': 'counter'}, ExpressionAttributeValues={':increment': {'N': '1'}} )
I know I can use 'begins_with' condition for keys. 'begins_with invoke or invokeexecution'. I need to figure out the correct syntax in this case. Any help on that will be appreciated.

Python: passing argument to generator object created by generator expression?
so i have this gen object:
yld123cu = (x * u for x in range(1, 4))
which i can only use like so:
u = 2 # some user given value for i in yld123cu: print(i, end=' ')
is there any syntax to avoid the extra line with u=.. assignment? any way to put the u value inside the for statement?
i'd want something similar to below but using gen expression, not function:
def yld123u(u): for i in range(1, 4): yield i * u for i in yld123u(2): print(i, end=' ')

How to add a border to all the images in a folder in Python?
What code would you have to enter in Python to make it so that all the images in a folder have a border around them?
Edit: This is what I've tried:
def add_border(input_image, output_image, border, color=0): img = Image.open(input_image) for item in os.listdir(path): if isinstance(border, int) or isinstance(border, tuple): bimg = ImageOps.expand(img, border=border, fill=color) add_border(in_img, output_image = new_image, border=100, color='white') else: raise RuntimeError('Border is not an integer or tuple!') bimg.save(output_image) new_image = add_border(image_list[n],.30) new_image_filename = os.path.join(new_directory, filename + '.png') new_image.save(new_image_filename)

How to set a dynamic width calculator/conversion of pixels for a photo
How to set a dynamic width calculator for a photo that changes as the image is rotated? Does anyone have any good advice?
class Image extends React.Component { constructor(props){ super(props); this.state = { imageField: '', rotation: 0, width: 0, height: 0 } onImgLoad = ({ target: img }) => { this.setState({ width: img.width, height: img.height, }); }; componentDidMount () { let canvas = document.getElementById('canvas'); console.log(canvas.width); console.log(this.myInput.current.offsetWidth); } rotate = (e) => { let newRotation = this.state.rotation + 60; if(newRotation >= 360){ newRotation = 360; // newRotation = 0; } this.setState({ rotation: newRotation, }) } rotateleft = (e) => { let newRotation = this.state.rotation  60; if(newRotation <= 360){ newRotation = 360; } this.setState({ rotation: newRotation, }) } //image Upload elements fileChangedHandler = (event) => { event.preventDefault(); this.setState({imageField: URL.createObjectURL(event.target.files[0]) }) } render(){ const { rotation, width, height } = this.state; console.log(width); const imgStyle = { transform: `rotate(${this.props.settings[6].value}deg) rotate(${rotation}deg)`, filter: ` contrast(${this.props.settings[0].value}) huerotate(${this.props.settings[1].value}) brightness(${this.props.settings[2].value}) saturate(${this.props.settings[3].value}) sepia(${this.props.settings[4].value}) invert(${this.props.settings[5].value})`, } const imgStyle2 = { maxWidth: '15%', maxHeight: '90%', padding: '1em', lineHeight: '1.5em', color: 'white' } const imgStyle3 = { maxWidth: '85%', maxHeight: '90%' } const imageContainerUpload = { width: '800px', height: '800px', display: 'flex', alignItems: 'center', justifyContent: 'center' } return( <div className="imageContainer"> <form style={imageContainerUpload} action="/upload" method="POST" encType="multipart/formdata" onSubmit={this.handleSumbit}> <div style={imgStyle3}> <input onClick={this.rotateleft} type="button" value="Lewo" /> <canvas id="canvas" > <img id="ing" src={this.state.imageField} width={width} height={height} onLoad={this.onImgLoad} ref={this.myInput} className="guitar" style={imgStyle}/> </canvas> <input onClick={this.rotate} type="button" value="Prawo" /> </div> <div style={imgStyle2}> <input type="file" id="imageField" onChange={this.fileChangedHandler} /> <p>Szerokość: {width} </p> <p>Wysokość: {height} </p> <ImagePixels value={this.state.pixels} /> {console.log(this.state.pixels)} </div> </form> </div> ) } } ImageEditor.defaultProps = { data : data }
I have a problem with making conversion of pixels of image width. The width does not recalculate with the rotation of the image only assigns me the initial width so far and I want it to also download the current one at the turnover but I have no idea how to do it?

Python imshow becomes smaller and smaller when I zoom in?
I have a very simple use case here. I have 2D data that I image with matplotlib's imshow. This works fine, however when I come to zoom in, the "image" becomes smaller and smaller... is there a way to stop it from doing that?
image = np.random.randn(100,100) plt.imshow(image)
This shows the image, but when I manually start to zoom in, the image becomes more and more narrow. How do I fix this? Thanks

Matlab PDE solver pdpde  how to set boundary condition correctly?
I have a PDE problem like this:
Du/Dt=Du/Dx
Initial condition:
u(x,0)=x+1
Boundary conditions:
u(0,t)=t+1
Du/Dt(10,t)=1
Following the examples pdex1.m I wrote a script like this:
%  m = 0; x = linspace(0,10,10); t = linspace(0,10,10); sol = pdepe(m,@pdex1pde,@pdex1ic,@pdex1bc,x,t); %  function [c,f,s] = pdex1pde(x,t,u,DuDx) c = 1; f = u; s = 0; %  function u0 = pdex1ic(x) u0 = x+1; %  function [pl,ql,pr,qr] = pdex1bc(xl,ul,xr,ur,t) pl = t1+ul; ql = 0; pr = 1+DurDx; qr = 0; %
This script does not work, and I believe the problem is due to "pr = 1+DurDx;"
In this case, how do I code the boundary condition correctly?
Thanks!

Calculate integral in Matlab
I am given the following data:
and I am asked to calculate the integral of Cp/T dT from 113.7 to 264.4.
I am unsure of how I should solve this. If I want to use the integral command, I need a function, but I don't know how my function should be in that case.
I have tried:
function func = Cp./T T = [...] Cp=[...] end
but that didn't work.

VBA's "Like" function in MATLAB
How would i turn something such as
str1 Like "?ab?"
into MATLAB?

Manipulate matrix based on two threshold vectors in R
I don't know exactly how I should frame this problem, nor can I think of any example of how to solve it. I came up with a solution but I'm wondering if there's an easier or more efficient way of dealing with it.
I'm working with a matrix of distances between individuals and events, and I want to transform the matrix based on characteristics of the events and the individuals. In this case, I want to know if an individual was exposed to an event within certain distance based on other criteria.
Let's say we have two vectors, one of 4 individuals and another of 3 events. We obtain a matrix of the distances in km between individuals and events:
> dist_mat = matrix(runif(12, 1, 100), ncol = 3) > dist_mat [,1] [,2] [,3] [1,] 21.318423 89.79522 75.29824 [2,] 36.812542 18.28413 92.90719 [3,] 45.012960 89.11778 38.55608 [4,] 8.470336 46.17020 26.67135
On top of that, I know when the individuals were born and when the events took place, which is stored in two vectors:
> event_year = c(2003, 2005, 2009) > indiv_born = c(2004, 2004, 2008, 2008)
My goal is to know if an individual was exposed to an event within that took place after she was born and within, say, 30km. My solution at this point is to expand the year vectors into matrices and work it out from there, and then use
rowSums
to obtain an indicator of whether an individual was exposed to such event:> event_year_m = matrix(rep(event_year, each = nrow(x1)), ncol = ncol(x1)) > indiv_born_m = matrix(rep(indiv_year, each = ncol(x1)), byrow = TRUE, ncol = ncol(x1)) > event_year_m [,1] [,2] [,3] [1,] 2003 2005 2009 [2,] 2003 2005 2009 [3,] 2003 2005 2009 [4,] 2003 2005 2009 > indiv_year_m [,1] [,2] [,3] [1,] 2004 2004 2004 [2,] 2004 2004 2004 [3,] 2008 2008 2008 [4,] 2008 2008 2008 > dist_mat[event_year_m < indiv_year_m] = NA > dist_mat[dist_mat < 30] = 1 > dist_mat[dist_mat >= 30] = 0 > dist_mat [,1] [,2] [,3] [1,] NA 0 0 [2,] NA 1 0 [3,] NA NA 0 [4,] NA NA 1 > indiv_exposure = rowSums(dist_mat, na.rm = TRUE) [1] 0 1 0 1
Does this make sense? Isn't there a simpler way to do this? Having only one vector would be simpler, but can't figure it out in the case of row and columnspecific thresholds.

Adding >2 matrices with cusparse
I need to add several (up to 10) sparse matrices together. The matrices have been formatted with cuSPARSE (for later cuSPARSE operations) and I assume there is a way to do this using that library. I'm reasonably familiar with CUDA, but this is my first time using cuSPARSE. I did find that cuSPARSE contains the function
cusparse<t>csrgeam()
which performsC = α∗A + β∗B
to add two sparse matrices (see Ch. 9 of the guide). I am now trying to determine the best approach to use this function to add >2 matrices together.My initial thought was to loop over the matrices and do the following metacode, where
M_i
are each of the sparse matrices and the addition is done withcusparse<t>csrgeam()
.for (size_t i=0; i<10; ++i){ C = C + M_i; }
Does
cusparse<t>csrgeam()
support having either of the matricesA
orB
be the same asC
? I did not see a comment about it in the function documentation, but maybe this is obvious for those more familiar with sparsematrices operations.I otherwise envision having to make a few temporary matrices for each subaddition of two matrices to build up the final sum a la this metacode (if, for example, there were four matrices to add)
tmp0 = M_0 + M_1; tmp1 = M_2 + M_3; C = tmp0 + tmp1;
This would require allocating the space for each temporary matrix along the way, which would reduce efficiency.
Are there other suggestions on how to add >2 sparse matrices with cuSPARSE? Thanks.

What is the proper way to assign to an array inside a C++ class?
I have this C++ class Matrix (see code snipet below).
In my randomize method, I set all the values of matr(matr is a 2x2 matrix).
When i call print_matrix it is duplicating elements (1,0) and (1,1) and printing them both twice, as well a not printing (0,0), or (0,1).
What am I doing incorrectly?
See the output below.
class Matrix { public: int rows; int cols; double rnd; double* matr; Matrix(int a, int b) { printf(" vals %d %d \n", a, b); rows = a; cols = b; matr = new double[a, b]; //this>print_matrix(); //clear_matrix(); //this>print_matrix(); //this>randomize(); //this>print_matrix(); } double &at(int pos1, int pos2) { return matr[pos1, pos2]; }; void setPos(int pos1, int pos2, double value) { matr[pos1, pos2] = value; }; void randomize() { for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { rnd = double(rand()) / double((RAND_MAX)+1.0); printf("Rand : %d, C: %d, Val: %f \n",r,c, rnd); this>setPos(r, c, rnd); //matr[r, c] = rnd; printf("New value R: %d C: %d Val: %f \n", r, c, matr[r,c]); //rnd = 0; } } }; void subtract_Scalar(double val) { double curr_Val = 0; double result = 0; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { curr_Val = this>at(r, c); result = curr_Val  val; this>setPos(r, c, 0); this>setPos(r, c, (float)result); //this>setPos(r, c, 5); //printf("SS CV : %f, Re: %f \n", curr_Val, result); curr_Val = 0; result = 0; } } }; void print_matrix() { for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { printf("PM R : %d, C: %d Val: %f \n", r, c, matr[r,c]); //printf("%f", this>at(r, c)); } //printf("\n"); } } void clear_matrix() { for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { this>setPos(r, c, 0.0); } } } };

extract words in between two commas in R
I have the following string
word < 'Fu Tien Mansion, Taikoo Shing, Hong Kong'
and I want to extract the word in between the two commas and concatenate it with the first word, what regex to use?
Desired output:
'Taikoo Shing Fu Tien Mansion'

Concatenation Unexpected Identifier error PHP
I'm trying to do some concatenation in Magento 1.x and am getting an "Unexpected Identifier" error, the following code is the snippet, and each of the PHP echos are formatted as:
 $product>getPrice()  Integer  e.g:
45.00
 $product>getName()  String  e.g:
Product Name Here
var testVar = "12345::'" + echo $product>getPrice() + "'::'" + echo $product>Name() + "'::ProductID";
I can't figure out why it's not working, can anyone help please?
 $product>getPrice()  Integer  e.g:

Rowwise concatenate a list of jagged arrays in c#
I'd like help* in creating a method or (linq) expression that can rowwise concatenate lists (of varying lengths) of jagged arrays as the one below:
List<double[][]> orgArrayList = new List<double[][]>(); double[][] one = { new [] {5d, 6}, new [] {7d, 9}}; double [][] two = { new [] {5d, 6}, new [] {7d, 9}}; double [][] three= { new [] {5d, 6}, new [] {7d, 9}}; orgArrayList.AddRange(new[] {one, two, three});
So that the resulting array will be equal to this one:
double[][] expected = { new [] {5d, 6, 5, 6, 5, 6}, new [] {7d, 9, 7, 9, 7, 9}};
The number of jagged arrays in my input list(s) will be >=1. All arrays within a single list will be jagged with 2 dimensions, but none of the 2 dimensions will have a fixed/known length (size).
*'help' being a euphemism for someone telling me how to do it