text:
Q: How to print digits with thousand separator? I'm trying to convert any number from just digits to a new form, where every three digits are separated by a dot starting from the end of the number.
This way, this file:
1000
10000
100000
1000000

Should become:
1.000
10.000
100.000
1.000.000

I'm trying to find one sed-command that converts all of these numbers to that form.
I know sed 's/.\{3\}/&,/g' does the something similar, but this starts from the beginning of the number instead of the end.

A: Use GNU awk's ' modifier to have thousands separator!!
$ awk '{printf "%'\''d\n", $0}' file
100
1.000
10.000
100.000
1.000.000.000

Or, using Ed Morton's wisdom:
awk '{printf "%\047d\n", $0}' file

if you use \047 instead of '\'' to represent ' then it'll work in any context in any OS and whether the script is called from the command line or stored in a file and invoked as awk -f script.

For a given file
$ cat file
100
1000
10000
100000
1000000000

From GNU awk user's guide in Format Modifiers:

'
A single quote or apostrophe character is a POSIX extension to ISO C. It indicates that the integer part of a floating-point value, or the entire part of an integer decimal value, should have a thousands-separator character in it. This only works in locales that support such characters.

A: You can use rev to reverse each line:
$ rev input | sed 's/.../&./g;s/\.$//' | rev
1.000
10.000
100.000
1.000.000

s/\.$// will remove the otherwise leading period on 100000:
100000 -> 000001 -> 000.001. -> 000.001 -> 100.000


text:
Q: Less than operator not working correctly in PHP 5.3.1 For the purpose of the example, var 2 is preset from a database as "147.22" type STRING. var 1 is calculated previously in the script and has 147.22 type FLOAT.
Script:
<?

$var1 = (float)$var1;
$var2 = (float)$var2;

var_dump($var1);
var_dump($var2);

if($var1 < $var2) { echo "hello"; }

?>

My expected results would be that the script NOT echo "hello" since the two values are equal in amount and type.
However here is the output I'm getting:
float(197.22)
float(197.22)
hello

If I do not mess with the types and leave the one a float and the other a string, then it still does not work (this is how I got here in the first place).
If i force the values at the time of execution like this:

$var1 = 147.22;
$var2 = 147.22;

var_dump($var1);
var_dump($var2);

if($var1 < $var2) { echo "hello"; }

?>

I get this, (and it works):
float(197.22)
float(197.22)

Notice no "hello"....
Anyone have any clue wth is going on here?

A: If one of the floats is calculated numerically, and one is created from string assignment, they could be different. Try the following:
$x = 147.22;
$y = 147.2200000000001;
printf("%.40f\n", $x);
printf("%.40f\n", $y);
var_dump($x);
var_dump($y);
var_dump($x < $y);

outputs
147.2199999999999988631316227838397026062012
147.2200000000001125499693443998694419860840
float(147.22)
float(147.22)
bool(true)

Cast them to a string with a specified precision for comparison.

A: If you are dealing with floats, then it's not safe to compare them directly, because there may be rounding or representation issues.
You'd better to check if the difference between those numbers is less than some predefined and very minimal epsilon, and then determine if they're equal, or which is the greater one.
This discussion may be worth reading: Is casting to float destructive?

EDIT:
More discussions to read:

*

*PHP: Floating point numbers

*php integer and float comparison mismatch

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use Database with Phonegap application This can't be a proper question to ask here, but I am a bit confused about How & which database to use with my phonegap application (made with HTML5 + Javascript+CSS)
If anyone having any Reference link or any Idea of'
How I can use database in this application?

Thanks in advance.

A: You can use SQLite wrapper.
Plugin Link
It's very easy to use.
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);

// Cordova is ready
function onDeviceReady() {
  var db = window.sqlitePlugin.openDatabase({name: "my.db"});

  db.transaction(function(tx) {
    tx.executeSql('DROP TABLE IF EXISTS test_table');
    tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');

    // demonstrate PRAGMA:
    db.executeSql("pragma table_info (test_table);", [], function(res) {
      console.log("PRAGMA res: " + JSON.stringify(res));
    });

    tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
      console.log("insertId: " + res.insertId + " -- probably 1");
      console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");

      db.transaction(function(tx) {
        tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
          console.log("res.rows.length: " + res.rows.length + " -- should be 1");
          console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
        });
      });

    }, function(e) {
      console.log("ERROR: " + e.message);
    });
  });
}

Detailed documentation available in the link.
If you need small data to save like few words, then you can use localStorage.


text:
Q: ¿Cómo puedo mostrar una clase JPanel dentro de un panel en una ventana principal? Tengo un programa con el mismo código, sin embargo, uno de ellos no muestra la clase dentro del panel.
Volumen V=new Volumen();

public Ventana() {
    initComponents();
    panel.add(V);
    V.setVisible(true);

}

Volumen es la clase JPanel que estoy intentando visualizar dentro de la variable panel.


text:
Q: Bash Script Function Writing a custom Shell Script for a college assignment. Have practically everything working apart from this....
I have an alias called ifc which will call a function called functionIfc. However, when this code is used, it tells me that unexpected token '}' is found. Cannot seem to be able to debug this. Been stuck on it for a while. Any help would be greatly appreciated!
  alias ifc="functionIfc";

  functionIfc(){

         echo  "Please enter which ethernet you would like to display"
         echo -e "\n Command ifc1: Shows loopback"
         echo -e "\n Command ifc2: Shows eth 0"
         echo -e "\n Command ifc3  Shows eth 1"
         echo -e "\n Command ifc4 shows eth 2"
         echo -e "\n Command ifc5 shows eth 3"

    read INPUT

    if [ $(INPUT) == "ifc1" ]; then
            echo $(ip addr show lo)

            else if [ $(INPUT) == "ifc2" ]; then
                   echo $(ip addr show eth0)

                    else if [ $(INPUT) == "ifc3" ]; then
                          echo  $(ip addr show eth1)

                            else  if [ $(INPUT) == "ifc4" ]; then
                                 echo $(ip addr show eth2)

                                    else if [ $(INPUT) == "ifc5" ]; then
                                            echo $(ip addr show eth3)

                                            else
                                                    echo Not a valid entry, Try again

    fi
}

A: you should close each if statement with fi as below;
#!/bin/bash
  functionIfc(){
         echo  "Please enter which ethernet you would like to display"
         echo -e "\n Command ifc1: Shows loopback"
         echo -e "\n Command ifc2: Shows eth 0"
         echo -e "\n Command ifc3  Shows eth 1"
         echo -e "\n Command ifc4 shows eth 2"
         echo -e "\n Command ifc5 shows eth 3"

    read INPUT

    if [ ${INPUT} == "ifc1" ]; then
            echo $(ip addr show lo)

            else if [ ${INPUT} == "ifc2" ]; then
                   echo $(ip addr show eth0)

                    else if [ ${INPUT} == "ifc3" ]; then
                          echo  $(ip addr show eth1)

                            else  if [ ${INPUT} == "ifc4" ]; then
                                 echo $(ip addr show eth2)

                                    else if [ ${INPUT} == "ifc5" ]; then
                                            echo $(ip addr show eth3)

                                            else
                                                    echo Not a valid entry, Try again
                    fi
                fi
            fi
        fi

    fi
}

functionIfc

and
you can define an alias as below;
alias ifc="/yourscriptpath/"

and you can use this alias in same terminal.
Eg;
user@host $ alias ifc="/tmp/test/t/test.sh"
user@host $ ifc
Please enter which ethernet you would like to display

 Command ifc1: Shows loopback

 Command ifc2: Shows eth 0

 Command ifc3  Shows eth 1

 Command ifc4 shows eth 2

 Command ifc5 shows eth 3
ifc2
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> ...


text:
Q: File load to Azure App Service root folder from another app service I am trying to save file one of app service folder from another app service folder.
Scenario:
I have admin app service hosted in Azure. Also I hosted my website which is different app service. Now I wish to save file from admin portal to website root like ~/content/...
How do I define the path in webconfig inside admin portal?
Best regards,
Shekhar


text:
Q: Use Ajax Json Data to Chart I have ajax response like this
{
  "status": "success",
  "data": [
    {
      "DAY": "11",
      "SIGNUPS": 0,
      "VISITS": "0"
    },
    {
      "DAY": "12",
      "SIGNUPS": 3,
      "VISITS": "13"
    }
  ]
}

I want use this data to my chart which have static data like this
var chartDom1 = document.getElementById('traffic_chart');
            var myChart1 = echarts.init(chartDom1);
            var option1;

            option1 = {
              title: {
                text: 'Stacked Line',
                show: false
              },
              tooltip: {
                trigger: 'axis'
              },
              legend: {
                data: ['Visits', 'Signups'],
                show:false
              },
              grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
              },
              toolbox: {
                feature: {
                  saveAsImage: {}
                }
              },
              xAxis: {
                type: 'Day',
                boundaryGap: false,
                data: [1,2]
              },
              yAxis: {
                type: 'value'
              },
              series: [
                {
                  name: 'Visits',
                  type: 'line',
                  stack: 'Total',
                  data: [150, 232]
                },
                {
                  name: 'Signups',
                  type: 'line',
                  stack: 'Total',
                  data: [150, 232]
                }
              ]
            };

            option1 && myChart1.setOption(option1);

I want use DAY Column in xAxis data and SIGNUPS and VISITS Column in Series, I have tried lot but not able to find proper way to do it. Sorry I am beginner and have not proper knowledge of JavaScript.
Thanks!

A: If you want to pass the Day data as an array to xAxis data you should make an  array like this:
let array = [];
for (const i in response.data) {
   array.push(response.data[i].DAY);
}

after this your array is like this:
[11, 12]

and now you can pass it to your xAxis object ...
and also you can use this method for SIGNUPS and VISITS too.


text:
Q: angular slide-toogle animation not working inside ng-repeat? hi i am new to angular animation,i need to animate the div like this click Here
Based on the above link  i tried the animation to the div inside ng-repeat but i am this error while doing this Uncaught Type Error: Cannot read property 'query Selector' of null(…).
Here is the link which i tried FIDDLE HERE
html

{{menu.displayName}}

         {{item.shortDesc}}

controller
angular.module('angularSlideables', [])
.controller('myctrl', function($scope){
$scope.menuArray = [{displayName:'jhon',items:[{shortDesc:'NYC'}]},{displayName:'rock',items:[{shortDesc:'canada'}]},{displayName:'punk',items:[{shortDesc:'Aus'}]}]
})
.directive('slideable', function () {
    return {
        restrict:'C',
        compile: function (element, attr) {
            // wrap tag
            var contents = element.html();
            element.html('
' + contents + '
');

            return function postLink(scope, element, attrs) {
                // default properties
                attrs.duration = (!attrs.duration) ? '1s' : attrs.duration;
                attrs.easing = (!attrs.easing) ? 'ease-in-out' : attrs.easing;
                element.css({
                    'overflow': 'hidden',
                    'height': '0px',
                    'transitionProperty': 'height',
                    'transitionDuration': attrs.duration,
                    'transitionTimingFunction': attrs.easing
                });
            };
        }
    };
})
.directive('slideToggle', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var target = document.querySelector(attrs.slideToggle);
            attrs.expanded = false;
            element.bind('click', function() {
                var content = target.querySelector('.slideable_content');
                if(!attrs.expanded) {
                    content.style.border = '1px solid rgba(0,0,0,0)';
                    var y = content.clientHeight;
                    content.style.border = 0;
                    target.style.height = y + 'px';
                } else {
                    target.style.height = '0px';
                }
                attrs.expanded = !attrs.expanded;
            });
        }
    }
});

A: The main issue is the fact that you have an id on ng-repeat. Id is a singelton value meaning you can't have two elements with the same id.
try that:

    {{item.shortDesc}}

It should solve the error you are getting and help you move forward on this feature.
Let me know if it helped :)


text:
Q: Matlab Interpolating Curve approximation I have been assigned a task to get a Lagrange interpolating curve from a set of 7 points, and the value of the function at a certain X
the second part is trivial however nobody knows how to get the coefficients of the curve itself.
here is the code I used:
clear
clc
x=[0 6 10 13 17 20 28];
y=[6 17 42 37 30 29 27];
m=15;
n=length(x);
  for i=1:n
        l(i)=1;
        for j=1:n
            if i~=j
            l(i)=l(i)*(m-x(j))/(x(i)-x(j));
      end
      final(i)=l(i)*y(i);
    end
    answer=sum(final);
    end

I cannot use interp1 for the assignment.
Is there any way to do this in matlab? I've been searching for a solution for hours but it seems like no one has ever attempted this yet.
Thank you!


text:
Q: Ubuntu 13.10 installed and worked, but now not working I have a HP G7000 laptop.
I updated/upgraded from 13.04 to 13.10, after the software updater recommended I upgrade.
I have duel booting system with Windows Vista.  The system was working for the past two days, but I start getting the errors below, after selecting Ubuntu in Grub Menu on startup and at the splash screen it says "Press S to Skip or M for manual configuration"
Pressing S gives a black screen and m takes you the errors below.
Windows boots and works fine after selection in the Grub Menu.
[   15.235703] EXT3-fs (sda5): error: unrecognized mount option "discard" or missing value.

[   16.788072] [drm:intel_pipe_config_compare] *ERROR* mismatch in adjusted_mode flags [expected 2, found 0]

[   20.860071] [drm:intel_pipe_config_compare] *ERROR* mismatch in adjusted_mode flags [expected 2, found 0]

[   20.980076] [drm:intel_pipe_config_compare] *ERROR* mismatch in adjusted_mode flags [expected 2, found 0]

Root filesystem Check failed

root@simamhar:~#

Tried boot-repair using the LiveCD method, no luck.  System still gives above error.
(you can view the boot-repair log here http://paste.ubuntu.com/6287287)
When I use the liveCD for 13.04 or 13.10 however, my hard disk is recognized and I can read the files.  Why is it that the installation on the hard disk has stopped working and does not recognize my / ?
What do the above errors mean and how can i solve them?
There was no power failure before, during or after the update/upgrade process from 13.04 to 13.10.
I now would like to go back to 13.04 without reinstalling afresh?
Any help will be appreciated.  Thanks.

A: The issue was the Intel Graphics Card and its drivers in the latest kernel.
I just upgraded to the latest kernel release.  Everything now works Great.

A: I have the same issue and it is to do with intel graphics cards, i have the i915. You need to download the latest drm fix which is not on updates yet.
Here is the link:
http://cgit.freedesktop.org/~danvet/drm-intel/


text:
Q: Questions about the function of Sine, Cosine, and Tangent in Python I am starting to learn the math module in Python and I am trying to wrap my head around the trigonometry functions of sine, cosine, and tangent in Python.
I spent some time learning more about trigonometry and understand how the basic formulas work for right angled triangles:
Sine Function:
sin(θ) equals Opposite / Hypotenuse
Cosine Function:
cos(θ) equals Adjacent / Hypotenuse
Tangent Function:
tan(θ) equals Opposite / Adjacent
But I am not clear on how this applies in Python when it only accepts one value. I read that the value must be a radian.
So if x = 1 radian and math.sin(x)
Output equals 0.8414709848078965
So the sine of 1 radian is 0.8414709848078965
So my question is what did the sine function actually do to a radian of 1?
I am hoping the answer will also help me understand what is happening if I did cosine and tangent to radian 1.

A: python is using the taylor series of sin to find the value of sin 1.
https://people.math.sc.edu/girardi/m142/handouts/10sTaylorPolySeries.pdf
Also, when you said how this is true when it accepts one value. I think you have a misconception. The sin, cosine, tangent functions take one argument i.e. theta and outputs a single value.
Now, that value is equal to the base/hypotenuse (or whichever the trig function you have used) of the triangle of which angle you input in the trig function. SO you must not expect trig functions to give out two values.


text:
Q: Best way to go about approximate search matching in MySQL/PHP? I'm looking for an effective way to do the following search in MySQL/PHP...
Imagine I have a number of fields in my DB I wish to search on:
User.username
Name.first_name
Address.line1
Phone.number
Email.email_address

I also have the following variables (with example data) in PHP to search with:
$username = "john123";
$name = "john";
$address = "10 fake street";
$phone = "23456789";
$email = "john@johnsemail.com";

Assuming there are 0 complete matches, how would I write a query which could see partial matches and then return results ordered by the number of matches?
For example, using my example data I'd might expect to see a result look something like this,
username | name | address        | phone    | email               | matches
----------------------------------------------------------------------------
john123  | john | 12 new street  | 23456789 | john@johnsemail.com | 4
tim123   | tim  | 10 fake street | 23456789 | tim@timsemail.com   | 2

Just to note, I'm not looking for a wild card search here. I want to return results which have exact matches, just not necessarily a complete match using all DB field. And also want to prioritize the results by the number of matches.
I can think of a very inefficient way of doing it by running each as a separate query, loading that into a PHP array then counting which IDs are found in the most arrays. However, the database running this has millions of records per table, so this wouldn't be feasible at all.

A: SELECT *,
  if (username = '$username', 1, 0) +
  if (name     = '$name'    , 1, 0) +
  if (phone    = '$phone'   , 1, 0) +
  if (address  = '$address' , 1, 0) AS matches
FROM   tab
ORDER BY matches DESC


text:
Q: apt-get update, unlinking I've recently moved to xenial ubuntu. After upgrading, I was no more able to run
sudo apt-get update

The output is the following:
Get:1 http://it.archive.ubuntu.com/ubuntu xenial InRelease [247 kB]
Hit:2 http://it.archive.ubuntu.com/ubuntu xenial-updates  InRelease
Hit:3 http://it.archive.ubuntu.com/ubuntu xenial-backports InRelease
Hit:4 http://security.ubuntu.com/ubuntu xenial-security InRelease
Hit:5 http://archive.canonical.com xenial InRelease
Hit:6 http://repository.spotify.com stable InRelease
Fetched 247 kB in 0s (307 kB/s)
Reading package lists... Done
W: Problem unlinking the file backup - Clean (21: Is a directory)

I've tried googling for this particular problem but with no success.
Thank you for your help

A: I have found a solution to this :)
Here you can find a similar issue: "Thread: Problems with software upgrading: aptdaemon".
The problem arises from the following directory:
/var/lib/apt/lists/partial

So doing the following:
sudo rm -rf /var/lib/apt/lists
sudo apt-get update

did the trick :)


text:
Q: Django Serializer Nested Creation: How to avoid N+1 queries on relations There are dozens of posts about n+1 queries in nested relations in Django, but I can't seem to find the answer to my question. Here's the context:
The Models
class Book(models.Model):
    title = models.CharField(max_length=255)

class Tag(models.Model):
    book = models.ForeignKey('app.Book', on_delete=models.CASCADE, related_name='tags')
    category = models.ForeignKey('app.TagCategory', on_delete=models.PROTECT)
    page = models.PositiveIntegerField()

class TagCategory(models.Model):
    title = models.CharField(max_length=255)
    key = models.CharField(max_length=255)

A book has many tags, each tag belongs to a tag category.
The Serializers
class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        exclude = ['id', 'book']

class BookSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True, required=False)

    class Meta:
        model = Book
        fields = ['title', 'tags']

    def create(self, validated_data):
        with transaction.atomic():
            tags = validated_data.pop('tags')
            book = Book.objects.create(**validated_data)
            Tag.objects.bulk_create([Tag(book=book, **tag) for tag in tags])
        return book

The Problem
I am trying to POST to the BookViewSet with the following example data:
{
  "title": "The Jungle Book"
  "tags": [
    { "page": 1, "category": 36 }, // plot intro
    { "page": 2, "category": 37 }, // character intro
    { "page": 4, "category": 37 }, // character intro
    // ... up to 1000 tags
  ]
}

This all works, however, during the post, the serializer proceeds to make a call for each tag to check if the category_id is a valid one:

With up to 1000 nested tags in a call, I can't afford this.
How do I "prefetch" for the validation?
If this is impossible, how do I turn off the validation that checks if a foreign_key id is in the database?
EDIT: Additional Info
Here is the view:
class BookViewSet(views.APIView):

    queryset = Book.objects.all().select_related('tags', 'tags__category')
    permission_classes = [IsAdminUser]

    def post(self, request, format=None):
        serializer = BookSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

A: The DRF serializer is not the place (in my own opinion) to optimize a DB query. Serializer has 2 jobs:

*

*Serialize and check the validity of input data.

*Serialize output data.

Therefore the correct place to optimize your query is the corresponding view.
We will use the select_related method that:

Returns a QuerySet that will "follow" foreign-key relationships, selecting additional related-object data when it executes its query. This is a performance booster which results in a single more complex query but means later use of foreign-key relationships won't require database queries.
  to avoid the N+1 database queries.

You will need to modify the part of your view code that creates the corresponding queryset, in order to include a select_related call.
You will also need to add a related_name to the Tag.category field definition.
Example:
# In your Tag model:
category = models.ForeignKey(
    'app.TagCategory', on_delete=models.PROTECT, related_name='categories'
)

# In your queryset defining part of your View:
class BookViewSet(views.APIView):

    queryset = Book.objects.all().select_related(
        'tags', 'tags__categories'
    )  # We are using the related_name of the ForeignKey relationships.

If you want to test something different that uses also the serializer to cut down the number of queries, you can check this article.

A: I think the issue here is that the Tag constructor is automatically converting the category id that you pass in as category into a TagCategory instance by looking it up from the database.  The way to avoid that is by doing something like the following if you know that all of the category ids are valid:

    def create(self, validated_data):
        with transaction.atomic():
            tags = validated_data.pop('tags')
            book = Book.objects.create(**validated_data)
            tag_instances = [ Tag(book_id=book.id, page=x['page'], category_id=x['category']) for x in tags ]
            Tag.objects.bulk_create(tag_instances)
        return book

A: I've come up with an answer that gets things working (but that I'm not thrilled about): Modify the Tag Serializer like this:
class TagSerializer(serializers.ModelSerializer):

    category_id = serializers.IntegerField()

    class Meta:
        model = Tag
        exclude = ['id', 'book', 'category']

This allows me to read/write a category_id without having the overhead of validations. Adding category to exclude does mean that the serializer will ignore category if it's set on the instance.

A: Problem is that you don't set created tags to the book instance so serializer try to get this while returning.
You need to set it to the book as a list:
def create(self, validated_data):
    with transaction.atomic():
        book = Book.objects.create(**validated_data)

        # Add None as a default and check that tags are provided
        # If you don't do that, serializer will raise error if request don't have 'tags'

        tags = validated_data.pop('tags', None)
        tags_to_create = []

        if tags:
            tags_to_create = [Tag(book=book, **tag) for tag in tags]
            Tag.objects.bulk_create(tags_to_create)

        # Here I set tags to the book instance
        setattr(book, 'tags', tags_to_create)

    return book

Provide Meta.fields tuple for TagSerializer (it's weird that this serializer don't raise error saying that fields tuple is required)
class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ('category', 'page',)

Prefetching tag.category should be NOT necessary in this case because it's just id.
You will need prefetching Book.tags for GET method. The simplest solution is to create static method for serializer and use it in viewset get_queryset method like this:
class BookSerializer(serializers.ModelSerializer):
    ...
    @staticmethod
    def setup_eager_loading(queryset): # It can be named any name you like
        queryset = queryset.prefetch_related('tags')

        return queryset

class BookViewSet(views.APIView):
    ...
    def get_queryset(self):
        self.queryset = BookSerializer.setup_eager_loading(self.queryset)
        # Every GET request will prefetch 'tags' for every book by default

        return super(BookViewSet, self).get_queryset()

A: select_related function will check ForeignKey in the first time.
Actually,this is a ForeignKey check in the relational database and you can use SET FOREIGN_KEY_CHECKS=0; in database to close inspection.


text:
Q: How do I use WPF bindings with RelativeSource? How do I use RelativeSource with WPF bindings and what are the different use-cases?

A: If you want to bind to another property on the object:
{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}

If you want to get a property on an ancestor:
{Binding Path=PathToProperty,
    RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}

If you want to get a property on the templated parent (so you can do 2 way bindings in a ControlTemplate)
{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}

or, shorter (this only works for OneWay bindings):
{TemplateBinding Path=PathToProperty}

A: If an element is not part of the visual tree, then RelativeSource will never work.
In this case, you need to try a different technique, pioneered by Thomas Levesque.
He has the solution on his blog under [WPF] How to bind to data when the DataContext is not inherited. And it works absolutely brilliantly!
In the unlikely event that his blog is down, Appendix A contains a mirror copy of his article.
Please do not comment here, please comment directly on his blog post.
Appendix A: Mirror of blog post
The DataContext property in WPF is extremely handy, because it is automatically inherited by all children of the element where you assign it; therefore you don't need to set it again on each element you want to bind. However, in some cases the DataContext is not accessible: it happens for elements that are not part of the visual or logical tree. It can be very difficult then to bind a property on those elements…
Let's illustrate with a simple example: we want to display a list of products in a DataGrid. In the grid, we want to be able to show or hide the Price column, based on the value of a ShowPrice property exposed by the ViewModel. The obvious approach is to bind the Visibility of the column to the ShowPrice property:
<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
                Visibility="{Binding ShowPrice,
                Converter={StaticResource visibilityConverter}}"/>

Unfortunately, changing the value of ShowPrice has no effect, and the column is always visible… why? If we look at the Output window in Visual Studio, we notice the following line:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=ShowPrice; DataItem=null; target element is 'DataGridTextColumn' (HashCode=32685253); target property is 'Visibility' (type 'Visibility')
The message is rather cryptic, but the meaning is actually quite simple: WPF doesn't know which FrameworkElement to use to get the DataContext, because the column doesn't belong to the visual or logical tree of the DataGrid.

We can try to tweak the binding to get the desired result, for instance by setting the RelativeSource to the DataGrid itself:
<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
                Visibility="{Binding DataContext.ShowPrice,
                Converter={StaticResource visibilityConverter},
                RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"/>

Or we can add a CheckBox bound to ShowPrice, and try to bind the column visibility to the IsChecked property by specifying the element name:
<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
                Visibility="{Binding IsChecked,
                Converter={StaticResource visibilityConverter},
                ElementName=chkShowPrice}"/>

But none of these workarounds seems to work, we always get the same result…
At this point, it seems that the only viable approach would be to change the column visibility in code-behind, which we usually prefer to avoid when using the MVVM pattern… But I'm not going to give up so soon, at least not while there are other options to consider
The solution to our problem is actually quite simple, and takes advantage of the Freezable class. The primary purpose of this class is to define objects that have a modifiable and a read-only state, but the interesting feature in our case is that Freezable objects can inherit the DataContext even when they're not in the visual or logical tree. I don't know the exact mechanism that enables this behavior, but we're going to take advantage of it to make our binding work…
The idea is to create a class (I called it BindingProxy for reasons that should become obvious very soon) that inherits Freezable and declares a Data dependency property:
public class BindingProxy : Freezable
{
    #region Overrides of Freezable

    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }

    #endregion

    public object Data
    {
        get { return (object)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}

We can then declare an instance of this class in the resources of the DataGrid, and bind the Data property to the current DataContext:
<DataGrid.Resources>
    <local:BindingProxy x:Key="proxy" Data="{Binding}" />
</DataGrid.Resources>

The last step is to specify this BindingProxy object (easily accessible with StaticResource) as the Source for the binding:
<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
                Visibility="{Binding Data.ShowPrice,
                Converter={StaticResource visibilityConverter},
                Source={StaticResource proxy}}"/>

Note that the binding path has been prefixed with "Data", since the path is now relative to the BindingProxy object.
The binding now works correctly, and the column is properly shown or hidden based on the ShowPrice property.

A: Bechir Bejaoui exposes the use cases of the RelativeSources in WPF in his article here:

The RelativeSource is a markup extension that is used in particular
  binding cases when we try to bind a property of a given object to
  another property of the object itself, when we try to bind a property
  of a object to another one of its relative parents, when binding a
  dependency property value to a piece of XAML in case of custom control
  development and finally in case of using a differential of a series of
  a bound data. All of those situations are expressed as relative source
  modes. I will expose all of those cases one by one.

*

*Mode Self:

  Imagine this case, a rectangle that we want that its height is always
  equal to its width, a square let's say. We can do this using the
  element name
<Rectangle Fill="Red" Name="rectangle"
                Height="100" Stroke="Black"
                Canvas.Top="100" Canvas.Left="100"
                Width="{Binding ElementName=rectangle,
                Path=Height}"/>

But in this above case we are obliged to indicate the name of the
  binding object, namely the rectangle. We can reach the same purpose
  differently using the RelativeSource
<Rectangle Fill="Red" Height="100"
               Stroke="Black"
               Width="{Binding RelativeSource={RelativeSource Self},
               Path=Height}"/>

For that case we are not obliged to mention the name of the binding
  object and the Width will be always equal to the Height whenever the
  height is changed.
If you want to parameter the Width to be the half of the height then
  you can do this by adding a converter to the Binding markup extension.
  Let's imagine another case now:
 <TextBlock Width="{Binding RelativeSource={RelativeSource Self},
               Path=Parent.ActualWidth}"/>

The above case is used to tie a given property of a given element to
  one of its direct parent ones as this element holds a property that is
  called Parent. This leads us to another relative source mode which is
  the FindAncestor one.

*

*Mode FindAncestor

  In this case, a property of a given element will be tied to one of its
  parents, Of Corse. The main difference with the above case is the fact
  that, it's up to you to determine the ancestor type and the ancestor
  rank in the hierarchy to tie the property. By the way try to play with
  this piece of XAML
<Canvas Name="Parent0">
    <Border Name="Parent1"
             Width="{Binding RelativeSource={RelativeSource Self},
             Path=Parent.ActualWidth}"
             Height="{Binding RelativeSource={RelativeSource Self},
             Path=Parent.ActualHeight}">
        <Canvas Name="Parent2">
            <Border Name="Parent3"
            Width="{Binding RelativeSource={RelativeSource Self},
           Path=Parent.ActualWidth}"
           Height="{Binding RelativeSource={RelativeSource Self},
              Path=Parent.ActualHeight}">
               <Canvas Name="Parent4">
               <TextBlock FontSize="16"
               Margin="5" Text="Display the name of the ancestor"/>
               <TextBlock FontSize="16"
                 Margin="50"
            Text="{Binding RelativeSource={RelativeSource
                       FindAncestor,
                       AncestorType={x:Type Border},
                       AncestorLevel=2},Path=Name}"
                       Width="200"/>
                </Canvas>
            </Border>
        </Canvas>
     </Border>
   </Canvas>

The above situation is of two TextBlock elements those are embedded
  within a series of borders and canvas elements those represent their
  hierarchical parents. The second TextBlock will display the name of
  the given parent at the relative source level.
So try to change AncestorLevel=2 to AncestorLevel=1 and see what
  happens. Then try to change the type of the ancestor from
  AncestorType=Border to AncestorType=Canvas and see what's happens.
The displayed text will change according to the Ancestor type and
  level. Then what's happen if the ancestor level is not suitable to the
  ancestor type? This is a good question, I know that you're about to
  ask it. The response is no exceptions will be thrown and nothings will
  be displayed at the TextBlock level.

*

*TemplatedParent

  This mode enables tie a given ControlTemplate property to a property
  of the control that the ControlTemplate is applied to. To well
  understand the issue here is an example bellow
<Window.Resources>
<ControlTemplate x:Key="template">
        <Canvas>
            <Canvas.RenderTransform>
                <RotateTransform Angle="20"/>
                </Canvas.RenderTransform>
            <Ellipse Height="100" Width="150"
                 Fill="{Binding
            RelativeSource={RelativeSource TemplatedParent},
            Path=Background}">

              </Ellipse>
            <ContentPresenter Margin="35"
                  Content="{Binding RelativeSource={RelativeSource
                  TemplatedParent},Path=Content}"/>
        </Canvas>
    </ControlTemplate>
</Window.Resources>
    <Canvas Name="Parent0">
    <Button   Margin="50"
              Template="{StaticResource template}" Height="0"
              Canvas.Left="0" Canvas.Top="0" Width="0">
        <TextBlock FontSize="22">Click me</TextBlock>
    </Button>
 </Canvas>

If I want to apply the properties of a given control to its control
  template then I can use the TemplatedParent mode. There is also a
  similar one to this markup extension which is the TemplateBinding
  which is a kind of short hand of the first one, but the
  TemplateBinding is evaluated at compile time at the contrast of the
  TemplatedParent which is evaluated just after the first run time. As
  you can remark in the bellow figure, the background and the content
  are applied from within the button to the control template.

A: In WPF RelativeSource binding exposes three properties to set:
1. Mode: This is an enum that could have four values:

a. PreviousData(value=0): It assigns the previous value of the property to
  the bound one
b. TemplatedParent(value=1):  This is used when defining the templates of
  any control and want to bind to a value/Property of the control.
For example, define ControlTemplate:

  <ControlTemplate>
        <CheckBox IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
 </ControlTemplate>

c. Self(value=2): When we want to bind from a self or a property of self.
For example: Send checked state of checkbox as CommandParameter while setting the Command on CheckBox

<CheckBox ...... CommandParameter="{Binding RelativeSource={RelativeSource Self},Path=IsChecked}" />

d. FindAncestor(value=3): When want to bind from a parent control
  in Visual Tree.
For example: Bind a checkbox in records if a grid,if header checkbox is checked

<CheckBox IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid}}, Path=DataContext.IsHeaderChecked, Mode=TwoWay}" />

2. AncestorType:  when mode is FindAncestor then define what type of ancestor
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid}}

3. AncestorLevel:  when mode is FindAncestor then what level of ancestor (if there are two same type of parent in visual tree)
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid, AncestorLevel=1}}

Above are all use-cases for RelativeSource binding.

Here is a reference link.

A: Don't forget TemplatedParent:
<Binding RelativeSource="{RelativeSource TemplatedParent}"/>

or
{Binding RelativeSource={RelativeSource TemplatedParent}}

A: I am constantly updating my research on Binding.
 Original Here
DataContext
DataContext is the DependencyProperty included in the FrameworkElement.
PresentationFramework.dll
namespace System.Windows
{
    public class FrameworkElement : UIElement
    {
        public static readonly DependencyProperty DataContextProperty;
        public object DataContext { get; set; }
    }
}

And, all UI Controls in WPF inherit the FrameworkElement class.

At this point in learning Binding or DataContext, you don't have to study FrameworkElement in greater depth.
However, this is to briefly mention the fact that the closest object that can encompass all UI Controls is the FrameworkElement.

DataContext is always the reference point for Binding.
Binding can directly recall values for the DataContext type format starting with the nearest DataContext.
<TextBlock Text="{Binding}" DataContext="James"/>

The value bound to Text="{Binding}" is passed directly from the nearest DataContext, TextBlock.
Therefore, the Binding result value of Text is 'James'.

*

*Type integer
When assigning a value to DataContext directly from Xaml, resource definitions are required first for value types such as Integer and Boolean.
Because all strings are recognized as String.
1. Using System mscrolib in Xaml

Simple type variable type is not supported by standard.
You can define it with any word, but mostly use sys words.

xmlns:sys="clr-namespace:System;assembly=mscorlib"

2. Create YEAR resource key in xaml

Declare the value of the type you want to create in the form of a StaticResource.

<Window.Resources>
    <sys:Int32 x:Key="YEAR">2020</sys:Int32>
</Window.Resources>
...
<TextBlock Text="{Binding}" DataContext="{StaticResource YEAR"/>

*All type of value
There are very few cases where Value Type is binding directly into DataContext.
Because we're going to bind an object.
<Window.Resources>
    <sys:Boolean x:Key="IsEnabled">true</sys:Boolean>
    <sys:double x:Key="Price">7.77</sys:double>
</Window.Resources>
...
<StackPanel>
    <TextBlock Text="{Binding}" DataContext="{StaticResource IsEnabled}"/>
    <TextBlock Text="{Binding}" DataContext="{StaticResource Price}"/>
</StackPanel>

*Another type
Not only String but also various types are possible. Because DataContext is an object type.

Finally...
In using Binding at WPF, most developers are not fully aware of the existence, function and importance of DataContext.
It may mean that Binding is being connected by luck.

Especially if you are responsible for or participating in a large WPF project, you should understand the DataContext hierarchy of the application more clearly. In addition, the introduction of WPF's various popular MVVM Framework systems without this DataContext concept will create even greater limitations in implementing functions freely.

Binding

*

*DataContext Binding

*Element Binding

*MultiBinding

*Self Property Binding

*Find Ancestor Binding

*TemplatedParent Binding

*Static Property Binding

DataContext Binding
string property
<TextBox Text="{Binding Keywords}"/>

Element Binding
<CheckBox x:Name="usingEmail"/>
<TextBlock Text="{Binding ElementName=usingEmail, Path=IsChecked}"/>

MultiBinding
<TextBlock Margin="5,2" Text="This disappears as the control gets focus...">
  <TextBlock.Visibility>
      <MultiBinding Converter="{StaticResource TextInputToVisibilityConverter}">
          <Binding ElementName="txtUserEntry2" Path="Text.IsEmpty" />
          <Binding ElementName="txtUserEntry2" Path="IsFocused" />
      </MultiBinding>
  </TextBlock.Visibility>
</TextBlock>

### Self Property Binding
<TextBlock x:Name="txt" Text="{Binding ElementName=txt, Path=Tag}"/>

If you have to bind your own property, you can use Self Property Binding, instead of using Element Binding.
You no longer have to declare x:Name to bind your own property.
<TextBlock Text="{Binding RelativeSource={RelativeSource Self}, Path=Tag}"/>

### Find Ancestor Binding
Imports based on the parent control closest to it.
<TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=Title}"/>

In addition to the properties of the controls found, the properties within the DataContext object can be used if it exists.
<TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext.Email}"/>

TemplatedParent Binding
This is a method that can be used within ControlTemplate, and you can import the control that is the owner of the ControlTemplate.
<Style TargetType="Button">
  <Setter Property="Template">
      <Setter.Value>
          <ControlTemplate TargetType="Button">
              <TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}"/>
          </ControlTemplate>
      </Setter.Value>
  </Setter>

You can access to all Property and DataContext.
<TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}"/>

Static Property Binding
You can access binding property value directly.
1. Declare static property.
namespace Exam
{
  public class ExamClass
  {
      public static string ExamText { get; set; }
  }
}

2. Using static class in XAML.
<Window ... xmlns:exam="clr-namespace:Exam">

3. Binding property.
<TextBlock Text="{Binding exam:ExamClass.ExamText}"/>

Or, you can set Resource key like using Converter.
<Window.Resource>
  <cvt:VisibilityToBooleanConverter x:Key="VisibilityToBooleanConverter"/>
  <exam:ExamClass x:Key="ExamClass">
</Window.Resource>
...

<TextBlock Text="{Binding Source={StaticResource ExamClass}, Path=ExamText}"/>

I have never used the Static Property under normal circumstances. This is because data that deviates from its own DataContext can disrupt the flow of whole WPF applications and impair readability significantly. However, this method is actively used in the development stage to implement fast testing and functions, as well as in the DataContext (or ViewModel).

Bad Binding & Good Binding
✔ If the property you want to bind is included in Datacontext,        you don't have to use ElementBinding.
      Using ElementBinding through connected control is not a functional problem,
      but it breaks the fundamental pattern of Binding.
 Bad Binding
<TextBox x:Name="text" Text="{Binding UserName}"/>
...
<TextBlock Text="{Binding ElementName=text, Path=Text}"/>

 Good Binding
<TextBox Text="{Binding UserName}"/>
...
<TextBlock Text="{Binding UserName}"/>

✔ Do not use ElementBinding when using property belonging to higher layers control.
 Bad Binding
<Window x:Name="win">
  <TextBlock Text="{Binding ElementName=win, Path=DataContext.UserName}"/>
  ...

 Good Binding
<Window>
  <TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext.UserName}"/>
  ...

 Great!
<Window>
  <TextBlock DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext}"
             Text="{Binding UserName}"/>
  ...

✔ Do not use ElementBinding when using your own properties.
 Bad Binding
<TextBlock x:Name="txt" Text="{Binding ElementName=txt, Path=Foreground}"/>

 Good Binding
<TextBlock Text="{Binding RelativeSource={RelativeSource Self}, Path=Foreground}"/>

A: It's worthy of note that for those stumbling across this thinking of Silverlight:
Silverlight offers a reduced subset only, of these commands

A: I created a library to simplify the binding syntax of WPF including making it easier to use RelativeSource. Here are some examples. Before:
{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}
{Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}
{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}
{Binding Path=Text, ElementName=MyTextBox}

After:
{BindTo PathToProperty}
{BindTo Ancestor.typeOfAncestor.PathToProperty}
{BindTo Template.PathToProperty}
{BindTo #MyTextBox.Text}

Here is an example of how method binding is simplified. Before:
// C# code
private ICommand _saveCommand;
public ICommand SaveCommand {
 get {
  if (_saveCommand == null) {
   _saveCommand = new RelayCommand(x => this.SaveObject());
  }
  return _saveCommand;
 }
}

private void SaveObject() {
 // do something
}

// XAML
{Binding Path=SaveCommand}

After:
// C# code
private void SaveObject() {
 // do something
}

// XAML
{BindTo SaveObject()}

You can find the library here: http://www.simplygoodcode.com/2012/08/simpler-wpf-binding.html
Note in the 'BEFORE' example that I use for method binding that code was already optimized by using RelayCommand which last I checked is not a native part of WPF. Without that the 'BEFORE' example would have been even longer.

A: Some useful bits and pieces:
Here's how to do it mostly in code:
Binding b = new Binding();
b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, this.GetType(), 1);
b.Path = new PropertyPath("MyElementThatNeedsBinding");
MyLabel.SetBinding(ContentProperty, b);

I largely copied this from Binding Relative Source in code Behind.
Also, the MSDN page is pretty good as far as examples go: RelativeSource Class

A: Binding RelativeSource={
    RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemType}
}
...

The default attribute of RelativeSource is the Mode property.  A complete set of valid values is given here (from MSDN):

*

*PreviousData Allows you to bind the previous data item (not that control that contains the data item) in the list of data items being displayed.

*TemplatedParent Refers to the element to which the template (in which the data-bound element exists) is applied. This is similar to setting a TemplateBindingExtension and is only applicable if the Binding is within a template.

*Self Refers to the element on which you are setting the binding and allows you to bind one property of that element to another property on the same element.

*FindAncestor Refers to the ancestor in the parent chain of the data-bound element. You can use this to bind to an ancestor of a specific type or its subclasses. This is the mode you use if you want to specify AncestorType and/or AncestorLevel.

A: Here's a more visual explanation in the context of a MVVM architecture:

A: I just posted another solution for accessing the DataContext of a parent element in Silverlight that works for me. It uses Binding ElementName.

A: This is an example of the use of this pattern that worked for me on empty datagrids.
<Style.Triggers>
    <DataTrigger Binding="{Binding Items.Count, RelativeSource={RelativeSource Self}}" Value="0">
        <Setter Property="Background">
            <Setter.Value>
                <VisualBrush Stretch="None">
                    <VisualBrush.Visual>
                        <TextBlock Text="We did't find any matching records for your search..." FontSize="16" FontWeight="SemiBold" Foreground="LightCoral"/>
                    </VisualBrush.Visual>
                </VisualBrush>
            </Setter.Value>
        </Setter>
    </DataTrigger>
</Style.Triggers>

A: I didn't read every answer, but I just want to add this information in case of relative source command binding of a button.
When you use a relative source with Mode=FindAncestor, the binding must be like:
Command="{Binding Path=DataContext.CommandProperty, RelativeSource={...}}"

If you don't add DataContext in your path, at execution time it can't retrieve the property.


text:
Q: Reading UTF-8 data from MySQL shows ? instead of ı Here is how I read the data:
<?php
$id = $_GET["id"];
$number = mysql_real_escape_string($id);
$result = mysql_query('SELECT * FROM `mystory` where `id` = ' . "$number" . ' LIMIT 1');

$row = mysql_fetch_assoc($result);
echo $row['story'];
?>

The data is encoded as utf8_bin.
Insted of ı PHP outputs ?
Why is that?

A: This is the only code worked for me :-
mysqli_set_charset($con,'utf8');

Where $con is your connection value to DB .
Be sure put the code after connect and error code and you will be fine .

A: You need to make sure that your connection to the database us in UTF-8 as well. You can do that this way:
mysql_query("SET NAMES utf8");

Also make sure that you are telling the browser that it is UTF-8:
header("Content-type: text/html; charset=utf-8");

A: I am use all this operations:
mysql_query ('SET NAMES utf8');
mysql_query ('SET CHARACTER utf8');
mysql_set_charset ('utf8', $LINK);


text:
Q: How to edit a .js file with nodes I'm trying to figure out if it's possible to simply open up a JSON data script with nodejs and edit it... as javascript ...
// my json data
{
    people : [{
        name : 'Joe',
        hobby : 'hunting',
        job : 'accountant'
    },{
        name : 'William',
        hobby : 'chess',
        job : 'manager'
    }]
}

i just want to do something like e.g.
people[0].name = 'Joseph'

so i'm trying
fs.open('/path/to/file', 'r+', function(err, fd){
    // not really sure what to do from here...
})

there are plenty of answers about how to read/write text files... i just thought there might be an easier way for the case of a file in JSON
Whoops this is a repeat question - please see an earlier response here
How to update a value in a json file and save it through node.js

A: Parse the JSON using JSON.parse(), modify the parsed object, turn it back into a new string using JSON.stringify(), then save the string to the file.


text:
Q: Help calculating a relativistic correction There is a turtle in a decelerating spaceship approaching you. His (her?) velocity is
$$\frac{dx}{dt} = -kx.$$
Normally we would would integrate and the result would be
$$x=e^{-kt}$$
But what if the spaceship's initial velocity is near to the speed of light? We need to make a relativistic correction as we observe the turtle Everything in the spaceship we observe seems to be going very slowly due to time dilation. The turtle's motions appear glacial, even more slow than we are used to seeing. The turtle of course has no sense of this and is lumbering around the spaceship at his usual slow pace.
Would we say
$$   dt'=((\frac{1}{1-(v/c)^2})^{.5})dt$$
and then integrate

*

*$$\frac{dx}{\Biggl((\frac{1}{1-(v/c)^2})^{.5}\Biggr)dt} = -kx$$
or
2)$$\frac{dx}{\Biggl(\frac{d(\frac{1}{1-(v/c)^2})^{.5})}{dt}\Biggr)} = -kx$$
After substituting $dx/dt$ for v , I am still having nightmares with solving either differential equation.

A: No relativistic correction is necessary, as you are trying to calculate displacement in the same frame for which you have the function for velocity.
A few notes:

*

*Check your integration. $\int_{t_0}^{t_f} -kx dt \ne e^{-kt}$

*an $x$-dependent velocity would make for a very strange rocket.

*If you want to convert to a different frame, you do need to do a
relativistic correction, and yes, the calculus can get tedious. See this text lecture.


text:
Q: Why isn't my div being applied inline? I've tried making my div's on the same line. I've tried floating, changing the display property and messing with the width and height properties. But nothing is working:

/* font */
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
/* end of font */

/* clear settings */
body {
  padding: 0;
  margin: 0;
  background: white;
}
/* end of clear settings */

/* nav */
  #nav {
    width: 1600px;
    height: 50px;
    background: #009ACD;
  }
/* end of nav */

/* info nav */
  #primary_nav_wrap
{
 width: 1600px;
  height: 50px;
  background: #1F1F1F;
}

#primary_nav_wrap ul
{
 list-style:none;
 position:relative;
 float:left;
 margin:0;
 padding:0;
 left: 3%;
 top: 5px;
}

#primary_nav_wrap ul a
{
 display:block;
 text-decoration:none;
 font-size:15px;
 padding: 10px 15px 10px 15px;
 font-family: 'Open Sans', sans-serif;
 color: white;
}

#primary_nav_wrap ul a:hover {
  background: white;
}

#primary_nav_wrap ul li
{
 position:relative;
 float:left;
 margin:0;
 padding:0;
}

#primary_nav_wrap ul li:hover a {
  color: black;
  background: white;
}

#primary_nav_wrap ul li a:hover {
  background: white;
}

#primary_nav_wrap ul ul li a:hover {
  background: #F4F4F4;
}

#primary_nav_wrap ul ul
{
 display:none;
 position:absolute;
 top:100%;
 left:0;
 background:#fff;
 padding:0;
 margin-top: 0.2px;
 border: 1px solid #ccc;
 border-top: none;
 z-index: 50;
}

#primary_nav_wrap ul ul li
{
 float:none;
 width:200px;
 position: relative;
 left: 0px;
}

#primary_nav_wrap ul ul a
{
 line-height:120%;
 padding:7.5px 9px;
}

#primary_nav_wrap ul ul ul
{
 top:0;
 left:100%
}

#primary_nav_wrap ul li:hover > ul
{
 display:block
}
/* end of info nav */

/* course div */
  #course_div {
    width: 1200px;
    position: relative;
    left: 180px;
    top: 30px;
    padding: 10px;
  }

  #course_img {
    width: 216px;
    height: 121.5px;
  }

  #course_info {
    border: 1px solid #ccc;
    width: 204px;
    padding: 5px;
    position: relative;
    top: -4px;
    font-family: 'Open Sans', sans-serif;
    font-size: 16px;
  }

   #course_div a {
    text-decoration: none;
    color: black;
    width: 204px;
  }

  #course_main {
    width: 216px;

  }

/* end of course div */
<!DOCTYPE html>

    <title> Hacked Genius </title>
    <link rel='stylesheet' href='main.css'>

Development

Web Development

Mobile Apps

Programming Languages

Game Development

Databases

Software Testing

Software Engineering

Development Tools

E-Commerce

Business

Finance

Entrepreneurship

Communications

Management

Sales

Strategy

Operations

Project Management

Business Law

Data and Anylytics

Home Business

Human Resources

Industry

Media

Real Estate

Other

IT & Software

IT Certification

Network & Security

Hardware

Operating Systems

Other

Office Productivity

Microsoft

Apple

Google

SAP

Intuit

Salesforce

Oracle

Other

Personal Development

Personal Transformation

Productivity

Leadership

Personal Finance

Career Development

Parenting & Relationships

Happiness

Religion & Spirituality

Personal Brand Building

Creativity

Influence

Self Esteem

Stress Management

Memory and Study Skills

Motivation

Other

Design

Web Design

Graphic Design

Design Tools

User Experience

Game Design

Design Thinking

3D & Animation

Fashion

Architectural Design

Interior Design

Other

Marketing

Digital Marketing

Search Engine Optimization

Social Media Marketing

Branding

Marketing Fundamentals

Analystics & Automation

Public Relations

Advertising

Video & Mobile Marketing

Content Marketing

Non-Digital Marketing

Growth Hacking

Affiliate Marketing

Product Marketing

Other

Lifestyle

Life Hacks

Arts & Crafts

Food & Beverage

Beauty & Makeup

Travel

Gaming

Home Improvement

Pet Care & Training

Photography

Digital Photography

Photography Fundamentals

Portraits

Landscape

Black & White

Photography Tools

Mobile Photography

Travel Photography

Commercial Photography

Wedding Photography

Video Design

Other

Health & Fitness

Fitness

General Health

Sports

Nutrition

Yoga

Mental Health

Dieting

Self Defense

Safety & First Aid

Dance

Meditation

Other

Language

English

Spanish

German

French

Japanese

Portuguese

Chinese

Russian

Latin

Arabic

Hebrew

Italian

Other

Music

Instruments

Production

Music Fundamentals

Vocal

Music Techniques

Music Software

Other

Academics

Social Science

Math & Science

Humanities

          Ki

          Two

A: Check your code.  The div tags are all messed up.
I fixed it here -> https://jsfiddle.net/kn7g54j1/1/
Is this what you want?
<!DOCTYPE html>

    <title> Hacked Genius </title>
    <link rel='stylesheet' href='main.css'>

Development

Web Development

Mobile Apps

Programming Languages

Game Development

Databases

Software Testing

Software Engineering

Development Tools

E-Commerce

Business

Finance

Entrepreneurship

Communications

Management

Sales

Strategy

Operations

Project Management

Business Law

Data and Anylytics

Home Business

Human Resources

Industry

Media

Real Estate

Other

IT & Software

IT Certification

Network & Security

Hardware

Operating Systems

Other

Office Productivity

Microsoft

Apple

Google

SAP

Intuit

Salesforce

Oracle

Other

Personal Development

Personal Transformation

Productivity

Leadership

Personal Finance

Career Development

Parenting & Relationships

Happiness

Religion & Spirituality

Personal Brand Building

Creativity

Influence

Self Esteem

Stress Management

Memory and Study Skills

Motivation

Other

Design

Web Design

Graphic Design

Design Tools

User Experience

Game Design

Design Thinking

3D & Animation

Fashion

Architectural Design

Interior Design

Other

Marketing

Digital Marketing

Search Engine Optimization

Social Media Marketing

Branding

Marketing Fundamentals

Analystics & Automation

Public Relations

Advertising

Video & Mobile Marketing

Content Marketing

Non-Digital Marketing

Growth Hacking

Affiliate Marketing

Product Marketing

Other

Lifestyle

Life Hacks

Arts & Crafts

Food & Beverage

Beauty & Makeup

Travel

Gaming

Home Improvement

Pet Care & Training

Photography

Digital Photography

Photography Fundamentals

Portraits

Landscape

Black & White

Photography Tools

Mobile Photography

Travel Photography

Commercial Photography

Wedding Photography

Video Design

Other

Health & Fitness

Fitness

General Health

Sports

Nutrition

Yoga

Mental Health

Dieting

Self Defense

Safety & First Aid

Dance

Meditation

Other

Language

English

Spanish

German

French

Japanese

Portuguese

Chinese

Russian

Latin

Arabic

Hebrew

Italian

Other

Music

Instruments

Production

Music Fundamentals

Vocal

Music Techniques

Music Software

Other

Academics

Social Science

Math & Science

Humanities

          Ki

          Two

/* font */
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
/* end of font */

/* clear settings */
body {
  padding: 0;
  margin: 0;
  background: white;
}
/* end of clear settings */

/* nav */
  #nav {
    width: 1600px;
    height: 50px;
    background: #009ACD;
  }
/* end of nav */

/* info nav */
  #primary_nav_wrap
{
    width: 1600px;
  height: 50px;
  background: #1F1F1F;
}

#primary_nav_wrap ul
{
    list-style:none;
    position:relative;
    float:left;
    margin:0;
    padding:0;
    left: 3%;
    top: 5px;
}

#primary_nav_wrap ul a
{
    display:block;
    text-decoration:none;
    font-size:15px;
    padding: 10px 15px 10px 15px;
    font-family: 'Open Sans', sans-serif;
    color: white;
}

#primary_nav_wrap ul a:hover {
  background: white;
}

#primary_nav_wrap ul li
{
    position:relative;
    float:left;
    margin:0;
    padding:0;
}

#primary_nav_wrap ul li:hover a {
  color: black;
  background: white;
}

#primary_nav_wrap ul li a:hover {
  background: white;
}

#primary_nav_wrap ul ul li a:hover {
  background: #F4F4F4;
}

#primary_nav_wrap ul ul
{
    display:none;
    position:absolute;
    top:100%;
    left:0;
    background:#fff;
    padding:0;
    margin-top: 0.2px;
    border: 1px solid #ccc;
    border-top: none;
    z-index: 50;
}

#primary_nav_wrap ul ul li
{
    float:none;
    width:200px;
    position: relative;
    left: 0px;
}

#primary_nav_wrap ul ul a
{
    line-height:120%;
    padding:7.5px 9px;
}

#primary_nav_wrap ul ul ul
{
    top:0;
    left:100%
}

#primary_nav_wrap ul li:hover > ul
{
    display:block
}
/* end of info nav */

/* course div */
  #course_div {
    width: 1200px;
    position: relative;
    left: 180px;
    top: 30px;
    padding: 10px;
  }

  #course_img {
    width: 216px;
    height: 121.5px;
  }

  #course_info {
    border: 1px solid #ccc;
    width: 204px;
    padding: 5px;
    position: relative;
    top: -4px;
    font-family: 'Open Sans', sans-serif;
    font-size: 16px;
  }

   .course_div a {
    text-decoration: none;
    color: black;
    width: 204px;
  }

  .course_main {
    width: 216px;
    display: inline-block;

  }

/* end of course div */


text:
Q: Is there a way to convert categorical variable into dummy with a dict with Pandas? I'm currently working on a pandas.DataFrame whose I need to convert some categorical variables into dummies.
However, as I construct my pandas.DataFrame from a proportion of a heavy database, I pretty sure that I'll miss some modalities if I simply use pd.get_dummies.
Fortunately, I retrieved all the modalities from the features that I need to convert.
I wanted to know if it's possible (using pd.get_dummies or not) ,to efficiently convert my variables depending on the modalities that I retrieved ?
I looked for a solution, with and without get_dummies but didn't found one.
Thanks :)

A: IIUC, you can use Pandas.Categorical dtype to handle this.
Example
# Setup
np.random.seed(0)
df = pd.DataFrame(np.random.choice(['A', 'B', 'C'], 6), columns=['cat'])
print(df)

[out]
  cat
0   A
1   B
2   A
3   B
4   B
5   C

And running pandas.get_dummies on this yields...
pd.get_dummies(df['cat'])

[out]
   A  B  C
0  1  0  0
1  0  1  0
2  1  0  0
3  0  1  0
4  0  1  0
5  0  0  1

Now cast this Series to categorical dtype, and pass in the list of known categories...
categories = ['A', 'B', 'C', 'D', 'E']
df['cat'] = pd.Categorical(df['cat'], categories=categories)

pd.get_dummies(df['cat'])

[out]
   A  B  C  D  E
0  1  0  0  0  0
1  0  1  0  0  0
2  1  0  0  0  0
3  0  1  0  0  0
4  0  1  0  0  0
5  0  0  1  0  0


text:
Q: Can I omit type in generics? - Kotlin If I have a following interface:
interface BaseDataRemote<T, in Params> {
    fun getData(params: Params? = null): Single<T>
}

Would it be possible have implementation of this interface that does not take Params?
To have effectively something like:
interface BaseDataRemote<T> {
    fun getData(): Single<T>
}

Implementation is as follows:
class RemoteSellerDataSource @Inject constructor(
    private val sellerApi: SellerApi,
    @Named("LANG") private val lang: String
) : BaseDataRemote<SellerEntity, Nothing> {
    override fun getData(params: Nothing?): Single<SellerEntity> {
        return sellerApi.getSeller(lang).map { it.fromApiEntity() }
    }
}

I use Dagger 2 to module to bind this implementation:
@Module
internal interface RemoteModule {

    @Binds
    @CoreScope
    fun bindsSellerRemote(remoteSellerDataSource: RemoteSellerDataSource): BaseDataRemote<SellerEntity, Nothing>
}

I tried using Nothing as second type parameter, but it does not seem to work
(I'm getting required: class or interface without bounds error
Full error message:
RemoteSellerDataSource.java:6: error: unexpected type
public final class RemoteSellerDataSource implements com.bigchangedev.stamps.business.sdk.data.base.data.BaseDataRemote<SellerEntity, ?> {
                                                                                ^
  required: class or interface without bounds
  found:?

Thanks.

A: EDIT: the original answer was a pure Kotlin answer because the OP didn't mention Dagger.
Using Nothing is correct and works in pure Kotlin. However, Dagger seems to convert your code to Java, and in doing so it uses wildcards for the generics (which it doesn't like because it wants exact type matches). To avoid this issue, you can try using @JvmSuppressWildcards on your generic type parameters:
class RemoteSellerDataSource @Inject constructor(
    private val sellerApi: SellerApi,
    @Named("LANG") private val lang: String
) : BaseDataRemote<SellerEntity, @JvmSuppressWildcards Nothing> {
    override fun getData(params: Nothing?): Single<SellerEntity> {
        return sellerApi.getSeller(lang).map { it.fromApiEntity() }
    }
}

Although I'm not sure what will happen in Java with Nothing in that case. I guess this should have the same effect on the Java code as removing the in variance for the second type param in the interface declaration, but without weakening your Kotlin types.
Another workaround would be to use Unit instead of Nothing, which Dagger will most likely convert to Void in this case. This is not great for your types, though.

Original answer:
You can technically already call getData() without arguments thanks to the default value. An implementation that doesn't care about the params argument can simply expect null all the time.
The Kotlin type that only contains null and no other value is technically Nothing?, and since getData is defined with Params? (note the ?) as input, it should be correct to specify Nothing (even without ?) as second type argument. So you should be able to define an implementation like this:
interface BaseDataRemote<T, in Params> {
    fun getData(params: Params? = null): Single<T>
}

class ImplementationWithoutParams<T> : BaseDataRemote<T, Nothing> {
    override fun getData(params: Nothing?): Single<T> {
        // params will always be null here
    }
}

To avoid confusion for the users, this implementation may additionally provide a getData() method without arguments at all:
class ImplementationWithoutParams<T> : BaseDataRemote<T, Nothing> {
    override fun getData(params: Nothing?): Single<T> = getData()

    fun getData(): Single<T> {
        TODO("implementation")
    }
}


text:
Q: Definir um discador como padrão eu já tenho um app simples que apenas faz a ligação a partir do momento que clica em um botão  que realiza a chamada,
 eu quero tornar este app como padrão no Dialer para que toda vez que eu clique no botão  "Call" padrão do telefone  ele abra meu app,
ou seja; torna-lo padrão dentro dele.

*

*estou usando a api 23

*dentro do Configurações/app/configurações padrões  meu app não aparece

minha dúvida é como faço para ele aparecer ali  ? que código eu coloco ?
não consegui achar nada sobre isso, gostaria de uma ajuda, obrigado..

A: Vá em Configurações -> Aplicativos -> Gerenciar Aplicativos.
Selecione a guia "Todos" e vá até o aplicativo de discagem atual.
Procure o botão "Limpar predefinições" e aperte. Agora, quando você seleciona discagem, você deve ser solicitado a selecionar um aplicativo específico e também ter a oportunidade de definir um novo padrão.


text:
Q: version change issues of angular and node This version of CLI is only compatible with Angular versions ^11.0.0-next || >=11.0.0 <12.0.0,
but Angular version 13.0.0 was found instead.
Please visit the link below to find instructions on how to update Angular.
https://update.angular.io/
can any one help to fix

A: If you run command ng update @angular/<package-name>@<version> cli automatically will install a compatible version of cli (temporary) and will do the update.
For example for upgrading @angular/core from 11.0.0 to 12.0.0 when the latest version is 13.0.0 you have to run:
ng update @angular/core@12.0.0

If it shows error try running with --force flag as below:
ng update @angular/core@12.0.0 --force


text:
Q: How do I get these to act on their own in their separate containers? I am a javascript/jquery novice and what I am trying to figure out is when you click the plus or minus buttons the numbers increase/decrease. However I have two sets of these in different containers but they both change their values when clicking on just one set. How can I separate these?
I looked up this javascript/jquery code on stackoverflow to make the plus/minus buttons to work and now I would like to get insight on how to make these work separately. Please help? Any help is appreciated!
Here is my demo: https://jsfiddle.net/hyona/yerfdkvk/

  <input type='button' value='-' class='qtyminus' field='quantity' />
  <input type='text' name='quantity' value='1' class='qty' />
  <input type='button' value='+' class='qtyplus' field='quantity' />

  <input type='button' value='-' class='qtyminus' field='quantity' />
  <input type='text' name='quantity' value='1' class='qty'/>
  <input type='button' value='+' class='qtyplus' field='quantity' />

//CSS Styling
.container {
  width: 120px;
  margin: 0 0 10px;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-align: center;
  -moz-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: justify;
  -moz-box-pack: justify;
  -webkit-justify-content: space-between;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

.qty {
  width: 50px;
  height: 30px;
  text-align: center;
}

input[type='button'] {
  border: none;
  background: none;
  font-size: 18px;
  outline: none;
  cursor: pointer;
}

$(document).ready(function(){
  $('.qtyplus').click(function(e){
    e.preventDefault();
    fieldName = $(this).attr('field');
    var currentVal = parseInt($('input[name='+fieldName+']').val());
    if (!isNaN(currentVal)) {
      if (currentVal < 20)
      {
        $('input[name='+fieldName+']').val(currentVal + 1);
        $('.qtyminus').val("-").removeAttr('style');
      }
      else
      {
        $('.qtyplus').val("+").css('color','#aaa');
      }
    } else {
      $('input[name='+fieldName+']').val(1);
    }
  });

  $(".qtyminus").click(function(e) {
    e.preventDefault();
    fieldName = $(this).attr('field');
    var currentVal = parseInt($('input[name='+fieldName+']').val());
    if (!isNaN(currentVal) && currentVal > 1) {
      $('input[name='+fieldName+']').val(currentVal - 1);
      $('.qtyplus').val("+").removeAttr('style');
    } else {
      $('input[name='+fieldName+']').val(1);
      $('.qtyminus').val("-").css('color','#aaa');
    }
  });
});

A: Within your event handler, you are using selectors like $('.qtyplus') and $('input[name='+fieldName+']'), which select all matching elements. To restrict to just the ones within the clicked element's container, use the .closest() and .find() methods:
$(this).closest('.container').find('input[name='+fieldName+']')

...where this is automatically set to be the clicked element.
(For your current HTML structure you could use .siblings() instead, but I wouldn't recommend it because .closest(...).find(...) will cope better with more complicated nested structures so you're less likely to need to change the JS if you change the HTML.)
In context:

$(document).ready(function(){
  $('.qtyplus').click(function(e){
    var fieldName = $(this).attr('field');
    var container = $(this).closest('.container');
    var field = container.find('input[name='+fieldName+']');
    var currentVal = parseInt(field.val());
    if (!isNaN(currentVal)) {
      if (currentVal < 20) {
        field.val(currentVal + 1);
        container.find('.qtyminus').val("-").removeAttr('style');
      } else {
        container.find('.qtyplus').val("+").css('color','#aaa');
      }
    } else {
      field.val(1);
    }
  });

  $(".qtyminus").click(function(e) {
    var fieldName = $(this).attr('field');
    var container = $(this).closest('.container');
    var field = container.find('input[name='+fieldName+']');
    var currentVal = parseInt(field.val());
    if (!isNaN(currentVal) && currentVal > 1) {
      field.val(currentVal - 1);
      container.find('.qtyplus').val("+").removeAttr('style');
    } else {
      field.val(1);
      container.find('.qtyminus').val("-").css('color','#aaa');
    }
  });
});

  <input type='button' value='-' class='qtyminus' field='quantity' />
  <input type='text' name='quantity' value='1' class='qty' />
  <input type='button' value='+' class='qtyplus' field='quantity' />

  <input type='button' value='-' class='qtyminus' field='quantity' />
  <input type='text' name='quantity' value='1' class='qty'/>
  <input type='button' value='+' class='qtyplus' field='quantity' />

Note that if you find yourself calling jQuery methods with the same selector more than once in the same function it is generally better to use a variable to cache the result, as shown above.
There is no need to call e.preventDefault() in a type="button" element's click handler, because there is no default behaviour, so I've removed that from your code.
(Note also that the logic you are using to set the +/- button styles/colours is incomplete (you don't reset them if the user types a non-numeric value into the field), but that has nothing to do with what you're asking so I'll leave fixing it as an exercise for the reader.)


text:
Q: How to check email for file using c#? I receive an email with an excel file every week.  I know there are probably better ways to accomplish my goal, but would it be possible to have a script task in SSIS that can open email, look for a specific file name as an attachment and then copy that file to another location?
Here is the scenario.  This excel file is important for my team to have in a SQL database, and the provider of the excel source is only willing to email this excel file to us once per week.  I then check my email, copy the file to a location where an SSIS dataflow task can then pick it up and insert it into a SQL table.  I would like to automate this.  So if my original approach is not doable, how else could this be automated?  Aside from using a shared network location.  Assume the excel file can ONLY come from the email.  Using outlook/office 365, SSIS, SSMS, I have DBO access, and can use c#.
I'll admit that I'm ignorant on the email.  If there is a procedure that the email client can actually execute to accomplish this, then I'd be all ears!
EDIT:  I also have access to a network drive as I realize saving to my local machine may be impossible.

A: Simple Answer Yes it is Possible.
I had written a console program to process email on Office365 that I was also interfacing with SQL, so it definitely can be done.  It isn't necessarily the easiest thing in the world but it is not too hard either.
You can use the Exchange Web Services (EWS) Managed API
Article on stating it is possible and the API documentation
https://msdn.microsoft.com/en-us/library/office/dd877012(v=exchg.150).aspx
Github location where you can find the API (note this link is directly form Microsoft's Site)
https://github.com/officedev/ews-managed-api
Link on how to reference the assembly which contains the second link above:
https://msdn.microsoft.com/en-us/library/office/dn528373(v=exchg.150).aspx
Create and Connect to Service
string emailAddress = 'YourEmail@Domain.com';
ExchangeService exService = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
exService.Credentials = new WebCredentials(emailAddress,"password");

you can autodiscover or if you know the URL just set it so 1 of these lines
exService.AutodiscoverUrl(_emailAddress, delegate { return true; });
exService.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");

Find your Inbox & a Folder to Move the File To After Being Processed:
FolderView folderView = new FolderView(1);
folderView.PropertySet = new PropertySet(BasePropertySet.IdOnly);
folderView.PropertySet.Add(FolderSchema.DisplayName);
folderView.Traversal = FolderTraversal.Deep;
SearchFilter searchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "ProcessedFolderName");
Folder Inbox = Folder.Bind(exService, WellKnownFolderName.Inbox);
FindFoldersResults folderResults = Inbox.FindFolders(searchFilter, folderView);
FolderId processedFolderId = folderResults.Folders[0].Id;

Find Messages That meet your criteria:
List<SearchFilter> searchFilterCollection = new List<SearchFilter();
searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject,"Words in Subject"));
searchFilterCollection.Add(new SearchFilter.IsEqualTo(ItemSchema.HasAttachments,true));
searchFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.From,new EmailAddress("From@SendersDomain.com")));
SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And,searchFilterCollection);

ItemView view = new ItemView(50, 0, OffsetBasePoint.Beginning);
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.DateTimeReceived, ItemSchema.Attachments);
view.Traversal = ItemTraversal.Shallow;
FindItemsResults<Item> findResults = exService.FindItems(WellKnownFolderName.Inbox,searchFilter,view);

Process the results and save the attachments when done move the message to another folder so you don't keep importing the same one.
foreach (Item i in findResults.Items)
{
    foreach(FileAttachment attachment in i.Attachments)
    {
        attachment.Load(@"\\FilePathDirectory\" + attachment.FileName);
    }

    i.Move(processedFolderId);
}

you can expand the solution by testing if you get no results sending yourself an error message or throwing an error for SSIS to pickup and fail the job.  It is likely that you will overwrite the file multiple times if you have multiple messages to process so you may consider adding something unique in the file name instead of just using the same one but that will present other challenges in SSIS as well.
anyway, its a start hope it helps.


text:
Q: Admin-approved User.Read.All scope is not granted in the OAuth token scopes My Azure app has the scope User.Read.All approved by an admin:

I request the following scopes in my oauth registration:
scope:
  - profile
  - email
  - openid
  - offline_access
  - User.Read.All
  - Files.Read.All

And manage to successfully make the authorize call, getting the following response:
{
    "token_type": "Bearer",
    "scope": "profile email openid https://graph.microsoft.com/Files.Read.All",
    "expires_in": 3600,
    "ext_expires_in": 3600,
    "access_token": "...",
    "refresh_token": "...",
    "id_token": "..."
}

Why is User.Read.All not present in the scope of the generated token?
I also verified the token indeed doesn't grant me access to https://graph.microsoft.com/v1.0/users:
{
    "error": {
        "code": "ErrorInsufficientPermissionsInAccessToken",
        "message": "Exception of type 'Microsoft.Fast.Profile.Core.Exception.ProfileAccessDeniedException' was thrown.",
        "innerError": { ... }
    }
}

Am I missing some configuration?
If I also request the https://graph.microsoft.com/.default permission in the scope, I do get a valid response from the /users endpoint, however it only contains my own user.

A: The problems with my setup were:

*

*Should use /organizations/ tenant instead of /common/

*Should use Delegated permissions instead of Application

*Specify the scope https://graph.microsoft.com/.default instead of specific graph scopes


text:
Q: What is the probability that a 4-digit pin number contains a 1 and 5 (assuming repeats)? I tried to find different way the 1 and 5 would show in place.
For example it could be 1 _ 5 _ or 5 _ 1 _ or 1 5 _ _ and so forth.. This is how I got there are 12 possibilities to rearrange 1 and 5 in a 4 digit pin number.
But how do I include the other values into this and incorporate it?

A: The question is to find the number of $4$ digit pins if both $1$ and $5$ must be included in them.
This is a straight application of inclusion-exclusion.
Assuming that $0000$ is admissible,
Number of ways = (Total ways) - (At least one desired digit missing) + (Both desired digits missing)
$ = 10^4 -\binom219^4 + \binom228^4 = 974$

A: We want to find the chance that both $1$ and $5$ were not chosen.
First off, if there is only a single one or a single five, we can choose to place this $1$ or $5$ in only $\binom{4}{1}$ ways.  Then we have to pick whether it is a $1$ or a $5$, which can be done in $2$ ways.  Finally, we pick the remaining three numbers.  There are 8 choices for each of them, for a total of $8^3$ choices or trials.  This gives us a total of $\binom{4}{1} \cdot 2 \cdot 8^{4-1}$ ways.
Similarly, for two $1$s or two $5$s, there are $\binom{4}{2} \cdot 2 \cdot 8^{4-2}$ ways.  For three of them, there are $\binom{4}{3} \cdot 2 \cdot 8^{4-3}$ ways.  By now you should know the pattern.
There is also the chance that no $1$ or $5$ was chosen, which can happen any of $8^4$ ways.
This gives us a total of
$$\left( \sum_{k=1}^{4}{\binom{4}{k} \cdot 2 \cdot 8^{4-k} } \right)+8^4 = 9026$$
trials, out of either 10,000 if you consider the combination $0000$ as valid, or 9,999 if you do not.


text:
Q: Android studio application notification permission off by default? I'm debugging my app and preparing to launch it.
I'm using Onesignal to send notifications, and everything works fine. I send notifications using the Onesignal custom category.
When I send a notification it arrives, but making any sound or vibration or showing up sliding from the top (like WhatsApp or Fb notification).
Notification image

The problem seems is when the app is installed by default some of the notification permissions come disabled like sound and floating notifications:
Permission image

Any ideas? Do I need to use any "manifest" permission to enable those settings by default?
Thanks.


text:
Q: Excel VBA: getting row of clicked button I am trying to make a button in Excel which copies a certain range of cells from the active workbook to another workbook. The copying of this range works perfectly when I specify a fixed range, but I am stumped on how to figure out the row of the clicked button.
Every row contains 7 or so cells, and the 8th cell contains a shape with a macro attached to it (the button).
When the user presses this button the 7 cells on the same row as the row containing the pressed button need to be copied.
Using ActiveCell is of no use, since pressing the button doesn't actually set that cell as active. I searched around a lot but I can't seem to find how to obtain this value.
Once I have the row number of the clicked button I can figure the rest out on my own.

A: Excellent answer. Btw It also works for Rownumber!
'Same for rownumbers!
Sub Mainscoresheet()
     ' Mainlineup Macro
    Dim b As Object, RowNumber As Integer
    Set b = ActiveSheet.Buttons(Application.Caller)
    With b.TopLeftCell
        RowNumber = .Row
    End With
    MsgBox "Row Number " & RowNumber
End Sub

A: Each Shape has TopLeftCell property. It contains a cell within which the top left corner of the shape resides.

A: Try this:
Sub Mainscoresheet()
     ' Mainlineup Macro
    Dim b As Object, cs As Integer
    Set b = ActiveSheet.Buttons(Application.Caller)
    With b.TopLeftCell
        cs = .Column
    End With
    MsgBox "Column Number " & cs
End Sub

A: This works too!  Selects the cell that the generated button resides in (knew it was in column "K" but that could be calculated too!.
ActiveSheet.Range("K" & ActiveSheet.Buttons(Application.Caller).TopLeftCell.Row).Select


text:
Q: Fail2ban log filled with entries saying "fail2ban.filter : WARNING Determined IP using DNS Lookup:.." My fail2ban log at /var/log/fail2ban.log is completely filled with entries saying:
fail2ban.filter : WARNING Determined IP using DNS Lookup: [IP address]

I think this may have begun after I changed my ssh port...
Any idea what the cause of this is and how to stop it?

A: Check the PTR record of the [IP address] and compare the resolved name with the original IP address, i.e.
drill -x ip_address or dig -x ip_address or host ip_address

Then compare the result with:
drill result or dig result or host result

It should be the same. If it is not - the attacker changed the PTR.
You may modify usedns directive to "no" or "warn" in jail.conf.

A: Had the same issue.
Simple solution: add the following line at the top of your /etc/fail2ban/jail.conf file, in the [DEFAULT] section
usedns = no

To understand why your log file is being filled with warnings, consult the following page in the Fail2Ban wiki. It's basically to prevent people manipulating PTR record of their attack IPs to inject false values in your logs.

A: In my case the warning was:
WARNING Determined IP using DNS Lookup: localhost = ['127.0.0.1', '127.0.0.1', '::1']
This appeared every 10s. Setting usedns=no was no option as I wanted to get the root cause - after all somewhere in my logs this "localhost" appeared. After trying a bunch of logs I took the "brute force" way:
find /var/log -type f -name '*.log' | xargs grep localhost -l
which gave me all the log files containing that "localhost" (which were only two, one of them the fail2ban.log itself).
It turned out that the "mysql/error.log" was the one. I dropped a database without stopping the service (omg...) which lead to (every 10s):
2021-01-20T05:31:17.784116Z 2680 [Note] Access denied for user 'myserviceaccount'@'localhost' (using password: YES).
In the end - no need to stop the warnings (just stop the service ;-) ).


text:
Q: Homomorphism from a finitely generated module to a direct sum of modules Let $R$ be a commutative ring with unit. If $M$ and $N_i$ are arbitrary $R$-modules, the module $\operatorname{Hom}_R(M,\bigoplus_{i\in I}N_i)$ is not isomorphic to $\bigoplus_{i\in I}\operatorname{Hom}(M,N_i)$ in general. But if $M$ is finitely generated, does the isomorphism hold?

A: Define a homomorphism $\phi: \bigoplus_{i \in I} Hom(M,N_i) \rightarrow Hom(M, \bigoplus_{i \in I} N_i)$ by sending $f = (f_k)_{k \in I^*}$ to $\phi(f) = \sum_{k \in I^*} f_k$, where $I^*$ is a finite subset of $I$.
Clearly $\phi$ is injective.
For surjectivity,
take $f \in Hom(M, \bigoplus_{i \in I} N_i)$ and let $x_1,\dots,x_n$ be the generators of $M$.
Then for $j \in \left\{1,\dots,n\right\}$, $f(x_j)$ will be non-zero in finitely many indices $I_j \subset I$. So the image of $f$ will be non-zero for at most finitely many indices $I^* = \bigcup_{j=1}^n I_j$. For each $k \in I^*$, $f$ induces a homomorphism $f_k : M \rightarrow N_k$, from which we can see that $f = \phi((f_k)_{k \in I^*})$.
Hence if $M$ is finitely generated, then $\phi$ is an isomorphism.


text:
Q: Cross-sections of a revolutionplot3D of a piece-wise function I trying to get multiple cross-sections of a revolution plot I made from a piece-wise function.
The end goal would be to calculate integrals underneath those cross-sections.
my code looks like this:
Table[RevolutionPlot3D[
Piecewise[{{2^(0.4 x), 0 < x < 10}, {5 x - 50,
10 < x < 13}, {5 x - 65, 13 < x < 16}}, Exclusions -> None], {x,
0, 30}, RegionFunction -> Function[{x, y}, Evaluate[f]],
PlotLabel -> f], {f, {0 < x < 1, 0 < y < 1}}]

My approach was to use RegionFunction, but it neither gave me the cross-sections that I wanted nor was I close to calculate any integrals. Should I try a completely different approach or does anyone have some an idea how to improve my code?
An example of an cross-section that I am interested in

A: Perhaps you wish to use SliceContourPlot3D
f[x_] := Piecewise[{{2^(0.4 x), 0 < x < 10}, {5 x - 50,
    10 < x < 13}, {5 x - 65, 13 < x < 16}, {0, True}},
  Exclusions -> None]
Manipulate[
 SliceContourPlot3D[
  f[Sqrt[x^2 + y^2]] - z, {v == p}, {x, -16, 16}, {y, -16, 16}, {z, 0,
    16}, Contours -> {{0}}], {v, {x, y, z, x + y}}, {p, -5, 5}]


text:
Q: INSERT into temporary table with Identity column from stored procedure I have this temporary table definition:
CREATE TABLE #tmpAbsences
(
    idCol   int IDENTITY (1,1)
    , ClientID  int
    , FROMDate  datetime
    , ToDate    datetime
    , NoOfDays  int
    , NoQualDaysForSSP  int
    , AveWeeklyEarnings_Override    float
    , AveWeeklyEarnings_Paid    float
    , QualifyingDaysInWeek  smallint
    , ActualQualifyingDays  smallint
    , Weeks decimal
    , TotalWeeksINTmpAbsence    decimal
    , Linked    int
    , DateCreated   datetime
    , SSPDays   int
    , Location  varchar
    , SSPPaid   float
    )

SET IDENTITY_INSERT #tmpAbsences ON

INSERT #tmpAbsences
    EXEC sprc_EXPORT_SSP1_LoadtmpAbsencesTable @ClientId

and the below stored procedure definition to populate the temp table:
CREATE PROC sprc_EXPORT_SSP1_LoadtmpAbsencesTable
    @ClientId int
AS
BEGIN
    --DECLARE @ClientID int=9814
    SELECT
        IDENTITY(INT) AS idCol,
        @ClientID AS ClientID
        --, AB.AbsenceID
        , AB.FROMDate
        , AB.ToDate
        , AB.NoOfDays
        , AB.NoQualDaysForSSP
        , AB.AveWeeklyEarnings_Override
        , AB.AveWeeklyEarnings_Paid
        , SSP.QualifyingDaysInWeek
        , SSP.ActualQualifyingDays
        , CAST(CAST(SSP.ActualQualifyingDays AS DECIMAL(10,2))/CAST(SSP.QualifyingDaysInWeek AS DECIMAL(10,2)) AS DECIMAL(10,2)) AS Weeks
        , SUM(CAST(CAST(SSP.ActualQualifyingDays AS DECIMAL(10,2))/CAST(SSP.QualifyingDaysInWeek AS DECIMAL(10,2)) AS DECIMAL(10,2))) OVER(ORDER BY FROMDate ASC) AS TotalWeeksINTmpAbsence
        , (CASE WHEN (SELECT COUNT(AB2.ClientId) FROM t_Absence AS AB2 WITH (NOLOCK)
                    LEFT JOIN t_AbsenceCategory AS ABR2 WITH (NOLOCK)  ON (AB2.AbsenceCategoryID = ABR2.AbsenceCategoryID)  AND DATEDIFF(DAY, AB2.ToDate, AB.FROMDate) - 1 >= 0 -- Precedes this absence
                    WHERE AB2.ClientId = @ClientID
                    AND (DATEDIFF(DAY, AB2.ToDate, AB.FROMDate) - 1 <= 8 * 7) -- but not by more that 8 weeks
                    AND ABR2.IsSSP > 0 AND ABR.IsSSP > 0
                    AND (DATEDIFF(DAY, AB2.FROMDate, AB2.ToDate) >= 3
                        or ABS(DATEDIFF(DAY, AB2.ToDate, AB.FROMDate)) - ISNULL(dbo.fn_GetTotalNonWorkingDays(@ClientID,AB2.ToDate, AB.FROMDate),0) = 1)
                    ) > 0
                    AND dbo.fn_IsPIW(AB.AbsenceID, 4) = 1 -- this will take care of checking for continous days AND qualifying days
            THEN 1 ELSE 0 END) AS 'Linked'
        , AB.DateCreated
        , SSPDays
        , (SELECT Descn FROM t_Locations WITH (NOLOCK) WHERE LocationId = dbo.fn_CheckClientHistory(@ClientID,14,AB.FROMDate)) AS 'Location'
        , ISNULL((SELECT SUM(SSPPaid) FROM t_PayrollSSPEmployeePaid AS EP WITH (NOLOCK) WHERE EP.AbsenceID = AB.AbsenceID),0)  AS 'SSPPaid'
    FROM
        t_Absence AS AB WITH (NOLOCK)
    LEFT JOIN
        t_AbsenceCategory AS ABR WITH (NOLOCK) ON (AB.AbsenceCategoryID = ABR.AbsenceCategoryID)
    INNER JOIN
        t_PayrollSSPEmployeePaid SSP ON AB.AbsenceID = SSP.AbsenceID
    WHERE
        ClientID = @ClientID
        AND SSP.ActualQualifyingDays>0
    ORDER BY
        AB.ToDate DESC
END

But I cannot get it to function correctly...
Either I am getting an error because the IDENTITY function can only be used with a SELECT...INTO or if I miss that out it fails to load the right data...
Where am I going wrong?

A: Okay, as the error said you can not use IDENTITY( INT ) directly in the select statement. Alternatively you can use the ROW_NUMBER() function in your select statement, something like this -
CREATE PROC sprc_EXPORT_SSP1_LoadtmpAbsencesTable
    @ClientId int
AS
BEGIN
    --DECLARE @ClientID int=9814
    ;WITH cteAbsencesTable
    AS
    (
        SELECT
            ROW_NUMBER() OVER(ORDER BY AB.ToDate DESC) AS idCol,
            @ClientID AS ClientID
            --, AB.AbsenceID
            , AB.FROMDate
            , AB.ToDate
            , AB.NoOfDays
            , AB.NoQualDaysForSSP
            , AB.AveWeeklyEarnings_Override
            , AB.AveWeeklyEarnings_Paid
            , SSP.QualifyingDaysInWeek
            , SSP.ActualQualifyingDays
            , CAST(CAST(SSP.ActualQualifyingDays AS DECIMAL(10,2))/CAST(SSP.QualifyingDaysInWeek AS DECIMAL(10,2)) AS DECIMAL(10,2)) AS Weeks
            , SUM(CAST(CAST(SSP.ActualQualifyingDays AS DECIMAL(10,2))/CAST(SSP.QualifyingDaysInWeek AS DECIMAL(10,2)) AS DECIMAL(10,2))) OVER(ORDER BY FROMDate ASC) AS TotalWeeksINTmpAbsence
            , (CASE WHEN (SELECT COUNT(AB2.ClientId) FROM t_Absence AS AB2 WITH (NOLOCK)
                        LEFT JOIN t_AbsenceCategory AS ABR2 WITH (NOLOCK)  ON (AB2.AbsenceCategoryID = ABR2.AbsenceCategoryID)  AND DATEDIFF(DAY, AB2.ToDate, AB.FROMDate) - 1 >= 0 -- Precedes this absence
                        WHERE AB2.ClientId = @ClientID
                        AND (DATEDIFF(DAY, AB2.ToDate, AB.FROMDate) - 1 <= 8 * 7) -- but not by more that 8 weeks
                        AND ABR2.IsSSP > 0 AND ABR.IsSSP > 0
                        AND (DATEDIFF(DAY, AB2.FROMDate, AB2.ToDate) >= 3
                            or ABS(DATEDIFF(DAY, AB2.ToDate, AB.FROMDate)) - ISNULL(dbo.fn_GetTotalNonWorkingDays(@ClientID,AB2.ToDate, AB.FROMDate),0) = 1)
                        ) > 0
                        AND dbo.fn_IsPIW(AB.AbsenceID, 4) = 1 -- this will take care of checking for continous days AND qualifying days
                THEN 1 ELSE 0 END) AS 'Linked'
            , AB.DateCreated
            , SSPDays
            , (SELECT Descn FROM t_Locations WITH (NOLOCK) WHERE LocationId = dbo.fn_CheckClientHistory(@ClientID,14,AB.FROMDate)) AS 'Location'
            , ISNULL((SELECT SUM(SSPPaid) FROM t_PayrollSSPEmployeePaid AS EP WITH (NOLOCK) WHERE EP.AbsenceID = AB.AbsenceID),0)  AS 'SSPPaid'
        FROM
            t_Absence AS AB WITH (NOLOCK)
        LEFT JOIN
            t_AbsenceCategory AS ABR WITH (NOLOCK) ON (AB.AbsenceCategoryID = ABR.AbsenceCategoryID)
        INNER JOIN
            t_PayrollSSPEmployeePaid SSP ON AB.AbsenceID = SSP.AbsenceID
        WHERE
            ClientID = @ClientID
            AND SSP.ActualQualifyingDays>0
    )
    SELECT * FROM cteAbsencesTable
    ORDER BY idCol

END