text:
Q: how to unbind data from view? - knockout.js I have some data bound to the View. Have used cleanNode to unbind the data- and clear the view. Here the is the jsfiddle for the same: http://jsfiddle.net/FENuV/26/
The code for the same is below:
View:

Sold to Account

                <input type="text" id="txtSoldToAccount" data-bind="value:SoldToAccount"/>

Job Name

                <input type="text" id="txtQDJobName"  data-bind="value:jobName"/>

    <input type="button" value="unbind" id="unbindbutton"></input>

View model:
    QuoteDetails = function () {
    var self = this;
    self.SoldToAccount = ko.observable();
    self.jobName = ko.observable();
};

function SimpleSearchResults() {
    var self = this;
    self.index = ko.observable();
    self.quoteDetailsObj = ko.observable(new QuoteDetails());
    self.productDetailsArrObj = ko.observableArray([]);

    self.BindDataToQuotesDetailVM = function (SimpleSearchResultsOb) {
        var self= this;
        //SimpleSearchResultsOb['SoldToAccount']('SoldToAccount test');
       SimpleSearchResultsOb.SoldToAccount = "SoldToAccount test";
        SimpleSearchResultsOb.jobName = ko.observable("jobName test");

        ko.applyBindings(SimpleSearchResultsOb, document.getElementById("QdetailsDiv"));
    };
};

function QuoteSimpleSearchVM() {

    var self = this;
    self.simpleSearchResultsArray = ko.observableArray([]);

    var SimpleSearchResultsObj= new SimpleSearchResults();
    SimpleSearchResultsObj.index=ko.observable("1");
    self.simpleSearchResultsArray.push(SimpleSearchResultsObj);

    var SimpleSearchResultsObj2= new SimpleSearchResults();
    SimpleSearchResultsObj2.index=ko.observable("2");
    self.simpleSearchResultsArray.push(SimpleSearchResultsObj2);

};
 var obj= new QuoteSimpleSearchVM();
$(document).ready(function () {

    $("#unbindbutton").click(function(){
        var element = $('#QdetailsDiv')[0];
        ko.cleanNode(element);
    });

    ko.utils.arrayForEach(obj.simpleSearchResultsArray(), function (SimpleSearchResultsObj) {
                if (SimpleSearchResultsObj.index() === "2") {
                    SimpleSearchResultsObj.BindDataToQuotesDetailVM(this);
                }
            });
});

On cleanNode, the data is not cleared from the view.
Can anyone help me with the solution.
Thanks in advance.


text:
Q: Dynamic subject in contact mail I am working on a simple contact system where i need to display a value from a querystring in the subject field of the sent email.
Today has been a slow descent into madness as this has failed to work in every way i have tried.
I am using Umbraco 4.7.2 with Ubootstrap (bootstrap by twitter) and modifying the contact form found within.
Below is the cshtml of my contact form macro
@using System.Text
@using System.Collections.Generic;
@using Bootstrap.Logic.Utils
@using umbraco.MacroEngines
@inherits DynamicNodeContext
@{
    dynamic form = Context.Request.Form.ToDynamic();

    if (IsPost)
    {
        if (!Context.IsValidAntiForgery()) { ModelState.AddFormError(@Dictionary.InvalidPost); }
        if (MainHelper.IsEmpty(form.Name)) { ModelState.AddError("name", @Dictionary.FormNameValidation); }
        if (!MainHelper.IsEmail(form.Email)) { ModelState.AddError("email", @Dictionary.FormEmailValidation); }
        if (MainHelper.IsEmpty(form.Enquiry)) { ModelState.AddError("enquiry", @Dictionary.FormCommentValidation); }
    }

    if (!IsPost || !ModelState.IsValid)
    {
    @Html.Raw(library.RemoveFirstParagraphTag(Model.FormText.ToString()))
    <form method="post" action="@Model.Url">
        <fieldset>
            <legend>@Parameter.subject </legend>

            @Html.Label(@Dictionary.FormName, "name")

@Html.TextBox("name", form.Name, new { @class = "xlarge" })
            @if (!ModelState.IsValidField("name"))
            { @string.Join(". ", @ModelState["name"].Errors) }

            @Html.Label(@Dictionary.AddressName, "address1")

@Html.TextBox("address1", form.Address1, new { @class = "xlarge" })

            @Html.Label("Add 2", "address2", new { @class = "hide" })

@Html.TextBox("address2", form.Address2, new { @class = "xlarge" })

            @Html.Label(@Dictionary.FormEmail, "email")

@Html.TextBox("email", form.Email, new { @type = "email", @class = "xlarge" })
            @if (!ModelState.IsValidField("email"))
            { @string.Join(". ", @ModelState["email"].Errors) }

            @Html.Label(@Dictionary.FormComment, "enquiry")

@Html.TextArea("enquiry", form.Enquiry, new { @rows = 5, @cols = 25, @class = "xlarge" })
            @if (!ModelState.IsValidField("enquiry"))
            { @string.Join(". ", @ModelState["enquiry"].Errors) }

            @Context.GetAntiForgeryHtml()
        </fieldset>

            <button id="SubmitForm" type="submit" class="btn">@Dictionary.Send</button>

    </form>
    @Html.ValidationSummary(@Dictionary.FormValidationSummary, new { @class = "alert-message block-message error" })
    }
    else
    {
        var ok = SendForm(form, @Parameter.subject);
        if (!ok)
        {

                @Model.ErrorMessage

        }
        else
        {
            // Set Thankyou text from our contact node

@Model.ThankYouHeaderText

                @Model.ThankYouMessageText

        }
    }
}

@functions
{
    public bool SendForm(dynamic form, string queryParam)
    {
        // Get the variables from the form and set them in strings
        string strName = Library.StripHtml(form.Name).ToString();
        string strAddressLine1 = Library.StripHtml(form.Address1).ToString();
        string strAddressLine2 = Library.StripHtml(form.Address2).ToString();
        string strEmailFrom = Library.StripHtml(form.Email).ToString();
        string strMessage = Library.StripHtml(form.Enquiry).ToString();

        // Lets set the values passed in from the Macro
        string strEmailTo = Model.EmailTo.ToString();
        string strEmailSubject = queryParam;

        var now = DateTime.Now;
        var strTime = String.Format("{0:HH:mm:ss}", now);
        var strDate = String.Format("{0:dd/MM/yyyy}", now);

        // Let's Replace the placeholders in the email message body
        var strEmailBody = new StringBuilder(Model.EmailBody.ToString());
        strEmailBody.Replace("[Name]", strName); // Find and Replace [Name]
        strEmailBody.Replace("[AddressLine1]", strAddressLine1); // Find and Replace [AddressLine1]
        strEmailBody.Replace("[AddressLine2]", strAddressLine2); // Find and Replace [AddressLine2]
        strEmailBody.Replace("[Email]", strEmailFrom); // Find and Replace [Email]
        strEmailBody.Replace("[Message]", strMessage); // Find and Replace [Message]
        strEmailBody.Replace("[Time]", strTime); // Find and Replace [Time]
        strEmailBody.Replace("[Date]", strDate); // Find and Replace [Date]

        // Now the email is sent out to the owner, lets send out an email
        // to let the user know we have recieved their email & will respond shortly
        string strEmailReplySubject = Model.EmailReplySubject.ToString();
        var strEmailReplyBody = new StringBuilder(Model.EmailReplyBody.ToString());
        strEmailReplyBody.Replace("[Name]", strName); // Find and Replace [Name]

        return MainHelper.TrySendMail(strEmailTo, strEmailSubject, strEmailBody.ToString()) && MainHelper.TrySendMail(strEmailFrom, strEmailReplySubject, strEmailReplyBody.ToString());
    }
}

(Wall of code i know but i figure more info is better than less)
This results in the display of the querystring from macro parameter via @Parameter.subjet in the legend field, but when i try further down in the send function to set the string strEmailSubject to @Parameter.subject i just get the empty field in the email.
Any help would be wonderful.

A: Aparently Parameter doesn't exist within the function context. I would suggest passing it in as a argument to the function:
...

var ok = SendForm(form, Parameter.subject);

...

public bool SendForm(dynamic form, string subject)
{
    ...

    string strEmailSubject = subject;

    ...
}

A: I managed to work around this problem doing the following:
I knew that @Parameter.subject would allow me to place the querystring in the form, so i made a new textbox in the form to hold the parameter and then stripped it out ala
Library.StripHtml(form.Subject).ToString();
and used this to call the SendForm function

redpajama_set_name: RedPajamaStackExchange


text:
Q: Porting driver from PPC2003 to WM6: ISR not called I'm trying to port the driver I've developed for a custom device that uses the CF port of the iPAQ hx4700.
The target is the new iPAQ 210 that runs Windows Mobile 6. Although WM6 (and Windows CE 5.0) switched to a new driver architecture, it claims to support legacy drivers.
Everything is working fine (registration, memory mapping, etc) except the interrupt handling part. I register my ISR with CardRequestIRQ() but when the IRQ is generated my ISR is never called.
Please note: I'm developing for a well-defined platform (the iPAQ 210), so no Platform Builder, OAL, ...
Is there anybody experienced with this kind of things that could help me shed some light on this matter?

A: It turned out that, surprisingly, it was a hardware problem.
The duration of the interrupt pulse generated by our custom device complied with the CF (Compact Flash) standard. After all, everything worked fine for years with the iPAQ hx4700.
After running out of ideas, I decided to play with the pulse duration and, lo and behold, when the pulse was much longer (100x) than the original, the IRQ was processed correctly (ISR called as expected).
Note: the whole thing was correctly configured for pulsed IRQ (not level).
Go figure.


text:
Q: "Can't unwrap Optional.None" and I can't figure out why This produces "fatal error: Can't unwrap Optional.None" and I don't seem to get why
var motionManager = CMMotionManager()
motionManager.accelerometerUpdateInterval = 0.2
motionManager.startAccelerometerUpdates()
var accelerationData = motionManager.accelerometerData
var accel = accelerationData.acceleration.x

If anyone can help me out, that would be great.

A: The issue is accelerationData is nil and you aren't checking for this. From the docs:

If no accelerometer data is available, the value of this property is nil.

You should check to make sure there is actually data before calling methods on it like this
if let accelerationData = motionManager.accelerometerData {
    var accel = accelerationData.acceleration.x
}

That will ensure that if there is no data your app won't crash. Now to make sure you get some data.
You aren't getting any data because you're asking for data immediately after you initialize the core motion manager. You can show this by waiting a few seconds before checking. You can add NSThread.sleepForTimeInterval(3) right above the if let and run the project and it will enter the if let. Make sure you are using an actual device though, the simulator won't generate any motion data.


text:
Q: JqGrid Custom Button Not Executing Function So I have added a custom button to the pager of my JqGrid Table. I have attempted to test it by adding a simple alert("hello") function to the onClick parameter like so:
jQuery("#jsonmap").jqGrid('navGrid','#pjmap',{edit:false,add:false,del:false,refresh:true}).
                jqGrid('navButtonAdd',"#pjmap",{caption:"Export to Excel",buttonicon:"", onclickButton: function(){
      alert("Hello");
   }, position:"last",title:"",cursor:"pointer"});

The button shows up properly on the JqGRid when it is generated on the webpage, but when I click on it nothing happens, no alert nothing.
Thanks in advance for your suggestions

A: Use onClickButton, it should be in camel case


text:
Q: Outlook stops reply in the format of the sent email today when I reply to an email, Outlook breaks all the formatting of the original email. The font, text color are all converted to black Arial. How can I fix this? Thank you

A: Change your default mail formatting when replying to html. If it's set to plain text or even rich text it will break html formatting. Also, if someone emailed you in plain/rich text it will automatically reply in the same.
The following screenshot is from Office '10.


text:
Q: How to test for assert in debug build, but returned value in release? I want to test a function:
#include <cassert>

int my_func(int myParam) {
    int ret = 0
    if (myParam >= 10) {
        assert(false);
        // Logger call like `qCritical << "myParam is too big. Returning 0";`
    } else {
        ret = myParam * 2;
    }
    return ret;
}

assert()s are only enabled in the debug build.
I want to write tests that will pass whether the tests were built with the debug configuration or not (I assume this is the right way? Or is it sensible to write tests only for a specific build configuration?). So with a test input of, for example, 999:

*

*If built with the debug configuration the test should expect a crash (from the assert()).

*But without the debug configuration the test should expect a return value of 0.

I'm aware of EXPECT_DEBUG_DEATH, which only expects a crash if built with the debug configuration. But I don't see a test macro for expecting a specific return value only if built without the debug configuration.

A: Like others mentioned above, how about just using NDEBUG pre-processor directive? NDEBUG disables standard C assertions.
You could do it like
#ifdef NDEBUG
TEST_F(FooTest, DISABLED_MyFuncAbortsOnInputBigger10)
#else
TEST_F(FooTest, MyFuncAbortsOnInputBigger10)
#endif
{
    // ...
    EXPECT_DEATH( /* .. */ );
}

#ifdef NDEBUG
TEST_F(FooTest, MyFuncLogsInvalidInput)
#else
TEST_F(FooTest, DISABLED_MyFuncLogsInvalidInput)
#endif
{
    // ...
}

This way, your death test is disabled when you compile and run your test suite in release mode. In debug mode, the death test is active.
The DISABLED_ prefix in the test name allows you to disable a test but keep compiling the test code. You can read about it in the AdvancedGuide.


text:
Q: how to get the information from a http head in android i've been given the task to send a POST message to the server giving it a JSON encoded message. The server would then send back a responce in a custom HTTP header field "X-SubmissionResponse"
so far i can successfully connect to the server (i know this because i get the responce code 202)
but i am having a lot of difficulty in getting the information from the responce, below is the code that i am currently using.
Error content not available

This code ends up returning null, Can anyone see what i am missing here?
This is the code above the if statement ^
    Error content not available

A: HttpHead head = new HttpHead();

creates a new HEAD request, empty, that does not do anything in itself.
You want the header from the response to your request. Get it by simply:
Header name = response.getFirstHeader("X-SubmissionResponse");

A: Header name = response.getFirstHeader("X-SubmissionResponse");
String whatsInhere = "";
if (name != null)
  whatsInhere = name.getValue();

Try using the correct methods of the Class Header.
See http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/Header.html


text:
Q: Application not getting installed in Silent Mode I was given a task to install application silently on a machine. I had NO clue as how to achieve this. After spending some time, I felt it can be done through batch files and I started to learn creating batch files. I learnt how to copy file in different locations and other basic stuff.
As a practice I am trying to install 7zip.msi silently. I create a batch file with code
start C:\Users\MyName\Desktop\7zip.msi /quiet

I ran the batch file from the command prompt and it asked me to confirm with below window

I clicked run. And then nothing happens. I felt it is installing in the background (silently) but I am not sure if the installation is finished. And don't know how to get the status of installation. I waited for 20 min and saw in installed programs but my application was not there. I restarted and again nothing was in installed programs.
I have even tried with following code but ended up with same result
start C:\Users\MyName\Desktop\7zip.msi <Silent>

Can any one help me on this?? I know there are lot of articles out there, but I have reached there with there help only. I could not figure out whats happening.
And will same batch will work with an .exe file also? Thanks.

A: You could try this
msiexec.exe /i "C:\Users\MyName\Desktop\7zip.msi" /quiet

I took this from here, which has documentation and examples on msi switches.
You can't do the same with exe's, unless they have the same switches built into them by the developer.


text:
Q: What does "To her fair works did Nature link" mean? I found this in "The Water Babies" fairy tale. It is part of the poem Lines Written in Early Spring by Wordsworth:

To her fair works did Nature link
  The human soul that through me ran;
  And much it grieved my heart to think,
  What man has made of man.

What does "To her fair works did Nature link" mean?

A: In this poem, the Poet is personifying Nature.
The line "To her fair works did Nature link" will be easier to understand when one will read it along with the next one.
"To her fair works did Nature link the human soul that through me ran".
Here 'her' refers to the Nature itself. Altogether the lines mean that the soul of the poet connects with the Nature in regards of the beautiful(fair) work that Nature has done.


text:
Q: Why was I able to install GStreamer third-party without disabling Secure Boot? I installed Ubuntu 16.04 LTS on my new ThinkPad E460 and for the first time in a decade I was shocked about a question Ubuntu was asking me. None of my previous computers had this Secure Boot thing, and all worked on BIOS, so I am clearly unaware of some things...
During the install it popped me this question about third-pary packages and disabling Secure Boot.

Not knowing what is Secure Boot, I decided to NOT disable it and NOT install third party packages.
The install went smooth.
Then I reboot and all seems fine. Of course, I can't play mp3. So I download an mp3, open it, and the player asks me to install GStreamer bad/ugly etc: third-party software. So I was expecting it would say "hey, we need to disable the secure boot". But instead it installed the packages and I can now play mp3.
So what is the deal with this thing?
Is it only for drivers (like NVidia etc) that you need to disable the secure boot? Because if that is the case, I think Ubuntu could check if any of those is necessary and then prompt the questions about Secure Boot instead of scaring people that only want to play mp3 files...


text:
Q: Is there any difference between md5 and sha1 in this situation? It is known that
1.    if   ( md5(a)   == md5(b)   )
2.    then ( md5(a.z) == md5(b.z) )
3.    but  ( md5(z.a) != md5(z.b) )

where the dots concatenate the strings.
EDIT ---
Here you can find a and b:
http://www.mscs.dal.ca/~selinger/md5collision/
Check these links:
hexpaste.com/qzNCBRYb/1 - this is a.md5(a)."kutykurutty"
hexpaste.com/mSXMl13A/1 - this is b.md5(b)."kutykurutty"
They share the same md5 hash, yet they are different. But you can call these strings a' and b', because they have the same md5.
--- EDIT
What happens in the second row if we change all the md5 to sha1? So:
1.    if   ( sha1(c)   == sha1(d)   )
2.    then ( sha1(c.z) ?= sha1(d.z) )

I couldn't find two different strings with same sha1, that's why I'm asking this. Are there any other interesting "rules" about sha1?

A: The first statement will only hold true for very specific z specifically computed for given a and b. It is true that you can generate an MD5 collision, but this is not trivial - some computational effort is required and certainly you can't expect that any z will do.
Currently SHA-1 is believed to be cryptographically secure which means noone has come up with a way to generate SHA-1 collisions. It doesn't mean that it is really secure and collision generation is not possible - maybe there is a yet uncovered vulnerability. Even if there is a vulnerability it's highly unlikely that the same strings will at the same time form both an MD5 and a SHA-1 collision.

A: SHA1 will behave exactly like MD5 in this scenario.
The only two references I have found are the following -

*

*http://www.iaik.tugraz.at/content/research/krypto/sha1/MeaningfulCollisions.php

*http://www.schneier.com/blog/archives/2005/02/sha1_broken.html#c1654 (See comment by David Schwartz)

From the IAIK website -

Note that for colliding SHA-1 message pairs (as for all other hash functions following a similar design principle) it is always possible to append suffixes to both messages as long as they are the same.

I don't think anybody has found two colliding strings for SHA1, so this is mostly an academic discussion. But from what I understand, when a collision is discovered, it should be possible to create several other collisions by using this property.

A: Sha1 isn't as easily cracked as md5, but they did find some vulnerabilities in it back in '05 I believe.

A: Your example is wrong in my opinion.
Let me show you why:
md5(a) == md5(b)

When both hashes are the same, the corresponding strings have to be same (this could be collisions, but it's not important in my thesis), so we'll have:
a = b

When you now concatenate both strings with a string z, you will have
    a.z = b.z
and their md5-hashes will be the same, because they have the same string-input
md5(a.z) == md5(b.z)

and the md5-hash will a third time be equals while both string inputs are the same
md5(z.a) == md5(z.b)

And this is true for md5 and every other hashing algorithm while they have to be deterministic and side effect free.

So your example will only make sense when z is a special string which will result in an collision. And therefore the behaviour of md5 and sha1 will exactly be the same:
The collision-string appended will result in a collision, but prepended will be different hashes (but there's a really really really low probability you find a collision-string which will be prependend and appended result in an collision, but none example has been yet found in reality)
You only didn't find thwo different string with same sha1 because collisions are harder to find as explained by the people before me.


text:
Q: What element is forcing my width to be fixed once the screen is small enough? I'm trying to figure out why my HTML email is doing this:

I feel like I've made it responsive (on browsers and email clients that support media queries) since I've replaced the fixed width with percentage-based width everywhere. None of the widths of the cells/tables inside add up to more than 400 pixels and yet it gets stuck around there. Anyone want to help me find the culprit? Which element is causing the trouble?
Fiddle: https://jsfiddle.net/j7y75g7t/.

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

HEADLINE

SUBHEADLINE

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

SUBHEADLINE

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

The Guidant Team

888.472.4455

Guidant Financial | 1100 112th Ave NE Ste 100 | Bellevue, WA 98004

This email was sent by MitchellLarsen@guidantfinancial.com. If you no longer want to receive these emails you may unsubscribe at any time.

A: You should first of all clean up the code and create a separate CSS file and define classes and their styles there.
Then:
You have several width properties assigned to elements that overlap / overwrite each other and then enforce that override with "!important".

It is bad practice to overwrite parameters with "!important" all the time.
One idea to do this is to put everything a container element that has 100% and a padding.
The cards then can be 100% width and centered and they will then be fully responsive.
An important thing to remember is when you want to center floating, responsive elements with unknown (percentage ) size is that you have to create wrapping "helper" elements, like such:
.centerWrapper {
  float: right;
  position: relative;
  left: -50%;
}

.container {
  position: relative;
  left: 50%;
  max-width: 600px;
  text-align: center;
}

.card {
  max-width: 100%;
  display: inline-block;
}

and then HTML

...

I made a fiddle for you which shows this very roughly.
It shows a fluid / responsive layout based on percentages without the need for and media queries breakpoints. You can still add @media breakpoints, to change font-sizes, for example.
https://jsfiddle.net/yphfgx51/2/


text:
Q: Parsing ASPX page in C# How can I parse an ASPX page such as this : http://www.shufersal.co.il/Pages/Catalog.aspx# to strings in C#? this website is shopping site and I want to take some details from it such as a product name and a price? Please help me...

A: You could use HTML Agility Pack for this. More information can be found here:
http://www.google.nl/url?sa=f&rct=j&url=http://www.4guysfromrolla.com/articles/011211-1.aspx&q=html+agility+pack+tutorial&ei=hwodUKGlHu220QWJmYBo&usg=AFQjCNH4auAyTI9GTpM2cistPrGGnMHLeg
There are also some examples available. It's very easy to use if your familliar with linq to X queries.


text:
Q: Swift - DatePicker - Allow Only Valid Intervals I am trying to configure two DatePickers, showing only time, where they must be a certain interval apart and match the interval.
For example:
Let's say I have two DatePickers, startTime and endTime. I also have a double variable called frequency.
If startTime is set to 8am and frequency is 2.5, I only want to be able to select 10:30am, 1pm, 3:30pm, 6pm, and so on from the endTime DatePicker.
This of course also goes the other way, where if the user has already set both the startTime and endTime values via their respective DatePickers, and then changes the frequency, the endTime should auto-update to the next closest value.
Example:
If startTime is 8am and endTime is 6pm and frequency is 2, all is well. If the user then changes frequency to be 3.5, endTime should auto-update to 6:30pm.
Hope that makes sense, here's some code:
struct ContentView: View {

    @State private var showsPicker: Bool = false
    @State private var frequency: Double = 1
    @State private var frequencyArray: [Double] = [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
    @State private var startTime: Date = Date()
    @State private var endTime: Date = Date()

    var body: some View {
        Group {
            VStack(alignment: .leading, spacing: 0) {
                Text("Frequency: \(frequency.formatted())")
            }
            .padding()
            .frame(maxWidth: .infinity)
            .background(.blue)
            .onTapGesture {
                withAnimation {
                    showsPicker.toggle()
                }
            }

            if showsPicker {
                Picker("", selection: $frequency) {
                    ForEach(frequencyArray, id: \.self) { freq in
                        Text("\(freq.formatted())")
                    }
                }
                .pickerStyle(WheelPickerStyle())
                .labelsHidden()
                .frame(maxWidth: .infinity)
            }

            VStack {
                DatePicker(
                    "",
                    selection: $startTime,
                    in: ...(Calendar.current.date(
                            byAdding: .minute,
                            value: Int((Double(frequency) * 60)),
                            to: endTime

                    ) ?? Date()),
                    displayedComponents: .hourAndMinute
                )
                    .padding()
                    .background(.blue)

                DatePicker(
                    "",
                    selection: $endTime,
                    in: (Calendar.current.date(
                        byAdding: .minute,
                        value: Int((Double(frequency) * 60)),
                        to: startTime
                    ) ?? Date())...,
                    displayedComponents: .hourAndMinute
                )
                    .padding()
                    .background(.blue)
            }
        }
        .onAppear {
            UIDatePicker.appearance().minuteInterval = 15
        }
    }
}

A: The answer is in two parts:

*

*Apparently because a DatePicker has a defined range, you cannot alter that range to only allow choices based on an interval.

*That being said, you can do this with a function so that you ensure the correct interval is maintained. From my testing, it seems best to only run this function on the endTime as running on both the startTime and endTime seems to cause issues with it trying to calculate over and over again, especially since for my purposes I have more than just this one check running.
Also, contrary to the one comment posted, you do not want to do this "onChange" because you'd have to have triplicate code (one for the frequency, one for startTime and one for endTime). Instead, simply use an EmtpyView() with a .task modifier so it's always watching for changes.
Here's the function:
func setClosestTime() {

    var timeAhead = Date()
    var timeBefore = Date()

    for i in stride(from: 0, to: -600, by: -15) {
        let dateCalc = Calendar.current.date(
                        byAdding: .minute,
                        value: i,
                        to: endTime
                        ) ?? Date()
        let timeCheck = (dateCalc.timeIntervalSince(startTime) / 3600).truncatingRemainder(dividingBy: (Double(frequency) ?? 0))
        if timeCheck == 0 {
            timeBefore = dateCalc
            break
        } // End If
    } // End For Loop

    for i in stride(from: 0, to: 600, by: 15) {
        let dateCalc = Calendar.current.date(
                        byAdding: .minute,
                        value: i,
                        to: endTime
                        ) ?? Date()
        let timeCheck = (dateCalc.timeIntervalSince(startTime) / 3600).truncatingRemainder(dividingBy: (Double(frequency) ?? 0))
        if timeCheck == 0 {
            timeAhead = dateCalc
            break
        }
    } // End For Loop

    if timeAhead.timeIntervalSince(endTime) < endTime.timeIntervalSince(timeBefore) {
        endTime = timeAhead
    } else {
        endTime = timeBefore
    }
} // End Func

What we are doing is using stride to loop in increments of 15 (backwards and forwards) and when the first match is found, set either the timeAhead or timeBefore variable.
Once both of these variables have been set, we compare the difference between the times to see which one is shorter and then set the endTime variable. This ensures that the time match will always be the closest to the time the user has chosen, while still maintaining our intervals.
To use this solution, write an if statement to check if the interval is set correctly and if not, run a task on an EmptyView().
Here's how:
if !((endTime.timeIntervalSince(startTime) / 3600).truncatingRemainder(dividingBy: (Double(frequency) ?? 0)) == 0) {
    VStack {
        EmptyView()
    }
    .task {
        setClosestTime()
    }
}


text:
Q: How do I keep the ssl key for our website confidential? I want to keep our SSL key for our website confidential. It's stored on 2 USB sticks, one in a safe deposit box and one I keep secure. And then I'm the only one who applies it to the web server so that it is totally secure.
Except...
On IIS at least, you can export the key. So anyone who's an admin can then get a copy of the key. Is there any way around this? Or by definition do all admins have full access to all keys?
Update:
I do have sysadmins I fully trust. What led to this is one of them quit (they had an hour commute to our company, a 5 minute commute to the new one). While I trust this individual, just as we disable their Active Directory account when someone leaves, I thought we should have a way to insure they don't retain the ability to use our SSL.
And what struck me as easiest is if I'm the only one who has it. Our cert expires in January so this was the time to change the practice if we could. Based on the answers it looks like we cannot.
So this leads to a new question - when someone who has access to the cert leaves, is it standard practice to get a new cert and have the existing one revoked. Or if the person who left is trustworthy, then do we continue with the cert we have?

A: A person with administrative (or often even physical) access to a server is going to be able to extract the private key. Whether through exporting, memory sniffing, or other such trickery.
Your administrators have access to the private keys of your web servers. Accept this as fact, and work around that. If your sysadmins aren't trustworthy, then you may need better sysadmins or at least fewer sysadmins with access to the web servers. If it's a matter of management security paranoia, then there may be a deeper issue regarding their ability to trust a sysadmin.
This isn't to say that you should just let everybody have access to the private key. There should always be a need for access before access is granted. With that in mind, are you going to take extreme measures to make sure that a sysadmin with full control of a website can not export the private key, but can still manipulate the website itself in any number of nearly untraceable ways?  We're back to trust here, and I think that's the core of the problem that needs to be addressed.

A: When you import the key, you have the option of marking it as non-exportable.  This will prevent you from using IIS or the certificate MMC to export it.  At least, it makes it a little harder.
However, if they have an administrator account on the machine, or have physical access to it - they will still be able to get the key through other means.

A: This is where an "intermediate CA" can help.
The "Root CA" in this example below is one owned by an SSL company and not you.
You don't have direct control of keys created by the Root CA, so if a key signed by the Root CA gets compromised, you have to go through them to revoke it.
But:
Root CA (SSL company)
 |
 +-Intermediate CA (You)
   |
   +-Server Key for site

If you place another CA in the middle, and have your bought SSL certificate sign your own CA certificate instead of directly signing your server certificate, you can retain control of server certificates below and issue revocation certificates or do whatever else if things below it are compromised.
You keep the Intermediate CA private key to yourself and the admins don't need to see it.
You can also do this:
Root CA (SSL company)
 |
 +-Intermediate CA (You)
   |
   +-Server Key 1 for site
   +-Server Key 2 for site
   +-Server Key 3 for site

You can prepare for compromise, and generate certificates ahead of time, so you can switch quickly in the event an individual key is revoked.  Admins do not get keys for 2 or 3 until compromise of 1.  You can put a notice on your site about this scheme, and this would also communicate to your admins that you are ready in the event of a compromise and that funny business on their end won't destroy your site.

A: There are many articles that suggest storing the private keys somewhere other than the server but those private keys are for code signing certificates. Imagine you have the keys on an offline computer that only you have access to, some software is written, you get the private key from offline server, sign the code and then you don't need the private key again until you need to sign some code again.

The best solution has always been, and will continue to be storing your key offline. How you do it is completely up to you (there are a few methods), just remember to keep it well guarded in an office safe or somewhere that it's not easy for someone to pocket.

Read more at: https://www.thesslstore.com/blog/heres-what-happens-when-your-private-key-gets-compromised/
In contrast, SSL certificates are for websites to enable HTTPS communication: The private key is needed during each and every handshake by the web server. Therefore, storing it offline will not work.


text:
Q: Store unmasked InputMask value in Formik and Material-UI Alright, so I have this implementation of Input Mask over a custom styled implementation of Material UI's text field, inside a Formik form:
<InputMask
                        mask="999-99-9999"
                        maskChar="X"
                        value={values.ssn}
                        onChange={handleChange}
                        onBlur={handleBlur}
                        className={classNames(
                          styles.inputField,
                          styles.override
                        )}
                      >
                        {() => (
                          <LNTextField
                            name="ssn"
                            label="Social Security Number"
                            error={touched.ssn && errors.ssn ? true : false}
                            helperText={
                              touched.ssn && errors.ssn ? "* " + errors.ssn : ""
                            }
                            type="text"
                          />
                        )}
                      </InputMask>

The problem now is that in values.ssn the value is stored with the mask, with the hyphens and all, I would instead like it to be stored as a number/string with no spaces/masks, how would I go about that?

A: Per @Kiran LM 's comment codesample, this was acheived by adding this instead of the existing onChange, aswell as destructuring setFieldValue from Formik
                      onChange={e => {
                        const value =
                          e.target.value
                            .replace(/-/g, "")
                            .replace(/X/g, "") || "";
                        setFieldValue("ssn", value);
                      }}

Many thanks to them.


text:
Q: Add custom header to http call I have this part of code
App.factory('httpRequestInterceptor', function () {
return {
    request: function (config) {

        console.log(config)
        config.headers['Access-Control-Allow-Origin'] = '*';
        config.headers['Access-Control-Allow-Methods'] = 'GET, PUT, POST, DELETE, HEAD, OPTIONS';
        config.headers['Access-Control-Allow-Credentials'] = 'true';
        config.headers['Access-Control-Allow-Headers'] = 'X-Requested-With, origin, content-type, accept, application/xml;charset=utf-8';

        return config;
    }
};

});
and this
App.config(['$stateProvider', '$httpProvider', '$locationProvider', '$urlRouterProvider', '$ocLazyLoadProvider', function ($stateProvider, $httpProvider, $locationProvider, $urlRouterProvider, $ocLazyLoadProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');}]);

Now everytime that run i get this error
Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.

A: I thinks you need to specified Access-Control-Allow-Origin in your server, not in your application angularjs.


text:
Q: Deregister scripts from plugin I have an own class that deregisters all scripts and styles and creates 2 cached files one for scripts and one for styles that is registered in the end. This runs inside theme, my problem is that I cant move it into plugin, as soon as i move it into plugin it wont work.
currently this code works inside theme
add_filter('wp_print_styles', array($this, 'optimize_styles'), 1);
add_filter('wp_print_scripts', array($this, 'optimize_scripts'), 1);

i have tried add action add filter, change priorities.... also i want some way to make my plugin load as last to ensure all plugin styles and scripts will be "compiled" into one.
Thankyou

A: There's a much better and more reliable way than naming your plugin "ZZ" - use a delayed hook on plugins_loaded, which fires after all plugins are loaded:
function wpse_191178_plugins_loaded() {
    // Do your stuff
}

add_action( 'plugins_loaded', 'wpse_191178_plugins_loaded', 100 );

A: Since plugins are loaded by the alphabetical order of plugin's folder name (not by plugin's name), name your plugin folder ZZ.. and it should load last :-)


text:
Q: How to add timestamp to Cucumber report How can I add timestamps to the HTML report for the test run start/end and for scenario start/end in Cucumber-JVM?
Is there a Cucumber option I can add to RunWith JUnit runner?

A: It's simple!!!!!!
Don't mention any folder path in plugin com.cucumber.listener.ExtentCucumberFormatter.
Example :
plugin= { "pretty", "html:FeaturesReport", "html:target/site/cucumber-pretty", "json:target/cucumber.json",

      "com.cucumber.listener.ExtentCucumberFormatter:",

},

*

*Run project and refresh it.

*check report will generate in default folder output/Run_with system time/report.html

If you want to generate a report in a specified path with a timestamp
just follow the below steps.

*

*goto maven dependencies.

*search cucumber-extentsreport.jar

*extend jar and select com.cucumber.listener package

*copy entire code in ExtentProperties class

*right on package and create new enum with name of ExtentProperties

*then paste ExtentProperties class code in the created enum.

*search below method
ExtentProperties() {
    this.reportPath = "output" + File.separator + "Run_" + System.currentTimeMillis() +File.separator+ "report.html";
    this.projectName = "default";
}

8.And Replace With below code
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

String userDir =System.getProperty("user.dir");

ExtentProperties()

{

    this.reportPath = "Extent_Reports" + File.separator + "" +
    timeStamp.replace(":","").replace(".","_") + File.separator + "Execution
report.html";
    this.projectName = "default";

}

*Run the project then refresh the project.

10.check report will generate in specified path with the name.
Extent_Reports/_2020_06_16_19_14_07/Execution report.html
Please comment if you have any questions

A: Work with latest cucumber version, you can get start timestamp of each scenario in json report as below:
"elements": [
  {
    "start_timestamp": "2019-11-18T11:06:15.606Z",
  ....
  }


text:
Q: How namespaces work in Ruby? I'm using namespaces in order to organize my code, but now I'm with a small doubt. I have the following code:
module ShopApplication
  module Models
    class Product < ::Sequel::Model
      # Model code
    end
  end
end

All my models are contained into this module called Models. In another part of my application, I have the following:
module ShopApplication
  module WebInterface
    class App < ::Sinatra::Base
      get '/' do
        @products = ShopApplication::Models::Product.all
      end
    end
  end
end

I wanna use my models without specify the full path. Can I transform @products = ShopApplication::Models::Product.all into @products = Product.all? If yes, how? I tried include ::ShopApplication::Models into the App class, but don't worked.

A: Module#include is what you want to use here:
module ShopApplication
  module Models
    class Product < ::Sequel::Model
      # Model code
    end
  end
end

module ShopApplication
  module WebInterface
    class App < ::Sinatra::Base
      include ShopApplication::Models
      get '/' do
        @products = Product.all
      end
    end
  end
end

Here's a contrived example that doesn't have your dependencies in it, but shows both class methods and instance methods:
module ShopApplication
  module Models
    class Product
      def name
        "Product-name"
      end
      def self.all
        ["array", "of", "products"]
      end
    end
  end
end

module ShopApplication
  module WebInterface
    class App
      include ShopApplication::Models
      def instance_meth
        p Product.new.name
      end
      def self.class_meth
        p Product.all
      end
    end
  end
end

ShopApplication::WebInterface::App.new.instance_meth
ShopApplication::WebInterface::App.class_meth


text:
Q: Displaying JSON text in foreign language I am making a program that show a tweet.
Basically this is how it works.

*

*Access the twitter json feed using the api.twitter.com: url

*Parse and display.

However, as you can see, the texts/tweets are in Korean, so the json file contains something like this \ud329\ud2b8\ub97c instead of Korean 트위터. What is this character representation called?
Now, I can successfully load the above JSON to my app, but if I display it on a textView, will it be displayed in Korean or in this representation \ud329\ud2b8\ub97c?
FYI, I don't want to use Twitter library for this.

A: You need to use NSUTF8StringEncoding, something along the line of following should work:
NSString* query = [NSString stringWithContentsOfURL:[NSURL URLWithString:queryString] encoding:NSUTF8StringEncoding error:&errorStr];
NSData *resultJson = [query dataUsingEncoding:NSUTF8StringEncoding];
if( query )
{
// do stuff
}

A: The stored text is encoded as Unicode char codes.
To get text from it, you need the JSON.parse (JS function) or similar. Though you did not mention which language you program is written in, there are JSON parsers in most of them.


text:
Q: Bokeh - Pandas not able to read bytesIO object of excel file from JS I need your inputs on some challenges I'm facing since few days.
My target is to have a upload button, from which I share .xlsx file with 2 sheets. Once I load this data and read it into pandas DataFrame, I perform some pythonic calculations/optimisation code etc and get few results(tabular summarised). Now based on the number of unique 'levels'/'groups'  I will create that many tabs and then display this summarise results in each tab. Also have a general(common) plot in the main page.
Below is my effort(not mine but community's :) ) :
1. Upload Button code : (from here)
## Load library
###########################################################################
import pandas as pd
import numpy as np
from xlrd import XLRDError
import io
import base64
import os

from bokeh.layouts import row, column, widgetbox, layout
from bokeh.models import ColumnDataSource, CustomJS, LabelSet
from bokeh.models.widgets import Button, Div, TextInput, DataTable, TableColumn, Panel, Tabs
from bokeh.io import curdoc
from bokeh.plotting import figure
###########################################################################
## Upload Button Widget
file_source = ColumnDataSource({'file_contents':[], 'file_name':[]})
cds_test = ColumnDataSource({'v1':[], 'v2':[]})

def file_callback(attr,old,new):

    global tabs, t
    print('filename:', file_source.data['file_name'])
    raw_contents = file_source.data['file_contents'][0]
    prefix, b64_contents = raw_contents.split(",", 1)
    file_contents = base64.b64decode(b64_contents)
    file_io = io.BytesIO(file_contents)

# Here it errors out when trying '.xlsx' file but work for .csv Any Idea ????
    #df1 = pd.read_excel(file_io, sheet = 'Sheet1')
    #df2 = pd.read_excel(file_io, sheet = 'Sheet2')

    # call some python functions for analysis
    # returns few results
    # for now lets assume main_dt has all the results of analysis

    df1 = pd.read_excel(file_path, sheet_name = 'Sheet1')
    df2 = pd.read_excel(file_path, sheet_name = 'Sheet2')

    main_dt = pd.DataFrame({'v1':df1['v1'], 'v2': df2['v2']})
    level_names = main_dt['v2'].unique().tolist()

    sum_v1_level = []
    for i in level_names:
        csd_temp = ColumnDataSource(main_dt[main_dt['v2'] == i])
        columns = [TableColumn(field=j, title="First") for j in main_dt.columns]
        dt = DataTable(source = csd_temp, columns = columns, width=400, height=280)
        temp = Panel(child = dt, title = i)
        t.append(temp)
        sum_v1_level.append(sum(csd_temp.data['v1']))

    tabs = Tabs(tabs = t)
    cds_plot = ColumnDataSource({'x':level_names, 'y':sum_v1_level})

    p_o = figure(x_range = level_names, plot_height=250, title="Plot")
    p_o.vbar(x='x', top = 'y', width=0.9, source = cds_plot)
    p_o.xgrid.grid_line_color = None
    p_o.y_range.start = 0
    p_o.y_range.end = max(sum_v1_level)*1.2
    labels_o = LabelSet(x='x', y = 'y', text='y', level='glyph',
        x_offset=-13.5, y_offset=0, render_mode='canvas', source = cds_plot)
    p_o.add_layout(labels_o)

    curdoc().add_root(p_o)
    curdoc().add_root(tabs)
    print('successful upload')

file_source.on_change('data', file_callback)

button = Button(label="Upload Data", button_type="success")
# when butotn is clicked, below code in CustomJS will be called
button.callback = CustomJS(args=dict(file_source=file_source), code = """
function read_file(filename) {
    var reader = new FileReader();
    reader.onload = load_handler;
    reader.onerror = error_handler;
    // readAsDataURL represents the file's data as a base64 encoded string
    reader.readAsDataURL(filename);
}

function load_handler(event) {
    var b64string = event.target.result;
    file_source.data = {'file_contents' : [b64string], 'file_name':[input.files[0].name]};
    file_source.trigger("change");
}

function error_handler(evt) {
    if(evt.target.error.name == "NotReadableError") {
        alert("Can't read file!");
    }
}

var input = document.createElement('input');
input.setAttribute('type', 'file');
input.onchange = function(){
    if (window.FileReader) {
        read_file(input.files[0]);
    } else {
        alert('FileReader is not supported in this browser');
    }
}
input.click();
""")

Bdw : Any way to suppress this warning or am I doing it the wrong way ?(while inserting read column into CDS)

BokehUserWarning: ColumnDataSource's columns must be of the same length. Current lengths: ('v1', 19), ('v2', 0)

2. Adding to the layout
curdoc().title = 'Test Joel'
curdoc().add_root(button)

Below is the output :

This was the original data :

Note : All data shared here are dummy and real case has more sheets and more dimensions .
So to summarise :

*

*Not able to read .xlsx file through the upload button

*Is it correct to do all steps in the button callback function itself ?

A: For those you would infuture reference this thread : Here is a solution to have a upload button to handle .xlsx file . This was for python3
I am sharing only the main data handling code. Rest everything is as it is above.
import pandas as pd
import io
import base64

def file_callback_dt1(attr,old,new):
    print('filename:', file_source_dt1.data['file_name'])
    raw_contents = file_source_dt1.data['file_contents'][0]
    prefix, b64_contents = raw_contents.split(",", 1)
    file_contents = base64.b64decode(b64_contents)
    file_io = io.BytesIO(file_contents)
    excel_object = pd.ExcelFile(file_io, engine='xlrd')
    dt_1 = excel_object.parse(sheet_name = 'Sheet1', index_col = 0)
    # rest is upto you :)

A: The general idea of using a CDS in this way is reasonable for now. In the future, there should be better mechanisms, but I can't speculate when they might be implemented. Regarding the error with read_excel, that is a Pandas issue/question, not a Bokeh one.
As for the warning about column lengths, that almost certainly indicates a usage problem. It is telling you that your v2 column is empty, which doesn't seem to be what you intend, and also violates the fundamental assumption that all CDS columns always be the same length. I'm not sure why you are generating an empty list for v2 though, without being able to run code.
Edit: For instance, adding one by one works fine if everything is the same length:
In [4]: s.add([1,2,3], 'foo')
Out[4]: 'foo'

In [5]: s.add([1,2,3], 'bar')
Out[5]: 'bar'

It's only a problem when the thing you add is not the right length, which is what the error message states:
In [6]: s.add([], 'baz')
/Users/bryanv/work/bokeh/bokeh/models/sources.py:138: BokehUserWarning: ColumnDataSource's columns must be of the same length. Current lengths: ('bar', 3), ('baz', 0), ('foo', 3)
  "Current lengths: %s" % ", ".join(sorted(str((k, len(v))) for k, v in data.items())), BokehUserWarning))
Out[6]: 'baz'

If you don't have the data for a column up front don't put in an "empty list" as a placeholder, or as soon as you put in a real column, you have inconsistent lengths. That is the cause of your problem.


text:
Q: iOS Sort array based on float value I wish to sort an array data based on height parameter which is in float. I used NSSortDescriptor but it isn't working.
Following is my code:
NSSortDescriptor *hDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Height" ascending:YES];

NSArray *sortDescriptors = @[hDescriptor];

[[[appDelegate.arr objectAtIndex:section] objectForKey:@"arrPerson"] sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"%@",[[appDelegate.arr objectAtIndex:section] objectForKey:@"arrPerson"]); // height is printed in random order. not sorted

How do I solve this?
edited: log
(
    {
    Height = "11.5766";
    Name = "abc";
},
    {
    Height = "11.8443";
    Name = "sdfsdf";
},
    {
    Height = "12.211";
    Name = "hnkhjk";
},
    {
    Height = "13.7271";
   Name = "ertert";
},
    {
    Height = "15.2694";
    Name = "sdf";
},
    {
    Height = "21.9242";
    Name = "fgh";
},
    {
    Height = "23.0857";
    Name = "ert";
},
    {
    Height = "6.48365";
    Name = "cvb";
},
    {
    Height = "7.5204";
    Name = "rt";
},
    {
    Height = "8.67856";
    Name = "asd";
}

)

A: -sortedArrayUsingDescriptors:sortDescriptors: returns the sorted array. So you are basically just sorting it and discarding the result.
You need to sort and assign this value to the NSDictionary you are pulling it out of.
NSArray *persons = [[appDelegate.arr objectAtIndex:section] objectForKey:@"arrPerson"];
NSArray *sortedPersons = [persons sortedArrayUsingDescriptors:sortDescriptors];
[[appDelegate.arr objectAtIndex:section] setObject:sortedPersons forKey:@"arrPerson"];

But to do that you need to have a NSMutableDictionary. If you post more code in your question it might help. But the above is your problem :)
EDIT:
As per discussion in the comments the values are stored as NSStrings
The following will try to convert any strings as numbers (and any other types):
NSArray *sorters = @[[NSSortDescriptor sortDescriptorWithKey:@"Height" ascending:YES comparator:^(id obj1, id obj2) {
        NSNumber *n1;
        NSNumber *n2;
        // Either use obj1/2 as numbers or try to convert them to numbers
        if ([obj1 isKindOfClass:[NSNumber class]]) {
            n1 = obj1;
        } else {
            n1 = @([[NSString stringWithFormat:@"%@", obj1] doubleValue]);
        }
        if ([obj2 isKindOfClass:[NSNumber class]]) {
            n2 = obj2;
        } else {
            n2 = @([[NSString stringWithFormat:@"%@", obj2] doubleValue]);
        }
        return [n1 compare:n2];
    }]];

NSArray *persons = [[appDelegate.arr objectAtIndex:section] objectForKey:@"arrPerson"];
NSArray *sortedPersons = [persons sortedArrayUsingDescriptors:sorters];
[[appDelegate.arr objectAtIndex:section] setObject:sortedPersons forKey:@"arrPerson"];

If you can guarantee that the Height value will always be an NSString or NSNumber (and not a NSNull if we're dealing with JSON) the following sort descriptor would also work:
NSArray *sorters = @[[NSSortDescriptor sortDescriptorWithKey:@"Height.doubleValue" ascending:YES]];

While the first sort descriptor is a bit longer, its also far more robust in case any other objects are put inside of the Height value as then you would get a class is not key value coding-compliant for the key length error.

A: Try this it may work.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Height"
                                                               ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [[[appDelegate.arr objectAtIndex:section] objectForKey:@"arrPerson"]sortedArrayUsingDescriptor:sortDescriptors];


text:
Q: If A is invertible then KerB=KerAB A is mm matrix and B is a mn matrix. Show that if A is invertible then KerB=KerAB.
I have been thinking that let x belongs to KerB so that Bx=0.
 A*A^-1*Bx=In*Bx=Bx
but dont know how to continue.

A: We always have $\ker( B)\subseteq \ker (AB)$. Here we have an inverse of $A$ and hence  additionally $\ker(AB)\subseteq \ker(A^{-1}AB)=\ker(B)$.

A: You have chosen an arbitrary element $x \in \ker B$. You should prove that this element also lies in $\ker AB$, to show the inclusion $\ker B \subset \ker AB$. After that you'll also have to show the other inclusion, where you'll have to use the fact that $A$ is invertible.


text:
Q: Why there isn't a "ListField" in Django? I have a model that has a Charfield (let's name it advantages) with a choices attribute. After a while, I've decided that this field should be "upgraded" to some kind of ListField, since more than one choice can be selected.
From what I have searched, I have two options:
1 - Create a new model, and use a ManyToManyField in the first model referencing this new model. This way, the "multiple select" default field used in admin will be rendered. Life is good.
2- Create a custom field that saves my field as a string with some kind of separator.
These two approaches are summarized in What is the most efficent way to store a list in the Django models? and the 2nd approach in more examples: How to create list field in django, http://cramer.io/2008/08/08/custom-fields-in-django/, https://djangosnippets.org/snippets/1200/, https://djangosnippets.org/snippets/1491/
Fact is: I don't want to create another model just to have the ManyToManyField. This is a controlled list of choices that I have (and don't want people adding new items) and think that creating a table for this is overkill (although I can create a fixture to this table and not register the model in admin.py, so people wouldn't be adding new items. But I don't know how would migrations work when changing these values in fixtures, when in the past I would just chance the choices tuple in my model definition).
...and creating a new custom field, I don't know. This seems like problems in the long run since I don't know the implications, problems when upgrading Django, etc.
Why there isn't a built in ListField? Which problems do you see in the long run for the two approaches I'm thinking of? I'm planning to do the first but I'm a little lost about migrations.

A: django.contrib.postgres has an ArrayField.

A: You seem to not be willing to create a new table with only the List inside (because it would be "overkill"), but what you are suggesting is to copy/paste the same exact values in all the entries of your table, which isn't a good model solution in my opinion.
I'd advise to go for the ManyToMany (or any other implementation doing the trick with another table).


text:
Q: Что значит отмечать друзей в API Taggable Friends от Facebook? Фейсбук сейчас не дает доступа к полному списку друзей и предлагает как альтернативу использовать API Taggable Friends
на офф написано так

В версии 2.0 список друзей, не использующих ваше приложение, недоступен. Однако вы можете предоставить людям возможность отмечать друзей с помощью API Taggable Friends.

Что значит предоставить возможность отмечать друзей?

A: Те user-ы в вашем friend-list которые позволяют вам отмечать их на фотографиях, записях, отмечать в комметариях,
 Example: @userName
Зачастую вы получите весь список друзей так как по умолчанию они позволяют вам отмечать их.
Можете ознокомиться ближе с этим вопросом тут Facebook thread


text:
Q: Facebook Native Ads in RycyclerView android I found similar issue Facebook Native ads in recycler view android , but had some problems with integration with Custom Ad.
For the first I tried to describe NativeAdsManager :
  @Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    manager = new NativeAdsManager(getActivity(),    "892769720837476_892772047503910", 5);
    manager.setListener(this);
    manager.loadAds();

    nativeAd = new NativeAd(getActivity(), "892769720837476_892772047503910");
    nativeAd.setAdListener(this);
    nativeAd.loadAd();
...
 }

Then I included Native ad as a parameter in RecyclerAdapter constructor:
  adapter = new RecyclerAdapter(foodDataList, getActivity(), nativeAd);

In this Class I also implement AdListener and NativeAdsManager.Listener methods:
@Override
public void onError(Ad ad, AdError adError) {

}

@Override
public void onAdLoaded(Ad ad) {
}

@Override
public void onAdClicked(Ad ad) {

}

@Override
public void onAdsLoaded() {

    System.out.println("Loaded in fragment");
    nativeAd = manager.nextNativeAd();
    nativeAd.setAdListener(this);

    adapter.notifyDataSetChanged();

}

@Override
public void onAdError(AdError adError) {

}

After that in RecyclerAdapter  class :
   public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
    switch (holder.getItemViewType()) {
    ...
    case 2:
            AdditionalHolder new_holder = (AdditionalHolder) holder;
            adView = NativeAdView.render(context, nativeAd, NativeAdView.Type.HEIGHT_100);
            new_holder.templateContainer.addView(adView);
            return;

   ...
    public class AdditionalHolder extends RecyclerView.ViewHolder {
    protected LinearLayout templateContainer;

    public AdditionalHolder(View view) {
        super(view);

        templateContainer = (LinearLayout) view.findViewById(R.id.ad_test2);

    }
}

After  all of that  my Fragment with RecyclerView becomes very "luggy" and every time I can see more and more ads items (1 - from the beginning, 2 - after 10 items, 3 - after next 10 and so on).
It's  my first time of using multiple RecyclerView holders, and find this issue difficult.
Provide you  with gist  of  2 Classes
https://gist.github.com/burnix/6af8196ee8acf5c8f94e - RecyclerAdapter.class
https://gist.github.com/burnix/53dc2ed7446969b78f07 - FragmentList.class
Help me please to solve lugs problem and to place AudienceNetwork as it needs to be.
Thanks in advance!

A: After several hours of headache  I solved my problem.
I needed to change the constructor of RecyclerView:
  public RecyclerAdapter(List<FoodData> food, Context context, NativeAd  nativeAd, NativeAdsManager manager) {
    this.foodDataList = food;
    this.context = context;
    this.nativeAd = nativeAd;
    this.manager = manager;
}

And implement the behavior of Native Ads  in onBindViewHolder:
  AdditionalHolder new_holder = (AdditionalHolder) holder;
            try {
                new_holder.templateContainer.removeViewInLayout(adView);
            } catch (Exception e) {
                e.printStackTrace();
            }
            nativeAd = manager.nextNativeAd();
            try {
                adView = NativeAdView.render(context, nativeAd, NativeAdView.Type.HEIGHT_300);
            } catch (NullPointerException e) {
                e.printStackTrace();
            }

            new_holder.templateContainer.addView(adView);
            new_holder.blank_holder.setVisibility(View.GONE);

But it hasn't solved my problem entirely (micro-lags while scrolling), but still it could be useful for someone, I hoped.

A:        Youur adapter==>

        import android.app.Activity;
        import android.support.v7.widget.CardView;
        import android.support.v7.widget.RecyclerView;
        import android.util.Log;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.ImageView;
        import android.widget.LinearLayout;
        import android.widget.ProgressBar;

        import com.bumptech.glide.Glide;
        import com.bumptech.glide.load.resource.drawable.GlideDrawable;
        import com.bumptech.glide.request.RequestListener;
        import com.bumptech.glide.request.target.Target;
        import com.romantic.pictures.hd.love.wallpaper.download.R;
        import com.romantic.pictures.hd.love.wallpaper.download.activity.ROMANTIC_LOVE_WALLPAPER;
        import com.romantic.pictures.hd.love.wallpaper.download.model.ImageStorage;

        import java.util.ArrayList;

        /**
         * Created by abc on 4/11/2018.
         */

        public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

            public final int CONTENT_TYPE = 0;
            public final int AD_TYPE = 1;

            private OnItemClickListener mOnItemClickListener;
            Activity context;
            ArrayList<ImageStorage> catagorilist;

            public ImageAdapter(Activity context, ArrayList<ImageStorage> catagorilist, OnItemClickListener mOnItemClickListener) {
                this.mOnItemClickListener = mOnItemClickListener;
                this.context = context;
                this.catagorilist = catagorilist;
            }

            public interface OnItemClickListener {
                public void onItemClick(View view, int position);
            }

            @Override
            public int getItemViewType(int position) {
                Log.e("TAG", "getItemViewType position : " + position);
                Log.e("TAG", "getItemViewType position% : " + position % 5);

                if (position % 7 == 0)
                    return AD_TYPE;
                return CONTENT_TYPE;
            }

            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                switch (viewType) {
                    case CONTENT_TYPE:
                        Log.e("TAG", "content type : ");
                        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout2, parent, false);
                        return new MyHolder(view);

                    case AD_TYPE:
                        Log.e("TAG", "ad type : ");
                        View nativeView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_nativead, parent, false);
                        return new NativeAd(nativeView);
                    default:
                        Log.e("TAG", "default : ");
                        LayoutInflater inflater1 = LayoutInflater.from(parent.getContext());
                        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout2, parent, false);
                        return new MyHolder(v);
                }
            }

            @Override
            public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
                holder.setIsRecyclable(false);
                int viewType = getItemViewType(position);
                ImageStorage listitem = catagorilist.get(position);

                switch (viewType) {
                    case CONTENT_TYPE:
                        Log.e("TAG", "bind CONTENT_TYPE : ");
                        final MyHolder menuItemHolder = (MyHolder) holder;

                        //        holder.imagview.setText(listitem.getId());
                /*holder.cat_name.setText(listitem.getName());*/
                        Glide.with(context).load("http://learntodraw.in/ImageApp/new_" + listitem.getCat_imagem()).listener(new RequestListener<String, GlideDrawable>() {
                            @Override
                            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                                menuItemHolder.progressBar.setVisibility(View.GONE);
                                return false;
                            }
                        }).into(menuItemHolder.imagview);
                        Log.e("TAG", "onBindViewHolder: " + "http://learntodraw.in/ImageApp/new_" + listitem.getCat_imagem());
                        Log.e("TAG", "onBindViewHolder: " + position);

                        menuItemHolder.mainLayout.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mOnItemClickListener.onItemClick(v, position);
                            }
                        });

                        break;

                    case AD_TYPE:
                        Log.e("TAG", "bind AD_TYPE : ");
                        final NativeAd nativeHolder = (NativeAd) holder;
                        ROMANTIC_LOVE_WALLPAPER.showNativeVidAd(context, nativeHolder.container);

                        nativeHolder.container_height.post(new Runnable() {
                            public void run() {
        //                        int height = nativeHolder.container_height.getHeight();
                                ViewGroup.LayoutParams params = nativeHolder.container.getLayoutParams();
        //                        params.height = height;
                                params.height = LinearLayout.LayoutParams.WRAP_CONTENT;
                                nativeHolder.container.setLayoutParams(params);

                              //  nativeHolder.linearlayout_title.setVisibility(View.GONE);
                            }
                        });
                        break;
                }

            }

            @Override
            public int getItemCount() {
                return catagorilist.size();
            }

            public class MyHolder extends RecyclerView.ViewHolder {
                public ImageView imagview;
                public LinearLayout mainLayout;
                public CardView cardview;
                public ProgressBar progressBar;

                public MyHolder(View itemView) {
                    super(itemView);

                    imagview = (ImageView) itemView.findViewById(R.id.imagview);
                    mainLayout = (LinearLayout) itemView.findViewById(R.id.mainLayout);
                    progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar);
                    cardview = (CardView) itemView.findViewById(R.id.cardview);
                }
            }

            public static class NativeAd extends RecyclerView.ViewHolder {

                LinearLayout container;
                LinearLayout container_height;
        //        LinearLayout linearlayout_title;

                public NativeAd(View view) {
                    super(view);
                    container = view.findViewById(R.id.native_ad_container);
                    container_height = view.findViewById(R.id.container_height);
                   /* linearlayout_title = view.findViewById(R.id.linearlayout_title);*/
                }
            }

        }

public static void showNativeVidAd(final Activity context, final LinearLayout nativeContainer) {

        final NativeAd  nativeAd = new NativeAd(context, context.getString(R.string.fb_test_ad_img) + context.getString(R.string.native_ads3));
//        final NativeAd nativeAd = new NativeAd(context, context.getString(R.string.facebook_native_ad_unit_id));
        nativeAd.setAdListener(new com.facebook.ads.AdListener() {

            @Override
            public void onError(Ad ad, AdError error) {
                // Ad error callback
                Log.e("TAG", "facebook native error : " + error.getErrorMessage());
                nativeContainer.setVisibility(View.GONE);
            }

            @Override
            public void onAdLoaded(Ad ad) {
                // Ad loaded callback
                Log.e("TAG", "facebook native onAdLoaded : ");
                if (nativeAd != null) {
                    nativeAd.unregisterView();
                }

                try {
                    LinearLayout nativeAdContainer = nativeContainer;

                    nativeAdContainer.setVisibility(View.VISIBLE);
                    // Add the Ad view into the ad container.
                    nativeAdContainer = (LinearLayout) context.findViewById(R.id.native_ad_container);
                    LayoutInflater inflater = LayoutInflater.from(context);
                    // Inflate the Ad view.  The layout referenced should be the one you created in the last step.
                    RelativeLayout adView = (RelativeLayout) inflater.inflate(R.layout.custom_nativead, nativeAdContainer, false);

                    nativeAdContainer.removeAllViews();
                    nativeAdContainer.addView(adView);

                    // Create native UI using the ad metadata.
                    MediaView nativeAdMedia = (MediaView) adView.findViewById(R.id.native_ad_media);

                  /*  //TextView nativeAdSocialContext = (TextView) adView.findViewById(R.id.native_ad_social_context);
                    Typeface typeface = Typeface.createFromAsset(context.getAssets(), "ProximaNova-Semibold.otf");
                    nativeAdSocialContext.setTypeface(typeface);*/

//                    TextView nativeAdCallToAction = (TextView) adView.findViewById(R.id.native_ad_call_to_action);

                    // Set the Text.
//                    nativeAdSocialContext.setText(nativeAd.getAdSocialContext());
//                    nativeAdCallToAction.setText(nativeAd.getAdCallToAction());

                    // Download and display the ad icon.
                   // NativeAd.Image adIcon = nativeAd.getAdIcon();

                    // Download and display the cover image.
                    nativeAdMedia.setNativeAd(nativeAd);

                    // Add the AdChoices icon
                    LinearLayout adChoicesContainer = (LinearLayout) adView.findViewById(R.id.ad_choices_container);
                    AdChoicesView adChoicesView = new AdChoicesView(context, nativeAd, true);
                    adChoicesContainer.addView(adChoicesView);

                    // Register the Title and CTA button to listen for clicks.
                    List<View> clickableViews = new ArrayList<>();
//                    clickableViews.add(nativeAdCallToAction);
                    clickableViews.add(nativeAdMedia);
                    clickableViews.add(adChoicesContainer);
                    nativeAd.registerViewForInteraction(nativeAdContainer, clickableViews);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onAdClicked(Ad ad) {
                // Ad clicked callback
            }

            @Override
            public void onLoggingImpression(Ad ad) {
                // Ad impression logged callback
                Log.e("TAG", "facebook native onLoggingImpression");
            }
        });

        // Request an ad
        nativeAd.loadAd(NativeAd.MediaCacheFlag.ALL);
    }


text:
Q: Loopback v3 relation users model and other model structure I Have Events model and this model there is Speakers and Attendees, Attendees and Speakers are users in the application.
how i can do it with relation in LoopBack? like: get event with his speakers and attendees
and how i can assign Attendee to event?

A: An Event could have one/Many speakers and many attendees, so the event relation should be like below
event.json
  "relations": {
    "speakers": {
      "type": "hasMany",
      "model": "Speaker",
      "foreignKey": ""
    },
    "attendees": {
      "type": "hasMany",
      "model": "Attendee",
      "foreignKey": ""
    }
  }

The speaker belongsTo to an event :
speaker.json
"relations": {
    "event": {
      "type": "belongsTo",
      "model": "Event",
      "foreignKey": ""
    }
  }

and finally an attendee belongs to an event
attendee.json
"relations": {
    "event": {
      "type": "belongsTo",
      "model": "Event",
      "foreignKey": ""
    }
  }

Putting the relations above will give you new endpoints in your explorer, now you can assign an attendee to an event using the POST method like below.
PS: Do not create the Attendee ID since the idInjection is TRUE so it will be created automatically just assign the eventId
{
  "name": "string",
  "id": "string",
  "eventId": "string"
}

Note that you don't have to create a foreign key since loopback will
  target the default id of each related model only if you need to use
  custom ones.

UPDATE
To make it work on the built in USER Model, we should extend it first.
To extend the user model we should create a new one :

*

*slc loopback:model

*name it user (lowercase) because loopback is using User, or just pick any other name as customUser or whatever.

*Select your datasource

*Select User the model's base class this one will override the the built in User model

*Expose via the REST API : (yes or no) as you wish

Once the model is created, edit the  config-model.json and disable the built in User model.
Add this property to User : "public": false (this will disable User from being shwon in the explorer)
"User": {
"dataSource": "MongoDs",
"public": false
}

Add Relation in event.json with the new user model
"relations": {
    "users": {
      "type": "hasMany",
      "model": "user",
      "foreignKey": ""
    }
  }

Add Relation user.json with Event model
  "relations": {
    "event": {
      "type": "belongsTo",
      "model": "Event",
      "foreignKey": ""
    }

Now you can assign a user to an event. However to assign a speaker or an attendee you should create type field like "type" : { "type": "string"} which could be "attendee" / "speaker"
To find users from your event model use this filter : {include: 'users'} in your find() function.


text:
Q: What is the abstract definition of an iteration? There are lots of iterated processes in mathematics. The basic example in arithmetic is where you obtain addition through iterating successor operator and multiplication by iterating addition and exponentiation by iterating multiplication and so on.

I look for an abstract (set/category theoretic) definition of the notion of iteration in mathematics if there is any (please provide references); a definition which covers almost all forms of iteration in mathematics. Can it be viewed as an operator itself?

A: I think that definition by recursion, in its various forms, is what you're looking for. I'll talk about definition by recursion from two angles: computability-theoretic and set-theoretic.

In the context of the natural numbers, there are many forms of recursion, beginning with primitive recursion (which is enough to build addition from successor, multiplication from addition, exponentiation from multiplication, tetration from exponentiation, etc.), and ending with $\mu$-recursion. One major topic in computability theory (often under the name "subrecursive hierarchies") is what functions can be built from a "starting set" using some fixed recursion principle; for example, $\mu$-recursion lets us build every computable function just starting with (essentially) successor, the projection functions, and the constant function $x\mapsto 0$, while primitive recursion can build lots of functions from these basic ingredients (addition, multiplication, exponentiation, tetration, ... the vast majority of functions on natural numbers which appear in practice are primitive recursive) but misses things like the Ackermann function.
Between primitive recursion and $\mu$-recursion is a vast swath of notions of recursiveness, and lots of research has gone into understanding this area and its various well-behaved subhierarchies. There is, however, a fundamental gap between primitive and $\mu$-recursion which prevents any "reasonable" hierarchy from "going all the way": namely, the primitive recursive functions are effectively listable and total, which means we can "diagonalize out of them:" letting $\psi(n)=1+p_n(n)$, where $p_n$ is the $n$th primitive recursive function in some fixed effective listing, yields a computable function which is not primitive recursive. Similarly, every level of the fast-growing hierarchy can be diagonalized out of. The $\mu$-recursive functions don't fall prey to this, since - while they are effectively listable - they aren't all total, and in fact we can't separate out the total ones from the partial ones.
Indeed, no good hierarchy for the computable functions in general is known, and in fact there are various results pointing towards the nonexistence of such a hierarchy.

Going far more generally, we can look at arbitrary definitions by transfinite recursion. The single-variable version goes as follows.
Suppose $\lambda$ is an ordinal and $X$ is some set (the codomain; often $\lambda$ itself). Let $F_{\lambda, X}$ denote the set of functions from some proper initial segment of $\lambda$ to $X$; an element of $F_{\lambda, X}$ can be thought of as a part of a whole function $\lambda\rightarrow X$.
Now suppose $I$ is a function from $F_{\lambda, X}$ to $X$; the idea being that when we feed $I$ some map $p: \alpha\rightarrow X$ ($\alpha<X$), $I$ tells us how to extend this map to one more value (namely, to a map $p': \alpha+1\rightarrow X$). We now intuitively want to define a map $f_I:\lambda\rightarrow X$ by iteratively applying $I$ at successor steps, and taking unions at limit steps.
We can in fact prove that this is always possible, and in a unique way:

Whenever $\lambda, X, I$ are as above, there is a unique map $f_I:\lambda\rightarrow X$ such that for all $\alpha<\lambda$, $f_I(\alpha)=I(f_I\upharpoonright\alpha)$.

The $n$-variable version of transfinite recursion is basically identical: we now have $n$-many iterators, $I_1, ...,I_n$; $I_i$ tells us how to define $f_{I_1, ..., I_n}(a_1, ...,a_i+1, ...,  a_n)$ having already defined $f_{I_1, ..., I_n}(b_1, ..., b_n)$ for all $b_i\le a_i$. (This is similar to induction on multiple variables simultaneously; indeed induction is the proof technique corresponding to the construction method of recursion.)
Again, there is a unique "solution" for each $\lambda, X, I_1, ..., I_n$, and this lets us e.g. define ordinal exponentiation in terms of ordinal multiplication and so forth. The details are messier to write down, though.
We can generalize this to arbitrary well-founded partial orders, not just ordinals - this is a transfinite version of structural induction. This is the most general notion of recursive definition that I'm aware of.
(We can also treat class-sized domains - e.g. we can define a class function on the ordinals, by recursion on the ordinals. Nothing new happens here, we just need to say "class function" instead of "function," and so forth - the usual stuff.)

As a coda, there are also category-theoretic takes on definition by recursion; but I'm basically illiterate here, so I'll just point vaguely at some sources.
I think that this text by Moss and Danner on definition by corecursion is a very good source in this direction. Let me also point to this paper of Milius and Moss, which discusses this in more detail and mentions a number of interesting sources. Also see this text by Rutten on coinduction, which can be thought of as an interesting alternate approach to definition by recursion. And the keyword "monad" is going to show up a lot when looking at recursive definitions from a category-theoretic perspective.
It's worth noting that when approaching recursion from a more algebraic perspective (and so, often in category theory), we're frequently interested in less generality than that above: not all recursions are created equal, and the ones with "appropriate structure" are often a very proper subset of all the things a computability- or set-theorist would call "recursion." Category theory doesn't always try to make things maximally general; I'd say rather that it looks for the right amount of generality, and that's often less than full.


text:
Q: Could not resolve androidx.appcompat:appcompat:1.5.1 - Error with Gradle in Android Studio I try to update my AppCompat library from 1.0.0 to 1.5.1 in the Gradle file and I got this error
Could not resolve androidx.appcompat:appcompat:1.5.1.
Required by:
    project :app

Possible solution:
 - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html

I try to update the library, but I always get errors.
This is the content of my Gradle file
buildscript {
ext {
    kotlin_version = '1.7.10'
}
repositories {
    jcenter()
    google()
    //maven { url 'https://maven.fabric.io/public' }
    //maven { url "https://maven.google.com" }
}
dependencies {
    classpath 'com.android.tools.build:gradle:7.2.2'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    classpath 'com.google.gms:google-services:4.3.10'
    classpath 'com.google.firebase:firebase-crashlytics-gradle:2.7.1'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
       jcenter()
        google()
    }
}

How I can fix this error?

A: I don't know why, but I try to use the code below
implementation group: 'com.google.android.material', name: 'material', version: '1.6.1'

instead of
implementation 'com.google.android.material:material:1.0.0'

and it works for me now to import the last app compat library without problems
implementation 'androidx.appcompat:appcompat:1.5.1'

Now I was able to import the library without problems


text:
Q: Xamarin - How to add a custom small pop up on each item image click on collectionView in Android & iOS I have a collection view, which will displays the list of items. In each item, i have a image button, on clicking on that image button I need to display a control,which display something like below image(a small pop up kind or custom toolbar item control which list few items for me to select on each item click), also looking for the co-ordinates should map with where the user clicked.

Is there any way we can implement the control on xamarin in collection view?

A: You should be able to implement what you have in mind by using an AbsoluteLayout. You can take inspiration from this example, which implements an overlay that displays an ActivityIndicator for loading. Instead of the ActivityIndicator, you can create a StackLayout with the fields Properties, Add to Favorites, and Share, and set the coordinates of the StackLayout to those of the point clicked by the user.


text:
Q: Recreate Az.Connect-AzAccount in c# PowerShell has a great function in the Az.Accounts library - "Connect-AzAccount" - that allows me to authenticate against my Azure instance and publish APIM's easily.  I need to port the code over to c# and am unable to find an easy equivalent.
Has anyone found a straightforward way to do this?  The Azure world / libraries seem to be updating frequently, along with the many security aspects.  It's difficult to find a recent, relevant example.
My ultimate goal is to authenticate against Azure, then publish API's to the API Gateway.
The PowerShell code:
$user = "account@domain.com"
$password = ConvertTo-SecureString -String "password goes here" -AsPlainText -Force

$azAccount = @{
    subscription = "subscription-guid-goes-here"
    credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $user,$password
}

Connect-AzAccount @azAccount

A: Currently, Azure Management Library for .NET can only be used to manage partial Azure resources. However, Azure API Management is not included.
So, I suggest you use Azure REST API to manage your resources.
As Azure REST APi is protected under Azure AD. So, the first step is to acquire an accesstoken for authentication.
Here is a sample by using Microsoft.IdentityModel.Clients.ActiveDirectory package
static string GetToken()
{
    string tenantId = "your tenant id or name, for example: hanxia.onmicrosoft.com";
    string clientId = "1950a258-227b-4e31-a9cf-717495945fc2"; // it is a public client for every tenant.
    string resource = "https://management.core.windows.net/";
    string username = "user name, jack@hanxia.onmicrosoft.com";
    string password = "password, D******";

    var upc = new UserPasswordCredential(username, password);
    var context = new AuthenticationContext("https://login.microsoftonline.com/" + tenantId);
    AuthenticationResult result = context.AcquireTokenAsync(resource, clientId, upc).Result;
    return result.AccessToken;
}

After that, you can call Azure REST API along with adding authorization header. Here is a POST request sample:
public static string postRequest(string url, string access_token, string data)
{
    byte[] buffer = null;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "post";
    request.ContentType = "application/json";
    request.Headers.Add("Authorization", "Bearer " + access_token);
    //request.Headers.Add("other header", "it's value");
    if (data != null)
        buffer = Encoding.UTF8.GetBytes(data);
    else
        buffer = Encoding.UTF8.GetBytes("");
    request.ContentLength = buffer.Length;
    request.GetRequestStream().Write(buffer, 0, buffer.Length);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
    {
        return response.StatusCode + " " + reader.ReadToEnd();
    }
}

A: the existing answer is a bit odd, its linking some old depreciated library. Official library supports "managing" Api Management. That would be the preferred way of managing Azure resources with C# and you dont have to recreate anything.


text:
Q: Python 3.x session, class, and serialization EDIT: I wonder if you think the issue might be that I'm trying to store an entire dictionary row returned from database in a session variable?
Here's the error (full error printout is at bottom of this post):
TypeError: Object of type User is not JSON serializable

FYI: I'm not using JSON anywhere in my code.
Here's the relevant parts of my code (main.py):
class User():
    def __init__(self, t_id_user=None, t_email=None):
        self.t_id_user = t_id_user
        self.t_email = t_email

    def create_or_update(self, t_create_or_edit="Edit"):
        #How necessary are the "=None" below?
        #self.t_id_user = userCreate(self, t_id_user=None, t_email=None):
        #How necessary are the "=None" above?
        if t_create_or_edit == "Create":
            self.t_id_user = userCreate(
                self.t_email
                )
        else:
            self.t_id_user = userUpdate(
                self.t_id_user_edit,
                self.t_email
                )

    def get_from_id(self, t_id_user):
        # logic to retrieve your user's data from your database of choice
        myData = usersGet(
            t_id_user="0",
            t_email=""
            )
        self.t_id_user = myData["t_id_user"]
        self.t_email = myData["t_email"]
        return self

def userClearSession(t_which="user_current"):
    logging.debug("Start of userClearSession()")
    t_id_user = "0"
    t_email = ""
    user_instance = User(t_id_user, t_email)
    if t_which == "user_current":
        session["user_current"] = user_instance
    else:
        session["user_edit"] = user_instance
    return

@app.route('/', methods=['GET', 'POST'])
@app.route('/userRegister', methods=['GET', 'POST'])
def index(t_title="Login or Register", t_message=""):
    if "user_current" not in session:
        userClearSession(t_which="user_current")
    return render_template(
        "userRegister.html",
        t_message=t_message,
        t_js="userRegister.js",
        t_title=t_title
        )

def userCreate(t_which="current"):
    id_user = 0
    db_cursor = data_cursor()
    q = ""
    q += "INSERT INTO tbl_users "
    q += " ( "
    q += " i_security_level"
    q += ", t_email"
    q += " ) "
    q += " VALUES "
    q += " ( "
    q += " %(t_security_level)s"
    q += ", '%(t_email)s'"
    q += " ) "
    try:
        if t_which == "current":
            user_instance = session["user_current"]
        else:
            user_instance = session["user_edit"]
        vars = {
            't_security_level': int(session["user_instance"].t_security_level),
            't_email': AsIs(session["user_instance"].t_email)
            }
        db_cursor.execute(q,vars)
    except Exception as e:
        t_message = "Error"
    else:
        id_found = userIsInDB(session["user_instance"].t_email)
        if id_found >= 1:
            t_id_user = id_found
            if t_which == "current":
                session["user_current"].t_id_user = t_id_user
            else:
                session["user_edit"].t_id_user = t_id_user
        t_message = "User Created"
    db_cursor.close()
    db_conn.close()

The full error message:
I'm having a hard time getting any meaning out of this error message and need help. It doesn't appear to point to any parts of main.py, though I know the error is somewhere in there and I'm pretty sure I narrowed it down to the code you see above:
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python\Python38\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 1953, in full_dispatch_request
return self.finalize_request(rv)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 1970, in finalize_request
response = self.process_response(response)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2269, in process_response
self.session_interface.save_session(self, ctx.session, response)
File "C:\Python\Python38\Lib\site-packages\flask\sessions.py", line 378, in save_session
val = self.get_signing_serializer(app).dumps(dict(session))
File "C:\Python\Python38\Lib\site-packages\itsdangerous\serializer.py", line 166, in dumps
payload = want_bytes(self.dump_payload(obj))
File "C:\Python\Python38\Lib\site-packages\itsdangerous\url_safe.py", line 42, in dump_payload
json = super(URLSafeSerializerMixin, self).dump_payload(obj)
File "C:\Python\Python38\Lib\site-packages\itsdangerous\serializer.py", line 133, in dump_payload
return want_bytes(self.serializer.dumps(obj, **self.serializer_kwargs))
File "C:\Python\Python38\Lib\site-packages\flask\json\tag.py", line 305, in dumps
return dumps(self.tag(value), separators=(",", ":"))
File "C:\Python\Python38\Lib\site-packages\flask\json\__init__.py", line 211, in dumps
rv = _json.dumps(obj, **kwargs)
File "C:\Python\Python38\Lib\json\__init__.py", line 234, in dumps
return cls(
File "C:\Python\Python38\Lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python\Python38\Lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Python\Python38\Lib\site-packages\flask\json\__init__.py", line 100, in default
return _json.JSONEncoder.default(self, o)
File "C:\Python\Python38\Lib\json\encoder.py", line 179, in default
Open an interactive python shell in this frameraise TypeError(f'Object of type {o.__class__.__name__}


text:
Q: How does Boxed closure calls work just like closure calls? Why does calling boxed closures work just like calling closures? Is it because of Deref implementation of Box ? Would it work on all smart pointers? As I tried some examples to better understand it, I get the following error.
fn main() {
    let mut x = String::new();
    let y = || {
        let t = &mut x;
    };
    let mut ww = Box::new(y);
    (&mut ww)();
}

This throws an error
error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnMut`
  --> src/main.rs:22:13
   |
22 |     let y = || {
   |             ^^ this closure implements `FnMut`, not `Fn`
23 |         let t = &mut x;
   |                      - closure is `FnMut` because it mutates the variable `x` here
...
26 |     (&mut ww)();
   |     ----------- the requirement to implement `Fn` derives from here

Any documentation on how boxed closures work would be helpful as well.

A: Box implements all FnX traits since Rust 1.35 (more info here, source), so it should be callable.
Looks like in this particular case the compiler is not smart enough to deref and cast your type which is &mut Box<Closure> into expected Box<impl FnMut() -> ()> to perform the call directly.
This works though:
(ww as Box::<dyn FnMut() -> ()>)();

And this works too:
ww.as_mut()()