text:
Q: Django testing of views.py and model.py I am new to django testing am doing the testing for my views.py file which cintain alot oif classes
Here we are take one of the class among the others
the views.py file looks like

class AssignSubFarmer(viewsets.ViewSet):
    permission_classes = [permissions.AllowAny]
    http_method_names = ['patch', 'post']
    serializer_class = BatchSerializer
    queryset = Farm.objects.all()

    def create(self, request, *args, **kwargs):
        header = {'Content-Type': 'application/json', 'Authorization': request.headers['Authorization']}
        farm_id = request.data.get('farm_id', None)
        batch_id = request.data.get('batch_id', None)
        subfarmer_id = request.data.get('user_id', None)
        mobile = request.data.get('mobile', None)
        name = request.data.get('name', None)
        document_photo = request.data.get('document_photo', None)
        user_type = request.data.get('user_type', None)
        aadhar_number = request.data.get('aadhar_number', None)
        pancard = request.data.get('pancard', None)
        voter_id = request.data.get('voter_id', None)
        gst_no = request.data.get('gst_no', None)
        primary_user_id = request.data.get('primary_user_id', None)
        if not subfarmer_id:
            payload = {
                "name": name,
                "mobile": mobile,
                "document_photo": document_photo,
                "user_type": user_type,
                "aadhar_number": aadhar_number,
                "pancard": pancard,
                "voter_id": voter_id,
                "gst_no": gst_no
            }
            response = requests.post(url=settings.CREATE_SUB_FARMER.format(primary_user_id), data=json.dumps(payload),
                                     headers=header)
            data = json.loads(response.content)
            secondary_user_id = None
            if not data['error'] and data['data']:
                secondary_user_id = data['data'].get('secondary_user_tbl_id', None)
            else:
                return Response({"message": data['message'], "error": data['error']}, status=status.HTTP_200_OK)
            subfarmer_id = 0
            if secondary_user_id:
                subfarmer_id = secondary_user_id
            if farm_id and subfarmer_id:
                Batch.objects.filter(farm_id=farm_id).update(sub_farmer_id=subfarmer_id)
            elif batch_id and subfarmer_id:
                Batch.objects.filter(id=batch_id).update(sub_farmer_id=subfarmer_id)
        elif farm_id:
            Batch.objects.filter(farm_id=farm_id).update(sub_farmer_id=subfarmer_id)
        elif batch_id:
            Batch.objects.filter(id=batch_id).update(sub_farmer_id=subfarmer_id)
        return Response({"message": "Successfully updated", "error": "False"}, status=status.HTTP_200_OK)

and when I am doin the testing for this class
in test_views.py file
from django.urls import reverse
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from igrow.urls import *
from farm_management.models import *
from django.contrib.auth.models import User
import json

class TestAssignSubFarmer(APITestCase):

    def test_assign(self):
        sample = {"farm_id": "123", "batch_id": "1222",}
        response = self.client.get(reverse('assignsubfarmer'),sample)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

In terminal when I give the test command
python manage.py test test_model.py

It shows an  error
UserWarning: The default behavior of S3Boto3Storage is insecure and will change in django-storages 2.0. By default files and new buckets are saved with an ACL of 'public-read' (globally publicly readable). Version 2.0 will default to using the bucket's ACL. To opt into the new behavior set AWS_DEFAULT_ACL = None, otherwise to silence this warning explicitly set AWS_DEFAULT_ACL.
  warnings.warn(
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_model (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_model
Traceback (most recent call last):
  File "/usr/lib/python3.8/unittest/loader.py", line 154, in loadTestsFromName
    module = __import__(module_name)
ModuleNotFoundError: No module named 'test_model'

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)

This Picture shows the directory of files that are arranged in this way

A: Looks like your file is named test_models.py and you're calling test_model.py (in singular).
Here's official documentation on how to run only one file / specific testcase / specific test.
For your particular case, I would try running python manage.py test farm_management.test.test_models (this is just a guess based on docs, I didn't actually check that).

On a related note, it looks like you're using Pycharm. It has a builtin mechanism for running tests, so you don't have to manually type in the dotted path every time you want to run a specific test. It allows you to run a specific test, or the whole testcase, and looks like this:


text:
Q: CSS Save image aspect ratio I have some graphics of size in inches:
4.25 x 6.875
5.5 x 8.5
6 x 9
8.5 x 8.5
8.264 x 11.694
I want to do a reduced preview of that graphics (I'll iterate throught all size and I want to show each image in the same, only one DIV) but I want to save the aspect ratio. I'm wondering that would be the best size of that DIV to avoid deforming of each image.

A: If you set max-width and max-height on the image, but don't set height or width, then the image will be confined to the size you defined while keeping the aspect ratio.
Example:

If big_image.png were 4000 by 2000 pixels, it would be rendered as 100 by 50.

A: My example controls the size of the images and div by css.
The div is set to auto, so it will adjust itself to the size of your images.
You can quickly control the size of the images in one go, instead of adjusting them one by one in the html code.
http://jsfiddle.net/KzXFm/
HTML

CSS
#container{
    max-width:auto;
    max-height: auto;
    background: red;
}

img {
    max-width:20%;
    max-height: 20%;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Populate EditText widget text from another EditText widget text I am trying to populate the text of a second EditText widget with the text from the first EditText widget only when the second EditText widget receives focus, the second widget is not empty, and the first widget is not empty.
I have the following OnFocusChangeListener handler code.
        public void onFocusChange(View v, boolean hasFocus) {

        EditText stxt = (EditText) findViewById(R.id.numberone);
        EditText etxt = (EditText) findViewById(R.id.numbertwo);

        if (hasFocus && stxt.getText().toString().trim() != "" && etxt.getText ().toString().trim() == "")
        {
            etxt.setText(stxt.getText().toString().trim());
        }
    }

When I run it and click into the second widget it does not populate. When I remove the third constraint ('etxt.getText ().toString().trim() == ""')) it works. so getText() on the second EditText widget is returning something even though the second widget has no initial value other then the text that is displayed via the hint attribute.
How can I accomplish this.
Thanks

A: You should be doing an object comparison using String.equals(), not just x == "".
I would rewrite this using Android's handy TextUtils class:
String one = stxt.getText().toString();
String two = etxt.getText().toString();

if (hasFocus && TextUtils.getTrimmedLength(one) != 0
      && TextUtils.getTrimmedLength(two) == 0) {
    etxt.setText(one);
}

A: Never compare strings in Java with == or !=. Use equals(). Try that and see if you get better results.


text:
Q: is this java interface tactic sound? I've been thinking about implementing a certain tactic for my code.
This is my setup:
I've got an interface called "Object".
Then I've got an interface called "Entity" that extends "Object".
From entity then springs countless implementations, like "army", "city", "lemon", etc.
Now, I want to gather all of these Objects into some form of map. Then from that map I want to get the particular implementation of "Object".
My thought out solution for this is as follows:
Object has method :
public Entity getEntity()

All implementations of Object returns null, while Entity returns itself.
Likewise, in entity I'd have:
public Army getArmy()
public City getCity()

That way, I can simply pull an object from the map and get the specific class from it with a series of null checks, like so;
Object o = Objects.getObject(2dCoordinates);
Entity e = o.getEntity();
if (e != null){
Army a = e.getArmy();
if (a != null)
a.armySpecificMethod();
}

All without using "instanceof" and casting, which I hate.
The question is whether there's some unforeseen problem about this? I'd rather learn from someone that knows before refactoring my code and find out for myself.

A: You asked if there are any pitfalls to your strategy. I would say no, since C# uses the same strategy with their as keyword. Example: e as Army would return e if e is-a Army, or null otherwise. It is basicly a cast that instead of failing returns null.
However you don't have to implement this functionality using interfaces, you can write your own as method for example like this:
static <T> T as(Class<T> clazz, Object obj) {
    if (clazz.isInstance(obj)) {
        return (T) obj;
    }
    return null;
}

usage:
Object o = Objects.getObject(2dCoordinates);
Entity e = as(Entity.class, o);
if (e != null) {
    Army a = as(Army.class, e);
    if (a != null)
    a.armySpecificMethod();
}

A: Another approach would be to register callbacks/strategies to be invoked on particular events. Something like that:
public interface OnMapClicked<T> {

    void onItemSelected(T item);

}

And your GameMap (or whatever) implementation would be:
public GameMap {

    private final Map<Class<?>, OnMapClicked> listeners = new HashMap<>();

    public <T> void registerListener(Class<? extends T> type, OnMapClicked<T> listener) {
         listeners.put(type, listener);
    }

    //

    private void onMapClicked(Coordinates coordinates) {
        Object object = findObject(coordinates);

        listeners.get(object.getClass()).onItemSelected(object);
    }

}

That's very rough untested implementation, but hopefully you got the idea. There is one usage of non-generic instance here (in onMapClicked), but it should be safe, since we're checking the input type in registerListener.


text:
Q: Draw horizontal line on chart in chart.js on v2 I have drawn a line chart using chart.js. For the labels and datasets i am getting values from the database. I am new to chart.js and its very powerful library, yet i am unable to completely understand it. I want to draw multiples horizontal lines. Like where if mean of dataset, standard deviation and min and max. I have tried the question here in stackoverflow but these are giving errors or may be i am not able to understand the working. This is my chart.js code
function display_graph(id, label, data) {
var ctx = document.getElementById(id);
var data = {
    labels: data.labels,
    datasets: [
        {
            label: label,
            fill: false,
            lineTension: 0.1,
            backgroundColor: "rgba(75,192,192,0.4)",
            borderColor: "rgba(75,192,192,1)",
            borderCapStyle: 'butt',
            borderDash: [],
            borderDashOffset: 0.0,
            borderWidth: 1,
            borderJoinStyle: 'miter',
            pointBorderColor: "rgba(75,192,192,1)",
            pointBackgroundColor: "#fff",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 1,
            pointHitRadius: 10,
            data: data.assay_value,
            spanGaps: false
        }
    ]
};

//options
var options = {
    responsive: true,
    title: {
        display: true,
        position: "top",
        text: label,
        fontSize: 18,
        fontColor: "#111"
    },
    legend: {
        display: true,
        position: "bottom",
        labels: {
            fontColor: "#333",
            fontSize: 16
        }
    }
};
var Blanks_Chart=null;
Blanks_Chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: options
});}

A: if you want to draw threshold line,easiest way is that using mixed line chart.
Note: Make an array filled with threshold value and the length should be same as your dataset.
var datasets = [1, 2, 3];
var ctx = document.getElementById('chart').getContext('2d');
var thresholdValue = 2;
var thresholdHighArray = new Array(datasets.length).fill(thresholdValue);
var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [
                {datasets}, thresholdHighArray]
            },
            options: {
                responsive: true,
                legend: {
                    position: 'bottom',
                },
                scales: {
                    xAxes: [{
                        display: true,
                        scaleLabel: {
                                display: true,
                                labelString: 'Readings'
                        }
                    }],
                    yAxes: [{
                        display: true,
                        scaleLabel: {
                                display: true,
                                labelString: 'Reading ( °C )'
                        }
                    }]
                },
                annotation: {
                  annotations: [
                    {
                      type: "line",
                      mode: "vertical",
                      scaleID: "x-axis-0",
                      borderColor: "red",
                      label: {
                        content: "",
                        enabled: true,
                        position: "top"
                      }
                    }
                  ]
                }
        });
    };

A: If you are using the NPM package chartjs-plugin-annotation.js, the important thing - which you may forget, is to register the plugin.
So first of all you installed the npm packages (here for React):
npm i react-chartjs-2                (depends on your framework)
npm i chartjs-plugin-annotation      (always required)

See Vue.js or Angular for their framework depending packages.
Option 1: Global plugin registration
import { Line } from 'react-chartjs-2';
import Chart from 'chart.js';
import * as ChartAnnotation from 'chartjs-plugin-annotation';

Chart.plugins.register([ChartAnnotation]); // Global

// ...
render() {
    return (
        <Line data={chartData} options={chartOpts} />
    )
}

Option 2: Per chart plugin registration
import { Line } from 'react-chartjs-2';
import * as ChartAnnotation from 'chartjs-plugin-annotation';

// ...
render() {
    return (
                                                   {/* per chart */}
        <Line data={chartData} options={chartOpts} plugins={[ChartAnnotation]} />
    )
}

chartData is equivalent to the data: { section and chartOpts to options: { from jordanwillis answer. See this github post for further information.
There are many other plugins available for chart.js.

A: You could use the chart.js annotation plugin to easily draw lines on your chart without having to mess with rendering pixels in your canvas manually (the old approach that is giving you errors).  Note, the plugin is created/supported by the same team as chart.js and is mentioned in the chart.js docs.
Here is an example codepen demonstrating creating a line on a chart.
Once you add the plugin, you simply just set annotation properties in your chart config.  Here is an example.
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["January", "February"],
    datasets: [{
      label: 'Dataset 1',
      borderColor: window.chartColors.blue,
      borderWidth: 2,
      fill: false,
      data: [2, 10]
    }]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: 'Chart.js Draw Line On Chart'
    },
    tooltips: {
      mode: 'index',
      intersect: true
    },
    annotation: {
      annotations: [{
        type: 'line',
        mode: 'horizontal',
        scaleID: 'y-axis-0',
        value: 5,
        borderColor: 'rgb(75, 192, 192)',
        borderWidth: 4,
        label: {
          enabled: false,
          content: 'Test label'
        }
      }]
    }
  }
});

A: Here's an example of getting it working in a Rails view if you're using it with the Chartkick gem:
<%=
  line_chart profit_per_day_chart_path(staff), xtitle: 'Day', ytitle: 'Profit',
    library: {
      annotation: {
        annotations: [
          {
            type: 'line',
            mode: 'horizontal',
            scaleID: 'y-axis-0',
            value: 20,
            label: {
              content: 'My Horizontal Line',
              enabled: true
            }
          }
        ]
      }
    }
%>

Ensure that you've registered the chartjs-plugin-annotation.js plugin with Chart.js first:
import ChartAnnotationsPlugin from 'chartjs-plugin-annotation';
Chart.plugins.register(ChartAnnotationsPlugin);


text:
Q: JQuery Javascript Sort Array by Highest Count I have:
myArray = ["ABAB", "ABAB", "ABAB", "CDCD", "EFEF", "EFEF"]

I need to count by occurrences and sort by highest count. This would be the return:
ABAB 3
EFEF 2
CDCD 1

Note, the parameters inside the array are constantly changed so by "grepping" for each static or literal text pattern won't help.
Any idea of the fastest way to accomplish this either with JQuery or plain JS?

A: Step one: build the histogram, as a map element -> its frequency for speed (assumes all elements are strings):
var histogramMap = {};
for(var i=0, len=myArray.length; i<len; i++){
  var key = myArray[i];
  histogramMap[key] = (histogramMap[key] || 0) + 1;
}

Step two: convert to an array of output objects:
var histogram = [];
for(key in histogramMap) histogram.push({key: key, freq: histogramMap[key]});

Step three: sort the histogram
histogram.sort(function(a,b){return b.freq - a.freq})

This also assumes that Object.prototype is not modified. This is a safe assumption to make, and lots (I think) of libraries, including jQuery, make that assumption. But, if you decide to add enumerable properties to Object.prototype, these will be picked up by for..in. If you want to be safe, modify the second step to:
var histogram = [];
for(key in histogramMap){
  if(histogramMap.hasOwnProperty(i)){
    histogram.push({key: key, freq: histogramMap[key]});
  }
}

A: I recently created a library with such a function.
var items = {}, sortableItems = [], i, len, element,
    listOfStrings = ["ABAB", "ABAB", "ABAB", "CDCD", "EFEF", "EFEF"];

for (i = 0, len = listOfStrings.length; i < len; i += 1) {
    if (items.hasOwnProperty(listOfStrings[i])) {
        items[listOfStrings[i]] += 1;
    } else {
        items[listOfStrings[i]] = 1;
    }
}

for (element in items) {
    if (items.hasOwnProperty(element)) {
        sortableItems.push([element, items[element]]);
    }
}

sortableItems.sort(function (first, second) {
    return second[1] - first[1];
});

console.log(sortableItems);

Output
[ [ 'ABAB', 3 ], [ 'EFEF', 2 ], [ 'CDCD', 1 ] ]

A: Try this:
array_elements = ["ABAB", "ABAB", "ABAB", "CDCD", "EFEF", "EFEF"];

var result_array = [];

var current = null;
var cnt = 0;
for (var i = 0; i < array_elements.length; i++) {
    if (array_elements[i] != current) {
        if (cnt > 0) {
            result_array.push([current,cnt]);
        }
        current = array_elements[i];
        cnt = 1;
    } else {
        cnt++;
    }
}
if (cnt > 0) {
    result_array.push([current,cnt]);
}

result_array.sort(function(x,y) {return y[1] - x[1]})
alert(result_array);

The result_array will have the result.

A: see console in firefox to see the resulting object
http://jsfiddle.net/4dqeK/1/
myArray = ["ABAB", "ABAB", "ABAB", "CDCD", "EFEF", "EFEF"];

container={};

 for(var i=0; i < myArray.length;i++){
        var el=myArray[i];
        if( el in container){
            container[el].push(el);
        }
        else{
            container[el]=[];
            container[el].push(el);
        }

    }
    console.log(container);

A: $array = array("ABAB", "ABAB", "ABAB", "CDCD", "EFEF", "EFEF");
   $array1=array_count_values($array);

    arsort($array1);

    foreach($array1 as $x=>$x_value)
    {
        echo "Key=" . $x . ", Value=" . $x_value;
        echo "<br>";
    }


text:
Q: Saving data with table associations in Grails I have two database tables 'Student' and 'Course'. I want a one-to-one relation where there is foreign key of 'Course' table in 'Student' table. The foreign key 'course_id' is appearing in the Student table but whenever I try to save the Student data (after filling form), the data does not get saved and there is no error as well. I am very new to grails. Please guide me how I can save the data correctly.
The table structure is as desired but the data is not getting saved to the database. There is no issue with other code parts because the data is getting saved when I remove the association between the two tables.

Student controller

package com.grails

class studentController {
    def save(Student student){
        student.save()
    }
}

Student domain class

class Student {
    Course course

    String firstName
    String lastName
}

Course domain class

class Course{
    String course_name
    String duration

    static hasOne = [student: Student]

    //static belongsTo = [student: Student]
}

A: Note that grails 4 introduced a bug with one-to-one relationships that gives inconsistent behavior based on the owning side of the relationship: https://github.com/grails/grails-core/issues/11606
I'm not sure if this is the same problem you may be seeing without more information on your error, or even if you're on this version of grails.


text:
Q: Meaning of symbol product (cross) in a circle: ⨂ I came across this expression:
$\tilde{\Phi}(\mu, \nu)\ \dot{=}\ \int_{A\times B}{\Phi(a, b)\ \mathrm{d}\mu \otimes \mathrm{d}\nu}$
In a context where:

*

*$A$ and $B$ are compact metric spaces

*$\mu$ and $\nu$ are probability distribution over $A$ and $B$, resp.

*$\Phi$ is a continuous function $A \times B \rightarrow \mathbb{R}$

*$\tilde{\Phi}(\mu, \nu)$ is said to be the expected value of $\Phi$

I understand that you need to integrate over $A \times B$ to get this expected value, and to take $\mu$ and $\nu$ distributions into account while doing this. But..
How am I supposed to understand the $\otimes$ symbol here? What is this operation? How does $\mathrm{d}\mu$ relates to $a$ and $\mathrm{d}\nu$ relates to $b$ within this integrand?
(To get the full context, I've found this in these pretty neat notes introducing differential game theory (equation 2.8 page 13).)

A: I assume $\mu$ and $\nu$ are distributions with $d\mu$ and $d\nu$ the corresponding measures. Then $d\mu\otimes d\nu$ denotes the product measure. Distributions $\mu$ can be seen as generalised functions, where $\mu(x)$ doesn't have to be defined. However, I think in your case $\mu$ and $\nu$ are just functions, so you may write $\mu(x)$ and $\nu(y)$. In this case $d\mu(x)=\mu(x)dx$, and the product measure becomes simply
$$(d\mu\otimes d\nu)(a,b)=\mu(a)\nu(b)dadb\,.$$
Now, to be (overly) precise, the author actually meant to write
$$\tilde{\Phi}:=\int_{A\times B}\Phi(a,b)(d\mu\otimes d\nu)(a,b)\,,$$
but he assumed that it was clear that $a$ and $b$ are integrated over.
So when $\mu$ and $\nu$ are functions, you have
$$\tilde{\Phi}=\int_{A\times B}\Phi(a,b)\mu(a)\nu(b)dadb\,.$$


text:
Q: View not clickable after translate in CoordinatorLayot I have a ConstraintLayout wrapping my FABs section in the bottom right of the app. I use a layout and not only the buttons because I have more views all around the FABs (they are omitted in the example below, the real layout is more complex). The layout has a CoordinatorLayout as main parent. I have two FABs, one near to the other, when I click the first one the second animates and move up using ViewPropertyAnimations, then I click the second one and other views should appear. ISSUE IS: the translated FAB isn't clickable. I can click on it before the animation starts but not after translation.

What I've found so far:

*

*If I leave only  CoordinatorLayout  and FAbs buttons --> OK, click works after translate

*If I leave only ConstraintLayout and FAbs buttons --> OK, click works after translate

*If I leave CoordinatorLayout , ConstraintLayout and FAbs buttons --> KO, click doesn't work after translate

*If I replace ConstraintLayout with LinearLayout --> KO, click doesn't work after translate

Can you help me to fix this?
Dependencies versions
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'

Fragment layout (it's a simplified version, the real one has many views)
<?xml version="1.0" encoding="utf-8"?>

<androidx.coordinatorlayout.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:clipToPadding="false"
    android:clipChildren="false" >

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/cl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="24dp"
        android:clipChildren="false"
        android:clipToPadding="false"
        app:layout_dodgeInsetEdges="bottom" >

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:src="@android:drawable/ic_delete"
            android:elevation="3dp"
            android:layout_gravity="end|bottom"
            app:fabSize="mini"
            app:layout_constraintBottom_toBottomOf="@+id/fab1"
            app:layout_constraintEnd_toStartOf="@+id/fab1"
            app:layout_constraintTop_toTopOf="@+id/fab1" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:elevation="6dp"
            android:layout_gravity="end|bottom"
            android:src="@android:drawable/btn_star_big_on"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:fabSize="normal"
            android:focusable="true" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Animation code
FloatingActionButton fab1 = requireView().findViewById(R.id.fab1);
FloatingActionButton fab2 = requireView().findViewById(R.id.fab2);

fab1.setOnClickListener(v -> fab2.animate().translationY(-200));
fab1.setOnLongClickListener(v -> {
    fab2.animate().translationY(0);
    return true;
});

fab2.setOnClickListener(v -> Toast.makeText(requireContext(),"click",Toast.LENGTH_SHORT).show());

A: The issue seems solved with constraintlayout:2.1.0


text:
Q: Error scheduling an Email Send Definition My client has been successfully creating and scheduling Email Send Definitions via the SOAP API in what they call the standard version.  Now they are Enterprise customers so I have been working to ensure the process that is already working continues to work.  So far most of the changes have been to add the ClientID to the subscriber list, the email and the Send Definition since they now have multiple Business Units.
 Everything is working except when it comes time to schedule the Email Send Definition, then I get an Error Code 2
The Status Message is:

"Exception occurred during [ScheduleEmailSendDefinition] ErrorID:
  1459951015"

The code I am using to create the Email Send Definition is this:
ClientID clientID = new ClientID();
clientID.ID = account_id;
clientID.IDSpecified = true;

String requestId = null;
String overallStatus = null;

//Define the EmailSendDefinition EmailSendDefinition
sendDef = new EmailSendDefinition();
sendDef.Name = "Test";
sendDef.CustomerKey = "Test";
sendDef.Description = "Used for automation";
sendDef.CategoryID = 819712;
sendDef.CategoryIDSpecified = true;
sendDef.Client = clientID;

//Specify Email
ExactTargetClient.Email email = new ExactTargetClient.Email();
email.ID = emailID;  //ID from validated email
email.IDSpecified = true;
email.Client = clientID;

//Specify SendClassification
SendClassification sc = new SendClassification();
sc.CustomerKey = "Default Commercial";
//Commercial
classification sc.Client = clientID;

//Specify the SendDefinitionList
SendDefinitionList[] defList = new SendDefinitionList[1];
defList[0] = new SendDefinitionList();
defList[0].SendDefinitionListTypeSpecified = true;
defList[0].SendDefinitionListType = SendDefinitionListTypeEnum.SourceList;
defList[0].DataSourceTypeID = DataSourceTypeEnum.List;
defList[0].DataSourceTypeIDSpecified = true;

List list = new List();
list.ID = listID;
list.IDSpecified = true;
list.Client = clientID;
defList[0].List = list;
defList[0].Client = clientID;

SenderProfile profile = new SenderProfile();
profile.CustomerKey = "Default";
profile.Client = clientID;
sendDef.SenderProfile = profile;

//Associate the email, the sendclassification, and SendDefinitionList
sendDef.Email = email;
sendDef.SendClassification = sc;
sendDef.SendDefinitionList = defList;

CreateResult[] results = etFramework.Create(new CreateOptions(), new APIObject[] { sendDef } , out requestId, out overallStatus);

And then the code to schedule the Email Send Definition:
String pRequestId = null;
String pOverAllStatus = null;
String statusMessage = null;

ClientID clientID = new ClientID();
clientID.ID = account_id;
clientID.IDSpecified = true;

ScheduleDefinition sd = new ScheduleDefinition();
sd.Occurrences = 1;
sd.OccurrencesSpecified = true;

DateTime time = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, scheduledTime.Hour, scheduledTime.Minute, 0, DateTimeKind.Local);
sd.StartDateTime = time;
sd.StartDateTimeSpecified = true;
sd.Client = clientID;

//sendDef was created above
sendDef.CustomerKey = "Test";
sendDef.Client = clientID;
ScheduleResult[] perfResults = etFramework.Schedule(new ScheduleOptions(), "start", sd, new APIObject[] { sendDef }, out pOverAllStatus, out statusMessage, out pRequestId);

A: The problem was the ScheduleOptions for the schedule message needed to specify a Client ID

A: Here's an example of what the soap should look like:
<ScheduleRequestMsg>
<Options>
    <Client><ClientID>12345678</ClientID></Client>
</Options></ScheduleRequestMsg>


text:
Q: Calculus Integral Rotation Circle
Is this equation the equation for a circle with radius r and shifted down R?
How would i find the bounds of the integral for this problem? or is the integral going to be in terms of r?

A: It is a circle of radius $r$ shifted up by $R$.  To see that it is shifted up, note that compared with $x^2+y^2=r^2$, you must increase $y$ by $R$ to get a solution.
Your solution will be in terms of both $r$ and $R$.
The volume will be a torus.  $R$ is the radius of the centerline circle and $r$ is the radius of the circle that has been swept around to create the torus.  The bounds on the integral depend on which direction you are integrating.  $x$ ranges from $-r$ to $r$, while $y$ ranges from $-r-R$ to $r+R$

A: The standard circle is shifted up by $R$.
The solid you get is a torus (doughnut).  Its volume depends on the parameters $r$ and $R$.
For the volume, there are various ways to proceed. For example, we can do slicing perpendicular to the $y$-axis, or use the method of cylindrical shells.
Let's do slicing. We have $(y-R)^2=r^2-x^2$, and therefore $y=R\pm\sqrt{r^2-x^2}$.
The expression with the $+\sqrt{r^2-x^2}$ is the top half of the circle, and the other expression gives the bottom half of that circle. So we find the volume obtained by rotating the top half, and subtract the volume obtained by rotating the bottom half.
Then our volume is
$$\int_{-r}^r \pi \left((R+\sqrt{r^2-x^2})^2-(R-\sqrt{r^2-x^2})^2\right)\,dx.$$
A little algebra simplifies the integrand very considerably: there is a lot of cancellation. And the integral we end up with has a familiar geometric interpretation, so we can give the answer without actually integrating.


text:
Q: Use Media Queries to make main website responsive or redirect to a new one for mobile? I want to make a mobile friendly version of my website, but I have this dilemma.
What is better? Use CSS3 Media Queries to make main website responsive or detect if user is using a mobile and redirect to a new one (for example m.example.com).

A: This really is depending upon what kind of website you are having. Your decision will not only affect the way your site is presenting, but also how you would deliver business strategies (if it's a commercial thing).
Responsive design will work just great with simple websites that doesn't really need too many detailed experiences. Company profiles, or landing pages will fit best with RWD.
Once you're building much more complicated application, you might need to re-think how the user will interact with even the tiniest part of it. Note that using RWD often require greedier resources compared to a dedicated mobile site. If you're dealing with e-commerce, social media, or some other mature applications, a mobile version is a way to go.


text:
Q: udp can not receive any data Here is my code
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.Bind(new IPEndPoint(IPAddress.Any, 0));

// Broadcast to find server
string msg = "Imlookingforaserver:" + udp_listen_port;
byte[] sendBytes4 = Encoding.ASCII.GetBytes(msg);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Parse("255.255.255.255"), server_port);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
sck.SendTo(sendBytes4, groupEP);

//Wait response from server
Socket sck2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck2.Bind(new IPEndPoint(IPAddress.Any, udp_listen_port));
byte[] buffer = new byte[128];
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, udp_listen_port);
sck2.ReceiveFrom(buffer, ref remoteEndPoint); //<<< I never pass this line

I use above code to try find a server. First I broadcast a message and then I wait for a response from the server.
A test I made with the server written in C++ and running in Windows Vista, client written in C# and run on the same machine with server.
Problem is: The server can receive message which client broadcast, but client can not receive anything from server.
I try to write a client with C++ and it work like a charm, I think my problem is in C# client.

A: I would start listening on that port before you broadcast.  You're using UDP which is connectionless so you could be missing your packet.
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.Bind(new IPEndPoint(IPAddress.Any, 0));
//Wait response from server
Socket sck2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck2.Bind(new IPEndPoint(IPAddress.Any, udp_listen_port));
byte[] buffer = new byte[128];
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, udp_listen_port);

// Broadcast to find server
string msg = "Imlookingforaserver:" + udp_listen_port;
byte[] sendBytes4 = Encoding.ASCII.GetBytes(msg);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Parse("255.255.255.255"), server_port);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
sck.SendTo(sendBytes4, groupEP);

sck2.ReceiveFrom(buffer, ref remoteEndPoint);


text:
Q: Why does my priorityqueue look like this? I created a Student class:
class Student implements Comparable<Student> {
int id;
String name;
double cgpa;

public Student(int id, String name, double cgpa) {
    this.id = id;
    this.name = name;
    this.cgpa = cgpa;
}

int getId() {
    return id;
}

String getName() {
    return name;
}

double getCgpa() {
    return cgpa;
}

@Override
public String toString() {
    return "id= " + id + " name= " + name + " cgpa= " + cgpa;
}

@Override
public int compareTo(Student second) {
    if (getCgpa() == second.getCgpa()) {
        if (getName().equals(second.getName())) {
            return Integer.compare(getId(),second.getId());
        } else {
            return getName().compareTo(second.getName());
        }
    } else {
        return Double.compare(getCgpa(), second.getCgpa());
    }
}
}

Then I inserted 3 students into a max heap:
Student john = new Student(50, "John", 3.75);
Student mark = new Student(24, "Mark", 3.8);
Student shafaet = new Student(35, "Shafaet", 3.7);
PriorityQueue<Student> pq = new PriorityQueue<Student>(1, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                // reverse order for max instead of min
                return s2.compareTo(s1);
            }
        }
        );
pq.add(john);
pq.add(mark);
pq.add(shafaet);

I expected Mark followed by John followed by Shafaet.  What did I do wrong?

A: There's a lot to debug there. I suggest you try to simplify your code and then unit test it in parts.
Firstly, there's really no need to implement your own compareTo - everything you need is in the Comparator class already:
Comparator<Student> studentOrder = Comparator
    .comparing(Student::getCgpa)
    .thenComparing(Student::getName)
    .thenComparing(Student::getId);

That's much easier to read and doesn't embed your order as a 'natural' ordering of Students.
Now you can unit test the comparator. E.g., using junit and assertj:
assertThat(new Student(1, "fred", 1.0)).usingComparator(studentOrder)
    .isLessThan(new Student(1, "fred", 1.1))
    .isLessThan(new Student(1, "gina", 1.0))
    .isLessThan(new Student(2, "fred", 1.0));

And so on.
Once you're confident you've got the ordering right then use it in your priority queue's constructor.
PriorityQueue<Student> queue = new PriorityQueue<>(studentOrder.reversed());


text:
Q: Unable to open a zip file that was made in Python I have created 1594 .npz files from dicom files after preprocessing. Now I want to open there zip files using np.load() method but its giving the bad zip file error. The thing is, this is working for a batch of 20 but not 1594. Is it because np.load() cant open so many zip files or would there have been a problem while creating the zip files like a disturbance thats causing this error?
patients = os.listdir(preprocessed_data_folder)
shuffle(patients) # randomize the order of data
# initialization
for i in range(len(patients)):
if patients[i].startswith('.'): continue # ignore hidden files
#patient_data =
if np.load(preprocessed_data_folder + patients[i])['set'] == 'test': continue

The error I'm getting is
      C:\Users\sahana\anaconda3\lib\zipfile.py in _RealGetContents(self)
      1323             raise BadZipFile("File is not a zip file")
      1324         if not endrec:
      -> 1325             raise BadZipFile("File is not a zip file")
      1326         if self.debug > 1:
      1327             print(endrec)

      BadZipFile: File is not a zip file


text:
Q: Issue on Stop Sliding a List to Left and Right on First and Last Child I am trying to create a simple Carousel slider at This Demo. As you can see the slider works fine! but I do not know how to stop it at both end(left and right) side. I mean how can I control to disable the left btn when the first child of ul is the first displaying( visible) item at left and disable the Right btn while the last child of <ul> is rendering in the .well box?
Here is the simple code which I have so far:
$(".leftslide").on("click",function(){
   $(".list-inline").animate({left:'-=187px'}, 300);
});
$(".rightslide").on("click",function(){
   $(".list-inline").animate({left:'+=187px'}, 300);
});

var maginLeft =  $("ul>:first-child").css("marginLeft");
var maginRight = $("ul>:last-child").css("marginRight");

alert(maginLeft + maginRight );

I tried to control this by using  var maginLeft =  $("ul>:first-child").css("marginLeft"); but it didnt do the job!
Thanks,

A: You would need to do something like this:
$(".leftslide").on("click",function(){
    rightbtn.removeAttr("disabled");
    current++;
    if(current+images_shown >= images.length) {
         leftbtn.attr("disabled","disabled")
    }
    console.log(imageWidth+offset);
    var qty=Math.ceil(imageWidth+offset);
    if(current+images_shown==images.length) qty+=offset;
    list.animate({left:'-='+qty+'px'}, 300);

});

Full code: http://jsfiddle.net/juvian/CXRP5/6/
You still need to do something about clicking several times before animation ends though, but this should give you an idea of how to approach the problem


text:
Q: UICollectionView zoom entire grid I am using a UICollectionView to display a grid of cells with 3 columns. When a cell is selected, I'd like to zoom into the entire collection with the selected cell in the centre. I'd also like to fade out the surrounding cells and keep the selected on at full opacity.
The following code scales the grid but doesn't scroll to the selected cell:
UIView.animate(withDuration: 0.35, animations: {
    self.collectionView.transform = CGAffineTransform(scaleX: 3, y: 3)
})

I was hoping I could do it by changing the UICollectionViewFlowLayout and the UICollectionView frame but I'm not sure whether I'm going down the wrong path with this (the following code just moves all the cells over to the left):
UIView.animate(withDuration: 0.35, animations: {() -> Void in
    self.collectionView.setCollectionViewLayout(self.zoomedGridLayout, animated: true)

    let zoomedRect = CGRect(x: -rect.width, y: 0, width: rect.width*3, height: rect.height)
    self.collectionView.frame = zoomedRect
    self.collectionView.collectionViewLayout.invalidateLayout()
})

The collection view doesn't need to be scrollable after the animation (I intend to use it only as a transition to another view).


text:
Q: crashing when writing to a vb string passed to c++ dll Using visual studio 2012, I need to pass a string to a DLL in C++.  To do this, in VB I create a string by s = new string("  ", 100), which creates a string s of 100 spaces.  I then pass this string which will be written into with less than 100 chars and it gets passed back with the new string as expected.
in the declare function I use
...,s as string...

And NOT:
by reference s as string

However, if before passing this string but after creating it as described above I write a short string in VB into it such as s = "hi fox" and then pass it into the DLL and write into it with a string longer then 6 chars, it crashes!!
The lesson seems to be that after creating a blank string with the new string() function, you cannot write a shorter string into it.  It is as if the memory allocated to the string in VB becomes not the 100 chars that you created the string with but the size of the memory of s is now the size of the shorter string.
If this is reasonable behavior, I would like to know.  It is quite different from the new function of C++, in which the size of memory allocated is not changed by the size of the array you write to it.
Thank you for any response and interest you may have.

A: Unlike C++, a VB string is not stored with the string header, and contains no terminating zero. When you assign "hi fox" to the string, the 100-character memory location is no longer available, replaced by the 6 character string. You might be able use a byte array in place of a string for this parameter, but you should be careful of 2-byte characters.


text:
Q: Need of the cold body in heat engine Purpose of heat engine is to transfer heat into the useful work, basically. Working object either gas or liquid takes heat from a thermal energy reservoir as a result of which their internal energy increases and this energy is somehow used to do work.  Why would we need a cold body then?

A: The heat engine is assumed to be brought back to it's original thermodynamic state, after each cycle of operation. That is, in particular, the operation is reversible, with the net change in entropy of the engine being 0.
The net change in internal energy $U$ and entropy $S$ have to be $0$, after a cycle of operation. The net energy change is indeed zero, considering that the work done is equivalent to the net heat taken in. For the entropy change to be zero, it has to get rid of some of the heat it took in, in the form of heat itself.
In order to maximize the amount of work done, it may expel heat at a very low temperature, so it has to give out as little heat as possible; but give out some heat it must, to the cold body.

A: The cold reservoir provides a heat sink for the excess heat that is rejected after some of the heat is converted into work. We know from the second law of thermodynamics that 100% conversion of heat to work is impossible hence a colder sink is necessary to allow a heat engine to work in the first place.

A: Entropy and the need to minimise its creation is the reason for the cold reservoir, $R_c $.

We need a heat sink because the entropy is a state function, and at the end of the reversible process (which is visualized through the Carnot cycle diagram relevant for this problem), the entropy value of the system must return to the value it had originally. Thanks to  Aritro Pathak for this

Since the state of the engine must be unchanged at the end of a cycle, the entropy it expels must be at least as much as the entropy it absorbs. It expels entropy, through its working fluid, usually a gas, to $R_c $.
The efficiency of a Carnot engine, for example  is $(1 -\frac {R_c}{R_h})$, which is as high as you can get, but at the cost of a very "slow" engine.
If you fitted it to a car, people could easily walk past you, even at your top speed.
Every engine utilises a  working fluid, that absorbs heat  from the hot reservoir,$R_h $, expels waste heat and does useful work. In say, a Carnot engine, the  working fluid that operates the piston in the "middle" of the engine, needs a source of heat. As it absorbs heat from $R_h $, the entropy of $R_h $ decreases, while the entropy of the working fluid increases. We need to keep the working fluid at a slightly lower temperature than $R_h $, as otherwise there will be no energy transfer between two objects at the same temperature.  We keep the gas at this temperature by letting it expand isothermally as it absorbs the energy.

Image Source: NASA Carnot Engine
During the part of the cycle where the working fluid is in contact with the cold reservoir,  $R_c $, we would like it's temperature to be just slightly higher than that of $R_c $, so to avoid creating any new entropy. As the heat leaves the gas, we want to compress it isothermally, to maintain its temperature.


text:
Q: Proving that $f:U\to\mathbb{R}^n$ differentiable is an open map when $\det \operatorname{J}f(a) \neq 0$
Let $U\subset\mathbb{R}^n$ be an open set and $f:U\to\mathbb{R}^n$ a differentiable function such that $\det \operatorname{J}f(a)\neq 0\; \forall a\in U$. Prove that if $V$ is an open subset of $U$ then $f(V)$ is an open subset of $\mathbb{R}^n$

I'm not sure how could I do this, I tried to sketch a proof as follows:
Let $V$ be an open set as the problem says, I have to prove that if $a\in V$ -therefore $a$ is an interior point- then $f(a)$ is an interior point of $f(V)$.
$\det \operatorname{J}f(a)\neq 0$ implies that $f$ is smooth for every $a\in U$ and by the inverse function theorem exists $f^{-1}$ and $Y\subset\mathbb{R}^n $ in which $f^{-1}$ is continuous.  Suppose $f(V)\subset Y$ is not open, therefore for some $y\in f(V)$ we have $B_{\epsilon}(y) \not\subset f(V)$ for  every $\epsilon>0\;$
Since $f$ is invertible we can get  $a$ with $f^{-1}$ such that $f(a) = y$ and since $V$ is open $\exists\delta>0$ such that $B_{\delta}(a)\subset V$.
The continuity of $f^{-1}$ implies that because of the openness of $B_{\delta}(a)$ the set $f(B_{\delta}(a))$ must be open in $f(V)$ which contradicts that $B_{\epsilon}(y)\not\subset f(V)$ for  every $\epsilon>0\;$.
Is this ok?


text:
Q: How 'MOD' the binary operation works with floor function? I was looking for some example on MOD and floor function from Concrete Mathematics book(1). But, the solution of each example is very confusing for me.
The general formula of x mod y is;
x mod y = x - y(lfloor (x / y) rfloor)  [for y is not equal to 0]
Here, lfloor means left floor and rfloor means right floor
I know, how it works when value of x and y is positive. But, I get confused when value of x or y or both becomes negative.
Examples from the book(1):
5 mod -3 = 5 - (-3)(lfloor (5 / (-3)) rfloor) = -1

-5 mod 3 = -5 -3(lfloor (-5 / 3) rfloor) = 1

-5 mod -3 = -5 - (-3)(lfloor (-5 / (-3)) rfloor) = -2

Resource:
(1) Book - Concrete Mathematics See page 95


text:
Q: Facing issue on adding ios platform for PhoneGap I am tring to add ios platform project for Phonegap using CLI but failing with following issue.
Creating ios project...
xcrun: Error: could not stat active Xcode path '/Volumes/Xcode/Xcode.app/Contents/Developer'. (No such file or directory)
Cordova can only run in Xcode version 4.6 or greater.
Error: /Users/Mahmood1/.cordova/lib/ios/cordova/3.4.1/bin/create: Command failed with exit code 2
    at ChildProcess.whenDone (/usr/local/lib/node_modules/cordova/src/superspawn.js:126:23)
    at ChildProcess.EventEmitter.emit (events.js:98:17)
    at maybeClose (child_process.js:743:16)
    at Process.ChildProcess._handle.onexit (child_process.js:810:5)

Note : i have two version of xcode is installed in applications ie. xcode 5.1 and xcode 4.6.Where xcode 5.1 is name as "xcode" and xcode 4.6 named as "xcode2".

A: more information on the xcode-select command if you have installed Xcode in a different location
The "Error: No developer directory found at /Developer" message is displayed if the create script can not find the location of the command line tools within Xcode. This can occur if more than one version of Xcode is installed on the system or when upgrading from older versions of Xcode. The solution is to run the xcode-select command to set the location. If you have installed Xcode in the default location the command to execute is:

more Information https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/xcode-select.1.html


text:
Q: Display messages from both users ORDER By time my problem is that I want to display the messages between two users and order them by time.
I nmanaged to display the messages from each user but it displays first for the user George and the for user Niklakis as it shows in the image below...

What I want is to display both of the messages order by time.
This is part of my code...
$query  = "SELECT * FROM messages WHERE recip='$view' ORDER BY time DESC";
        $query2  = "SELECT * FROM messages WHERE recip='$username' ORDER BY time DESC";
        $result = queryMysql($query);
        $result2 = queryMysql($query2);
        $num    = mysql_num_rows($result);
        $num2    = mysql_num_rows($result2);

        for ($j = 0 ; $j < $num ; ++$j)
        {
            $row = mysql_fetch_row($result);

            if ($row[3] == 0 || $row[1] == $username || $row[2] == $username)
            {
                echo date('M jS \'y g:ia:', $row[4]);
                echo " $row[1] ";

                if ($row[3] == 0)
                    echo "wrote: "$row[5]" ";
                else echo "private message: " .
                      ""$row[5]" ";

                if ($row[2] == $username)
                    echo "[erase]";

                echo "
";
            }
        }
        for ($j = 0 ; $j < $num2 ; ++$j)
        {
            $row2 = mysql_fetch_row($result2);

            if ($row2[3] == 0 || $row2[1] == $username || $row2[2] == $username)
            {
                echo date('M jS \'y g:ia:', $row2[4]);
                echo " $row2[1] ";

                if ($row2[3] == 0)
                    echo "wrote: "$row2[5]" ";
                else echo "private message: " .
                      ""$row2[5]" ";

                if ($row2[2] == $username)
                    echo "[erase]";

                echo "
";
            }
        }

I can understand that my problem happens because I have two different for loops and I probably need only ONE for loop to do this work. But I tried and I could find a way to do this.
Can you help?
Thank you.

A: You use the same code for both query results (tip for the future: PHP supports something like functions :D try it out) and your queries have the same structure so why don't you just fecht all entries for both users and sort them? Have you tried this out?
$query  = "SELECT * FROM messages WHERE (recip='$username' AND auth='$view') OR (recip='$view' AND auth='$username') ORDER BY time DESC";


text:
Q: How do I consolidate migrations using EF Core? I have these migrations:
00000000000000_First
20161101000000_Foo
20161102000000_Bar
// ...many many MANY more
20161108000000_Baz

I want to consolidate from Foo to Baz into one new migration. I know how to do that in EF, but not in EF Core.
I tried this:
dotnet ef update database 00000000000000_First
// delete all other migration classes
dotnet ef migrations add Consolidated
dotnet ef update

I expect that the new Consolidated migration will contain all changes to the model. But its Up() and Down() methods are empty.
What am I doing wrong?

A: You're missing one step. Because of the new model snapshot, after you manually delete the migration files, you'll need to run dotnet ef migrations remove (or Remove-Migration in PMC) to get it back in sync.
Instead of manually deleting the files, you could also just run dotnet ef migrations remove multiple times, but it's smart enough to detect manually deleted migrations.

A: EF Core, when executing ef migrations add, does NOT look into real database. Only your code (and DB model snapshot in Migrations folder) is used.
So, you need remove migrations from your migrations folder (using dotnet ef migrations remove multiple times) and then create consolidated using ef migrations add.
About your real database - if you want to roll it back too, you should run ef database update XXX before removing migrations. Or, if you are collapsing all migrations - you can simple drop database completely and then recreate from new migration(s).


text:
Q: SADES SA-806 on xbox one Bought this headset, wont work can only hear people talk in parties, no place to put the mic (red) cord, wondering if the split adapter for both of these plug ins will work on xbox one.

A: I use a headset very similar to this for my Xbox One.  It has separate 3.5mm male connectors for mic and stereo audio out.
If your XB1 controller doesn't have a 3.5 mm jack on it, you'll need a Xbox One Stereo Headset Adapter.  It sounds like you're already plugging your headset into your controller, though.  That means you've either got a second-gen XB1 controller that has the jack, or you're using the adapter already.
The other piece you'll need is a 3.5mm headset adapter, one that goes from two, 3-position 3.5mm female in to one, 4-position 3.5mm male out.  It sounds complicated, but it's really quite simple.  Just plug in the two cords from your headset to one end, and then put the single male jack into the controller.
Here's one device that will likely work, but there are tons available on Newegg, Amazon, etc.


text:
Q: Is there a standard for Album Art? I using a couple of methods to assign the artwork to my music files. The source images ranges from really small ones e.g. 100px X 100px to bigger ones like 500px (all jpegs). Somehow, they don't always appear (e.g. on my walkman phone or my wife's ipod), but they do appear on my PC media player.
I'm wondering is it due to the size, aspect ratio or other reasons.

A: I would say it depends.  The images iTunes downloads are all consistent, but linux players like Amarok look for Album art from Amazon - it basically does a keyword search and whatever images it can find it makes available as album art choices.  Those images are all sorts of sizes and formats.
As far as players, some older players had a resolution of 176x132 pixels versus the newer 320x240.  The iPod touch has 480x320.

A: Which media player do you use ? Windows Media Player, IIRC, picks up album art and stores them as folder.jpeg or AlbumArtSmall.jpg in the folder where the music files exist.

A: 80x80 pixels, plain and simple.

A: You said that your album art dont appear. Simple suggestions -

*

*Always use ones whose resolutions are above 250 pixels.

*Make sure that they have an aspect ration of 1:1 or black/white bands will appear depending on the device.

*Tag them, don't use WMP as it assigns 200x200 ones no matter what the original image resolution.

That ought to do it.


text:
Q: I want to sort value in pivot using pandas at multilevel df = pd.DataFrame({'A': ['John', 'Boby', 'Mina', 'Peter', 'Nicky'],
      'B': ['Pune', 'Mumbai', 'Pune', 'Mumbai', 'Pune'],
      'C': [27, 23, 21, 25, 24]})

      A      B      C
0   John    Pune    27
1   Boby    Mumbai  23
2   Mina    Pune    21
3   Peter   Mumbai  25
4   Nicky   Pune    24

table = pd.pivot_table(df, values ='C', index =['B', 'A'],
                          aggfunc = np.sum)
table

                C
  B      A
Mumbai  Boby    23
        Peter   25
Pune    John    27
        Mina    21
        Nicky   24

I want to sort this pivot 'B' groupwise summation in descending order.Here as pune have (27+21+24) 72 numbers which is greater than mumbai(23+25=48)
SO pune should be at level 1 and mumbai.
Again in Pune group it should be in s=descending order .i.e John,Nicky and then Mina
in Mumbai group peter and Boby.
There could be many values in B
required output:
               C
  B      A
Pune    John    27
        Nicky   24
        Mina    21
Mumbai Peter    25
        Boby    23

A: Create helper level with aggregated values and use it for sorting with first level:
#simplify solution - aggregate sum for all numeric columns
table = df.groupby(['B', 'A']).sum()

table = (table.set_index(table.groupby(level=0)['C'].transform('sum'), append=True)
              .sort_index(level=[-1,0], ascending=[False, True])
              .droplevel(-1))
print (table)
               C
B      A
Pune   John   27
       Mina   21
       Nicky  24
Mumbai Boby   23
       Peter  25


text:
Q: In angular 8, when uplaod the build error occurs due to polyfills-es2015 In angular 8, When I upload the build error occurs
Error :-
polyfills-es2015.db074f152f5fbfd29825.js:1 Uncaught TypeError: Cannot set property 'true' of undefined
    at Object.6dTf (polyfills-es2015.db074f152f5fbfd29825.js:1)
    at a (runtime-es2015.30fc626ba611e35f5ac3.js:1)
    at Module.hN/g (polyfills-es2015.db074f152f5fbfd29825.js:1)
    at a (runtime-es2015.30fc626ba611e35f5ac3.js:1)
    at Object.1 (polyfills-es2015.db074f152f5fbfd29825.js:1)
    at a (runtime-es2015.30fc626ba611e35f5ac3.js:1)
    at t (runtime-es2015.30fc626ba611e35f5ac3.js:1)
    at Array.r [as push] (runtime-es2015.30fc626ba611e35f5ac3.js:1)
    at polyfills-es2015.db074f152f5fbfd29825.js:1

How to resolve this error.
Environment:-
Angular CLI: 8.0.1
Node: 10.15.3
OS: linux x64
Angular: 8.0.0
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... platform-server, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.800.1
@angular-devkit/build-angular     0.800.1
@angular-devkit/build-optimizer   0.800.1
@angular-devkit/build-webpack     0.800.1
@angular-devkit/core              8.0.1
@angular-devkit/schematics        8.0.1
@angular/cli                      8.0.1
@angular/http                     7.2.15
@ngtools/webpack                  8.0.1
@schematics/angular               8.0.1
@schematics/update                0.800.1
rxjs                              6.5.2
typescript                        3.4.5
webpack     4.30.0

I am used ng build --prod --aot --build-optimizer command to build the app.

A: web-animations-js published 2.3.2 which includes the fix for this error on angular 8

A: The problem is coming from web-animations-js.
Since Angular 6, it is no longer needed:

We've updated our implementation of Animations to no longer need the
  web animations polyfill. This means that you can remove this polyfill
  from your application and save approximately 47KB of bundle size,
  while increasing animations performance in Safari at the same time.

https://angular.io/guide/browser-support#enabling-polyfills
Remove the import from polyfills.ts:
import 'web-animations-js';

And remove "web-animations-js" from your package.json:
"web-animations-js": "^2.3.1"

This solved my problem.
The current polyfills.ts from Angular does not contain it anymore:
https://github.com/angular/angular/blob/master/aio/src/polyfills.ts

A: Angular 8 has the breaking changes with the versions of typescript and Node
typescript version should be 3.4
Node version should be 12 or later

A: polyfills-es2015.94d3ba46aae3a65c2d88.js:2          GET http://localhost:3000/api/stuff 404 (Not Found)
_ @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
scheduleTask @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
onScheduleTask @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
scheduleTask @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
scheduleTask @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
scheduleMacroTask @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
u @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
(anonymous) @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
s. @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
(anonymous) @ main-es2015.bd44af9c4a4f085f43e6.js:2
_trySubscribe @ main-es2015.bd44af9c4a4f085f43e6.js:2
subscribe @ main-es2015.bd44af9c4a4f085f43e6.js:2
$ @ main-es2015.bd44af9c4a4f085f43e6.js:2
_innerSub @ main-es2015.bd44af9c4a4f085f43e6.js:2
_tryNext @ main-es2015.bd44af9c4a4f085f43e6.js:2
_next @ main-es2015.bd44af9c4a4f085f43e6.js:2
next @ main-es2015.bd44af9c4a4f085f43e6.js:2
(anonymous) @ main-es2015.bd44af9c4a4f085f43e6.js:2
_trySubscribe @ main-es2015.bd44af9c4a4f085f43e6.js:2
subscribe @ main-es2015.bd44af9c4a4f085f43e6.js:2
call @ main-es2015.bd44af9c4a4f085f43e6.js:2
subscribe @ main-es2015.bd44af9c4a4f085f43e6.js:2
call @ main-es2015.bd44af9c4a4f085f43e6.js:2
subscribe @ main-es2015.bd44af9c4a4f085f43e6.js:2
call @ main-es2015.bd44af9c4a4f085f43e6.js:2
subscribe @ main-es2015.bd44af9c4a4f085f43e6.js:2
getStuff @ main-es2015.bd44af9c4a4f085f43e6.js:2
ngOnInit @ main-es2015.bd44af9c4a4f085f43e6.js:2
(anonymous) @ main-es2015.bd44af9c4a4f085f43e6.js:2
(anonymous) @ main-es2015.bd44af9c4a4f085f43e6.js:2
no @ main-es2015.bd44af9c4a4f085f43e6.js:2
Ao @ main-es2015.bd44af9c4a4f085f43e6.js:2
(anonymous) @ main-es2015.bd44af9c4a4f085f43e6.js:2
updateDirectives @ main-es2015.bd44af9c4a4f085f43e6.js:2
to @ main-es2015.bd44af9c4a4f085f43e6.js:2
co @ main-es2015.bd44af9c4a4f085f43e6.js:2
uo @ main-es2015.bd44af9c4a4f085f43e6.js:2
to @ main-es2015.bd44af9c4a4f085f43e6.js:2
co @ main-es2015.bd44af9c4a4f085f43e6.js:2
ao @ main-es2015.bd44af9c4a4f085f43e6.js:2
to @ main-es2015.bd44af9c4a4f085f43e6.js:2
co @ main-es2015.bd44af9c4a4f085f43e6.js:2
uo @ main-es2015.bd44af9c4a4f085f43e6.js:2
to @ main-es2015.bd44af9c4a4f085f43e6.js:2
co @ main-es2015.bd44af9c4a4f085f43e6.js:2
ao @ main-es2015.bd44af9c4a4f085f43e6.js:2
to @ main-es2015.bd44af9c4a4f085f43e6.js:2
detectChanges @ main-es2015.bd44af9c4a4f085f43e6.js:2
tick @ main-es2015.bd44af9c4a4f085f43e6.js:2
(anonymous) @ main-es2015.bd44af9c4a4f085f43e6.js:2
invoke @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
onInvoke @ main-es2015.bd44af9c4a4f085f43e6.js:2
invoke @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
run @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
run @ main-es2015.bd44af9c4a4f085f43e6.js:2
next @ main-es2015.bd44af9c4a4f085f43e6.js:2
r @ main-es2015.bd44af9c4a4f085f43e6.js:2
__tryOrUnsub @ main-es2015.bd44af9c4a4f085f43e6.js:2
next @ main-es2015.bd44af9c4a4f085f43e6.js:2
_next @ main-es2015.bd44af9c4a4f085f43e6.js:2
next @ main-es2015.bd44af9c4a4f085f43e6.js:2
next @ main-es2015.bd44af9c4a4f085f43e6.js:2
emit @ main-es2015.bd44af9c4a4f085f43e6.js:2
Gs @ main-es2015.bd44af9c4a4f085f43e6.js:2
onHasTask @ main-es2015.bd44af9c4a4f085f43e6.js:2
hasTask @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
_updateTaskCount @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
_updateTaskCount @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
runTask @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
_ @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
Promise.then (async)
g @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
scheduleTask @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
onScheduleTask @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
scheduleTask @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
scheduleTask @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
scheduleMicroTask @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
E @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
then @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
appInitializer @ main-es2015.bd44af9c4a4f085f43e6.js:2
runInitializers @ main-es2015.bd44af9c4a4f085f43e6.js:2
(anonymous) @ main-es2015.bd44af9c4a4f085f43e6.js:2
(anonymous) @ main-es2015.bd44af9c4a4f085f43e6.js:2
(anonymous) @ main-es2015.bd44af9c4a4f085f43e6.js:2
invoke @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
onInvoke @ main-es2015.bd44af9c4a4f085f43e6.js:2
invoke @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
run @ polyfills-es2015.94d3ba46aae3a65c2d88.js:2
run @ main-es2015.bd44af9c4a4f085f43e6.js:2
bootstrapModuleFactory @ main-es2015.bd44af9c4a4f085f43e6.js:2
zUnb @ main-es2015.bd44af9c4a4f085f43e6.js:2
l @ runtime-es2015.cdfb0ddb511f65fdc0a0.js:1
0 @ main-es2015.bd44af9c4a4f085f43e6.js:2
l @ runtime-es2015.cdfb0ddb511f65fdc0a0.js:1
t @ runtime-es2015.cdfb0ddb511f65fdc0a0.js:1
r @ runtime-es2015.cdfb0ddb511f65fdc0a0.js:1
(anonymous) @ main-es2015.bd44af9c4a4f085f43e6.js:2
Show 40 more frames
main-es2015.bd44af9c4a4f085f43e6.js:2 ep {headers: Hd, status: 404, statusText: 'Not Found', url: 'http://localhost:3000/api/stuff', ok: false, …}


text:
Q: Diffusion equation with time-dependent boundary condition The bottom surface (located at $y=0$) of a semi-infinite, electrically conducting slab is subject to the slowly oscillating magnetic field $B = B_0 \cos(\omega t)$.
I am trying to find an expression for the magnetic field within the conductor as a function of $y$ and $t$ using the 1D diffusion equation:
$$\frac{\partial B}{\partial t} = \alpha \frac{\partial^2 B}{\partial y^2}$$
I know that the solution is given by:
$$B = B_0 \exp(-\frac{y}{\delta})\cos(\omega t -\frac{y}{\delta})$$
where $\delta = \sqrt{2 \alpha/\omega}$.
However, I can't quite figure out how to get there due to the time-dependent boundary condition.
I have tried separation of variables but with not much luck, since the solution I am looking for can't be expressed as a product $Y(y)T(t)$.
Could someone please tell me how to get to the solution?

A: With slight changes in notation, we look for bounded solutions of $B_t = \alpha B_{yy}$ in the
half-plane $y>0$ subject to $B(t, y=0) = B_0\cos\omega_0 t$.
Suppose $B$ is a solution. Proceeding formally, assume
\begin{equation*}
 B(t, y) =
 \frac{1}{\pi}\int_0^\infty c(\omega, y)\cos\omega t\, d\omega +
 \frac{1}{\pi}\int_0^\infty s(\omega, y)\sin\omega t\, d\omega
 \tag{1}
\end{equation*}
where
\begin{align*}
 c(\omega, y) &= \int_{-\infty}^\infty\, B(t, y)\cos\omega t\, dt, \\
 s(\omega, y) &= \int_{-\infty}^\infty\, B(t, y)\sin\omega t\, dt
\end{align*}
are the Fourier cosine and sine transforms of $B(t, y)$ with respect to $t$.
If $B$ satisfies $B_t = \alpha B_{yy}$ then substitution into (1) and rearrangement
shows these transforms must be related as
\begin{equation}
    \begin{aligned}
     -\omega c(\omega, y) &= \alpha s_{yy}(\omega, y), \\
    \omega s(\omega, y) &= \alpha c_{yy}(\omega, y).
    \end{aligned}
 \tag{2}
\end{equation}
Computing $c_{yyyy}$ and $s_{yyyy}$ we see that $c$ and $s$ satisfying this system
also satisfy $c_{yyyy} + (\omega/\alpha)^2 c = 0$ and $s_{yyyy} + (\omega/\alpha)^2 s = 0$.
Each has four linearly independent solutions
\begin{align*}
 & \exp(-\sqrt{\omega/2\alpha}y)\cos(\sqrt{\omega/2\alpha}y), \\
 & \exp(-\sqrt{\omega/2\alpha}y)\sin(\sqrt{\omega/2\alpha}y), \\
 & \exp(\sqrt{\omega/2\alpha}y)\cos(\sqrt{\omega/2\alpha}y), \\
 & \exp(\sqrt{\omega/2\alpha}y)\sin(\sqrt{\omega/2\alpha}y).
\end{align*}
The third and fourth forms are unbounded as $y\rightarrow\infty$ so we ignore them
and make use of the first and second only:
\begin{equation*}
 c(\omega, y) = \exp(-\sqrt{\omega/2\alpha}y)\biggl(c_1(\omega)\cos(\sqrt{\omega/2\alpha}y)
 + c_2(\omega)\sin(\sqrt{\omega/2\alpha}y)\biggr),
\end{equation*}
and similarly
\begin{equation*}
 s(\omega, y) = \exp(-\sqrt{\omega/2\alpha}y)\biggl(s_1(\omega)\cos(\sqrt{\omega/2\alpha}y)
 + s_2(\omega)\sin(\sqrt{\omega/2\alpha}y)\biggr).
\end{equation*}
Note that (2) implies a relation between $c_1, c_2$ and $s_1, s_2$,
specifically $s_1(\omega) = - c_2(\omega)$, $s_2(\omega) = c_1(\omega)$.
With these results, at $y = 0$ we have
\begin{align*}
 B(t, 0) &= \frac{1}{\pi}\int_0^\infty\, c(\omega, 0)\,\cos\omega t\, d\omega + \frac{1}{\pi}\int_0^\infty\, s(\omega, 0)\,\sin\omega t\, d\omega \\
 &= \frac{1}{\pi}\int_0^\infty\,c_1(\omega)\cos\omega t \, d\omega
 + \frac{1}{\pi}\int_0^\infty\,s_1(\omega)\sin\omega t \, d\omega.
\end{align*}
The condition $B(t, 0) = B_0\cos\omega_0 t$ suggests $c_1(\omega) = \pi B_0\delta(\omega - \omega_0)$
and $s_1(\omega) = 0$. Thus $c_2(\omega) = 0$, $s_2(\omega) = \pi B_0\delta(\omega - \omega_0)$. So
\begin{align*}
 c(\omega, y) &= \pi B_0\exp(-\sqrt{\omega/2\alpha}y)\cos(\sqrt{\omega/2\alpha}y)\delta(\omega - \omega_0) \\
 s(\omega, y) &= \pi B_0\exp(-\sqrt{\omega/2\alpha}y)\sin(\sqrt{\omega/2\alpha}y)\delta(\omega - \omega_0).
\end{align*}
Substitution into (1) and a bit of algebra gives
\begin{equation*}
 B(t, y) = B_0\exp(-\sqrt{\omega_0/2\alpha}y) \cos(\sqrt{\omega_0/2\alpha}y - \omega_0 t).
\end{equation*}
Addendum in hindsight
The above approach works for a large class of driving functions at $y = 0$, however, with $B_0\cos\omega_0 t$, things are far simpler. From a physics perspective you might argue the driver is $\omega_0$-periodic, so look for $\omega_0$-periodic solutions. That is:
$$B(t, y) = u(y)\cos\omega_0 t + v(y)\sin\omega_0 t.$$
Working with this form to begin with gets you to the same result with a lot less pain, and maybe a bit of physical-reasoning satisfaction.


text:
Q: How to use winecfg headless? I cannot find documentation for how winetricks or winecfg create permanent exe overrides. I also would like to set desktop integration and windows version from the shell.
The reason for this is that I am testing a difficult program. It installs correctly sometimes, but not others. Tracking down the exact problem has led me to re-create a wine-prefix for it upwards of 10 times a day. It is simply not practical to use the GUI for that. I need to know the commands/options I can pass to winecfg/wine/winetricks so that I can create the initial prefix faster.
Is there any documentation for: set permanent exe override or set desktop integration paths or set windows version ? I appreciate any help with any of those three things!

A: Just like Windows does, everything in Wine is configured through the registry. Every single settings winecfg access can also be accessed through the registry using the regedit utility, which can also be used in command line to either import a big .reg file or set individual keys on the command line itself.
All the used keys are in the Useful Registry Keys wiki page.
The easiest option in your case would be to export the configuration in a .reg file (right click on the keys you need, export) and then import then with wine regedit MyConfig.reg in your auto-configure script. You can write the .reg manually as well if you want, it's just a .ini-style text file.
Edit: wanted to add that as a comment as it doesn't answer the question itself but suggest another way of doing it but I lack reputation here: I'd recommend to just create a full copy of your clean pre-installation prefix and just copy it back when you need to reset. You will avoid the whole script to reconfigure a clean prefix, and will also be much faster than reinstalling libraries through winetricks and running regedit as all its a disk only operation.


text:
Q: Checkbox in UITableView Cell I've written an app which list the title, a thumbnail and the second-hand price of some books. It's all done using a UITableView and the data is taken from a .plist file.
What I want to add is a checkbox to each cell which can be toggled if the user has the book or not and then store that checkbox state for the next time they use the app. Is it possible to store a value back to the .plist file or is there another way to do it?
Here's the code I have so far for the cell:
@implementation ffbooksCell

@synthesize ffbooksLabel = _ffbooksLabel;
@synthesize priceLabel = _priceLabel;
@synthesize thumbnailImageView = _thumbnailImageView;

- (void) viewDidLoad {
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSString* path = [documentsDirectory stringByAppendingPathComponent:@"ffbooks.plist"];
    NSMutableArray* checkboxSelected = nil;
    // Attempt to load saved data from the documents directory
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]){
        checkboxSelected = [NSMutableArray arrayWithContentsOfFile:path];
    }else{
        // No saved data in documents directory so we need to load the data from the bundle
        NSString* bundlePath = [[NSBundle mainBundle] pathForResource:@"ffbooks" ofType:@"plist"];
        checkboxSelected = [NSMutableArray arrayWithContentsOfFile:bundlePath];
    }

    //...
    // Toggle check box for book 0
    if ([checkboxSelected[0][@"checkbox"] boolValue]){
        checkboxSelected[0][@"checkbox"] = @NO;
    }else{
        checkboxSelected[0][@"checkbox"] = @YES;
    }
    // Note: @"checkbox" does not need to be in the original plist
    //...

    [checkboxSelected writeToFile:path atomically:YES];

    if (checkboxSelected == 0){
        [checkboxButton setSelected:NO];
    } else {
        [checkboxButton setSelected:YES];
    }

}

- (IBAction)checkboxButton:(id)sender{

    if (checkboxSelected == 0){
        [checkboxButton setSelected:YES];
        checkboxSelected = 1;
    } else {
        [checkboxButton setSelected:NO];
        checkboxSelected = 0;
    }

}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end

A: There are lots of alternatives to storing the data in a plist. Core Data would be my choice. Learning how to use core data is worth the time investment. You could still use the plist to pre populate your database.
However to answer your question yes you can store the data in a plist. Assuming the initial data is stored in the bundle and is an array of dictionaries here is some example code.
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString* path = [documentsDirectory stringByAppendingPathComponent:@"books.plist"];
NSMutableArray* info = nil;
// Attempt to load saved data from the documents directory
if ([[NSFileManager defaultManager] fileExistsAtPath:path]){
    info = [NSMutableArray arrayWithContentsOfFile:path];
}else{
    // No saved data in documents directory so we need to load the data from the bundle
    NSString* bundlePath = [[NSBundle mainBundle] pathForResource:@"books" ofType:@"plist"];
    info = [NSMutableArray arrayWithContentsOfFile:bundlePath];
}

//...
// Toggle check box for book 0
if ([info[0][@"checkbox"] boolValue]){
    info[0][@"checkbox"] = @NO;
}else{
    info[0][@"checkbox"] = @YES;
}
// Note: @"checkbox" does not need to be in the original plist
[info writeToFile:path atomically:YES];

Update:
I have created a gist for you to help you load the data into a table view controller
https://gist.github.com/datinc/9075686

A: You can use NSUserDefaultsto store small amount of data (mostly like settings...)
Just check this tutorial


text:
Q: seeing outline on checkmarks when tabbing How do I add a focus outline to checkmarks? For example, when pressing "tab" on the keyboard, the user will see an outline on each content that has been tabbed on.

td:focus {
  outline: 3px dotted #000000;
  outline-offset: 1px;
  color: red;
}

                    A-1
                    <input type="checkbox" value="A1" name-"A1" id="A1">

I do not know what exactly I am doing wrong.

A: Regardless of what you want focused, add tabindex="0" to the element's tag.

td:focus {
    outline: 3px dotted #000000;
    outline-offset: 1px; color:red;
}

                A-1
                <input type="checkbox" value="A1" name-"A1" id="A1">

EDIT: For completeness, when you change the "0" to another integer > 0, that becomes that element's place in the tab order.  E.g.  tabindex="3" makes the element third in the page's tab order.

A: You can use attribute selector if you want to specify just checkboxes.

input[type="checkbox"]:focus {
  outline: 3px dotted #000000;
  outline-offset: 1px;
  color: red;
}

       A-1
        <input type="checkbox" value="A1" name-"A1" id="A1">


text:
Q: Kernel of a matrix using the rref of its transpose What is the most elegant way to calculate a basis for the kernel of a matrix $$
if one has already calculated the row reduced echelon form of its transpose $^T$
? Can one avoid further row reductions or matrix inversions?

A: Here is something that works if we have access to the row-operations used to obtain the rref of $A^T$ (or equivalently, if we have the rref of the augmented matrix $[A^T \mid I]$, where $I$ denotes the identity matrix).
Suppose that $R$ is the rref of $A^T$ and that the elementary matrices $E_1,\dots,E_k$ are such that $E_k\cdots E_1 A^T = R$. Let $E = E_k \cdots E_1$, so that $EA^T = R$ (alternatively, obtain $E$ with $[A^T \mid I] \to [R \mid E]$). Partition $R$ so that
$$
R = \pmatrix{R_0\\ 0},
$$
where $R_0$ has no zero-rows. Partition $E$ into
$$
E = \pmatrix{E_1\\E_2},
$$
where $E_1$ has the same number of rows as $R_0$. Note that
$$
EA^T = R \implies \pmatrix{E_1\\E_2}A^T = \pmatrix{R_0\\0} \implies \\
E_1A^T = R_0, \quad E_2A^T = 0\implies\\
AE_1^T = R_0^T, \quad AE_2^T = 0.
$$
With that, we can conclude that the columns of $E_2^T$ form a basis for the kernel of $A$.


text:
Q: CSS transition and perspective doesn't give same result in chrome/ie and firefox I'm playing with CSS perspective and I don't get the same result between firefox and chrome/ie.
I want it to work as in chrome/ie (the flipping panel doesn't go over the non flipping cat when it closes).
Here the codepen.io I made for the question :http://codepen.io/mourtazag/pen/cdAuL
Thanks !

A: you may not be using proper vendor prefix.
-khtml- (Konqueror, really old Safari)
-moz- (Firefox)
-o- (Opera)
-ms- (Internet Explorer)
-webkit- (Safari, Chrome)
and also dont forget to use default code, i.e. code without vendor prefix.


text:
Q: Reactjs hooks to run function in parent from child I have a parant that contains a child and a function within the parent that I wish to run form the child. However with the current code what is happening is the function is ran instantly instead of when the button is pressed on the child component. any ideas? Here is the code:
const Parent  = () => {

const [showPayment, setShowPayment] = useState(true);
const [showSignupComplete, setShowSignupComplete] = useState(false);

const CompleteSignup = () => {
  setShowPayment(false);
  setShowSignupComplete(true);
}

return (

{showPayment ?(
      <Payment paymentChange={CompleteSignup}/>
):null }

{showSignupComplete ?(

 Sign up complete

):null }

}

const Payment = ({paymentChange}) => {
  const handleSubmitSub = async (event) => {
  paymentChange
  }

return (

 <Button
          type="submit"
          fullWidth
          variant="contained"
          color="primary"
          className="submit"
           onClick={handleSubmitSub}
           >
            Complete Payment
          </Button>

)

}
I've updated the code with the suggestions below. however get the error: paymentChange is not a function

A: I reformatted your code for better readability
It actually works. completeSignup is called in Payment and it changes states in Parent
The only thing I fixed is handleSubmitSub in Payment component
In handleSubmitSub you should call paymentChange as a function()
Like this
const handleSubmitSub = async (event) => {paymentChange()}
Full code:
const Parent  = () => {
  const [showPayment, setShowPayment] = useState(true);
  const [showSignupComplete, setShowSignupComplete] = useState(false);

  const completeSignup = () => {
      setShowPayment(false);
      setShowSignupComplete(true);
  }

  return (

      {showPayment && <Payment paymentChange={completeSignup}/>}
      {
        showSignupComplete &&

 Sign up complete

      }

  )
}

const Payment = ({paymentChange}) => {
  const handleSubmitSub = async (event) => {paymentChange()}

  return (

      <button
          type="submit"
          fullWidth
          variant="contained"
          color="primary"
          className="submit"
           onClick={handleSubmitSub}
           >
            Complete Payment
        </button>

  )
}

P.S: I'd recommend naming functions inside components with a lower camelCase = () => {}, so those functions will not be misread as a react Component = () => {}

A: Your naming is a bit confucing here, that onClick you put on the  component is not an actual event handler, it's a prop. You have to accept the "handleSubmitSub" function in the child component as props.
In the child component do the following:
const Button = ({onClick as fn}) => {

/// your code here.....

return (
<button onClick={fn}>YOUR BUTTON TEXT</button>
)

}


text:
Q: Find out if line is empty in a textarea I'm using this code to check if the caret is on an empty line inside a textarea. It works well but has a single flaw: If you start a line with some text and finish it with a space, the code thinks that the line is empty; this is not true. I don't care about lines as a result of word wrapping.
Here's a fiddle: http://jsfiddle.net/jZN5w/
$('#area').on("keyup change focus", function() {
    if( this.value.substr(0,this.selectionStart).match(/(?:^|\s+)$/)
     && this.value.substr(this.selectionStart).match(/^(?:\s+|$)/)) {
        console.log("empty");
    } else {
        console.log("has stuff");
    }
});

This will log "has stuff"
The above line will log empty while this will log "has stuff"   This will log empty if I end the line with a space

A: Your regular expressions don't look for empty lines, but for spaces.
$('#area').on("keyup change focus", function() {
    if( this.value.substr(0,this.selectionStart).match(/(?:^|\n|\r)\s*$/)
     && this.value.substr(this.selectionStart).match(/^\s*(?:\n|\r|$)/)) {
        console.log("empty");
    } else {
        console.log("has stuff");
    }
});

http://jsfiddle.net/jZN5w/6/


text:
Q: Hiding api key with firebase function I'm trying to hide my reCAPTCHA key from appearing in my front end (React). I don't know how useful it can be but how about making a request to a certain endpoint and then make it a componentDidMount when getting the data back. This might sound not secure at all but what's the best solution for these kinds of problems?

ok so I should create a function (that I still don't get right) that looks similar to this
exports.captcha = functions.https.onRequest((req, res) => {
//should i set the origin to be my domain.com here
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET, PUT, POST, OPTIONS');   res.set('Access-Control-Allow-Headers', '*');
if (req.method === 'OPTIONS') {
 res.end();
}  else {
 cors(req, res, () => {
  if (req.method !== 'GET') {
   return;
 }
   return res.send('Api key',(err,info)=> {
    if(err){
     return res.send(err.toString())
    }
      return res.send("sent")
    }
 });
}});

A: Any time the API key is used inside client-side code, a malicious user can take it and use it. Since that is exactly what you're trying to prevent, the only secure solution is to not use that API key in client-side code. That means you'll need to wrap the functionality in your server-side code, and expose only inputs and outputs that you want. It also means you'll want to secure access to the Cloud Functions endpoint (who can call it and what they can do), as unsecured access is equivalent to allowing them to use the API key directly.
Some API keys, such as those for Firebase's Authentication, Realtime Database, Cloud Firestore, and Cloud Storage products allow you to restrict where or how a user with the keys can use those products. In cases such as those, it's better to see the API keys as configuration data


text:
Q: Connecting isolines (i.e.points of equal value) in 3D scene using ArcGIS for Desktop? I have a point shp theme with fields Lat, Long, Altitude (m), and Number.
The Number field – is a numerical parameter of each point (Lat, Long).
The Altitude field – is the parameter of elevation of each point (Lat, Long) above the surface.
I made a 3d map in ArcScene of ArcGIS10 where I represented each point as a symbol of different size (according to the "Number" field), and then – elevated each point above the surface (according to the "Altitude" field).
Is it possible to connect by isolines (or something like that) all  points of the equal value of the "Number" field (i.e. all points of the same size) in this 3d map?

A: *

*Create a TIN from the 3D points

*Create 2D lines by digitizing the lines in ArcMap, using snapping environment to snap to the points you want.

*Use the Interpolate Shape tool to create 3D lines using the 2D lines and the TIN surface as input.


text:
Q: ng-repeat highlights all links when only one visited Here's the code:

            {{company.name}}

The code is working, but what happens is that when I select just one company, all companies in the list gets highlighted like I visited them. Is there something I have add to this code?

A: It is because you have the same href for all companies, if you are using ui-router you can add a param to your route, for example:
$stateProvider.state({
    name: 'companies',
    url: '/companies/:companyId'
});

and you can use this way:

            {{company.name}}

By this way, every company will have its own href and this will not happen.
If it is not clear, please let me know which route lib you are using.

A: Indeed you have set the same href but You should use ng-style and not ng-click like so :

            {{company.name}}

and in your js
$scope.isActive = function (viewLocation) {
     return viewLocation === $location.path();
};

A: The href is the same for every link. You need to append something to the end of each one to make them unique. Something like:

it doesn't matter if your code doesn't do anything with the parameter.


text:
Q: Azure Function Suddenly Returns 401 Unauthorized When Called Remotely I have a web API set up with Azure functions. This has been working fine from my web server for about a week. Suddenly today the functions return 401 unauthorised when call remotely but when fine in the Azure Portal. AFAIK nothing has changed.
Any one know why I now get a 401?
I have tried restarting the function app but that doesn't fix it.

A: Change the AuthorizationLevel to Anonymous.
public static async Task<IActionResult> Run(
                [HttpTrigger(**AuthorizationLevel.Anonymous**, "get", "post", Route = null)] HttpRequest req,
                ILogger log){

    }

A: By default, when you create this function, it will start with the function (key) for the Authorization level. Please take a try to switch the Authorization level to Anonymous, this should allow the function to work.


text:
Q: Thread-local storage (TLS) and OpenMP What does OpenMP (e.g. Intel C++ 12 implementation) currently do with the TLS variables declared with __thread in Linux and __declspec(thread) on Windows? Does it make them threadprivate or just ignores TLS?
Found one related paper, but still confused.
http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=1639501&tag=1

A: From my experience, __thread is used to implement OpenMP threadprivate (this page on MSDN also mentions that) in a number of compilers (VC, gcc, icc).


text:
Q: Error parsing query in SQL Server CE I have an existing application running on Windows Mobile running SQL Server CE and am using inline queries with C# language. This is my query that works correctly in Management Studio:
command = @"SELECT
                P_InspectionStep.InspectionStepID,
                P_InspectionStep.Sequence AS Sequence,
                P_InspectionStep.Title AS Title,
                P_InspectionStep.Body AS Body,
                P_InspectionStep.Photo AS Photo,
                P_Inspection.RevisionID
            FROM
                P_InspectionStep
            LEFT JOIN
                P_Inspection ON P_Inspection.InspectionID = P_InspectionStep.InspectionID
            WHERE
                P_Inspection.InspectionID = '" + mInspectionID + "'" +
                @"AND P_Inspection.CreateDate = (SELECT MAX(P_Inspection.CreateDate) FROM P_Inspection)

            UNION ALL

            SELECT
                C_InspectionStep.InspectionStepID,
                C_InspectionStep.Sequence AS Sequence,
                C_InspectionStep.Title AS Title,
                C_InspectionStep.Body AS Body,
                C_InspectionStep.Photo AS Photo,
                C_Inspection.RevisionID
            FROM
                C_InspectionStep
            LEFT JOIN
                C_Inspection ON C_Inspection.RevisionID = C_InspectionStep.RevisionID
            WHERE
                C_Inspection.InspectionID = '" + mInspectionID + "'" +
                @"AND C_Inspection.CreateDate = (SELECT MAX(C_Inspection.CreateDate) FROM C_Inspection)
            ORDER BY 2;";

But running it in the application returns this SqlCeException:

There was an error parsing the query. [ Token line number = 10,Token line offset = 132,Token in error = SELECT ]

I've done a lot of searching but can't find out how to resolve this.

A: Provide the value of
(SELECT MAX(P_Inspection.CreateDate) FROM P_Inspection)

from another query run in advance.

A: You cannot have a sub-query that returns a scalar value but you can return a set so use IN instead of an equality test:
... C_Inspection.CreateDate IN (SELECT MAX(C_Inspection.CreateDate) FROM C_Inspection)


text:
Q: Proper way of coding return statement with many conditions I'm wondering if there is a nice way of coding something like this:
return IOTools.CreateFile(@"D:\test")
    && IOTools.CreateDir(@"D:\test_folder\")
    && IOTools.DeleteFile(@"D:\test_file_2")
    && IOTools.DeleteDir(@"D:\test_folder_2\");

I know that I can put it all in other function and there use if statements to return false after every condition, but maybe there is another way to stop program from trying to do next conditions if one is false?

A: && is already a short-circuiting operator. So it stops as soon as one condition is false.

if x is false, y is not evaluated, because the result of the AND
  operation is false no matter what the value of y is. This is known as
  "short-circuit" evaluation.

Btw, || does also stop evaluation as soon as one condition is true.
If you instead ask for a more readable way, you could use variables:
bool canCreateFile = IOTools.CreateFile(@"D:\test");
bool canCreateDir = IOTools.CreateDir(@"D:\test_folder\");
bool canDeleteFile = IOTools.DeleteFile(@"D:\test_file_2");
bool canDeleteDir = IOTools.DeleteDir(@"D:\test_folder_2\");

return canCreateFile && canCreateDir && canDeleteFile  && canDeleteDir;

If code is getting too complicated i use variables to increase readability, maintainability and testability.

A: This is about as clean as you will get.  Introducing anything else will likely add, rather than reduce, complexity.

A: A few really important guidelines:

*

*If you use "&&" and something returns false, the rest of the 'if' will not be executed. This may be the desire or it may not be. In your case, if any create directory/delete fails, the rest of them are not going to be executed.

*You need to think about maintainability with code. Boolean statements checking a series of conditions with side effects can be difficult to edit later because the programmer making the changes may not be aware of these side effects.

Hopefully that helps a bit.
More Details
An example of where editing is difficult. Lets say another programmer wants to add a new create to your program. Now the program is:
return IOTools.CreateFile(someNewFile)
    && IOTools.CreateFile(@"D:\test")
    && IOTools.CreateDir(@"D:\test_folder\")
    && IOTools.DeleteFile(@"D:\test_file_2")
    && IOTools.DeleteDir(@"D:\test_folder_2\");

But the new programmer makes a mistake and that file happens to never be created. They followed your pattern - and actually broke your code. This is a serious issue suddenly! A much better pattern would be:
var overallSuccess = false;
overallSuccess |= IOTools.CreateFile(someNewFile);
overallSuccess |= IOTools.CreateFile(@"D:\test");
overallSuccess |= IOTools.CreateDir(@"D:\test_folder\");
overallSuccess |= IOTools.DeleteFile(@"D:\test_file_2");
overallSuccess |= IOTools.DeleteDir(@"D:\test_folder_2\");
return overallSuccess;

Now all statements run and the return value represents whether or not ANY create was successful. You can change the "|=" to an "&=" to have true return if ALL statements were successful. Best of luck!