text:
Q: How to reference a class blueprint as an argument in a function while specifying the class' arguments? The following is the set-up.
class SomeClass():
    def __init__(self):
        pass

    def some_func1(self, paramA):
        some_input = paramA
        print(some_input)

class SomeOtherClass():
    def __init__(self, param1, param2):
        self.param1 = param1
        self.param2 = param2

obj = SomeClass()

# Scenario #1
some_var = obj.some_func1(paramA=SomeOtherClass)
# <class '__main__.SomeOtherClass'>

# Scenario #2
some_other_var = obj.some_func1(paramA=SomeOtherClass(param1='val1', param2='val2'))
# <__main__.SomeOtherClass object at 0x000002576E88FD60>

The problem is in my actual example, none of these two configurations works. In Scenario #1, SomeOtherClass is referenced for the some_func1's paramA argument. In Scenario #2, the required arguments to instantiate SomeOtherClass were specified, but the problem is I do NOT want to instantiate it at the argument level.
How can I reference (and not instantiate) the SomeOtherClass with specified parameter values, as a value of a function's argument?

A: An easy way to delay evaluation of something (including object instantiation) is to wrap it in a lambda:
class SomeClass():
    def some_func1(self, thunk):
        """thunk: a callable that takes no args and constructs an object."""
        print(thunk)
        obj = thunk()  # this actually instantiates the object
        print(obj)

class SomeOtherClass():
    def __init__(self, param1, param2):
        self.param1 = param1
        self.param2 = param2

obj = SomeClass()

some_var = obj.some_func1(lambda: SomeOtherClass('val1', 'val2'))

If you needed the class and the params as distinct args for some other purpose, you could do:
def some_func1(self, obj_class, *params):
    print(obj_class, params)
    obj = obj_class(*params)
    print(obj)

some_func1(SomeOtherClass, 'val1', 'val2')


text:
Q: Loop through database and display them in new file I have this script that loops through the database and displays all of it's contents.
$select_report = $conn->prepare("SELECT test_db FROM report");
$select_report->execute();
while ($result_report = $select_report->fetch(PDO::FETCH_ASSOC)){
   echo $result_report["test_db"];
}

My question is, can I create a HTML file that has the looped content?
I tried using this script but it only displays the last row in the generated HTML file.
$select_report = $conn->prepare("SELECT test_db FROM report");
$select_report->execute();
while ($result_report = $select_report->fetch(PDO::FETCH_ASSOC)){
   $html_report = "
                <!DOCTYPE html>

                <title>Sales report

                             test

                             ". $result_report["test_db"] ."

                  ";
$myfile = fopen("report - ".date("m, d, s").".html", "w") or die("Unable to open file!");
fwrite($myfile, $html_report);
fclose($myfile);
}

IMAGE:
generated html table

A: Looks like you are recreating the table for each row. Only the TR part in the body needs to be manipulated.

A: It is all a matter of just looping the items (in this case table rows) that need to be looped:
$select_report = $conn->prepare("SELECT test_db FROM report");
$select_report->execute();
$html_report = "
                <!DOCTYPE html>

                <title>Sales report

";

while ($result_report = $select_report->fetch(PDO::FETCH_ASSOC)){
   // concatenate rows
   $html_report .= "

                             test

                             ". $result_report["test_db"] ."

";
}
// outside of loop
$html_report .= "

                  ";

$myfile = fopen("report - ".date("m, d, s").".html", "w") or die("Unable to open file!");

fwrite($myfile, $html_report);
fclose($myfile);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to drive MCU pin high I'm trying to drive a MCU input with a RS-485 driver chip, specifically the SP3485 on the SparkFun RS-485 transceiver breakout.
When I connect the MCU pin directly to the 3.3V power rail, the pin reads 3.3V and an ammeter shows 6.8 uA of current going into the pin.
I assert the RS-485 signal and measure the voltage at the SP3485 receiver output (RO) pin with the pin floating (disconnected from the MCU). I see 3.3V.
When I connect the RO pin to the MCU the MCU pin is only driven to 1V and the ammeter shows 3.7 uA of current going into the pin.
What is going on? Surely the RO output pin isn't current-limited to 3.7 uA?

A: What have you done with the pin on the Spark Fun breakout called "RTS"?
If this signal is high at ~3.3V the RO pin of the SP3485 will be tri-stated and highly likely lead to the situation you are seeing on your MCU input at 1V.

Picture Source


text:
Q: How can I fix this searchbar error in django? I'm trying to create a searchbar in my blog in python, but I'm receiving the following error: Reverse for 'article-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['app1/article/(?P[0-9]+)$'] and I'm not sure why, so here's the code so you guys can see what's going on here:
Traceback
Traceback (most recent call last):
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\snin2\Desktop\basura\lapagina\app1\views.py", line 187, in searchbar
    return render(request, 'app1/search.html', {'query':query, 'results':results})
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\backends\django.py", line 61,
in render
    return self.template.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 170, in render
    return self._render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 162, in _render
    return self.nodelist.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\loader_tags.py", line 150, in
render
    return compiled_parent._render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 162, in _render
    return self.nodelist.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\defaulttags.py", line 312, in
render
    return nodelist.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\defaulttags.py", line 211, in
render
    nodelist.append(node.render_annotated(context))
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\defaulttags.py", line 446, in
render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\urls\base.py", line 87, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'article-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['app1/article/(?P<pk>[0-9]+)$']

Models.py
class StockNames(models.Model):
    name = models.CharField(max_length=255)
    symbol = models.CharField(max_length=255)

    def __str__(self):
        return self.symbol

class Post(models.Model):
    title = models.CharField(max_length= 255)
    header_image = models.ImageField(null = True, blank = True, upload_to = 'images/')
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = RichTextField(blank = True, null = True)
    #body = models.TextField()
    post_date = models.DateField(auto_now_add=True)
    category = models.CharField(max_length=255, default='coding')
    snippet = models.CharField(max_length=255)
    likes = models.ManyToManyField(User, related_name = 'blog_posts')
    stock = models.ForeignKey(StockNames, null=True, on_delete = models.CASCADE)

    def total_likes(self):
        return self.likes.count()

    def __str__(self):
        return self.title + ' | ' + str(self.author)

    def get_absolute_url(self):
        return reverse('app1:article-detail', args=(self.id,))

Views.py
def searchbar(request):
    query = None
    results = []
    if request.method == 'GET':
        query=request.GET.get("search")
        results= Post.objects.filter(Q(title__icontains=query) | Q(stock__symbol__icontains=query))
    return render(request, 'app1/search.html', {'query':query, 'results':results})

search.html
{% extends "app1/base.html" %}
    {% block body_block %}

Search Page

        {% if query %}

{% with results.count as total_results %}
            Found {{total_results}} total results
            {% endwith %}

        {% for x in results %}

{{sym}} -
            {{post.author}} - {{post.post_date}} -
            {% if user.is_authenticated %}
            Edit
            - Delete

            {% endif %}

    {% empty %}

There's no query

    {% endfor %}
    {% else %}

Error in your query

    {% endif %}

    {% endblock %}

base.html (specifically the search input)
<form action="{% url 'app1:searchbar' %}" class="form-inline my-2 my-lg-0" method="GET">
   <input name="search" class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search", name='search'>
   <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>

urls.py (the last one)
app_name = 'app1'

urlpatterns = [
    path('post/', PostView.as_view(), name = 'Post'),
    path('article/<int:pk>', ArticleDetailView.as_view(), name = 'article-detail'),
    path('add_post/<str:sym>',AddPostView.as_view(), name='addpost'),
    path('update_post/<int:pk>', UpdatePostView.as_view(), name = 'updatepost'),
    path('delete_post/<int:pk>', DeletePostView.as_view(), name = 'deletepost'),
    path('add_category/', AddCategoryView.as_view(), name = 'add_category'),
    path('category/<str:cats>/', views.CategoryView, name = 'category'),
    path('category-list/', views.CategoryListView, name ='category-list'),
    path('like/<int:pk>/', views.LikeView, name = 'like_post'),
    path('my_posts/', views.MyPostsView.as_view(), name = 'my_posts'),
    path('article/<int:pk>/add_comment/', AddCommentView.as_view(), name = 'add_comment'),
    path('update_comment/<int:pk>', UpdateCommentView.as_view(), name = 'updatecomment'),
    path('delete_comment/<int:pk>', DeleteCommentView.as_view(), name = 'deletecomment'),
    path('stock/<str:sym>/', views.StockView, name = 'stock'),
    path('searchbar/', views.searchbar, name = 'searchbar'),

]

Thanks in advance!

A:     {% for post in results %}

{{sym}} -
      {% if user.is_authenticated %}
    Edit
    - Delete

    {% endif %}

A:

here 'post' is not declared/contexted/retrieved from db.thats why you are getting error.


text:
Q: Store 'Data' in a HashMap after every Test Execution (TestNG Class)? Is it possible to store all test cases which have failed in a hashmap, and then call all values stored in the map at the end of a class?
Variable:
    private HashMap<String, Integer> serverStatusMap = new HashMap<String, Integer>();

After Method Code:
    @AfterMethod
public void trackServerStatus(ITestResult testResult) {
    if (testResult.getStatus() == ITestResult.FAILURE) {
        try {
            String testName = this.getClass().getSimpleName().toString();
            int serverStatus = ServerStatus.getResponseCode(basePage.getCurrentURL());
            int i = 0;
            while(i < serverStatusMap.size()) {
                serverStatusMap.put(testName, serverStatus);
                i++;
            }
            //serverStatusMap.put(testName, serverStatus);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Calling the stored values in the map After class:
    @AfterClass
public void sendEmailBasedOnFailure(ITestContext context) throws WebDriverException, Exception {
    String tempTime = new SimpleDateFormat("hh.mm.ss").format(new Date());

    if(context.getFailedTests().size() > 0) {
        SendEmailFile.sendEmailReport(
                "TIME: " + tempTime + " | " + this.getClass().getPackage().toString(),

                "TIME: " + tempTime + " | " + this.getClass().getPackage().toString() + " | " + "CLASS NAME: "
                        + this.getClass().getSimpleName().toString() + "\n\n" +
                        "TOTAL NUMBER FAILED TESTS: " + context.getFailedTests().size() + "\n\n" +
                        "FAILED TEST CASES: " + context.getFailedTests().getAllMethods().toString() + "\n\n" +
                        serverStatusMap.toString());
    }

Look at the last line of code: 'serverStatusMap.toString()'
Current Output of the Map:
{}

A: I do not understand what you are trying to do.
Do you want to send an email with failed tests?
Why not using the appropriate features like Listener or Reporter?
Have a look on the documentation about logging.

A: You have initialized variable "serverStatusMap". From below code
int i =0;
while(i < serverStatusMap.size()) {
                serverStatusMap.put(testName, serverStatus);
                i++;
            }

I can see that i=0 and also serverStatusMap.size()=0. So it will never enter in while loop. so Finally when you print map there is nothing inside map. You need to change your while condition.


text:
Q: my choices over javascript framework and javascript UI libraries I heard many people say if you're looking for a Javascript UI library to be used with jQuery, it's best to go for jQuery UI.
My question here is: is there any other combinational option for me for other javascript frameworks apart from jQuery and js ui libraries to recommend? I just would like to explore more in their ui enhancement capabilities and that can definitely be my alternative ways in web development.
any advice would be really much appreciated!

A: MooTools is quite elegant. see http://mootools.net/


text:
Q: How can an Interlaced .png file's size be smaller than the original file? Ok, so I tried to use the imagemagick command:
"convert picA.png -interlace line picB.png"

to make an interlace version of my .png images. Most of the time, I got the resulting image is larger than the original one, which is kinda normal. However, on certain image, the resulting image size is smaller.
So I just wonder why does that happen? I really don't want my new image to lose any quality because of the command.
Also, is there any compatibility problem with interlaced .png image?
EDIT: I guess my problem is that the original image was not compressed as best as it could be.

A: The following only applies to the cases where the pixel size is >= 8 bits. I didn't investigate for other cases but I expect similar outcomes.
A content-identical interlaced PNG image file will almost always be greater because of the additional data for filter type descriptions required to handle the passes scanlines. This is what I explained in details in this web page based on the PNG RFC RFC2083.
In short, this is because the sum of the below number of bytes for interlaced filter types description per interlacing pass is almost always greater than the image height (which is the number of filter types for non-interlaced images):
nb_pass1_lines = CEIL(height/8)

nb_pass2_lines = (width>4?CEIL(height/8):0)

nb_pass3_lines = CEIL((height-4)/8)

nb_pass4_lines = (width>2?CEIL(height/4):0)

nb_pass5_lines = CEIL((height-2)/4)

nb_pass6_lines = (width>1?CEIL(height/2):0)

nb_pass7_lines = FLOOR(height/2)

Though, theoretically, it can be that the data entropy/complexity accidentally gets lowered enough by the Adam7 interlacing so that, with the help of filtering, the usually additional space needed for filter types with interlacing may be compensated through the deflate compression used for the PNG format. This would be a particular case to be proven as the entropy/complexity is more likely to increase with interlacing because the image data is made less consistent through the interlacing deconstruction.
I used the word "accidentally" because reducing the data entropy/complexity is not the purpose of the Adam7 interlacing. Its purpose is to allow the progressive loading and display of the image through a passes mechanism. While, reducing the entropy/complexity is the purpose of the filtering for PNG.
I used the word "usually" because, as shown in the explanation web page, for example, a 1 pixel image will be described through the same length of uncompressed data whether interlaced or not. So, in this case, no additional space should be needed.
When it comes to the PNG file size, a lower size for interlaced can be due to:

*

*Different non-pixel encoding related content embedded in the file such as palette (in the case of color type =! 3) and non-critical chunks such as chromaticities, gamma, number of significant bits, default background color, histogram, transparency, physical pixel dimensions, time, text, compressed text. Note that some of those non-pixel encoding related content can lead to different display of the image depending on the software used and the situation.

*Different pixel encoding related content (which can change the image quality) such as bit depth, color type (and thus the use of palette or not with color type = 3), image size,... .

*Different compression related content such as better filtering choices, accidental lower data entropy/complexity due to interlacing as explained above (theoretical particular case), higher compression level (as you mentioned)

If I had to check whether 2 PNG image files are equivalent pixel wise, I would use the following command in a bash prompt:
diff <( convert non-interlaced.png rgba:- ) <( convert interlaced.png rgba:- )

It should return no difference.
For the compatibility question, if the PNG encoder and PNG decoder implement the mandatory aspects of the PNG RFC, I see no reason for the interlacing to lead to a compatibility issue.
Edit 2018 11 13:
Some experiments based on auto evolved distributed genetic algorithms with niche mechanism (hosted on https://en.oga.jod.li ) are explained here:
https://jod.li/2018/11/13/can-an-interlaced-png-image-be-smaller-than-the-equivalent-non-interlaced-image/
Those experiments show that it is possible for equivalent PNG images to have a smaller size interlaced than non-interlaced. The best images for this are tall, they have a one pixel width and have pixel content that appear random. Though, the shape is not the only important aspect for the interlaced image to be smaller than the non-interlaced image as random cases with the same shape lead to different size differences.
So, yes, some PNG images can be identical pixel wise and for non-pixel related content but have a smaller size interlaced than non-interlaced.

A:
So I just wonder why does that happen?

From section Interlacing and pass extraction of the PNG spec.

Scanlines that do not completely fill an integral number of bytes are padded as defined in 7.2: Scanlines.
NOTE If the reference image contains fewer than five columns or fewer than five rows, some passes will be empty.

I would assume the behavior your experiencing is the result of the Adam7 method requiring additional padding.


text:
Q: Visualforce Error , unexpected token list How can I resolve this issue?
Error

Visualforce Error , unexpected token list

Page
<apex:page controller="CustomPagination">
    <apex:form>
        <apex:pageBlock title="Custom Pagination of Lead List">
            <apex:pageblockTable value="{!AllLead}" var="cl" >
                <apex:column value="{!cl.firstName}"/>
                <apex:column value="{!cl.lastName}"/>
                <apex:column value="{!cl.company}"/>
                <apex:column value="{!cl.phone}"/>
                <apex:column value="{!cl.status}"/>
            </apex:pageblockTable>
            <apex:pageBlockButtons >
                <apex:commandbutton value="First Page" action="{!first}"/>
                <apex:commandbutton value="<< Previous" action="{!previous}"/>
                <apex:commandbutton value="List" action="{!list}"/>
                <apex:commandbutton value="Next >>" action="{!Next}"/>
                <apex:commandbutton value="Last Page" action="{!last}"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller
public with sharing class CustomPagination{
    integer counter;

        public void previous(){
            if(counter>10) counter=counter-10;
            else counter=0;
        }

        public void next(){
            counter=counter+10;
        }

        public list<lead> getAllLead(){
        list<lead> AllLead=[select id, firstName, lastName, company, phone, status from lead limit 15 offset:counter];
        return AllLead;
        }

}

A: You have several bindings which correspond to nothing on your controller:

*

*first

*last

*list
For each of these, you must define a method. I suggest you just expose a StandardSetController. There's little benefit to writing your own pagination here.
public with sharing class MyController
{
    public ApexPages.StandardSetController controller { get; private set; }
    public MyController()
    {
        controller = new ApexPages.StandardSetController([
            SELECT ... FROM Lead
        ]);
        controller.setPageSize(15);
    }
}

Then in your markup, you just bind to controller instead:

*

*<apex:pageBlockTable value="{!controller.records}" var="lead" />

*<apex:commandButton value="First Page" action="{!controller.first}" />

*<apex:commandButton value="<<" action="{!controller.previous}" />

*<apex:commandButton value="List" action="{!controller.list}" />

*<apex:commandButton value=">>" action="{!controller.next}" />

*<apex:commandButton value="Last Page" action="{!controller.last}" />
Another benefit is that you can add disabled properties for next and previous if those options should not be available:
<apex:commandButton value="<<"
                    action="{!controller.previous}"
                    disabled="{!NOT(controller.hasPrevious)}" />

A: The line
<apex:commandbutton value="List" action="{!list}"/> is not pointing to a method or variable that exists. That is your problem.
PS: You might want to consider using Standard Set Controllers for your use-case. Read here.


text:
Q: Model binding in MVC core from KnockoutJS I'm following the Pluralsight 'Parent-Child with EF, MVC, Knockout' course which was written for MVC4. I'm working against MVC Core and am banging my head against what I think is a model binding problem on a POST back to the server.
My Controller:
        public JsonResult Save(SalesOrderViewModel salesOrderViewModel)
    {
        if (ModelState.IsValid)
        {
            var salesOrder = new SalesOrder();
            salesOrder.CustomerName = salesOrderViewModel.CustomerName;
            salesOrder.PONumber = salesOrderViewModel.PONumber;
            _context.SalesOrder.Add(salesOrder);
            _context.SaveChanges();

            return Json(JsonConvert.SerializeObject(salesOrderViewModel));
        }
        else
        {
            return Json(JsonConvert.SerializeObject(ModelState));
        }
    }

//ModelState is coming in 'Valid' but all values are null.
My ajax call:
 SalesOrderViewModel = function (data) {
    var self = this;
    ko.mapping.fromJS(data, {}, self);

    console.log(self);

    self.save = function () {
        console.log(self);
        console.log(ko.toJSON(self));
        debugger;
        $.ajax({
            url: "/Sales/Save/",
            type: "POST",
            data: ko.toJSON(self),
            headers: {
                "contentType": "application/json"
            },

            success: function (data) {
                if (data.salesOrderViewModel)
                    ko.mapping.fromJS(data.salesOrderViewModel, {}, self);
            },
            always: function (data) {
                console.log(data);
            }
        });
    }
};

console.log on the ajax postback is:
postback data: {"SalesOrderId":0,"CustomerName":null,"PONumber":null}

Checking Chrome's report on FormData shows:
{"SalesOrderId":0,"CustomerName":"Steve","PONumber":"PO","MessageToClient":null,"__ko_mapping__":{"ignore":[],"include":["_destroy"],"copy":[],"observe":[],"mappedProperties":{"SalesOrderId":true,"CustomerName":true,"PONumber":true,"MessageToClient":true},"copiedProperties":{}}}
console.logs on the pre-post shows some strangeness re: 'self' vs. 'ko.toJSON(self)' but i'm not familiar with KO so not sure how strange it is.

I've seen a couple questions related to model binding and the error message I saw in the locals window ('((Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest)this.Request).Form' threw an exception of type 'System.InvalidOperationException').
Changing
contentType: "application/json"

to
    headers: {
        "ContentType": "application/json"
    },

eliminated the error in Locals but did not change the behavior. Controller's model is still showing null values.
Another answer suggested adding '[FromBody]' (also '[FromForm]) in the signature -- neither helped me out. hoping you can!

A: I think you are sending the wrong data up to the controller action when you use ko.toJSON(self).  This is converting the entire ko model to Json. Instead try sending just the mapped values with ko.mapping.toJSON(self)
Try:
SalesOrderViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);

console.log(self);

self.save = function () {
    console.log(self);
    console.log(ko.toJSON(self));
    debugger;
    $.ajax({
        url: "/Sales/Save/",
        type: "POST",
        data: ko.mapping.toJSON(self),
        headers: {
            "contentType": "application/json"
        },

        success: function (data) {
            if (data.salesOrderViewModel)
                ko.mapping.fromJS(data.salesOrderViewModel, {}, self);
        },
        always: function (data) {
            console.log(data);
        }
    });
}
};

Alternatively you could just send this data, which is passed into the function, assuming it contains only the values you wish to post.  data: data

A: I'm following your own course. And, like you, I noticed that there are some problems going to Asp.net Core.
My Controller:
public JsonResult Save([FromBody]SalesOrderViewModel salesOrderViewModel)
        {
            SalesModel salesOrder = new SalesModel();
            salesOrder.CustomerName = salesOrderViewModel.CustomerName;
            salesOrder.PONumber = salesOrderViewModel.PONumber;

            _context.SalesModels.Add(salesOrder);
            _context.SaveChanges();

            salesOrderViewModel.MessageToClient = string.Format("{0}'s sales order has been added to the database.", salesOrder.CustomerName);

            return Json(new { salesOrderViewModel });
        }

My Knockout Script:
SalesOrderViewModel = function (data) {
    var self = this;
    ko.mapping.fromJS(data, {}, self);

    self.save = function () {
        $.ajax({
            url: "/Sales/Save/",
            type: "POST",
            data: ko.toJSON(self),
            contentType: "application/json",
            success: function (data) {
                if (data.salesOrderViewModel != null) {
                    ko.mapping.fromJS(data.salesOrderViewModel, {}, self);
                }
            }
        });
    }
};

My Create Page:
@model SolutionName.ViewModels.SalesOrderViewModel
@using Newtonsoft.Json

@{
    ViewBag.Title = "Create a Sales Order";
}

@{
    string data = JsonConvert.SerializeObject(Model);
    }

@section scripts{

}

@ViewBag.Title

        Customer Name:
        <input data-bind="value: CustomerName" />

        P.O. Number:
        <input data-bind="value: PONumber" />

<button data-bind="click: save">Save</button>

    @Html.ActionLink("Back to List", "Index")

I used "FromBody" in my Controller and the data saved in the database works correctly. What does not work, however, is that after pressing the button saves the view does not update correctly.
I understand that with asp.net Core, this piece of code does not work properly:
ko.mapping.fromJS(data.salesOrderViewModel, {}, self);


text:
Q: Command Prompt Separation of text by Character while I was on Stack Exchange to figure out how to separate text by character, I thought I could simply modify the solution I found (which is supposed to divide by line), but I was unable to.  Can anyone show me how to fix this code with explanation.  Thank you!  Here is the code I found:
set i=0
for /F %%a in (test.txt) do (
    set /A i+=1
    set array[!i!]=%%a
)
set n=%n%

for /L %%i in (1,1,%n%) do echo !array[%%i]!

A: The script was supposed to put each line of test.txt into a separate variable.
@Echo Off
SetLocal EnableDelayedExpansion
Set "i=0"
For /F "UseBackQ Delims=" %%a In ("test.txt") Do (
    Set/A "i+=1"
    Set "line[!i!]=%%a"
)
For /L %%a In (1,1,%i%) Do Echo=!line[%%a]!


text:
Q: Using HttpClient to auto submit document I am using Apache HttpClient to fetch data from a webservice. Instead of getting the JSON response, I am getting a response which has a document.autosubmit.submit(); Is HttpClient capable of handling this automatically? or should I send the submit using httpclient again ?
Any help is appreciated.

A: From your question I assume that the response you are getting has document.autosubmit.submit() in JavaScript where autosubmit is the name of the form.
If that is the case, no, HTTPClient is not capable of executing the JavaScript. Its worth looking at http://htmlunit.sourceforge.net/ which does browser emulation.


text:
Q: Which one is correct- '1980's Wimbledon' or 'Wimbledon of 1980'? I stuck to one point while writing a blog. Basically, I wrote ...

'This technology is used in tennis since 1980's Wimbledon.

But then...

This technology is used in tennis since Wimbledon of 1980.'

...also looks fine to me.
My questions are: Which one of this is correct? If both are correct then which style is more preferable?
I also welcome suggestions to improve the given sentence.

A:
This technology has been used in tennis since 1980's Wimbledon.

"1980's Wimbledon" could refer to any year 1980-1989, not specifically 1980. It is like "since the 1980's".

This technology has been used in tennis since Wimbledon of 1980.

I would reword this to:

This technology has been used in tennis at Wimbledon since 1980.


text:
Q: Can I change the result of the summary.lm function to another language? Can I change the result of the summary.lm function to another language?
I tried these...
trace("summary.lm", edit=T)

and, I modified some codes.
before
ans$coefficients <- cbind(Estimate = est, `Std. Error` = se,
`t value` = tval, `Pr(>|t|)` = 2 * pt(abs(tval), rdf,
  lower.tail = FALSE))

after
ans$coefficients <- cbind(추정치 = est, 표준오차 = se,
                        `t value` = tval, `p value` = 2 * pt(abs(tval), rdf,
                                                              lower.tail = FALSE))

but I cannot change other terms to another language
"Call:, Residuals: Min, 1Q, Median, 3Q, Max ... " and so on...


text:
Q: Merge two list into a single list I have a ArrayList as below.
ArrayList<ArrayList<String>> a = new ArrayList<ArrayList<String>>();

Where ArrayList 'a' contains two ArrayList of string as below.
[a,b,c,d] & [1,2,3,4]

How to merge these two list into a single list as below.
[a,b,c,d,1,2,3,4]

Thanks In Advance.

A: You combine a foreach loop and the addAll method.
Example
ArrayList<String> combined = new ArrayList<String>();

for(ArrayList<String> list : a) {
    combined.addAll(list);
}

 How this works?
A for each loop will traverse through every member of a Collection. It has a temporary variable, in this case list that it assigns the current element too. All you're doing is adding every element inside each value for list, to one ArrayList named combined.

A: This should work
ArrayList<ArrayList<String>> a = new ArrayList<ArrayList<String>>();
        List<String> result = new ArrayList<String>();
        for (ArrayList<String> arrayList : a) {
            result.addAll(arrayList);
        }

Look into main loop and get each list in it and add to your result list.

A: Just iterate through all the inner lists of a using foreach loop and addAll to result arraylist
ArrayList<String> merged = new ArrayList<String>();

for(ArrayList<String> list : a){
   merged.addAll(list);
}

EDIT:
As @Lubo pointed out.
Note that this way you can end up with many arrays being created and thrown away internally in ArrayList. If you have large lists (number of contained elements), consider looking here: Union List

A: We have some other ways too, If you can use Apache commons-collection
ListUtils.union(java.util.List list1, java.util.List list2)

Returns a new list containing the second list appended to the first list.

A: Use ArrayList.addAll(). Something like this should work (assuming lists contain String objects; you should change accordingly).
List<String> combined = new ArrayList<String>();
combined.addAll(firstArrayList);

A: If you need an Iterable, you can use Guava:
Iterables.concat(Iterable<? extends Iterable<? extends T>> inputs)

And if you really need a List, you can cast a resulting Iterable to a List using this:
Lists.newArrayList(Iterable<? extends E> elements)

or
Lists.newLinkedList(Iterable<? extends E> elements)

A: Java 8 streams provide another solution:
List<List<String>> list = Arrays.asList(
        Arrays.asList("1", "2"),
        Arrays.asList("3", "4"),
        Arrays.asList("5", "6")
);

List<String> merged = list
        .stream()
        .reduce(new ArrayList<>(),(accumulator, sublist) -> {accumulator.addAll(sublist);return accumulator;});

System.out.println(merged);

It is similar to the accepted answer: you loop through your list (using Stream.reduce) to add all of your sublists elements to your merged list.

A:     List<Integer> one = Arrays.asList(1, 2,3);
    List<Integer> two = Arrays.asList(4, 5,6);
    List<Integer> out = Stream.of(one, two)
            .collect(ArrayList::new, (listStream, item) -> listStream.addAll(item), (item1, item2) -> {});
    System.out.println(out);

A: Merging lists without loop with Guava
Using FluentIterable.transformAndConcat.

Applies function to each element of this fluent iterable and returns a fluent iterable with the concatenated combination of results. function returns an Iterable of results.

Usage
List<String> combined = FluentIterable.from(a)
      .transformAndConcat(Functions.identity())
      .toList();


text:
Q: Can you Plot over some range but apply the "Filling" option over a smaller range? I would like to shade the area between a function, and a line, but only over a specific range. This range is smaller than the range of the entire plot. The example code and plot below make my goal more clear.
R4 = 8.3144621;(*m^3 Pa K^-1mol^-1 *)
pvDw[T_, V_, Rr_, a_, b_] =
p /. Solve[(p + a/V^2) (V - b) == Rr T, p] // First

aAr = 0.1355; (*a*)
bAr = .000032;(*b*)
TAr = 130;
guesspv = 2.6*10^6;
Show[Plot[
  Evaluate[pvDw[TAr, Vm, R4, aAr,
    bAr], {Vm, (3.2*10^-5), (1.0*10^-3)}],
  PlotStyle -> {Thick, Black}, PlotRange -> Automatic,
  Filling -> {1 -> {guesspv, Yellow}}]]

This code generates this figure

I would like to be able to show the shading only in the 2nd and third regions not the first and fouth.  How would I go about doing this?
I realize that using the Filling option may not be the best way to do this also, so I am open to hearing about other options, plot types ect. I used Filling in the title because that is what I am using in my flawed solution.

A: {min, max} = {Min@#, Max@#} &@(Last @@@ NSolve[pvDw[TAr, Vm, R4, aAr, bAr] == guesspv, {Vm}]);

Plot[{ConditionalExpression[guesspv, min < Vm < max],
      Evaluate[pvDw[TAr, Vm, R4, aAr, bAr]]}, {Vm, (3.2*10^-5), (1.0*10^-3)},
 PlotStyle -> {Directive[{Thin, Yellow}], Directive[{Thick, Black}]},
 PlotRange -> Automatic, Filling -> {1 -> {{2}, Yellow}}]

Explanatory notes:
Find the intersection of the curve with guesspv:
soln = NSolve[pvDw[TAr, Vm, R4, aAr, bAr] == guesspv, {Vm}] ;
(* {{Vm -> 0.000285782},{Vm -> 0.000107816},{Vm -> 0. 0000541249}} *)

See Apply:
intersections = Last @@@ soln   (* same as  Vm /. soln  to get the RHSs of ->s*)
(* {0.000285782,0.000107816,0.0000541249}

See Prefix, Slot and Function:
Min@intersections (* same as Min[intersections]*)
(* 0.0000541249 *)
Max@intersections (* same as Max[intersections]*)
(* 0.000285782 *)

Define a function to do the previous two steps in a single step:
function = {Min@#, Max@#} &  ;(* same as {Min[#], Max[#]}& *)
function@intersections (* same as function[intersections] *)
(* {0.0000541249,0.000285782} *)

A: Another way is to show two plots one with filling and one without.
{min, max} = {Min@#, Max@#} &@(Last @@@
     NSolve[pvDw[TAr, Vm, R4, aAr, bAr] == guesspv, {Vm}]);
Show[Plot[
  Evaluate[pvDw[TAr, Vm, R4, aAr,
    bAr]], {Vm, (3.2*10^-5), (1.0*10^-3)},
  PlotStyle -> {Thick, Black}, PlotRange -> Automatic],
 Plot[Evaluate[pvDw[TAr, Vm, R4, aAr, bAr]], {Vm, min, max},
  PlotStyle -> {Thick, Black}, PlotRange -> Automatic,
  Filling -> {1 -> {guesspv, Yellow}}]]

Or you can do it like this:
Plot[Evaluate[
   pvDw[TAr, Vm, R4, aAr, bAr], {Vm, (3.2*10^-5), (1.0*10^-3)}],
  PlotStyle -> {Thick, Black}, PlotRange -> Automatic,
  Filling -> {1 -> {guesspv, Yellow}}] /.
 GraphicsGroup[{Polygon[__], Polygon[y__]}] :>
  GraphicsGroup[{Polygon[y]}]

A: You can do this rather easily using Show. Here is a simple example.
f[x_] := x^2;
plot1 = Plot[f[x], {x, 0, 1}];
plot2 = Plot[f[x], {x, 1/3, 2/3}, Filling -> 1/3];
Show[plot1, plot2]


text:
Q: Restler API Explorer array parameter in GET request
Is it possible to make a call from the explorer to an GET API that has an array parameter? As you can see in the picture above, the explorer generates the URL by encoding the comma instead of treating it as an array separator. Is there a way to make it accept an array?
Here's my parameter definition in the code.
@param array $ids array of user ID's {@type int} {@from query}

A: Correct way of passing array as a query string is to use [] and repeat the name. For example
users.json?ids[]=1&ids[]=2

Unfortunately Explorer does not support it yet!
We use to support string to array conversion by splitting out of the box in earlier versions of Restler but then taken out to support the above method instead
We just brought it back in the latest v3 branch (just pushed) which will soon be part of RC5 release
In order to make use of it, you need to add {@fix} or {@fix true} to the parameter comment


text:
Q: How do I write loops inside functions? The question is to write a for loop inside a function that will take in array and return the total of all the numbers added together. Not sure what I'm doing wrong here.
let total = 0

function totalGoals(numbers) {
  for (let i = 0; i<numbers.length; i++) {
    let num = numbers[i]
    total = total + num
  }
  return total
}
totalGoals([0, 1, 2])

A: First, lets confirm that you HAVE to learn the basics of Javascript and basic looping (using for loop for example), but also on your journey, you have to learn what tools in the language might make your life easier and your code mode readable.
When it comes to accumulative operation (like adding and so..) you should learn about "reduce" method, which you can write your desired function like:
function totalGoals(numbers){
  return numbers.reduce((acc, val) => acc + val, 0)
}

A: You define total variable globally (outside of function), so here are 2 options: it's better to define variable for sum inside the function:
function totalGoals(numbers) {
  let total = 0
  for (let i = 0; i<numbers.length; i++) {
    let num = numbers[i]
    total = total + num
  }
  return total
}
totalGoals([0, 1, 2])

or if it is necessary to be global - set it to 0 in the start of function, so if won't be affected if function is called more than once:
let total = 0
function totalGoals(numbers) {
  total = 0
  for (let i = 0; i<numbers.length; i++) {
    let num = numbers[i]
    total = total + num
  }
  return total
}
totalGoals([0, 1, 2])

A: You have some sytanxys problems. Try this code:
function totalGoals(numbers) {

        let total= 0, num = 0;

        for (let i = 0; i< numbers.length; i++) {
            num = numbers[i];
            total = total + num;
        }

        alert(total);

    return total;
    }
    totalGoals([0, 1, 2]);

You need to learn about Scope of variable:
https://www.w3schools.com/js/js_scope.asp
And you need be more carefully with your sintaxys:
Dont forget add ; at final of a code line.
And also you are start the variable num more than one time with the word let inside your loop.


text:
Q: Formula en Excel diferencia de meses(fecha) Básicamente quiero hacer una fórmula por la cual yo tengo una columna de fechas y quiero que en otra me ponga un valor dependiendo si han pasado más de 1 mes ponga >30 pero si ha pasado más de 2 ponga >60 ; con respecto a la fecha actual.
He probado con estas lógicas pero no se ajusta al resultado que quiero. Gracias.
=SIFECHA(HOY(),E4,"d")

=SI(E4+31>HOY();">60",">30")

=SI(E4+60>HOY();">60";">30")

A: La solución para ponerlo todo en una línea seria haciendo funciones anidadas.
Debemos empezar por la condición más restrictiva (la de mayor número) y ir poniendo condiciones inferiores.
Por lo que tu sentencia a usar quedaría como la siguiente.
=SI(HOY()>$A1+60;">60";SI(HOY()>$A1+31;">31";"VALOR SI NO SE CUMPLE NINGUNA CONDICION"))

*Cambia $A1 por tus celdas.
PD: Ojo al problema si la fecha es hace 31 días exactos respecto hoy. No entrará en la condición. Podría considerarse añadir MAYOR.O.IGUAL. Lo mismo si son 60 días.


text:
Q: Compile classfile issue in Spring 3 I have used spring framework 3 for my application.  Everything is ok while developed in
Netbeans  But i need a custom build  and   done for the same The build created without any
issue, but i got the following error The error occurred while calling the following method
@RequestMapping(value = "/security/login", method = RequestMethod.POST)
public ModelAndView login(@RequestParam String userName, @RequestParam String password,
    HttpServletRequest request) {
    ......................

But There is no issue while creating the war with  netbeans
(I am sure it is about the compilation issue)
have you any experiance on this issue ...
There is any additional javac argument for compile the same (netbeans used there custom task for the compilation)
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.bind.annotation.support.HandlerMethodInvocationException: Failed to invoke handler method [public org.springframework.web.servlet.ModelAndView com.mypackage.security.controller.LoginController.login(java.lang.String,java.lang.String,javax.servlet.http.HttpServletRequest)]; nested exception is java.lang.IllegalStateException: No parameter name specified for argument of type [java.lang.String], and no parameter name information found in class file either.
 org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:659)
 org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:563)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 com.mypackage.security.controller.AuthFilter.doFilter(Unknown Source)
 org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
 org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
root cause
org.springframework.web.bind.annotation.support.HandlerMethodInvocationException: Failed to invoke handler method [public org.springframework.web.servlet.ModelAndView com.mypackage.security.controller.LoginController.login(java.lang.String,java.lang.String,javax.servlet.http.HttpServletRequest)]; nested exception is java.lang.IllegalStateException: No parameter name specified for argument of type [java.lang.String], and no parameter name information found in class file either.
 org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
 org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:414)
 org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402)
 org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
 org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
 org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
 org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:563)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 com.mypackage.security.controller.AuthFilter.doFilter(Unknown Source)
 org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
 org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
root cause

java.lang.IllegalStateException: No parameter name specified for argument of type [java.lang.String], and no parameter name information found in class file either.
 org.springframework.web.bind.annotation.support.HandlerMethodInvoker.getRequiredParameterName(HandlerMethodInvoker.java:618)
 org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestParam(HandlerMethodInvoker.java:417)
 org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:277)
 org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:163)
 org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:414)
 org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402)
 org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
 org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
 org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
 org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:563)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 com.mypackage.security.controller.AuthFilter.doFilter(Unknown Source)
 org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
 org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)

note The full stack trace of the root cause is available in the Apache Tomcat/6.0.18 logs.

A: Argument names are stored in the compiled code only when it's compiled in debug mode, so you should either compile it in debug mode or supply @RequestParam with explicit parameter names. The latter approach is more reliable because it doesn't depend on the environment:
@RequestMapping(value = "/security/login", method = RequestMethod.POST)
public ModelAndView login(@RequestParam("userName") String userName,
    @RequestParam("password") String password,
    HttpServletRequest request) {
    ......................


text: Q: Cannot import sbt._ or Keys._ to Build.scala I am trying to workout a conditional libraries set-up for a single project/module in a multi-project build.  This one module needs to have a conditional dependency list to load a locally stored jar dependency for either a development or production environment.  From this post and this other post, it seems that replacing the build.sbt file with a Build.scala file for this module is the best route.  However, when I do the import sbt._ and import Keys._ I get a Cannot resolve symbol Keys warning from IntelliJ.  I am able to do the import calls in the various other build.sbt files, but they do not resolve in any of the .scala files.


text:
Q: Why the radiative zone of the sun rotates uniformly, while the convective zone of the sun rotates differentially? Wikipedia says this about the tachocline

This is a region where the sharp regime change between the uniform rotation of the radiative zone and the differential rotation of the convection zone results in a large shear between the two—a condition where successive horizontal layers slide past one another.

Can someone please give the reason that for what does the radiative zone rotates uniformly but not the convective zone?


text:
Q: Best way to bind an interface to the result of another binding Let's say I have the following interface and class:
public interface IMyService
{
    void DoSomething();
}

public class MagicInterfaceImplementor<T>
{
    public T GetImplementation()
    {
        // Not relevant.
    }
}

The only way to get an instance of IMyService is through MagicInterfaceImplementor<IMyService>.  I can obviously setup injection pretty easily for MagicInterfaceImplementor<IMyService>:
Bind<MagicInterfaceImplementor<IMyService>().ToSelf();

[Strictly, this isn't necessary in this particular instance, but I'm doing a bit more with the binding in the actual case.]
My question is - how do I bind IMyService?
I think I can do this, but I'm not sure that it's the best way, since I'm explicitly calling the Kernel, which is typically frowned upon:
Bind<IMyService>().ToMethod(context => {
    return ((MagicInterfaceImplementor<IMyService>)
            context.Kernel.GetService(typeof(MagicInterfaceImplementor<IMyService>)))
                .GetImplementation();
});

Any suggestions of a more proper way to do this would be appreciated.

A: Maybe it would be interesting what exactly MagicImplementor does. So this is more of a guess, but maybe a Provider might help you.
https://github.com/ninject/ninject/wiki/Providers,-Factory-Methods-and-the-Activation-Context
Otherwise you can simply write
Bind<IMyService>().ToMethod(ctx => ctx.Kernel.Get<MagicInterfaceImplementor<IMyService>>().GetImplementation());


text:
Q: how could I change variable value into a target? here I am again with another make issue Im trying to handle (hardly), I have set several values I want make to read, but when I try to change inside a loop it does not work; $(FOUND) stills being the same as it was first, what could I being doing bad? is other way to set variables or to change them into?
here's a part of my code related to this question:
$(shell for d in $(INPUT); \
        do \
            $(if $(FOUND) -eq 1, REL=$(REL)../); \
            $(if $(findstring $(WORD),$(INPUT)), \
                echo '$(WORD)../'; FOUND=1)\
        done)

$(FOUND) variable is defined outside but want it to change when it gets $(WORD)
any suggestion for that???
thank you so much

A: There are several things wrong with the code above, so much so that it is difficult to understand your intention. Here is a partial list (sorry if I sound like Microsoft clippy)

*

*The code $(if $(FOUND) -eq 1, REL=$(REL)../), looks like a mix between gnu-make syntax and shell syntax.

*Your loop seems to be superfluous. You are not using the loop variable d, and you are using a construct that process the entire sequence. E.g.: $(findstring $(WORD),$(INPUT)

*It seems that you are trying to generate code like echo '$(WORD)../', but the context of this code is unclear. If it is outside a rule, the code has no meaning. If it is inside a rule, it will evaluate too late to set a makefile variable. There is a way to work around this problem, but first you need to clarify your intention better.

*I can only suspect you intended to have REL=$(REL)/.. or REL=../$(REL) but I can be mistaken.

*Lastly it is important to understand that what you really should do in a Makefile is to describe a dependency graph, and let make figure out the order of operation needed to be performed. So a procedural approach such as may inferred from your code above should be minimized.

Edit:
If I read you correctly, you are trying to achieve a tricky goal in Makefile. Let me assure you that your inexperience is not the only stumbling block you have. Writing good Makefiles is hard. If you have any control over this, I strongly suggest to have a look at some other build solutions. For example, cmake can write good Makefiles for you.
If you are trying to calculate a base-dir or a relative-dir, please note that the concept of current-working-directory as saved in $(CURDIR) might or might not be what you expect.
For your question, you can indeed use a GNU make $(foreach ...) construct, but there are several functions that are designed to handle sequences without iterations, that might serve you better.


text:
Q: Do we say "on" or "in the highway"? I am not sure, which one is valid. I feel "on" is more appropriate, but I often hear both. Strangely enough, "in" is wrong when "on" is ok. Like, we say "on the bus" and never "in the bus", so I might think it's the case, but I have heard "in the highway" often enough to have a little doubt.
For example:

Do a sharp U turn in the highway, or we're doomed.

A: One is never "in" the highway but "on" the highway.
One is never "in" a bus but "on the bus.
One cannot be "on" the tunnel, but one can be "in" a tunnel.
I try to use the preposition "inside" when describing my current, static location without specifying where I am. Ex. "I am inside."
When describing movement, I like to say, "He is going into the house" instead of "He is going in the house."


text:
Q: How to put RecyclerView inside NestedScrollView? With creation of NestedScrollView you can put scrolling view inside another scrolling view as long as those implement NestedScrollingChild and NestedScrollingParent correctly.
(This is not bad design pattern "Ian Lake (from Google) actually recommends putting a RecyclerView inside a nestedscrollview here: plus.google.com/u/0/+AndroidDevelopers/posts/9kZ3SsXdT2T")
I want to put RecyclerView inside NestedScrollView and fortunately RecyclerView implements NestedScrollingChild so you can put it inside NestedScrollView.
public class RecyclerView extends ViewGroup implements ScrollingView, NestedScrollingChild

I have read these posts:
How to use RecyclerView inside NestedScrollView?
NestedScrolling with NestedScrollView, RecyclerView (Horizontal), inside a CoordinatorLayout
But the problem with most voted solution is, it calls all of the items of RecyclerView so for example if it is an endless RecyclerView and when the user reaches the end of the list you want to make a network request then with that solution the RecyclerView calls server repeatedly because it automatically reaches the last item of RecyclerView.
Anyway, how to set parameter so I can put RecyclerView inside NestedScrollView.(actually  I want to put a viewgroup like framelayout or relativelayout as a single childe of nestedscrollview and then I want to put recyclerview inside framelayout or relativelayout)
When I put RecyclerView inside NestedScrollView there is nothing to display.

In order to create a sample project you can use cheesesquare and change the CheeseDetailActivity to have a RecyclerView.

Although the answer of BNK is not correct but BNK has tried a lot. So I award him the bounty. Still looking for nice solution....

A: The following is my new updated answer:
<android.support.v4.widget.NestedScrollView
        android:id="@+id/scrollview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.CardView
                android:id="@+id/cardview1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/card_margin">

                <LinearLayout
                    style="@style/Widget.CardContent"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Info CardView1"
                        android:textAppearance="@style/TextAppearance.AppCompat.Title" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/cheese_ipsum" />

                </LinearLayout>

            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView
                android:id="@+id/cardview2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/cardview1"
                android:layout_margin="@dimen/card_margin">

                <LinearLayout
                    style="@style/Widget.CardContent"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Info CardView2"
                        android:textAppearance="@style/TextAppearance.AppCompat.Title" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/cheese_ipsum" />

                </LinearLayout>

            </android.support.v7.widget.CardView>

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/cardview2"
                android:clipToPadding="false"
                android:paddingTop="0dp"/>

        </RelativeLayout>

    </android.support.v4.widget.NestedScrollView>

In Activity:
        RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(true); // true: with header
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        final MyLinearLayoutManager layoutManager = new MyLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false, getScreenHeight(this));
        // final CustomLinearLayoutManager layoutManager = new CustomLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(recyclerViewAdapter);
        // recyclerView.setNestedScrollingEnabled(false); // Disables scrolling for RecyclerView, however, CustomLinearLayoutManager used instead of MyLinearLayoutManager

I have also updated to My GitHub's sample project
Screenshot:

A: Here is solution to call server only when you are realy need to load more data. In this way you can put your endless RecyclerView and many other views inside NestedScrollView. For me it is working well.
1. Create EndlessParentScrollListener class to handle scroll events from NestedSrollView.
public abstract class EndlessParentScrollListener implements NestedScrollView.OnScrollChangeListener {
        // The current offset index of data you have loaded
        private int currentPage = 0;
        // The total number of items in the dataset after the last load
        private int previousTotalItemCount = 0;
        // True if we are still waiting for the last set of data to load.
        private boolean loading = true;
        // Sets the starting page index
        private int startingPageIndex = 0;
        // The minimum amount of pixels to have below your current scroll position
        // before loading more.
        private int visibleThresholdDistance = 300;

        RecyclerView.LayoutManager mLayoutManager;

        public EndlessParentScrollListener(RecyclerView.LayoutManager layoutManager) {
            this.mLayoutManager = layoutManager;
        }

        @Override
        public void onScrollChange(NestedScrollView scrollView, int x, int y, int oldx, int oldy) {
            // We take the last son in the scrollview
            View view = scrollView.getChildAt(scrollView.getChildCount() - 1);
            int distanceToEnd = (view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY()));

            int totalItemCount = mLayoutManager.getItemCount();
            // If the total item count is zero and the previous isn't, assume the
            // list is invalidated and should be reset back to initial state
            if (totalItemCount < previousTotalItemCount) {
                this.currentPage = this.startingPageIndex;
                this.previousTotalItemCount = totalItemCount;
                if (totalItemCount == 0) {
                    this.loading = true;
                }
            }

            // If it's still loading, we check to see if the dataset count has
            // changed, if so we conclude it has finished loading and update the current page
            // number and total item count.
            if (loading && (totalItemCount > previousTotalItemCount)) {
                loading = false;
                previousTotalItemCount = totalItemCount;
            }

            // If it isn't currently loading, we check to see if we have breached
            // the visibleThreshold and need to reload more data.
            // If we do need to reload some more data, we execute onLoadMore to fetch the data.
            // threshold should reflect how many total columns there are too
            if (!loading && distanceToEnd <= visibleThresholdDistance) {
                currentPage++;
                onLoadMore(currentPage, totalItemCount);
                loading = true;
            }
        }

        // Defines the process for actually loading more data based on page
        public abstract void onLoadMore(int page, int totalItemsCount);
    }

2. Set listener
private void initRecycler() {
        //TODO init recycler adapter here

        recycler.setNestedScrollingEnabled(false);
        LinearLayoutManager _layoutManager = new LinearLayoutManager(this);
        recycler.setLayoutManager(_layoutManager);
        NestedScrollView scrollView = (NestedScrollView) findViewById(R.id.scrollView);
        scrollView.setOnScrollChangeListener(new EndlessParentScrollListener(_layoutManager) {
                @Override
                public void onLoadMore(int page, int totalItemsCount) {
                    if (loadedItemCount < serverItemsCount)
                        customLoadMoreDataFromApi();
                }
            });
        customLoadMoreDataFromApi();
    }

Short xml if someone find it usefull:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/background_light"
        android:fitsSystemWindows="true">

        <android.support.design.widget.AppBarLayout>
            ...
        </android.support.design.widget.AppBarLayout>

        <android.support.v4.widget.NestedScrollView
            android:id="@+id/scrollView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            android:scrollbars="vertical"
            android:scrollbarAlwaysDrawVerticalTrack="true"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:scrollbarAlwaysDrawVerticalTrack="false"
                android:scrollbars="vertical">

                <!-- some views goes here-->

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/recyclerFeed"
                    android:scrollbars="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

                <!-- and possibly here-->

            </LinearLayout>
        </android.support.v4.widget.NestedScrollView>

    </android.support.design.widget.CoordinatorLayout>

A: So put RecyclerView inside NestedScrollView directly will unfortunately display nothing. However, there is a way to put the recyclerview inside the NestedScrollView indirectly - just use a frameLayout as the third party to hold your recyclerview.
This is the framelayout which holds the nested recyclerview in your activity class:
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context=".ExampleFragment"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true"
            >
        </android.support.v4.widget.NestedScrollView>
   </FrameLayout>

Put your fragment into the framelayout (code sits within the activity class):
 ExampleFragment exampleFragment = new ExampleFragment();

    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.add(R.id.container, exampleFragment);
    ft.commit();

In your exampleFragment, you can then put your recyclerview.
<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/post_container"
        android:background="#E0E0E0">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/my_recycler_view"
                android:scrollbars="vertical"

                android:layout_width="match_parent"
                android:layout_height="match_parent">
            </android.support.v7.widget.RecyclerView>

    </RelativeLayout>

This is the fragment code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    super.onCreateView(inflater, container, savedInstanceState);
            llLayout = (RelativeLayout) inflater.inflate(R.layout.example_fragment_layout, container, false);
                    mRecyclerView = (RecyclerView) llLayout.findViewById(R.id.my_recycler_view);

The following is the CheeseSquare XML layout you should have:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/detail_backdrop_height"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp">

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:layout_collapseMode="pin" />

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

   <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context=".ExampleFragment"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true"
            >
        </android.support.v4.widget.NestedScrollView>
   </FrameLayout>

    <android.support.design.widget.FloatingActionButton
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        app:layout_anchor="@id/appbar"
        app:layout_anchorGravity="bottom|right|end"
        android:src="@drawable/ic_discuss"
        android:layout_margin="@dimen/fab_margin"
        android:clickable="true"/>

</android.support.design.widget.CoordinatorLayout>

A: I have wasted at least a week behind this and the only solution that works is to remove the nestedscrollview. I know that is not the answer to this particular question of adding recyclerview inside nestedscrollview, but to make the recyclerview to actually recycle the view, you HAVE TO REMOVE the nestedscrollview. If you happen to have multiple view inside instead of just the recyclerview, You have to add them as items of the recyclerview by setting different viewholders, and then adding
app:layout_behavior="@string/appbar_scrolling_view_behavior"
to the recyclerview or the parent of recyclerview(the parent cannot have any other view other than Recyclerview for this to work).
In my case, the requirement was as follows:
  <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:fitsSystemWindows="true"
        app:layout_constraintTop_toTopOf="parent">

        <!-- Scrollable view here -->

        <com.google.android.material.appbar.AppBarLayout
            ....   >

            <com.google.android.material.appbar.CollapsingToolbarLayout
                ....>

                <androidx.appcompat.widget.Toolbar
                    ....>

                    <include
                        android:id="@+id/toolbar_header_view"
                        .... />
                </androidx.appcompat.widget.Toolbar>

                <include layout="@layout/widget_header" />
            </com.google.android.material.appbar.CollapsingToolbarLayout>
        </com.google.android.material.appbar.AppBarLayout>

        <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
            ....>
            <LinearLayout orientation="vertical" ....>
                <View .../>  <!-- I needed to have these two views along with recyclerview and i wanted them to do nestedscroll along with recyclerview -->
                <View .../>
                <androidx.recyclerview.widget.RecyclerView
                .... />
        </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

I needed to have two views before recyclerview and I wanted them to do nestedscroll along with recyclerview. The only thing that worked was by removing these to views and adding them as the first two items of recyclerview, and then adding
app:layout_behavior="@string/appbar_scrolling_view_behavior"

to the swipetorefresh layout
Hope this helps someone. I will add more info If required.


text:
Q: How to get the list of installed Browser Apps in an Android 7.0 running devices programmatically? Before Android 7.0 I was able to retrieve the list of installed browser type applications and it's package name. Then, I upgrade to Android 7.0 and I am only able to retrieve Samsung's Internet browser, but not the other browser type applications such as Chrome .
Device Samsung Tab A
This is the code :
public static List<String> getListOfBrowser(Context context) {
    List<String> browserPackageName = new ArrayList<String>();
    try {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("http://www.google.com"));
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> browserList = pm.queryIntentActivities(intent, 0);
        for (ResolveInfo info : browserList) {
            browserPackageName.add(info.activityInfo.packageName);
            Log.e("BrowserList Info ",info.activityInfo.packageName+" total browser"+browserList.size());
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("BrowserList Info ",e.getMessage());
    }
    return browserPackageName;
}

A: If Android API level >= 23, then you can do like so:
List<ResolveInfo> browserList;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.MARSHMALLOW) {
    // gets all
    browserList = pm.queryIntentActivities(intent, PackageManager.MATCH_ALL);
    // only the defaults
    browserList = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
} else {
    browserList = pm.queryIntentActivities(intent, 0);
}

A: Code looks fine. However you should use PackageManager.MATCH_DEFAULT_ONLY flag -
pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);

instead of
pm.queryIntentActivities(intent, 0);


text:
Q: How to add column name to my java table? (from database) Hi so i was wondering why my the Jtable didnt have any column title however it does have the data from my postgres db
I want to be able to choose a column title for each data
public class aaaaa extends JFrame {

private JPanel contentPane;
private static JTable table;

/**
 * Launch the application.
 */
public static void main(String[] args) {
 Connection c = null;
 Statement stmt = null;
 try{
  Class.forName("org.postgresql.Driver");
  c = DriverManager
     .getConnection("jdbc:postgresql://localhost:5432/MovieDatabase",
     "postgres", "password");
    c.setAutoCommit(false);
    System.out.println("Opened database successfully");

     stmt = c.createStatement();
    ResultSet rs = stmt.executeQuery( "SELECT * FROM film" );
    table = new JTable(buildTableModel(rs));

     while ( rs.next() ) {
     int filmid = rs.getInt("filmid");
     String  filmtitle = rs.getString("filmtitle");
     int filmyear  = rs.getInt("filmyear");
     String  filmgenre = rs.getString("filmgenre");

     System.out.println( "ID = " + filmid );
     System.out.println( "TITLE = " + filmtitle );
     System.out.println( "YEAR = " + filmyear );
     System.out.println( "GENRE = " + filmgenre );

     System.out.println();
 }
  rs.close();
  stmt.close();
  c.close();
 }catch ( Exception e ) {
  System.err.println( e.getClass().getName()+": "+ e.getMessage() );
  System.exit(0);
}

    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                aaaaa frame = new aaaaa();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public aaaaa() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 411);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    table.setBounds(10, 11, 414, 350);
    contentPane.add(table);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(10, 11, 414, 350);
    contentPane.add(scrollPane);
}

public static DefaultTableModel buildTableModel(ResultSet rs)
        throws SQLException {

    ResultSetMetaData metaData = rs.getMetaData();

    // names of columns
    Vector<String> columnNames = new Vector<String>();
    int columnCount = metaData.getColumnCount();
    for (int column = 1; column <= columnCount; column++) {
        columnNames.add(metaData.getColumnName(column));
    }

    // data of the table
    Vector<Vector<Object>> data = new Vector<Vector<Object>>();
    while (rs.next()) {
        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
            vector.add(rs.getObject(columnIndex));
        }
        data.add(vector);
    }

    return new DefaultTableModel(data, columnNames);

}
}

Thanks for ur help.

A: You are using your table outside of a scrollpane. If you really wish to use the JTable in a standalone view, you can get the headers using getTableHeader():
JTableHeader header = table.getTableHeader();
And then add the header to where you want it to be.
The other, more prefered, way would be to simply add the table to a scrollpane:
contentPane.add(new JScrollPane(table));
See here:
https://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html

Note that if you wish to use a JTable in a standalone view (outside of a JScrollPane) and want the header displayed, you can get it using getTableHeader() and display it separately.


text:
Q: JOINing two tables and make group and sums correct Been trying to figure this out for hours now and would really appreciate your help!
So I have two tables, transactions and transactions_rebuy
My SELECT goal is to join/combine these tables and get them grouped by date.
Right now I have this statement:
SELECT tr.SoldDate, SUM(tr.TotalAmount) as SumByReceipt,
COUNT(DISTINCT(tr.`ForsNr`)) as TotalCustomers, rebuy.RebuySum
FROM transactions tr
CROSS JOIN (
SELECT SUM(TotalAmount) as RebuySum
    FROM transactions_rebuy
    WHERE SoldDate BETWEEN '2016-10-22' AND '2016-10-27'
    ) as rebuy
WHERE tr.SoldDate BETWEEN '2016-10-22' AND '2016-10-27'
GROUP by tr.SoldDate
ORDER by tr.SoldDate DESC

Which gives me following result:
SaldDatum SumByReceipt TotalCustomers RebuySum

2016-10-27 54855.8001       99        10435.9997
2016-10-26 41749.8009       76        10435.9997
2016-10-25 46626.8001       79        10435.9997
2016-10-24 38678.8017       76        10435.9997
2016-10-22 30351.9997       48        10435.9997

The problem is that "RebuySum" column is grouped of the total sum for all the above dates. As "SumByReceipt", I want it grouped BY DATE, not the total sum on each row.
I've tried back and forth with grouping and sum, and got it to work but then it messes up the "SumByReceipt" column instead.
Most grateful for ideas on this.

A: Group the subquery by date, then join them on the date.
SELECT tr.SoldDate, SUM(tr.TotalAmount) as SumByReceipt,
        COUNT(DISTINCT(tr.`ForsNr`)) as TotalCustomers, IFNULL(rebuy.RebuySum, 0) RebuySum
FROM transactions tr
LEFT JOIN (
    SELECT SoldDate, SUM(TotalAmount) as RebuySum
    FROM transactions_rebuy
    WHERE SoldDate BETWEEN '2016-10-22' AND '2016-10-27'
    GROUP BY SoldDate
    ) as rebuy
ON tr.SoldDate = rebuy.SoldDate
WHERE tr.SoldDate BETWEEN '2016-10-22' AND '2016-10-27'
GROUP by tr.SoldDate
ORDER by tr.SoldDate DESC


text:
Q: Android turn off ChromeCast Screen Mirroring function I have a problem with ChromeCast Screen Mirroring function. Because my content is protected (DRM video) if the user use Screen Cast i need check and turn off or show something else (like protected content message picture) and not the video.
My question is: Its possible detect Screen Mirroring and disable in code?

A: You can implement Chromecast-support in your app and choose which layout to cast when the screen is mirrored (so just cast an empty layout or information etc). If you check the example PresentationWithMediaRouterActivity in Android ApiDemos (or Google it and you will find the files needed), you can see a good example implementation that does just that.


text:
Q: Slide UITableView up when scrolling starts There is a particular element of the app I am developing at the moment that I am not sure of the best way to go about implementing.
Basically, I would like to have a view that has a UITableView about half way down the page. When the table view is scrolled down, the UITableView would start to slide up to the top of the page. Once it reaches that point, the table would just scroll as normal until the user scrolls back up (the table would slide back down to it's original position).
I managed to find an example of what I mean in the Spotify app. In a playlist, once you start scrolling, the whole able scrolls up. I'm pretty sure it's a feature in quite a few apps.
So like I say, I am just looking for some advice about the best way to do this.

A: I do not know the Spotify app so maybe I don't get your question right but if you want to implement the behaviour like I think this library should do what you want:
CSStickyHeaderFlowLayout
You should note that this library is made to be used with an UICollectionView and not an UITableView but I guess you could work with that.
EDIT
Also have a look at this SO Thread which deals with using this library in Swift code:
csstickyheaderflowlayout-swift


text:
Q: Javascript и событийность, асинхронность, setTimeout Javascript - событийно-ориентированный язык программирования.
function first() {
  console.log('first');
}

function second() {
  setTimeout(function() {
      console.log('second');
  }, 1000);
}

second()
first()

First - синхронная функция. Second - синхронная функция, в которой находится асинхронная функция, выполнение которой завершиться после одной секунды.
Вывод:
first

second

Почему, если first и second синхронные функции, первой завершает свою работу first?
*Является ли это особенностью языка программирования и его архитектуры, строения и работы? (или той же самой функции setTimeout).

A: В setTimeout создается асинхронная функция (через которую выводится second после 1 секунды), как ты сам и написал - она асинхронна, другими словами: она уходит на второй план ждать 1 секунду, когда на первом first(функция)
По шагам, код выглядит так:
0 (()=>{ // "main"
    0.1 const first=()=>{
        5 console.log('first');
    };

    0.2 const second=()=>{
        2 setTimeout(()=>{
            7 console.log('second');
        }, 1000);
        3
    };

    1 second();
    4 first();
    6 // some
})();

Тебе нужно идти и читать про event loop, вот хорошее видео на тему, правда на английском


text:
Q: How to add a border to a plot? Consider a plot as
ListLinePlot[{{10, 15, 20, 25, 30, 35, 40}, {1, 2, 3, 4, 5, 6, 7}}]

I want to add a border to this plot like this

I tried to use
ImageCompose[
 Graphics[{EdgeForm[{RGBColor[192/255, 0, 0], Thickness[0.01]}],
   LABColor[1, 0, 0, 0],
   Rectangle[{0, 0}, {x, y}, RoundingRadius -> 0.1]}],
 ListLinePlot[{{10, 15, 20, 25, 30, 35, 40}, {1, 2, 3, 4, 5, 6, 7}}]]

and checked with different values of x and y. However, I am not getting the desired border.
How can I do this (without losing the resolution)?

A: pic = Framed[
 ListLinePlot[{
   {10, 15, 20, 25, 30, 35, 40},
   {1, 2, 3, 4, 5, 6, 7}}],
 FrameMargins -> 20,
 FrameStyle -> {Thick, Red},
 RoundingRadius -> Scaled[.05]]

Export["/Users/roberthanlon/Downloads/pic.EPS", pic]

(* "/Users/roberthanlon/Downloads/pic.EPS" *)


text:
Q: Magento 2 Custom Admin module giving 404 I have followed many tutorials but im still getting a 404 error when trying to access with a custom menu item in my module.
This is what i have, :
 registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Digital_Custom',
__DIR__
);

etc/adminhtml/menu.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
    <menu>
        <add id="Digital_Custom::regenerate"
             title="Digital Custom"
             module="Digital_Custom"
             sortOrder="9999"
             action="importer/packadgeable/regenerate"
             resource="Magento_Backend::content" />

    </menu>
</config>

Here the new menu item is visible, but when click im getting 404
My controller Structure:
Digital
  - Custom
    - Controller
      - Adminhtml
        - Packadgeable
          - Regenerate.php
This is my controller code Regenerate.php
<?php
namespace Digital\Custom\Controller\Adminhtml\Custom;

class Regenerate extends \Magento\Backend\App\Action
{
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $_resultPageFactory;

    /**
     * @param \Magento\Backend\App\Action\Context        $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    )
    {
        parent::__construct($context);
        $this->_resultPageFactory = $resultPageFactory;
    }

    /**
     * Grid List page.
     *
     * @return \Magento\Backend\Model\View\Result\Page
     */
    public function execute()
    {
        /** @var \Magento\Backend\Model\View\Result\Page $resultPage */
        $resultPage = $this->_resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->prepend(__('Grid List'));

        return $resultPage;
    }

    protected function _isAllowed() {
        return true;
        }
}

My route
 etc/adminhtml/routes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/framework/App/etc/routes.xsd">
<router id="admin">
    <route id="regenerate" frontName="regenerate">
        <module name="Digital_Custom" before="Magento_Backend" />
    </route>
</router>
</config>

A: I'd say the URL isn't matching. Instead of:
action="importer/packadgeable/regenerate"

you should try:
action="regenerate/packadgeable/regenerate"

or change the route id and frontName to importer.