Swift – if string is nil. don’t add it to the array

Swift – if string is nil. don’t add it to the array

I have an Array of Image links –

Array

Image

let alamofireSource = [AlamofireSource(urlString: Img1!)!, AlamofireSource(urlString: Img2!)!,
AlamofireSource(urlString: Img3!)!, AlamofireSource(urlString: Img4!)!]
slideshow.setImageInputs(alamofireSource)

some posts have only one image or two or three, and so on. so, sometimes image 2 (for example) is nil, In that case, I don’t want it to be added to the array, is that possible?

3 Answers
3

You can try ( Swift 4 )

let arr = [img1,img2].compactMap{$0}.map{AlamofireSource(urlString:$0)!}

or

let arr = alamofireSource.compactMap{$0}

for Swift 3

let arr = alamofireSource.flatMap{$0}

Thanks a trillion! It fixed the problem 🙂
– Sophie Bernard
Jul 3 at 10:22

This is Swift 4. You may want to add flatMap for Swift 3 or prior
– smnk
Jul 3 at 12:08

@SophieBernard Note that the approach in this answer (forcibly unwrapping the result of the initializer) may lead to a run-time exception, as the AlamofireSource(urlString:) initializer is a failable initializer. I’ve added an answer below showing one approach to safely unwrap the result of the possibly failing initialization, taking also into account the fact that the url strings themselves (Img1, … Img4 in your example) are optionals, and should also be safely unwrapped.
– dfri
Jul 7 at 23:10

AlamofireSource(urlString:)

Img1

Img4

so, sometimes image 2 (for example) is nil, In that case, I don’t want
it to be added to the array, is that possible?

Yes it is. Although I would go with Sh_Khan’s suggestion to use the compactMap method to achieve it, but it would be useless for your current case:

compactMap

Based on your code snippet, I’d assume that alamofireSource of type [AlamofireSource], but not [AlamofireSource?] and that’s because you are forcibly unwrap its elements (by adding ! to each of its elements). So far alamofireSource doesn’t contain nils (actually it could be more danger than just a declaration, your app might crash!)

alamofireSource

[AlamofireSource]

[AlamofireSource?]

!

alamofireSource

So first of all, I would recommend to remove the ! from alamofireSource:

!

alamofireSource

let alamofireSource = [AlamofireSource(urlString: Img1!),
AlamofireSource(urlString: Img2!),
AlamofireSource(urlString: Img3!),
AlamofireSource(urlString: Img4!)]

which means let it be as [AlamofireSource?], therefore you would gain the benefit of using compactMap(_:):

[AlamofireSource?]

compactMap(_:)

Returns an array containing the non-nil results of calling the given
transformation with each element of this sequence.

As:

let alamofireSourceWihoutNils = alamofireSource.compactMap { $0 }

Assuming you put your Optional url strings into an array, say urlStrings (of type [String?]), you can construct alamofireSource according to (Swift 4):

Optional

urlStrings

[String?]

alamofireSource

let alamofireSource = urlStrings.compactMap { $0.map(AlamofireSource.init) }

Which make use of the map(_:) operator of Optional and compactMap(_:) to unwrap the two-level optionality.

map(_:)

Optional

compactMap(_:)

Details

Your example contains two levels of optionality:

ImgX

String?

img1

img4

CapitalFirstLetter

init?(urlString: String, placeholder: UIImage? = nil)

AlamofireSource

First of all, lets gather the optional image links (imgX) into an array

imgX

let urlStrings = [url1, url2, url3, url4] // [String?]

You can combine the map(_:) operator of Optional with compactMap(_:) to safely unwrap and make use of the .some entires of urlStrings, thereafter collect the successful invocations of the failable initializer of AlamofireSource:

map(_:)

Optional

compactMap(_:)

.some

urlStrings

AlamofireSource

let alamofireSource = urlStrings.compactMap { $0.map(AlamofireSource.init) }

// or, use a named closure argument
let alamofireSource = urlStrings.compactMap { str in str.map(AlamofireSource.init) }

If using Swift 3, replace the compactMap(_:) invocation above with flatMap(_:):

compactMap(_:)

flatMap(_:)

let alamofireSource = urlStrings.flatMap { $0.map(AlamofireSource.init) }

// or, use a named closure argument
let alamofireSource = urlStrings.flatMap { str in str.map(AlamofireSource.init) }

By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Specifically assign contrasts in R model.matrix

Specifically assign contrasts in R model.matrix

If I have a variable (condition) of 2 levels and want to create a model.matrix R automatically assigns conditionB as the term in the design matrix.

condition <- as.factor( c("A","A","A","B","B","B"))
df <- data.frame(condition)
design <- model.matrix( ~ condition)

> df
condition
1 A
2 A
3 A
4 B
5 B
6 B

> design
(Intercept) conditionB
1 1 0
2 1 0
3 1 0
4 1 1
5 1 1
6 1 1
attr(,"assign")
[1] 0 1
attr(,"contrasts")
attr(,"contrasts")$condition
[1] "contr.treatment"

Question: I would like to have my results relative to conditionA. How can I specify this in model.matrix() ?

(A workaround would be to inverse the resulting FCs)

What do you mean by relative to condition A?
– Onyambu
Jul 3 at 9:35

If you run the code, you will see that the resulting design matrix has two terms: (Intercept) conditionB. I would like to have conditionA instead of B.
– Obama
Jul 3 at 9:38

Possible duplicate of How to force R to use a specified factor level as reference in a regression?
– LAP
Jul 3 at 9:43

My question is specific to the model.matrix() function, cant see this in the mentioned post.
– Obama
Jul 3 at 9:54

1 Answer
1

You can use the C function to determine the base that you want to be taken into consideration:

C

Taking A as the base:

model.matrix(~C(condition,base=1))
(Intercept) C(condition, base = 1)2
1 1 0
2 1 0
3 1 0
4 1 1
5 1 1
6 1 1
attr(,"assign")
[1] 0 1
attr(,"contrasts")
attr(,"contrasts")$`C(condition, base = 1)`
2
A 0
B 1

Taking B as the base:

model.matrix(~C(condition,base=2))
(Intercept) C(condition, base = 2)1
1 1 1
2 1 1
3 1 1
4 1 0
5 1 0
6 1 0
attr(,"assign")
[1] 0 1
attr(,"contrasts")
attr(,"contrasts")$`C(condition, base = 2)`
1
A 1
B 0

I think just re-leveling does not work. It indeed changes the term in the designmatrix to conditionA, but If you compare with the dataframe (see main post) the “1″ is still “B". Just relevelling would potentially compare the wrong cases.
– Obama
Jul 3 at 10:13

By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

How to count the number of combination of rows with a drop down list selection in datatables

How to count the number of combination of rows with a drop down list selection in datatables

I would like to count the number of rows in a table after making a selection in a drop down list (Name). but the only problem here is i would like to count number of rows basing on an other attribute in my table (position).
for example:
if i make a selection in the Name: Tiger Nixon
i would like to get
total rows: 3
Position 1 : 1 rows Position 2 : 1 rows Position 3 : 1 rows

Here the code I use to make a drop down list selection with attribute (Name) and it worked perfectly.

$(document).ready(function () {
$('#example').DataTable({
initComplete: function () {
this.api().columns(0).every(function () {
var column = this;
var select = $('<select class="Search"><option value=""></option></select>')
.appendTo($(column.header()))
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});

$('.Search').change(function () {
if ($("#example > tbody > tr > td").length == 1) {
$('#Count').empty();

$('#Count').append('Count: 0' );;
} else {
$('#Count').empty();
$('#Count').append('Count: ' + $("#example > tbody > tr").length);
}
});
});

this pict for counting number of rows using just selection on Name

Possible duplicate of How to get filtered row count
– Peter B
Jul 3 at 9:50

Yep, it’s a duplicate of that thread @PeterB mentioned above – just use $('#table_id').DataTable().page.info().recordsDisplay
– colin0117
Jul 4 at 9:44

$('#table_id').DataTable().page.info().recordsDisplay

thanks for ur ansers guys. i found a half solution. could you please see how can solve this. i edited the question a litte bit thanks.
– Mohammed Ajeddig
Jul 4 at 10:48

@colin0117 is it possible to $(‘#table_id’).DataTable().page.info().recordsDisplay to count number of rows with a specific value? thanks
– Mohammed Ajeddig
Jul 5 at 10:25

No, page.info() returns information about the current dataset. You could use filter() to determine that – see datatables.net/reference/api/filter()
– colin0117
Jul 5 at 14:25

By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

How to mock and test RxJava/RxAndroid with Mockk?

How to mock and test RxJava/RxAndroid with Mockk?

I want to mock and test my Presenter with the Observable, but I don’t know how to do that, the main part of the code as below:

Presenter

Observable

//in my presenter:
override fun loadData(){
this.disposable?.dispose()
this.disposable =
Observable.create<List<Note>> {emitter->
this.notesRepository.getNotes {notes->
emitter.onNext(notes)
}
}
.doOnSubscribe {
this.view.showProgress()
}
.subscribe {
this.view.hideProgress()
this.view.displayNotes(it)
}
}

//in test:
@Test
fun load_notes_from_repository_and_display(){
val loadCallback = slot<(List<Note>)->Unit>();
every {
notesRepository.getNotes(capture(loadCallback))
} answers {
//Observable.just(FAKE_DATA)
loadCallback.invoke(FAKE_DATA)
}
notesListPresenter.loadData()
verifySequence {
notesListView.showProgress()
notesListView.hideProgress()
notesListView.displayNotes(FAKE_DATA)
}
}

I got the error:
Verification failed: call 2 of 3: IView(#2).hideProgress()) was not called.

Verification failed: call 2 of 3: IView(#2).hideProgress()) was not called.

So, how to test the Rx things with Mockk in Android unit test? Thanks in advance!

Not sure I understand. If it is a bug, then just please submit github issue here: github.com/mockk/mockk/issues/new otherwise lets just wait some people with RxJava experience appear.
– oleksiyp
Jun 25 at 17:06

I fixed it with spky instead of mockk, thanks!
– SpkingR
Jul 3 at 9:25

spky

mockk

1 Answer
1

Add the RxImmediateSchedulerRule from https://github.com/elye/demo_rxjava_manage_state, then Use spyk instead of mockk, and it works!

RxImmediateSchedulerRule

spyk

mockk

companion object
{
@ClassRule @JvmField
val schedulers = RxImmediateSchedulerRule()
}

@Test
fun load_notes_from_repository_and_display()
{
val loadCallback = slot<(List<Note>)->Unit>();
val notesRepo = spyk<INotesRepository>()
val notesView = spyk<INotesListContract.IView>()
every {
notesRepo.getNotes(capture(loadCallback))
} answers {
loadCallback.invoke(FAKE_DATA)
}

val noteList = NotesListPresenter(notesRepo, notesView)
noteList.loadData()

verifySequence {
notesView.showProgress()
notesView.hideProgress()
notesView.displayNotes(FAKE_DATA)
}
}

By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Close dropdown menu after click outside of navbar using only JavaScript?

Close dropdown menu after click outside of navbar using only JavaScript?

I want to make a drop-down menu which one is very simple and when after click outside of nav its automatically hide. note I already make drop-down menu but… I don’t understand how to close it. here is my HTML and javascript code.

<section class="dropdownone">

Dropdown One


  • Click Dropdown

    • home
    • about
    • profile
  • </section>

    Possible duplicate of How do I detect a click outside an element?
    – Lars-Olof Kreim
    Jul 3 at 7:58

    write an event that checks if the select dropdown is out of focus, ie, it is blurred, you need to write a blur event, when that event is fired, hide the dropdown menu.
    – Code_Ninja
    Jul 3 at 8:14

    2 Answers
    2

    Using JavaScript :

    <!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    .dropbtn {
    background-color: #3498DB;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
    }

    .dropbtn:hover, .dropbtn:focus {
    background-color: #2980B9;
    }

    .dropdown {
    position: relative;
    display: inline-block;
    }

    .dropdown-content {
    display: none;
    position: absolute;
    background-color: #f1f1f1;
    min-width: 160px;
    overflow: auto;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    }

    .dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    }

    .dropdown a:hover {background-color: #ddd;}

    .show {display: block;}
    </style>
    </head>
    <body>

    <h2>Clickable Dropdown</h2>
    <p>Click on the button to open the dropdown menu.</p>

    Convert image to string without losing data in c++

    Convert image to string without losing data in c++

    I am sending data from my C++ client to C# WCF service where it accepts JSON data.

    We need to send an image to WCF service by converting it to a JSON string, but while converting image (jpg/jpeg) it has some null characters inside a string () so the string is getting terminated when converting std::string to char* and I am able to send only part of the string to service. Is there way that I can convert the image to string (const char *) without having null characters in it so that I can send all the image data (as char*) without loosing any data?

    std::string

    char*

    const char *

    char*

    The available function from C++ client is:

    httpClient.POST("ServiceName", const char* data, "ContentType")

    Convert to base64
    – Aram
    Jun 28 at 13:10

    You should not create a “string" from the raw binary data. Instead you use some encoding scheme that is textual but can handle arbitrary binary data. One such common encoding scheme is base64.
    – Some programmer dude
    Jun 28 at 13:10

    Convert the data to hex or base64 first.
    – Retired Ninja
    Jun 28 at 13:10

    use an array of uchar of known size
    – petacreepers23
    Jun 28 at 13:24

    Converting to base64 has worked. Thanks
    – NDestiny
    Jun 29 at 13:53

    By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

    Testing :id routes

    Testing :id routes

    How can I test routes with :id into it.

    For example, we have suppose a route like this

    Router.get('/:id/profile

    Now, I want to do a test case, the example scenario I saw from someone’s else code was that he was passing a string of numbers (probably user ID or something)

    Being a total tester in beginner who have been asked to test something, how can I find that string which I can send when testing something.

    For example here

    describe('Admin users API testing', () => {
    it('GET /admin/users/:id/activityLog', (done) => {
    request(URL)
    .get('/admin/users/5a82b1a61dab4b54fj01f212e/activityLog')
    .set('accept', '/application/json')

    We are sending request to

    it('GET /admin/users/:id/activityLog

    Which then looks like this

    .get('/admin/users/5a82b1a61dab4b54fj01f212e/activityLog')

    inside the above get request we have, something like this

    5a82b1a61dab4b54fj01f212e

    So my question is how do the person doing testing knows this?

    By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

    Bringing a laptop and a VM on another laptop on the same network

    Bringing a laptop and a VM on another laptop on the same network

    I am a newbie to networking.
    I am currently running an application on a VM (windows based also hosted on a windows based PC (say PC1)). I want my VM to communicate with the Linux based PC (say PC2). I have connected PC1 and PC2 with an ethernet cable and gave tem static IP addresses. Now they can communicate with each other. Ping tested. Now I want the VM hosted on PC1 to communicate with PC2. How can I bring the VM also in the same network ?

    By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

    /var/run/docker.sock: permission denied while running docker within Python CGI script

    /var/run/docker.sock: permission denied while running docker within Python CGI script

    I am trying to run Python CGI script inside which I need to run docker image.
    I am using Docker version 1.6.2. user is “www-data", which is added in docker group.

    www-data : www-data sudo docker

    On machine, with www-data I am able to execute docker commands

    www-data@mytest:~/html/new$ docker ps
    CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

    I am getting following error while running docker image from Python CGI script:

    fatal msg="Get http:///var/run/docker.sock/v1.18/images/json: dial unix /var/run/docker.sock: permission denied. Are you trying to connect to a TLS-enabled daemon without TLS?"

    Is there anything I am missing here?

    1 Answer
    1

    Permission denied on a default install indicates you are trying to access the socket from a user other than root or that is not in the docker group. You should be able to run:

    sudo usermod -a -G docker $username

    on your desired $username to add them to the group. You’ll need to logout and back in for this to take effect (use newgrp docker in an existing shell, or restart the daemon if this is an external service accessing docker like your cgi scripts).

    newgrp docker

    Note that doing this effectively gives that user full root access on your host, so do this with care.

    Thanks! That helped in resolving the issue.
    – user5154816
    Nov 30 ’16 at 0:31

    Restarting your machine might also help to take effect the changes.
    – learner
    Apr 18 ’17 at 7:10

    I had to run sudo chgrp docker /var/run/docker.sock, too.
    – Milanka
    Apr 27 at 6:19

    sudo chgrp docker /var/run/docker.sock

    @Milanka if that happens on an install from the docker repos, there’s something broken.
    – BMitch
    Apr 27 at 9:44

    @BenyaminJafari did you log out and back in? The comment on restarting the service was about other daemons connecting to docker, I’ve removed it to avoid confusion.
    – BMitch
    Jul 3 at 9:44

    By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

    Changing the color of the ‘active’

    Changing the color of the ‘active’

    The active color is still White even after rgb is changed.

    .nav li>a:hover,
    .nav .open>a:hover,
    .nav li>a:focus,
    .nav .open>a:focus,
    .nav li>a:active,
    .nav .open>a:active {
    background-color: rgb(255, 0, 0)

    <nav class="navbar navbar-m2p sidebar" role="navigation">

    </nav>

    I can not see any li in html code
    – לבני מלכה
    Jul 3 at 9:46

    li

    Think you need to learn about basic css selectors – do a tutorial, it will save you a lot of time and questions. But the main problems I see is you have nothing with a class of nav and no li so obviously your css is not styling anything
    – Pete
    Jul 3 at 9:51

    2 Answers
    2

    instead use of nav use navbar and inside navbar a

    nav

    navbar

    navbar a

    .navbar a:hover,
    .navbar .open>a:hover,
    .navbar span>a:focus,
    .navbar .open>a:focus,
    .navbar a:active,
    .navbar a:active {
    background-color: rgb(255, 0, 0)

    <nav class="navbar navbar-m2p sidebar" role="navigation">

    </div>
    </nav>

    I would also like to make a hover to the other sub-menus
    – James Theuma
    Jul 3 at 10:51

    Use .navbar instead .nav and I can not see any li element so remove it from css:

    .navbar

    .nav

    li

    I recommand you learn about selector in css:https://www.w3schools.com/cssref/css_selectors.asp

    .navbar a:hover,
    .navbar a:focus,
    .navbar a:active {
    background-color:rgb(255,0,0);
    }

    <nav class="navbar navbar-m2p sidebar" role="navigation">

    tell me if you have any li in html code…
    – לבני מלכה
    Jul 3 at 9:49

    what are you repeating the selector with open ?
    – Temani Afif
    Jul 3 at 10:06

    open

    you right… if he want apply style to a anyway it never mind if it open or not I will edit answer
    – לבני מלכה
    Jul 3 at 10:08

    a

    @TemaniAfif edited thanks for turned my attention…
    – לבני מלכה
    Jul 3 at 10:10

    By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.