text:
Q: How do you generalize the compression of data into N dimensional space? I have a theory that in order to best compress 1D data between 0 and 1 in a lossy way, you should map each data point $i$ to:
$\int_0^i \! P(x) \, \mathrm{d}x$
Where $P(x)$ is the probability density function of the data. The probability density function over the mapped data should be level and being level when you store the values to a finite precision, the amount of redundant information should be minimized.
My question is: how can I generalize this to more dimensions? Say I have a set of points which fit a given distribution and I want to compress points that fit the same distribution.
My initial assessment is that I should incrementally move the points so that they follow a level probability density function, then (with lots of arm waving) it should be possible to traverse the mapping using the proximity to the reference points.
A further constraint is that given data that fits something that looks like a spiral, rather than squashing it together, it should unwind it.
Can anyone shed any light on this?

*

*I assume that I'm not the first person to talk about such a concept. What is its name?

*Is this a good approach?

*How do you incrementally move the points so that they fit a level probability density function?

*How do you traverse the mapping?

*How do I modify the above approach to fit the added constraint?

edit: To clarify, essentially what I want to do is take a set of points, then warp the space the points are in so that the points are equally spaced.

A: If I understand it right, what you are trying to do is conceptually similar to vector quantization: this tries to partition the N-dimensional space in zones that measure (in probability) the same, so that you can assign to each zone a representative value (which would corespond to the quantized/coded value).


text:
Q: Change permissions of a SharePoint list using JavaScript I have an app that creates a list. I'd like the app to also set the list permissions to only allow admins to make changes to the list. I know how to hide the list, but I understand that this will not prevent clever users from typing in the URL of the list and modifying it anyway.
I don't see a way of changing list permissions with JavaScript. The functions available to me for lists don't seem to allow for modification of permissions, but it's possible I overlooked the correct one(s).
Any pointers on what functions I should be looking at?

A: How to enable unique permissions for a List object via JSOM
Use SP.SecurableObject.hasUniqueRoleAssignments property to determine  whether the role assignments are uniquely defined for a List or inherited from a parent securable object.
Use SP.SecurableObject.breakRoleInheritance(copyRoleAssignments, clearSubscopes) Method to set unique role assignments for the List object.
Example
var listTitle = 'Documents';
var context = SP.ClientContext.get_current();
var list = context.get_web().get_lists().getByTitle(listTitle);

context.load(list,'HasUniqueRoleAssignments');
context.executeQueryAsync(
   function(){
      var hasUniqueAssgns = list.get_hasUniqueRoleAssignments();
      if(!hasUniqueAssgns) {
         list.breakRoleInheritance(false, true);
         context.executeQueryAsync(
            function(){
                console.log('Success');
            },
            function(sender,args){
               console.log(args.get_message());
            }
         );
      }
   },
   function(sender,args){
      console.log(args.get_message());
   }
);

How to grant custom permissions for a List object via JSOM
The following example demonstrates how to break role inheritance for a List object and grant Full Control permissions for a current user
Example
var listTitle = 'Documents';
var context = SP.ClientContext.get_current();
var list = context.get_web().get_lists().getByTitle(listTitle);
var currentUser = context.get_web().get_currentUser();

list.breakRoleInheritance(false, true); // break role inheritance first!

var roleDefBindingColl = SP.RoleDefinitionBindingCollection.newObject(context);
roleDefBindingColl.add(context.get_web().get_roleDefinitions().getByType(SP.RoleType.administrator));
list.get_roleAssignments().add(currentUser, roleDefBindingColl);

context.executeQueryAsync(
   function(){
      console.log('Success');
   },
   function(sender,args){
      console.log(args.get_message());
   }
);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why isn't my Angular directive correctly binding one of my fields? I wanted to create a directive to create sortable table headers. The headers appear to be rendered and clicking on them cause the sort order to be toggled between ascending/descending like I'd expect, but the sorted column never changes.

angular
  .module('myApp', [])

angular.module('myApp')
    .directive('sortableheader', function () {
        return {
            template: '

{{col.name}}

 '
            ,
            restrict: 'E',
            replace: true,
            scope: {
                columns: '=',
                orderByField: '=',
                sortDesc: '=',
            },
            controllerAs: 'ctrl',
            bindToController: true,
            controller: function () {
                var vm = this;
                // Any additional functionality?
            }
        }
    });

(function () {
    'use strict';

    angular.module('myApp')
           .controller('SampleController', SampleController);

    function SampleController() {
        var vm = this;

        vm.orderByField = 'col1';
        vm.sortDesc = true;

        vm.data = [
          {col1: 'ABC', col2: '123'},
          {col1: 'XYZ', col2: '321'},
          {col1: 'GHI', col2: '234'},
          {col1: 'DEF', col2: '456'},
                  ];

        vm.columns = [
            { name: 'Column 1', field: 'col1' },
            { name: 'Column 2', field: 'col2' },
        ];
    }

})();

  Order by: {{report.orderByField}}

       <sortableheader columns="report.columns" orderByField="report.orderByField" sort-desc="report.sortDesc"></sortableheader>

            {{d.col1}}
            {{d.col2}}

Where am I going wrong with this? I'm sure it's some scoping issue (as it always seems to be), but I'm not seeing it.

A: You don't need to put col.field in quotes - see updated code

angular
  .module('myApp', [])

angular.module('myApp')
    .directive('sortableheader', function () {
        return {
            template: '

{{col.name}}

 '
            ,
            restrict: 'E',
            replace: true,
            scope: {
                columns: '=',
                orderByField: '=',
                sortDesc: '=',
            },
            controllerAs: 'ctrl',
            bindToController: true,
            controller: function () {
                var vm = this;
                // Any additional functionality?
            }
        }
    });

(function () {
    'use strict';

    angular.module('myApp')
           .controller('SampleController', SampleController);

    function SampleController() {
        var vm = this;

        vm.orderByField = 'col1';
        vm.sortDesc = true;

        vm.data = [
          {col1: 'ABC', col2: '123'},
          {col1: 'XYZ', col2: '321'},
          {col1: 'GHI', col2: '234'},
          {col1: 'DEF', col2: '456'},
                  ];

        vm.columns = [
            { name: 'Column 1', field: 'col1' },
            { name: 'Column 2', field: 'col2' },
        ];
    }

})();

  Order by: {{report.orderByField}}

       <sortableheader columns="report.columns" order-by-field="report.orderByField" sort-desc="report.sortDesc"></sortableheader>

            {{d.col1}}
            {{d.col2}}


text:
Q: Python Float Lost with Big Numbers I am working with some large numbers and have run into a problem with lost floating values.
When multiplying large numbers, the float portion seems to go missing, lost, becomes zero.
When using the same code with smaller numbers, this does not happen.
Trivial example:
import math
f_ProNum(31 * 61) ## Correct: DEBUG float: 314.833333
f_ProNum(5915587277 * 3367900313) ## Incorrect: DEBUG float: 3320518040297852928.000000

def f_ProNum(v_Num):
    """Syntax: (int); Returns: (float)"""
    print("DEBUG float: %f") %((v_Num - 2.0)/6.0) # DEBUG
    v_PDNum = (v_Num - 2.0)/6.0
    return v_PDNum

As seen in the second call, the float seems to get lost, or set to zero.
Why is it doing this, and how may it be addressed, fixed?

A: Larger float values lose precision.  To simplify a bit, floats have a fixed number of "digits" that are used, called the mantissa or significand, so large enough numbers are essentially going to use all their digits on the part to the left of the decimal place.
For more see: https://en.wikipedia.org/wiki/Floating_point#Internal_representation
To solve your problem, you might try using the decimal module, which allows you to configure the precision you need: https://docs.python.org/2/library/decimal.html


text:
Q: $.ajax datatype:json throws error I'm  trying to retrieve a json object through a ajax request from a php file. My ajax request looks like the following:
function validateForm() {
var name = $('#usernameLogIn').val();
var password = $('#passwordLogIn').val();
  $.ajax({
    type: 'GET',
    url: '../webroot/login/validateForm/',
    data: {name: name, password: password},
    dataType: 'json',
    success: function(result) {
    var data = JSON.stringify(result);
    var b = $.parseJSON(data);
    alert(b);

        },
        error: function(a,b,c) { console.log(a,b,c); }
  });
}

and my php file looks like this:
$form = $this->form;
      $status = false;
      $name = preg_replace("/[^A-Za-z0-9]/", " ", $_GET['name']);
      $formPassword = preg_replace("/[^A-Za-z0-9]/", " ", $_GET['password']);
      $now = date(DATE_RFC2822);
      $user =  $this->user->findName($name);

      if(isset($user->name))
      {
        $password = $user->password;
        $status = password_verify($formPassword, $password);
      }

      if ($status === true)
      {
         $this->session->set('loggedIn', $this->user->name);
      }

      else if ($status === false) {

          $this->session->clearSession('loggedIn');
    }

      $sessionLog = $this->session->get('loggedIn');

      $advert = array(
    'session' => $sessionLog,
    'name' => $name,
    'password' => $formPassword,
 );

echo json_encode($advert);
exit;

Finally when it passes the values back to my Ajax request it goes straight into the error function and prints the following into the console:
Object "parsererror" SyntaxError
message: Unexpected Token <"

Is it any way to tell where this goes wrong and why?
thankfull for answers, cheers.

A: I think you have verbose set to true in you config file.


text:
Q: Looking for a location based push service I am looking for location based push service. What I want to achieve with it is to be able to send requests to some geo location areas like London for example.
I have been trying to use PushWoosh, but it seems that their maximum range of GeoLocation is 1000 meters, which is too small area, as I would want to be able to send push for whole city.
I know it is possible to just send json with custom data area defining area of message, however I am looking for out of the box solution that could do this work for me. Especially because one of the requirements is that some non technical people will be able to send geo located pushes to the users, so I would need some nice looking frontend for them to do so.

A: I'm using a wordpress plugin.. I think it may can solve your problem..
http://smartiolabs.com/product/push-notification-system/


text:
Q: Sometimes why do we have to pass the argument as a tuple in python? So I wrote this simple program in python which has a function named num that takes two arguments as integers and checks if there some is "20" and if it is, then it returns True else it returns False and you would notice that in if statement I have called another function sum which is a built-in function in python, So when I try to pass the values of a  and b in this function without passing them as a tuple then it gives me the error mentioned below, So my question is that why does it works when I pass them like this sum((a,b)) and not like this sum(a,b)
 File "c.py", line 8, in <module>
    print(num(220,10))
  File "c.py", line 3, in num
    if sum(a,b) == 20:
TypeError: 'int' object is not iterable

def num(a,b):
    if sum(a,b) == 20:
        return True
    else:
        return False

print(num(220,10))

A: Python sum() is an inbuilt function that takes an iterable and returns the sum of items in it.
So basically you have to pass to it an iterable object (as tuple, or list) sum((a,b)) and not two separate objects sum(a, b).

A: This is very simple actually, when using
sum((1,3,4,5,6,7))
you want it to be as simple as possible, to quickly understand what it'll result.
but as you can see,
sum(iterable, /, start=0)
there are more parameters to be used, that you don't have to write them, but they must be passed.
The quick solution? use iterable instead of starred arguments and remove the hassle of knowing the parameters name to skip the defaults (note that starred arguments must be the last args on function signature)

A: when you are using sum(a,b) it is considering as an a,b as an individual object hence say's "'int' object is not iterable, so we need to pass it as a tuple like sum((a,b)).
Thanks, If you liked my answer please click on "This is useful answer button on side".


text:
Q: Single page deployment of oracle apex using SQL developer Currently we export a application entirely from Apex development workspace and run the below commands to deploy in a different environment
Apex_application_install.get_application_name;

Begin
Apex_application_install.set_workspace(above statement result ); Apex_application_install.generate_offset;
End;

Copy paste the exported application say f112.sql and execute it. We need to deploy individual pages developed rather than whole application via same method. I tried exporting single page and followed the same method. Copy paste the contents of exported fpage1.sql after running the same above commands
I'm getting error

Ora-01400 cannot insert null into (apex_190200.wwv_flow_worksheet_rpts.page_id)
Ora -06152 at apex_190200.wwv_flow_api


text:
Q: javascript object inside object I am working on react and using ant design list component, made it stateless child component to use it everywhere.  my datasource (props.datasource in this case) is array of objects. List component iterate through each object.
On title and description of list component i want to pass props which i am not able to do. For now it is title = {item.line1} and description = {item.city}, here "line1" and "city" are predefined but i want to use props. From parent component i want to pass title="line1" and then use it as {props.title} in list component title field.
<List
dataSource={props.dataSource}
renderItem={(item) => (
<List.Item
  key={item.id}
>
  <List.Item.Meta
    avatar={
      <Avatar
        icon={<CheckOutlined />} //anything
      />
    }
    title={item.line1}
    description={item.city}
  />
</List.Item>
)}
/>

with all my efforts i am not able to do this, How Can i add objects inside an object ?
Thanks

A: If I understood it correctly, what you need is destructure props to child component, it could achieved like this:
<List
  dataSource={props.dataSource}
  renderItem={(item) => (
    <List.Item
      key={item.id}
    >
      <List.Item.Meta
        avatar={
          <Avatar
            icon={<CheckOutlined />} //anything
          />
        }
        {...item} // Like this
      />
    </List.Item>
  )}
/>

A: I read somewhere to access property of objects by : expression[expression]
and by writing title={item[${props.title}]} the problem was solved.
Thanks


text:
Q: Strange behavior on GROUP BY and LIKE? Below is simplified example of my data. As you can see – there are just two rows here

So I run below and suddenly getting unexpected result

What I expected was something like:

Why am I getting wrong result?

Moreover, when I run below – I am getting only one row. Why second row with id=1 is not showing??

Is there BigQuery bug or what?

Disclaimer: I was asked exactly this type of question few times offline (outside of StackOverflow) and recently saw very same question on SO (I can't understand this BigQuery magic. find string with LIKE) but unfortunately it was deleted so I decided to Post this on my own

A: The reason for GROUP BY not grouping those two rows is that str field in those rows are actually different. Unfortunately, BigQuery Web UI collapses spaces in result panel when it is in Table mode. To see real/original values you can switch to JSON mode, as below

Same reason is for unexpected result for use of LIKE
As of how to deal with this? It depends!
For example you can kind of normalize your strings by suppressing spaces by yourself as it is shown below

P.S. In our internal tools – we just fixed the issue with suppressed spaces and just simply show all spaces:


text: Q: PythonAnywhere и асинхронность Как в pythonanywhere на django написать асинхронную функцию? К примеру пользователь что-то нажал, и это активирует асинхронную функцию, которая к примеру обработает введённые данные асинхронно, чтобы не прерывать работу основного скрипта.


text:
Q: Return list of affected indices from in Elasticsearch I need to write a query which will search across all indices in Elastisearch and return me a list of all indices where at least one document meets query requirements.
For now I`m getting top 2000 documents and distinct them by index name.

A: To search across all indices in the elastcsearch, you can use the _all option.
You can try similar to following, to get the indices which gets hits for the query
POST _all/_search
{
  "query": {
    "filtered": {
      "query": {
        "query_string": {
          "query": "you search criteia"
        }
      }
    }
  }
}

Most APIs that refer to an index parameter support execution across multiple indices, using simple test1,test2,test3 notation (or _all for all indices)
You can extract the index name from the result set which will be present under _index
sample result:
"hits": [
         {
            "_index": "index-name",
         }
       ]


text:
Q: Ways to serialize a class with Object field? I've been using a class:
public class Change {
    Object affectedObj;  //takes an instance of any class
    String affectedFieldName;
    float shift;
    ...

    public void apply() {
        affectedObj.getClass().getField(affectedFieldName).setFloat(affectedObj, shift);
    }
}

which I now need to serialize. Since Object is not serializable, how can I make my class serializable?
One thing that came to my mind is to replace Object with generic <T> type:
public class Change<T> {
    T affectedObj;  //takes an instance of any class
    String affectedFieldName;
    float shift;
    ...

    public void apply() {
        affectedObj.getClass().getField(affectedFieldName).setFloat(affectedObj, shift);
    }
}

But I can't judge about the downsides of this approach. If it's a good way to go what are the pitfalls here regarding serialization?
PS
Thank you, guys, for your reply. They all were revealing and helpful to me.

A: There is not necessarily any problem. Object is not Serializable, but it's also not not Serializable. You can still serialize a class which declares Object fields, provided that at the moment of serialization the fields happen to be either null or they point to instances of Serializable objects. (Otherwise, serialization will fail with a NotSerializableException.)
If you really need affectedObj to be "any class", well then you do have a problem, because there are some things that cannot be serialized no matter how hard you try (open net connections, for example).
If you want to restrict affectedObj to Serializable objects, simply declare the field as type Serializable:
public class Change implements Serializable {
    Serializable affectedObj; // takes an instance of any Serializable class
    ...
}

It is not necessary to use generics for this. You can still use generics if you want it for other reasons, for example if you want users of the class to be able to set and get that field in a fully-typed way. It doesn't affect serialization however.

A: Making your class generic wont help you unless you restrict T to be Serializable by adding Change<T extends Serializable>, however it will restrict the types your class can accept.
Another option is to implement Externalizable but then you would need to implement both read() and write() and will have to serialize an unknown object anyway.
Is there any reason not to use a non java specific format such as json, thrift, msgpack or other?

A: It doesn't look like a bad approach, but I would definitely upper-bind your generic parameter as such:
public class Change<T extends Serializable> {
    ...
}

This will ensure you can't parametrize your class with non-serializable types.


text:
Q: How is it specific use UIDocumentPickerViewController in SwiftUI Have this code:
struct ContentView: View {

    var d1: [String: Any]? = nil
    var res: ValidationResult?
    let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.jpeg, .png])
    documentPicker.delegate = self // <----- HERE
    documentPicker.modalPresentationStyle = .overFullScreen

raise: Expected declaration
Why? What is wrong?
Also how can I start to show document view controller? How to get a reference to a viewcontroller?
Unfortunatelly this crashes:
var body: some View {
    VStack {
        Button(action: {
            documentPicker.present(documentPicker, animated: true)

        }){ Text("Load JSON schema").padding() }

I found this for document handling: https://maheshsai252.medium.com/document-handling-in-swiftui-664cf050c724
Strange it does not have body like this:
var body: some View {
    VStack {

why?


text:
Q: Parity Transformation on Classical Fields I've been confused by this parity transformation in classical field theory for a long time.
Let $\phi(t,\vec{x})$ be a scalar field. Then, up to some constant phase factor, it transforms to $\phi^{\mathrm{P}}(t,\vec{x})=\phi(t,-\vec{x})$. Now, consider the current
$$j^{\mu}(t,\vec{x})=i\left\{\phi^{\dagger}(t,\vec{x})\partial^{\mu}\phi(t,\vec{x})-(\partial^{\mu}\phi^{\dagger}(t,\vec{x}))\phi(t,\vec{x})\right\}. \quad\quad\quad\quad\quad\quad(\ast)$$
Under a parity transformation $\mathrm{P}:(t,\vec{x})\rightarrow(t,-\vec{x})$, I expect to have
$$(j^{\mathrm{P}})^{0}(t,\vec{x})=j^{0}(t,-\vec{x}),\quad\vec{j^{\mathrm{P}}}(t,\vec{x})=-\vec{j}(t,-\vec{x})$$
However, if I use $(\ast)$ directly, replacing $\phi$ by $\phi^{\mathrm{P}}$, why shouldn't I also transform each $\partial^{i}$ to $-\partial^{i}$?

A: The parity transformation doesn't act on the coordinates. It acts on the fields. In other words, it acts on the whole function $\phi$. Given a function $\phi$ whose value at $(t,\vec x)$ is $\phi(t,\vec x)$, the parity transform gives a new function $\phi_P$ whose value at $(t,\vec x)$ is
$$
\phi_P(t,\vec x)=\phi(t,-\vec x).
\tag{1}
$$
Sometimes this is abbreviated by writing
$$
\vec x\mapsto-\vec x,
\tag{2}
$$
 but that's only a convenient abbreviation. Parity acts on the fields, not on the coordinates.
When we say that a model has parity symmetry, we mean that if a given function $\phi$ satisfies the equations of motion, then so does $\phi_P$. We call this a symmetry of spacetime, again as a way of being concise, but it isn't really a symmetry of spacetime itself; it's a symmetry of the behavior of the scalar fields that occupy spacetime.
If the transformation $\vec x\mapsto -\vec x$ preserves the spacetime metric (say, the Minkowski metric), then that is a symmetry of spacetime itself, at least if we consider the metric to be a property of spacetime itself. But we don't usually consider the scalar fields to be a property of spacetime itself. Instead, the scalar fields are something that occupies the spacetime. We can contrive a model (a set of equations of motion for the scalar fields) that is not parity-symmetric even if the spacetime itself is parity-symmetric.

A: Let $M$ be a manifold in which a theory $\mathfrak{T}$ is define. Let $\rho:x\rightarrow y$ be a coordinate transformation on $M$. Then $\rho$ is a classical symmetry of $\mathfrak{T}$ iff it preserves the equation of motion. In general, one can write down the EOM of $\mathfrak{T}$ in a generic form
$$F^{A}[D(x)]\phi_{A}(x)=0,$$
where $\phi_{A}$ are the fundamental fields of theory $\mathfrak{T}$, $D(x)$ is a local differential operator (e.g $i\frac{\partial}{\partial t}$, $\partial_{\mu}\partial^{\mu}$, and $\partial\!\!\!/$, etc.) and $F$ is a generic function.
If $\rho$ is a symmetry of $\mathfrak{T}$, then denoting objects in new coordinates by $F^{\prime A}$ and $\phi^{\prime}_{A}$, one has
$$F^{\prime B}[D(y)]\phi^{\prime}_{B}(y)=0.$$
Then, one must have the transformation properties
$$\rho:F^{\prime B}[D(\rho(x))]=R^{B}_{\,\,\,A}F^{A}[D(x)],$$
and
$$\rho:\phi^{\prime}_{B}(y)=(R^{-1})^{C}_{\,\,\,B}\,\phi_{C}(x),$$
where $R$ is a constant, so that the naturality condition
$$F^{\prime B}[D(\rho(x))]\phi^{\prime}_{B}(\rho(x))=F^{C}[D(x)]\phi_{C}(x)$$
holds.
This current $J[\phi^{\dagger},\phi]$ can be understood as a one form $d\phi^{\dagger}\phi-\phi^{\dagger}d\phi$. In local coordinate, it is given by
$$J[\phi^{\dagger},\phi](x)=J[\phi^{\dagger},\phi]_{\mu}(x)dx^{\mu},$$
where $J[\phi^{\dagger},\phi]_{\mu}(x)=(\partial_{\mu}\phi^{\dagger})\phi(x)-\phi^{\dagger}(\partial_{\mu}\phi)(x)$. Then it is clear how $J_{\mu}(x)$ should transform under parity. The transformation is given by a pull-back.
The minus sign for $\vec{J}(x)$ does not come from replacing $\vec{x}$ by $-\vec{x}$ in $\phi(x)$. In this picture, the pull-back does not change $\phi$ to $\phi_{\mathrm{P}}$. The minus sign comes from the pull-back
$$dy^{\mu}=\frac{\partial y^{\mu}}{\partial x^{\nu}}dx^{\nu}.$$
To relate this to the above "naturality condition", one considers the conservation equation
$$d\ast J=0$$
This equation should hold universally in all coordinates.
For simplicity, Let $M$ be a Minkowski spacetime with metric $\eta=(+1,-,\cdots,-1)$. Denoting $\eta^{\mu\nu}$ as the metric on the cotangent bundle $T^{\ast}M$, and $\eta_{\mu\nu}$ as the metric on the tangent bundle $TM$. Then, in local coordinate, one has to show that the equation
$$\eta^{\mu\nu}\partial_{\mu}J_{\nu}=0$$
should be independent of the choice of coordinate.
Let $\rho:x\rightarrow y$ be a coordinate transformation. Then in $y$-coordinate, one has fields $\phi^{\prime\dagger}$, $\phi^{\prime}$, $J^{\prime\mu}$, and $\tilde{\eta}^{\mu\nu}$ satisfying
$$\frac{\partial J^{\prime\mu}(y)}{\partial y^{\mu}}=0$$
or
$$\tilde{\eta}^{\mu\nu}(y)\frac{\partial}{\partial y^{\mu}}\left(\frac{\partial\phi^{\prime\dagger}(y)}{\partial y^{\nu}}\phi^{\prime}(y)-\phi^{\prime\dagger}\frac{\partial\phi^{\prime}(y)}{\partial y^{\nu}}\right)=0$$
Using the chain rule, one has, in $x$-coordinate,
$$\tilde{\eta}^{\mu\nu}(y(x))\frac{\partial x^{\alpha}}{\partial y^{\mu}}\frac{\partial x^{\beta}}{\partial y^{\nu}}\frac{\partial}{\partial x^{\alpha}}\left(\frac{\partial\phi^{\prime\dagger}(y(x))}{\partial x^{\beta}}\phi^{\prime}(y(x))-\phi^{\prime\dagger}(y(x))\frac{\partial\phi^{\prime}(y(x))}{\partial x^{\beta}}\right)=0$$
But
$$\tilde{\eta}^{\mu\nu}(y(x))\frac{\partial x^{\alpha}}{\partial y^{\mu}}\frac{\partial x^{\beta}}{\partial y^{\nu}}=\eta^{\alpha\beta},$$
one has, in $x$-coordinate
$$\eta^{\alpha\beta}\frac{\partial}{\partial x^{\alpha}}\left(\frac{\partial\phi^{\prime\dagger}(y(x))}{\partial x^{\beta}}\phi^{\prime}(y(x))-\phi^{\prime\dagger}(y(x))\frac{\partial\phi^{\prime}(y(x))}{\partial x^{\beta}}\right)=0$$
Since $\phi$ and $\phi^{\dagger}$ are scalar fields, one has
$$\phi^{\prime}(y(x))=\phi(x),\quad\phi^{\prime\dagger}(y(x))=\phi^{\dagger}(x)$$
Therefore, the transformation property of $J_{\mu}$ is indeed consistent with the naturality condition.


text:
Q: How do I fade out a particular Rectangle object in XAML ? (Without knowing which one it will be) I loaded up blend and select rectangle #1 (there are 6) and created a simple fade out storyboard.
How can I easily apply that Storyboard to other rectangles programmatically ?
I was hoping I could simply say something like
Storyboard.TargetNameProperty = this.rect2;
and run the storyboard and that would fade out rectangle #2 but

Error 2   Cannot implicitly convert type
  'System.Windows.Shapes.Rectangle' to
  'System.Windows.DependencyProperty'   C:_Code\WP7_SL_WStest\wp7wstest\Views\GameTimer.xaml.cs    63  49  wp7wstest

My XAML
<phone:PhoneApplicationPage.Resources>
    <Storyboard x:Name="StoryboardFadeOut">
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="rect1">
            <EasingDoubleKeyFrame KeyTime="0" Value="1"/>
            <EasingDoubleKeyFrame KeyTime="0:0:1" Value="0"/>
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>
</phone:PhoneApplicationPage.Resources>

A: You'll have to use the Attached Property Storyboard.SetTargetName. Example
<Rectangle Name="rect1" IsHitTestVisible="True" Fill="Green"
           MouseEnter="rect_MouseEnter"
           MouseLeave="rect_MouseLeave"/>
<Rectangle Name="rect2" IsHitTestVisible="True" Fill="Red"
           MouseEnter="rect_MouseEnter"
           MouseLeave="rect_MouseLeave"/>

Code behind
private void rect_MouseEnter(object sender, MouseEventArgs e)
{
    Rectangle clickedRectangle = sender as Rectangle;
    Storyboard StoryboardFadeOut = this.FindName("StoryboardFadeOut") as Storyboard;
    Storyboard.SetTargetName(StoryboardFadeOut, clickedRectangle.Name);
    StoryboardFadeOut.Begin();
}
private void rect_MouseLeave(object sender, MouseEventArgs e)
{
    Storyboard StoryboardFadeOut = this.FindName("StoryboardFadeOut") as Storyboard;
    StoryboardFadeOut.Stop();
}

Update
As decyclone pointed out, it's better to use SetTarget instead when we have direct access to the Target. The updated MouseEnter method would look like this
private void rect_MouseEnter(object sender, MouseEventArgs e)
{
    Storyboard StoryboardFadeOut = this.FindName("StoryboardFadeOut") as Storyboard;
    Storyboard.SetTarget(StoryboardFadeOut, sender as DependencyObject);
    StoryboardFadeOut.Begin();
}


text:
Q: jQuery: event.preventdefault not working with Firefox (mac and PC) I have this bit of jQuery toggling a paragraph after an H3 link. It works in IE and Chrome on PC and Safari and Chrome on Mac. On Firefox on both platforms, clicking the link does nothing at all?
<script type="text/javascript">
$(document).ready(function(){
$("#rightcolumn .article .collapse").hide();
$("#rightcolumn h3 a").click(function(){
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue = false;
};
$(this).parent().next().toggle(400);
});
});
</script>

If I disable the event.preventDefault(); section it works in Firefox, but of course then I get the page jumping to the top which I don't want. What can I do to get it working in Firefox?

A: You are missing the event declaration from your function.  Also as a convention I see most examples using evt as the variable name.
$("#rightcolumn h3 a").click(function(evt)
{
   evt.preventDefault();
   $(this).parent().next().toggle(400);
}

Comment from T.J. Crowder as to including the evt in function()

You need to declare the parameter to the click handler (event is not a global except on IE and browsers that throw a bone to IE-specific websites.) And note that you don't need (or want) the test for preventDefault. jQuery supplies it on browsers that don't provide it natively

More explanation on jQuery events

A: You need to provide the Event parameter:
<script type="text/javascript">
$(document).ready(function(){
$("#rightcolumn .article .collapse").hide();
$("#rightcolumn h3 a").click(function(event){
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue = false;
};
$(this).parent().next().toggle(400);
});
});
</script>

This question already been answered here https://stackoverflow.com/a/17712808
Note how the handler in the docs show this eventObject as the parameter passed to it: http://api.jquery.com/click/
And note how the Event object has the preventDefault method: http://api.jquery.com/category/events/event-object/


text:
Q: Whitebox and Blackbox testing I ve been reading for the whitebox and blackbox testing.
If im not wrong:
Whitebox tests the implementation of a Software Program, but blackbox tests the inputs and outputs.
Can someone please give me an example of a simple code for the both cases?
Thank you in advance.
so, the code here is a blackbox testing?
  class Schalter
  {
     private boolean
     {
       private boolean _istAn;
       public Schalter(boolean anfangsAn)
       {
          _istAn = anfangsAn;
       }
       public boolean istAn()
       {
          return _istAn;
       }
       public void umschalten()
       {
         _istAn = !_istAn;
       }
  }

A: Blackbox testing is a way of testing where you don't care how the program manipulates the input; you're only checking to see if the outputs are valid for the specified inputs.
Whitebox testing is a way of testing when you care how the program manipulates the input, as well as the output.
I guess one example is if you were writing a test for sorting algorithims. A blackbox test would simply check to see if the outputs are sorted according to what you would expect. A whitebox test might check to see if the sorting is stable or not, because that depends on the implementation of the sorting algorithm. For example, Merge Sort is stable, whereas the typical in-place version of Quicksort is not (although stable versions do exist).

A: See in simple words, White box testing is a testing where you are aware of the inner paths and coding of software or any app. Programming skills are needed to design Test Cases in White box testing. White box testing can be performed in Unit testing, Integration testing and System testing.
While in Black Box testing you just need SRS(Software Requirement Specification) to understand what system does and what are Client's requirement. Here tester's Programming skills are not tested. Usually in Manual testing BlackBox approach is followed. Black Box testing is done in almost all levels i.e Unit testing, Integration testing , System testing and Acceptance testing.

A:
In Black box testing the structure of the program is not considered. Test cases are decided solely on the basis of the requirements or specification of the program or module, and the internals of the program are not considered for the selection of the test cases. black box testing is concerned with functionality of the program.

Lifted from https://in.answers.yahoo.com/question/index?qid=20101031090207AAbYHrB

A: Blackbox -> you're really just checking if you're getting correct output for the input you gave your program.
Say you have a prompt that asks you to enter 2 digits to get the sum of the numbers.
Enter 2 numbers:  2 5
output:  2 + 5 = 7
That's all there is to black box really.

White box you would want to check to see HOW it's happening.
You could do the normal thing which would be something like
int adder(int firstNum, int secondNum)
{
    return firstNum + secondNum;
}

this is more efficient than say something like:
int adder(int firstNum, int secondNum)
{
    int temp;
    for(int i = 0; i < (firstNum + secondNum + 1); i++)
        temp = i;
    return temp;
}

In whitebox testing you would look at your code and figure out which is more efficient and/or is easier to read.  Obviously the first one is since:

*

*the code is simpler and easier to understand

*The first does not involve loops to find the answer this takes up more processing time than the first

*The first doesn't create extra variables that are not needed.  This means less memory needed to keep track of the data.

This is a simple and arbitrary example, but when you get into larger projects you'll do a lot of whitebox testing when you do unit tests to figure out if smaller segments of your code works and you would normally do black box testing when you start integrating the smaller segments of your code into the larger project to check if you were still getting correct output for given input.
Another way to look at it you could use blackbox testing to see if you were getting bad output and if so then you could go in and do whitebox testing to see what you were doing wrong in your code.

A:
White box testing is the detailed investigation of internal logic and structure of the code. White box testing is also called glass testing or open box testing. In order to perform white box testing on an application, the tester needs to possess knowledge of the internal working of the code.

Lifted from http://www.tutorialspoint.com/software_testing/testing_methods.htm


text:
Q: Why this function causes memory leak function parseAttach(b)
{
    var h="";
    for(i=0;i<b.length;i++)
    {
        var a=b[i];
        switch(a['type'])
        {
            case "image":
                h+='

';
            break;
            case "video":
                h+='

';
            break;
            case "music":
                h+='
<embed src="http://www.xiami.com/widget/0_'+a['id']+'/singlePlayer.swf" type="application/x-shockwave-flash" width="257" height="33" wmode="transparent"></embed>
';
            break;
        }
    }
    return h;
}

Once above function is running, the page cannot be interacted, memory and cpu usage of that page skyrocket.
this is an example of parameter b passed to this function:
[{"type":"video","from":"k6","id":"kyxGTZbD-vQ8Domm-eeHiQ"}]

b.length is not more than 2 and this function was executed no more than three times. If  this function is removed, memory leaking will not happen.
UPDATE:
Following @GarethMcCaughan 's suggestion, I added alert(i) to the top of the loop, it keeps alerting 0, I headed to the invocation code:
for(i=0;i<c[0].length;i++)//the breakpoint
{
    ......
    if(t[6].length>0)
    {
        //console.log(t[6].length);
        //var a=parseAttach(t[6]);
        var a="";
        h+='
'+a+'
';
    }
   ......
}

as you see in the comment, if I replace the invocation with a console.log, the log only show 4 times of execution. But why the function are invoked repeatedly?
Then I found the console report a breakpoint at the top of the loop(I've comment it out), is this the reason why the function keeps invoking?

A: In both of your loops you have not put var before your i variable.  This means it is global.  If it is global then both loops are using the same i.
for(i=0;i<b.length;i++)

add var and it should fix it:
for(var i=0;i<b.length;i++)

EDIT:  Further clarification:
for(i=0;i<c[0].length;i++)
{
    ......
    if(t[6].length>0)
    {
        // THIS CALL WILL SET THE GLOBAL i TO t[6].length
        var a=parseAttach(t[6]);
    }
   ......
}

Therefore, the exit condition of the outer loop is never met, every iteration of the loop sets i back so that i never reaches c[0].length.

A: Everything seems fine apart from one bug: You forgot to make the counter variable i local. When invoked from a loop, the code would reset the same-named counter variable of the outer loop (to 2, as this is the max length) and make it never reach its end condition:
var i; // this variable will always be referenced
function x(number) {
    for (i=0; i<number; i++)
        dosomething;
}
for (i=0; i<5; i++)
    x(2); // resets i to 2
// => never-ending loop

The infinite loop will make your browser hang, freezing the interface until the code is executed. Some browser might throw an error for too-long-running scripts, implemented with a timeout.


text:
Q: Node js closures need pushing to array I have a problem that my code wont return the array which has been pushed data into, I figured out last night it was something about closures, I researched them and I don't really get them. All the examples are using addeventlistener.
I know I have to somehow wait until my push is done because this is async.
app.post("/search", function(req, res){
    var test = []
    for (var key in req.body.movie){
        Movie.find({title: "Gotham"}, function(err, foundMovie){
            test.push(foundMovie)
        })
    }
    console.log(test)
    res.render("index")
});

A: MongoDB/Mongoose operations are asynchronous. A possible fix for your problem would be to use async/await like so.
app.post("/search", async function(req, res){
    var test = []
    for (var key in req.body.movie){
        let foundMovie = await Movie.find({title: "Gotham"})
        test.push(foundMovie)
    }
    console.log(test)
    res.render("index")
});

You will need to use newer version of Node for async/await to work. :)
Also never execute DB queries in loops.


text:
Q: Changed root password on my server, now can't login anymore I decided to change the root password that came preset on a fresh DigitalOcean server (ubuntu 12.04).
I used the first answer to this post: How to change root password in ubuntu?
which is:
sudo -i
passwd

(set my new password on prompt)
sudo passwd -dl root

Now I can't login as root on tty1 on my server, nor can I access my server on Filezilla, etc...
What did I do wrong, and more importantly how can I recover my root login?
Thank you for your help.

A: The command
 sudo passwd -dl root

is for disabling root and removing root password. As explained in man passwd:

-d --delete
Delete a user's password (make it empty). This is a quick way to disable a password for an account. It will set the named account passwordless.
-l --lock
Lock the password of the named account. This option disables a
  password by changing it to a value which matches no possible encrypted value (it adds a ´!´ at the beginning of the password).

So you just need to set root password again.
So, first execute in a terminal
sudo passwd root

or
sudo -i
passwd

you will be prompted for a new Unix password. Write it twice (second time for confirmation).
Then execute
sudo passwd -u root

to unlock the account. This should return
passwd: password expiry information changed

Now you will be able to access root. But it is not a good idea as you can see here.


text:
Q: How do I search a list for a number between two values? In Python I have a list of numbers that have been added using .append(). I need to search my list to find if it contains any particular integer between two set values eg/ between 30 and 40.
I know I can use the code if x in n: to search a list for a single integer but I do not know how to do this for multiple integers.

A: Here's a function for you. It returns a list with all the values between the low and high limits given, including duplicates. If you want to get rid of duplicates, use set. I wouldn't sort it first because that would be less efficient than just iterating through the list.
def between(l1,low,high):
    l2 = []
    for i in l1:
        if(i > low and i < high):
            l2.append(i)
    return l2

l = [1,3,4,5,1,4,2,7,6,5]

print( between(l,2,5) )

[3, 4, 4]

edit:
Or, hey, let's use list comprehension if you're into the whole brevity thing!
l = [1,3,4,5,1,4,2,7,6,5]
l2 = [i for i in l if i > 2 and i < 5]
print(l2)

[3, 4, 4]

A: Some of above answers are efficient. I am just giving an approach with sorting the list.
filter(lambda x: x>30 and x<40,sorted(a))

a is input list

A: Since you didn't provide any code yet, I'll give you a simple algorithm:
for every number in the list
    if the number is greater than 30 and less than 40
        do something with the number

For example, if you simply need to know if such a number exists, you can set a boolean value to true once the condition has been met.
This answer includes a more abbreviated way to accomplish what you have in mind.

A: min=30
max=40

nums = [8, 32, 35, 180]
nums.append(13)

for x in nums:
   if x > min and x < max: print x


text:
Q: FCC / CE requirements for adapter pcb? A product consisting (electronically) just of a PCB with a male USB-C one one side, 5mm of traces and a female USB-C on the other end. No other components at all. To be used as consumer device.
How much FCC and CE testing would really be required, if any?

A: If you want to sell the thing in Europe, you need to affix CE. For CE, the intended use determines what directives you need to comply to.
This is probably limited to:

*

*Electromagnetic compatibility

*Restriction of Hazardous Substances in Electrical and Electronic Equipment

You can use harmonised standards to make very plausible your product is satisfying the EMC directive, and while it is one of the best ways to do it, you don't have to.
I think when you connect the shields of the USB such that it forms a cage of Faraday, you can make use of article 2 (d) of the EMC directive

equipment the inherent nature of the physical characteristics of which is such that:
(i) it is incapable of generating or contributing to electromagnetic emissions which exceed a level allowing radio and telecommunication equipment and other equipment to operate as intended; and
(ii) it operates without unacceptable degradation in the presence of the electromagnetic disturbance normally consequent upon its intended use;

The generating of EM emmisionis obviously not present. The contribution and susceptibility to EM emmision is made plausible by the Faraday cage.


text:
Q: BufferedReader with InputStreamReader fed with a finished HTTPResponse causes NetworkOnMainThreadException I have some code that converts my HTTPResponse Object into a JSONObject, which works fine most of the time:
public static JSONObject httpResponseToJson(HttpResponse response) {
    if (response != null) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),
                    "UTF-8"));
            String json = reader.readLine();
            if (json != null) {
                JSONObject jsonObject = new JSONObject(json);
                printStatus(jsonObject);
                return jsonObject;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

However, sometimes it throws a the Android NetworkOnMainThread exception. I cannot figure out why, because the response is already finished and there should not be any more network IO involved in that call. For test reasons, if I allow NetworkOnMainThread, this method works fine all the time.
Note that all the HTTPResponse is fetched with an AsyncTask and this is working fine.
I am very interested in any suggestions.

A: Reading the response from a HttpResponse object also involves a Network Operation. Simply process that also in the doInBackground() method and modify your AsyncTask to pass to the onPostExecute() the real result once processed.

A: its mean you are performing some network operation on main thread.The point here is Unless the stream is not closed, you are still performing network operation so move that part into doInBackGround() too.


text:
Q: Finding the values of real constants to satisfy an expression on limit at infinity Find the values of real constants $a$ and $b$ such that $\lim_{x\to\infty} (\sqrt{ax^2+1} -\sqrt{x^2+bx}) = 2021$
I'm not sure how to start, I've considered separating the expression and finding $\lim_{x\to\infty} \sqrt{ax^2+1}$ first but I don't know how to cancel out the $x$ valued at infinity. What should I do?

A: Hint
$$
\sqrt{ax^2+1} -\sqrt{x^2+bx}=\left(\sqrt{ax^2+1} -\sqrt{x^2+bx}\right)\frac{\sqrt{ax^2+1} +\sqrt{x^2+bx}}{\sqrt{ax^2+1} +\sqrt{x^2+bx}}\\
=\frac{\left(a-1\right)x^2-bx+1}{\sqrt{ax^2+1} +\sqrt{x^2+bx}}
$$
It is a useful trick when you deal with difference of square roots.
Do you know how to evaluate this kind of limit now that it is a quotient ?
Edit :
Replying to @Sukhoi234 :
Let's analyze
$$
\frac{\left(a-1\right)x^2-bx+1}{\sqrt{ax^2+1} +\sqrt{x^2+bx}}
$$
you see that the limit goes to $\pm \infty$ iif $a \ne 1$ because the degree of the numerator is more than the denominator and it is necessary to make the $x^2$ vanish. Hence $a=1$. The expression is hence
$$
\frac{-bx+1}{\sqrt{x^2+1} +\sqrt{x^2+bx}}\underset{(+\infty)}{\sim}\frac{-b}{2}
$$
Hence you need to choose $b=-4042$

A: $$L=\lim_{x\to \infty}[\sqrt{ax^2+1}-\sqrt{x^2+1}]=\lim_{x\to \infty} x\sqrt{a}\left(1+\frac{1}{ax^2}\right)^{1/2}-x\left(1-\frac{b}{x}\right)^{1/2}$$
Use $\lim_{z\to 0} (1+z)^{k}=1+kz+O(z^2).$
Then $$L=\lim_{x\to \infty} x\sqrt{a}\left(1+\frac{1}{2ax^2}\right)-x\left(1+\frac{b}{2x}\right)=\lim_{x\to \infty} x\sqrt{a}-x+\frac{1}{2\sqrt{a}x}-\frac{b}{2}=2021$$
$$\implies a=1, b=-4042$$


text:
Q: Main point of Application Delegate class What's the main point behind putting variables and method signatures inside ApplicationDelegate.h in Objective-C ? By doing this, all those methods and variables are seen by another view controller classes? Is that the point?
And also: is there only one application delegate class inside each project?

A: The Application Delegate (and yes, there is only one per application) is the backbone of the Controller layer in Cocoa and Cocoa Touch applications. Its main function is to customize the behaviour of NS/UIApplication in certain circumstances (such as application termination, application opening, etc.). It is also commonly used to assign delegates to other responders (such as table views, outline views, etc.).
In small applications, it will usually act as both delegate and dataSource to most interface elements, but as Felixyz points out, this can deteriorate quickly if the application grows.

A: "By doing this, all those methods and variables are seen by another view controller classes? Is that the point?"
Of course, any class that imports the app controller's header can access public properties and methods (and ivars), but that goes for any class, not just the app delegate.
It's pretty common to put a few important objects and methods that are needed all over the app in the app delegate. In that way, yes that's often the reason why you see variables and methods defined on the app delegate class.
This makes sense sometimes, but it can very quickly deteriorate into very bad design. You should make sure not to use the app delegate as some basket where you can just throw all shared state and functionality in the app. I'm working with some code where someone did this right now, and it's extremely hard to change and refactor functionality.
This is just a version of the well-know problems of using global state for everything. In short, you should analyze functionality and divide it into separate classes, or groups of classes. Try to keep your app delegate as slim as possible!
EDIT: ...and read Matt Gallagher's post on this issue.


text:
Q: Google Sign In API consent form I have an android app that is using google sign in to authenticate users to my app.
On my Google API console, I've set up my project and i can see the following warning:

It asks me to configure my consent screen.
When i try to configure it, i land on the following fields:

I do not have any websites' url to input in the authorized domain since i only have an android app published on the play store. This field is mandatory to send for verification.
Can someone advise what to put in this field ?

A: Unfortunately some of these links are required if you intend to verify your application.  Mainly the privacy policy link. Your going to have to put this page up on the internet somewhere so that users can see your policy rules.
You shouldn't need to authorize a domain unless this is a web application.
You may want to read though Setting up OAuth 2.0
There are some other things you will need to supply like You need to specify your Android app's package name and SHA1 fingerprint.


text:
Q: Change entire CSS file on refresh All other questions I've found relating to this are about changing specific elements, or changing the CSS file with a button, but what I'm looking to find out is:
Is there a script that will swap an entire CSS file whenever the page is refreshed?
I.e. I've got my core style.css and supplementary {color}.css files which replace certain elements in style.css, and I'd like those supplementary CSS files to be loaded randomly on refresh.
Sorry, I don't even know where, to begin with this. Hopefully, someone can offer some pointers?
Thank you.

A: Fundamentally this is just a matter of picking something at random, e.g.:
<head>
<!-- ... -->
<script>
var sheets = ["sheet1.css", "sheet2.css", "sheet3.css"];
var sheet = sheets[Math.floor(Math.random() * sheets.length)];
document.write('<link rel="stylesheet" href="' + sheet + '">');
</script>
<noscript>
<link rel="stylesheet" href="sheet1.css">
</noscript>
<!-- ... -->

(One of the rare cases where document.write isn't actually a bad solution.) Note the noscript fallback will always use the same stylesheet on browsers with JavaScript disabled.

A: All you need to do to load a CSS-file with Javascript is to add a <link> element to the DOM/body and it will be loaded automatically.
So in your <head> section you could include a <script> tag that just randomly selects a color.css from an array and generate the link tag, preferably as early as possible in the file to prevent flickering.
<script>
  var colors = ['red.css', 'blue.css', 'green.css'];
  var colors_idx = Math.floor(Math.random()*colors.length);

  document.write('<link href="'+colors[ colors_idx ]+'" rel="stylesheet" type="text/css" />');
</script>

(PS. There are cleaner ways to inject HTML, keeping it concise to focus on the solution. Use your favorite approach, document.write can be a bit fickle.)


text:
Q: Shared session cookie is not being recognised by authentication scheme This follows on from a previous post which started as a general issue and is now more specific.
In short, I've been following guidance (such as this from Microsoft, this from Scott Hanselman, and this from Barry Dorrans) to allow me to share the authentication cookie issued by a legacy ASP.NET web app with a new dotnet core app running on the same domain.
I'm confident that I'm using the recommended Microsoft.Owin.Security.Interop library correctly. On that side (the old ASP.NET app), the CookieAuthenticationOptions are configured with AuthenticationType and CookieName both set to the same value - SiteIdentity. This same value is also used in the interop data protector setup:
var appName = "SiteIdentity";

var encryptionSettings = new AuthenticatedEncryptorConfiguration
{
    EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
    ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
};

var interopProvider = DataProtectionProvider.Create(
    new DirectoryInfo(keyRingSharePath),
    builder =>
    {
        builder.SetApplicationName(appName);
        builder.SetDefaultKeyLifetime(TimeSpan.FromDays(365 * 20));
        builder.UseCryptographicAlgorithms(encryptionSettings);

        if (!generateNewKey)
        {
            builder.DisableAutomaticKeyGeneration();
        }
    });

ShimmedDataProtector = new DataProtectorShim(
    interopProvider.CreateProtector(
        "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
        appName,
        "v2"));

I log in using this app, confirm I have a cookie named SiteIdentity then switch to a new dotnet core app running on the same domain.
There, without adding authentication middleware I can confirm that I can unprotect and deserialize the cookie. I do this by setting up data protection in Startup to match the other app:
var appName = "SiteIdentity";

services.AddDataProtection()
    .PersistKeysToFileSystem(new DirectoryInfo(keyRingSharePath))
    .SetDefaultKeyLifetime(TimeSpan.FromDays(365 * 20))
    .DisableAutomaticKeyGeneration()
    .UseCryptographicAlgorithms(new AuthenticatedEncryptorConfiguration()
    {
        EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
        ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
    })
    .SetApplicationName(appName);

Then in my controller I can use a data protector to manually unprotect the cookie:
var appName = "SiteIdentity";

var protector = _dataProtectionProvider.CreateProtector(
    "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
    appName,
    "v2");

var cookieValue = Request.Cookies[appName];
var format = new TicketDataFormat(protector);
var ticket = format.Unprotect(cookieValue);

I can confirm that ticket.Principal does indeed reference a claims principal representing the account which I signed in with on the other app.
However, I've found it impossible to wire up the cookie authentication middleware to properly protect my endpoints using this cookie. This is what I've added to Startup, after the data protection code above:
var protectionProvider = services.BuildServiceProvider().GetService<IDataProtectionProvider>();

var dataProtector = protectionProvider.CreateProtector(
    "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
    appName,
    "v2");

services
    .AddAuthentication(appName)
    .AddCookie(appName, options =>
    {
        options.TicketDataFormat = new TicketDataFormat(dataProtector);
        options.Cookie.Name = appName;
    });

By my understanding this is telling the middleware that I have an authentication scheme named "SiteIdentity" (the advice is that authentication scheme must match the ASP.NET authentication type) which expects a cookie also called "SiteIdentity" which will contain protected data that the supplied data protector can interpret.
But when I add the attribute [Authorize(AuthenticationSchemes = "SiteIdentity")] to my controller I'm kicked away to a login page.
I can't understand what I'm doing wrong. As I've shown, I can confirm that it is indeed possible to use this data protector and ticket format to interpret the authentication cookie, so I guess I must have something wrong in this middleware wiring, but I'm not sure what.

A: Please ignore. It turns out that my code is actually correct. I had been working on this solution for long enough that the session represented by the cookie value I was using to test had expireed. Will leave this question here in case the code benefits anyone trying to achieve the same.


text:
Q: Одинаковые ячейки таблиц Не могу реализовать одну идею. Есть таблицы, при описании текста в ячейки, ячейки увеличиваются, а у остальных таблиц нет, мне нужно, чтобы ячейки и в остальных таблицах тоже увеличивались (не только первого столбца), их может быть много и в этих столбцах тоже ячейки должны увеличиваться.
Буду очень благодарен за помощь.
Был подобный вопрос уже был задан, но там код работает не так, как нужно мне.

A: Насколько я понял вам скорее нужен JavaScript, на одном только css у вас не получиться так сделать. Так как вам нужно динамически меня размер не связанных ячеек.

A: Как-то так

let table = document.querySelectorAll("table");
let max = 0;

for (let temp = 0; temp < table.length; temp++) {
  let tbody = table[temp].querySelector("tbody");

  for (let i = 0; i < tbody.children.length; i++) {
    let tr = tbody.querySelectorAll("tr");
    for (let j = 0; j
 max) max = tr[i].children[j].offsetWidth;
    }
  }

  for (let i = 0; i < tbody.children.length; i++) {
    let tr = tbody.querySelectorAll("tr");
    for (let j = 0; j < tr[i].children.length; j++) {
      tr[i].children[j].style.width = max + "px";
    }
  }
}
td {
  border: 2px solid #000;
  text-align: center;
}

Таблица 1

    1
    2
    3
    4

    5
    6
    7
    8

    9
    10
    11
    Длинее всех

Таблица 2

    asd
    asd
    asd
    asd
    asd
    asd

Таблица 3

    asd
    asd
    asd
    asd

    asd
    asd
    asd
    asd

A: Возможно, что Вам подойдёт вариант с одной таблицей, но с несколькими секциями
 (JS здесь, только для того, чтобы размножить секции, добавить интерактивность и не писать "простыню" HTML) :

/* For example only --> */ let table = document.querySelector('table'), tbody = document.querySelector('tbody'); for (let i = 2; i < 4; i++) { let clone = tbody.cloneNode(true); clone.querySelector('th[colspan]').textContent = `Таблица ${i}`; table.append(clone); } table.querySelectorAll('td').forEach(el => el.contentEditable = true);
table { border-collapse: collapse; }

tbody { box-shadow: inset 0 1px 0 0 #000;}
tbody:not(:last-of-type)::after { content: ""; display: block; padding: 1em; }

th { padding: 0.5em; box-shadow: inset -1px -1px 0 #000; background-color: #0004; }
th:first-of-type { box-shadow: inset -1px -1px 0 #000, inset 1px 0 0 #000; }

td { padding: 0.5em; box-shadow: inset -1px -1px 0 #000; }

Таблица 1

	Колонка 1	Колонка 2	Колонка 3	Колонка 4

Строка 1	Попробуйте	изменить	текст в этих	ячейках

Строка 2


text:
Q: Delete a specific string (not line) from a text file python I have a text file with two lines in a text file:
<BLAHBLAH>483920349<FOOFOO>
<BLAHBLAH>4493<FOOFOO>

Thats the only thing in the text file. Using python, I want to write to the text file so that i can take away BLAHBLAH and FOOFOO from each line. It seems like a simple task but after refreshing my file manipulation i cant seem to find a way to do it.
Help is greatly appreciated :)
Thanks!

A: If it's a text file as you say, and not HTML/XML/something else, just use replace:
for line in infile.readlines():
    cleaned_line = line.replace("BLAHBLAH","")
    cleaned_line = cleaned_line.replace("FOOFOO","")

and write cleaned_line to an output file.

A: f = open(path_to_file, "w+")

f.write(f.read().replace("<BLAHBLAH>","").replace("<FOOFOO>",""))
f.close()

Update (saving to another file):
f = open(path_to_input_file, "r")
output = open(path_to_output_file, "w")

output.write(f.read().replace("<BLAHBLAH>","").replace("<FOOFOO>",""))
f.close()
output.close()

A: Consider the regular expressions module re.
result_text = re.sub('<(.|\n)*?>',replacement_text,source_text)

The strings within < and > are identified. It is non-greedy, ie it will accept a substring of the least possible length. For example if you have "<1> text <2> more text", a greedy parser would take in "<1> text <2>", but a non-greedy parser takes in "<1>" and "<2>".
And of course, your replacement_text would be '' and source_text would be each line from the file.


text:
Q: Is is possible to animate text color changing only in a part of text in iOS? I wonder if it even possible in iOS to animate changing color in only a part of the text, preferably not char by char, but pixel by pixel, like on this picture?

I know how to change text color in static with NSAttributedString and I know how to animate the whole text with CADisplayLink, but this makes me worry.
Maybe I can dive into CoreText, but I'm still not sure it is possible even with it. Any thoughts?
UPD I decided to add a video with my first results to make the question more clear:
my efforts for now (the label is overlapping)

A: You can quite easily achieve this using CoreAnimation possibilities.
I've added a simple demo, you play with it here (just build the project and tap anywhere to see the animation).
The logic is the following:

*

*Create a custom subclass of UIView.

*When some text is set, create two similar CATextLayers, each with the same text and frame.

*Set different foregroundColor and mask for those layers. The mask of the left layer will be the left part of the view, and the mask of the right layer will be the right part.

*Animate foregroundColor for those layers (simultaneously).

The code of a custom view:
class CustomTextLabel: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .green
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private var textLayer1: CATextLayer?
    private var textLayer2: CATextLayer?

    func setText(_ text: String, fontSize: CGFloat) {
        // create 2 layers with the same text and size, we'll set the colors for them later
        textLayer1 = createTextLayer(text, fontSize: fontSize)
        textLayer2 = createTextLayer(text, fontSize: fontSize)

        // estimate the frame size needed for the text layer with such text and font size
        let textSize = textLayer1!.preferredFrameSize()
        let w = frame.width, h = frame.height

        // calculate the frame such that both layers will be in center of view
        let centeredTextFrame = CGRect(x: (w-textSize.width)/2, y: (h-textSize.height)/2, width: textSize.width, height: textSize.height)
        textLayer1!.frame = centeredTextFrame
        textLayer2!.frame = centeredTextFrame

        // set up default color for the text
        textLayer1!.foregroundColor = UIColor.yellow.cgColor
        textLayer2!.foregroundColor = UIColor.yellow.cgColor

        // set background transparent, that's very important
        textLayer1!.backgroundColor = UIColor.clear.cgColor
        textLayer2!.backgroundColor = UIColor.clear.cgColor

        // set up masks, such that each layer's text is visible only in its part
        textLayer1!.mask = createMaskLayer(CGRect(x: 0, y: 0, width: textSize.width/2, height: textSize.height))
        textLayer2!.mask = createMaskLayer(CGRect(x: textSize.width/2, y: 0, width: textSize.width/2, height: textSize.height))

        layer.addSublayer(textLayer1!)
        layer.addSublayer(textLayer2!)
    }

    private var finishColor1: UIColor = .black, finishColor2: UIColor = .black
    func animateText(leftPartColor1: UIColor, leftPartColor2: UIColor, rightPartColor1: UIColor, rightPartColor2: UIColor) {
        finishColor1 = leftPartColor2
        finishColor2 = rightPartColor2

        if let layer1 = textLayer1, let layer2 = textLayer2 {
            CATransaction.begin()
            let animation1 = CABasicAnimation(keyPath: "foregroundColor")
            animation1.fromValue = leftPartColor1.cgColor
            animation1.toValue = leftPartColor2.cgColor
            animation1.duration = 3.0
            layer1.add(animation1, forKey: "animation1")

            let animation2 = CABasicAnimation(keyPath: "foregroundColor")
            animation2.fromValue = rightPartColor1.cgColor
            animation2.toValue = rightPartColor2.cgColor
            animation2.duration = 3.0
            layer2.add(animation2, forKey: "animation2")

            CATransaction.setCompletionBlock {
                self.textLayer1?.foregroundColor = self.finishColor1.cgColor
                self.textLayer2?.foregroundColor = self.finishColor2.cgColor
            }

            CATransaction.commit()
        }
    }

    private func createTextLayer(_ text: String, fontSize: CGFloat) -> CATextLayer {
        let textLayer = CATextLayer()
        textLayer.string = text
        textLayer.fontSize = fontSize // TODO: also set font name
        textLayer.contentsScale = UIScreen.main.scale

        return textLayer
    }

    private func createMaskLayer(_ holeRect: CGRect) -> CAShapeLayer {
        let layer = CAShapeLayer()

        let path = CGMutablePath()

        path.addRect(holeRect)
        path.addRect(bounds)

        layer.path = path
        layer.fillRule = CAShapeLayerFillRule.evenOdd
        layer.opacity = 1

        return layer
    }
}

The calls of a custom view:
class ViewController: UIViewController {

    var customLabel: CustomTextLabel!
    override func viewDidLoad() {
        super.viewDidLoad()

        let viewW = view.frame.width, viewH = view.frame.height
        let labelW: CGFloat = 200, labelH: CGFloat = 50

        customLabel = CustomTextLabel(frame: CGRect(x: (viewW-labelW)/2, y: (viewH-labelH)/2, width: labelW, height: labelH))
        customLabel.setText("Optimizing...", fontSize: 20)
        view.addSubview(customLabel)

        let tapRecogniner = UITapGestureRecognizer(target: self, action: #selector(onTap))
        view.addGestureRecognizer(tapRecogniner)
    }

    @objc func onTap() {
        customLabel.animateText(leftPartColor1: UIColor.blue,
                                leftPartColor2: UIColor.red,
                                rightPartColor1: UIColor.white,
                                rightPartColor2: UIColor.black)
    }

}

A: Thanks to Olha's (@OlhaPavliuk) answer, I used two CATextLayer shapes and two CAShapeLayer masks for text layers. In draw method I just change masks frames to calculated size (bounds.width * progress value), and also change the second mask origin to a new start (bounds.width - bounds.width * progress value).
Also, it was very important to set layer.fillRule = CAShapeLayerFillRule.evenOdd while creating a mask, so that both layers became visible.
It turned out that I actually didn't need any animation code involved, because changing frames looks just ok.

In motion: https://giphy.com/gifs/LMbmlMoxY9oaWhXfO1
Full code: https://gist.github.com/joliejuly/a792c2ab8d97d304d731a4a5202f741a


text:
Q: Spring Batch - Clustered Environment - Failover mechanism Question: What is the failover strategy that spring batch supports best? Resource usage, failover mechanism have to be focussed on. Any suggestions?
Usecase - Spring batch has to be run to read a file(that will be put on the server by another application) from the server and process it.
Environment is clustered. So, there could be multiple server instances that could trigger the batch jobs trying to read the same file on arrival.
My thoughts: Polling can be done to check the arrival of the file and call the spring batch job. Since it is clustered, we could use active/passive strategy to poll. The other types such as roundrobin or time slicing can also be used.
Pardon me if I am not clear. I can explain if something is unclear.

A: As I understand from here
http://static.springsource.org/spring-batch/reference/html/scalability.html
the better approach would be to have just one poller and than distribute the job to the cluster through one of the mechanisms provided by spring Batch (I think the one named Remote Chunks is the best choice here).
I don't think you should worry about the clustering strategy as this is handled either by Spring Batch or by other clustering distribution mechanisms.


text:
Q: Back-to-back tab order between textBoxes in different groupBoxes Is it possible to get the following tab order (according to the numbers in the textBoxes)?
I have tried setting the same tabIndex for the groupBoxes, but it still jumps through all the textBoxes in groupBox1 before getting to groupBox2.

A: One way you can force a tab order to whatever you want would be to override the Tab key.
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
            switch (keyData)
            {
                case Keys.Tab:
                  if (txtBox1.Focused)
                  {
                      txtBox2.Focus();
                      return;
                  }
                  else if (txtBox2.Focused)
                  {
                      txtBox3.Focus();
                      return;
                  }
                  else if (txtBox3.Focused)
                  {
                      txtBox4.Focus();
                      return;
                  }
                  else if (txtBox4.Focused)
                  {
                      txtBox1.Focus();
                      return;
                  }
                    return base.ProcessCmdKey(ref msg, keyData);
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

Now, if what your original post meant by changing the Tab order by what the user entered in the boxes, that will be a little trickier.


text:
Q: Unable to use ICD3 with CCS C Compiler I have recently bought ICD3 since I think that being able to debug a microcontroller program requires that we be able to see what is happening inside it. I really want to learn this stuff :)
I have a version 5 CCS C Compiler. I used this compiler before at the university as well. The problem is that the CCS C Compiler is neither able to program the PIC18F Microcontroller via ICD3 nor does it execute the debug function. Is ICD3 even supported by CCS C Compiler? Note that I am able to program my microcontroller via the Microchip "Integrated programming environment" but not via CCS C Compiler.
When it comes to programming the microcontroller, ICD3 is not even in the list in the CCS C Compiler GUI. So I use the Microchip software to program the microcontroller. Now when I click on debug in the CCS C Compiler, it says "Select JRE directory". I am not sure what JRE is. Once I select any directory, I get an error message saying "Target could not be detected".
There are then 2 options, either click on "run diagnostics" or click on "ok". If I click on "run diagnostics" the next error message says "The application was unable to start correctly (0x0000142). Click OK to close the application".
Does this mean that I should now abandon the CCS C Compiler and move to MPLAB?

A: It looks as if you need to download a software interface module from CCS.
From CCS FAQ FAQ ICD3
Copy begins:
How can I use MPLAB® ICD 2, MPLAB ® ICD 3 and MPLAB® Real Ice™ with CCS Compiler?
MPLAB® ICD 2, MPLAB® ICD 3 and MPLAB® REAL ICE™ Support
How MPLAB® ICD 2, MPLAB® ICD 3 and MPLAB® REAL ICE™ works with our Compiler: Microchip's MPLAB® ICD 2, MPLAB® ICD 3 and MPLAB® REAL ICE™ can now be integrated with the CCS IDE Compiler. In the past, our IDE Compilers (PCW, PCWH, PCWHD and PCDIDE) only supported the ICD-U40 or ICD-S40 in-circuit debugger/programmer, but now users can seamlessly utilize the CCS windows environment with the MPLAB® ICD 2, MPLAB® ICD 3 and MPLAB® REAL ICE™. All CCS Command-Line Compilers (PCB, PCM, PCH and PCD) can already be integrated with MPLAB® ICD 2, MPLAB® ICD 3 and MPLAB® REAL ICE™.
CCS IDE Compiler and MPLAB® ICD 2, MPLAB® ICD 3 or MPLAB® REAL ICE™ Integration:
You will need version 4.064 or higher of the CCS IDE Compiler (PCW, PCWH, PCDIDE or PCWHD)
You will also need to download the MPLAB® ICD 2, MPLAB® ICD 3 and MPLAB® REAL ICE™ interface module from the CCS Downloads Page. Note: If you do not have MPLAB® already installed, you will need to so by visiting www.microchip.com.
The debug environment is built-in to the C Aware Real-Time Debugger, once the hardware is connected to your PC and select the programmer/debugger you would like to use from the "Debug Configure" option on the IDE menu tab.
End of copy.


text:
Q: Quercus + WordPress email configuration I am working with jWordPress that combines Quercus and JavaMail 1.4.1 with WordPress 4.2.2 in a WAR file executed under Tomcat on Windows. I am having trouble configuring outgoing email service: By default, Quercus attempts to contact an SMTP server on port 25 of localhost, which fails.
In the WAR file, Quercus is configured via WEB-INF/web.xml that, among other settings, has the following one (I uncommented it in the original file):
<init-param>
  <param-name>ini-file</param-name>
  <param-value>WEB-INF/php.ini</param-value>
</init-param>

I created a WEB-INF/php.ini file with the following settings for AWS SES, which work fine with JavaMail in a different app (note that this is an authenticated STARTTLS connection on port 587):
[PHP]
[mail function]
SMTP = <address of the AWS SES SMTP host>
smtp_port = 587
smtp_username = <AWS SES username>
smtp_password = <AWS SES password>
sendmail_from = <a 'no-reply' email address>

The names of the above parameters correspond to the ones found in the Quercus' MailModule:
https://github.com/moriyoshi/quercus-gae/blob/master/src/main/java/com/caucho/quercus/lib/MailModule.java
The WEB-INF/web.xml file appears to be processed at startup because if errors are introduced in it, they are reflected in the Tomcat log as well as in the WordPress operation. However, there is no indication in the log that the WEB-INF/php.ini is read or processed.
WordPress seems to be working fine. A simple test of the WP outgoing email is to click on "Log In" under Meta, then on "Lost your password?", enter the WP username and click on "Get New Password". This results in the following warnings in the Tomcat log:
10-Sep-2015 09:57:47.836 WARNING [http-nio-8080-exec-4] com.caucho.quercus.lib.mail.MailModule.mail Quercus[] mail could not send mail to '<user email address>'

Could not connect to SMTP host: localhost, port: 25

So, it looks like Quercus MailModule is not seeing settings from php.ini. How do I fix this?
P.S. Please do not suggest workaround solutions that require an installation of sendmail or alike on port 25 of localhost.

A: Well, it turned out that the php.ini file specified in
<init-param>
  <param-name>ini-file</param-name>
  <param-value>WEB-INF/php.ini</param-value>
</init-param>

must have an absolute path instead of just WEB-INF/php.ini, e.g.
C:/Program Files/Apache/Tomcat/.../WEB-INF/php.ini

(I experimented with multiple relative paths to no avail.) This solved the problem of the file not being read.
However, another problem emerged: the 'sendmail_from' setting in php.ini has no effect. Looking at the Quercus MailModule code at the link above, if there is a 'from' setting in additional headers, then it will be used and the 'sendmail_from' setting will not be used at all.
Wordpress appears to use a 'wordpress@localhost', regardless of the configured admin email address setting. When this address is used with a remote SMTP host, the email is either rejected (AWS SES) or accepted but silently dropped (Comcast). I will post this on SO as a separate problem.


text:
Q: Find words in long string in Python I want to find an efficient way to look for words that I have in a file and then compare to a long string line with no spaces to look for these words:
Example:
FileOfWords.txt
  THE
  HOUSE
  DOG
  ON
  LINE

  string1 = " ASASASASASATHEHFGFDFGDFDFDDOGFDFDF"
  string2 = "DOGLINEJSDKJSDJKSDKJSDTHECVCVVCV"
  string3 = "UHFDUIHKDFSHUIDSFUIHDSFHUSDSHUIS"

  compare words in FileOfWords.txt to string

  Output:
  Words in string1 found: THE, DOG
  Words in string2 found: DOG, LINE
  Words in string3 found:

What would be the best way to do this?

A: An easy way of doing this is simple as

*

*read the file

*word by word check if that word is in the larger strings

That is,
with open(fname) as f:
    wrds = f.read().strip().split('\n')

mtches = [[] for x in range(3)]

for w in wrds:
    if w in string1: mtches[0].append(w)
    if w in string2: mtches[1].append(w)
    if w in string3: mtches[2].append(w)

A: The most intuitive way to do this is using a bruteforce approach, that is looking for every substring (k-mer) of length k (where k goes from 1 to the length of the string itself) and check if such substring is in your file.
First thing to do is to define a function (generator) that returns every possible k-mer:
def all_kmers(sequence, k):
    for i in range(len(sequence) - k + 1):
        yield sequence[i:i + k]

Now it is time to import the file and your three strings:
# open the file, import its lines thanks to readlines() and then close it
fileIN=open('FileOfWords.txt','r')
myWords=fileIN.readlines()
fileIN.close()

# remove newline tags
for id in range(len(myWords)):
    myWords[id]=myWords[id].strip()

# load the strings
string1 = " ASASASASASATHEHFGFDFGDFDFDDOGFDFDF"
string2 = "DOGLINEJSDKJSDJKSDKJSDTHECVCVVCV"
string3 = "UHFDUIHKDFSHUIDSFUIHDSFHUSDSHUIS"

And now it's time to rock:
print "In string 1:"
for k in range(len(string1)):
    for kmer in all_kmers(string1, k):
        if kmer in myWords:
            print kmer

print "\nIn string 2:"
for k in range(len(string2)):
    for kmer in all_kmers(string2, k):
        if kmer in myWords:
            print kmer

print "\nIn string 3:"
for k in range(len(string3)):
    for kmer in all_kmers(string3, k):
        if kmer in myWords:
            print kmer

Such code returns:
In string 1:
THE
DOG

In string 2:
DOG
THE
LINE

In string 3:

Note: by enclosing the three strings in a list you can avoid 3 separate steps and enclose everything in a unique loop that runs through such list.
So basically after the string(s) definition, the code is:
myList=[string1,string2,string3]

for l in range(len(myList)):
    StringUnderTest=myList[l]
    print "String #"+str(l+1)
    for k in range(len(StringUnderTest)):
        for kmer in all_kmers(StringUnderTest, k):
            if kmer in myWords:
                print kmer
    print

And such code returns
String #1
THE
DOG

String #2
DOG
THE
LINE

String #3

A: A simple way would be to load the strings into a list.  And search using two nested loops:
strings = [" ASASASASASATHEHFGFDFGDFDFDDOGFDFDF","DOGLINEJSDKJSDJKSDKJSDTHECVCVVCV","UHFDUIHKDFSHUIDSFUIHDSFHUSDSHUIS"]

words = ['THE','HOUSE','DOG','ON','LINE']

for i,string in enumerate(strings):
    result = "Words in String{0} found: ".format(i+1)
    for word in words:
        idx = string.find(word)
        if idx != -1:
            result += word +', '

    print(result[:-2])

or load the Words from the text file as per @guiscri 's answer


text:
Q: Does a ticking watch have more mass? In the video on YouTube, The Real Meaning of E=mc² | PBS| Space Time Studios, it claims that a ticking watch has more mass then a non ticking watch due to the intrinsic KE, PE and thermal energy of the watch's internal movements that manifests itself as part of the watch's mass.
Is this correct ?
To me there is something wrong with this argument, but I cannot put my finger on it.

A: It's not so much that it is ticking that is crucial here but the fact that the watch is in a higher energy state that in its, say unwound state. This fact increases the rest mass of the watch by an amount $\Delta E/c^2$, where $\Delta E$ is the potential energy input to elastically stress the spring and thus wind the watch.
A wound, broken, unticking watch (as long as its spring can store potential energy) also has more rest mass - by the analogous amount - as an unwound, broken unticking watch.

A: What's wrong with it is that they didn't define the two watches very clearly. It's obvious to assume they meant identical watches (my watch is more massive than my wife's, ticking or not) but they don't specify the conditions of the watches. Really though, we only need one watch and an arbitrarily accurate scale to show what's going on.
Let's say our watch starts with a fully charged but disconnected battery. At this point it is not ticking. We weigh the watch to determine its non-ticking mass. Then we connect the battery and weigh the watch while it's ticking. Aside from small vibrations due to the clockwork, the scale will not read a higher weight/mass; in fact, the reading will decline slowly as the watch runs, until the battery "dies" and no more charge is flowing. The watch is once again not ticking, but now it is less massive than before.
The reason the mass does not increase when the battery is connected is because the kinetic energy of the clockwork, which must be included in a full inventory of the mass-energy of the system, is generated from the chemical potential energy stored in the full battery, which must also be included. When the battery runs the clockwork, that kinetic energy is then converted to heat, which is lost to the environment, reducing the overall mass-energy of the watch.
Basically what it comes down to is that a charged battery is more massive than a depleted identical battery due to the stored energy in the chemical potential, so really the main mistake was unclear writing: technically they did mention the "intrinsic potential energy" as a factor, though that only implies a charged battery without being explicit about why a charged vs. uncharged battery matters.

A: It is correct to say that we measure the mass of moving objects to be greater than an object at rest relative to our reference frame. Another way of saying moving object is- an object with kinetic energy.
Think about it this way, if moving objects didn't appear to gain mass then as you give them more kinetic energy they could accelerate to the speed of light. By having an increase in mass with velocity, objects become difficult to accelerate indefinitely and ultimately impossible toward the speed of light.

A:
Does a ticking watch have more mass?

Yep. As does a wound-up watch, or a hot watch, or a watch that's higher up in a gravitational field.

It claims that a ticking watch has more mass then a non ticking watch due to the intrinsic KE, PE and thermal energy of the watch's internal movements that manifests itself as part of the watch's mass. Is this correct ?

Yep, it's what E=mc² is all about.

To me there is something wrong with this argument, but I cannot put my finger on it.

It's the enormity of it. Check out Compton scattering. That's where E=hf photon wave energy is converted into the motion of electrons:

Image courtest of Rod Nave's hyperphysics
There's nothing unusual about this, in that the photon wave energy is kinetic energy, and the motion of the electrons is kinetic energy too. In theory you could perform another Compton scatter on the residual photon until all the photon energy is converted into electron motion and there's no wave left. It has been entirely converted into electron kinetic energy.
Where things get interesting is when you realise that you could have performed pair production using that photon. To create an electron and a positron. That's when you realise that the electron is made out of kinetic energy. It's made out of the same thing as the motion of electrons. This is what Einstein's E=mc² is all about. And it's all down to the wave nature of matter. We can diffract electrons, just like we can diffract light. And electrons have spin, as evidenced by the Einstein-de Haas effect which "demonstrates that spin angular momentum is indeed of the same nature as the angular momentum of rotating bodies as conceived in classical mechanics". Once it clicks it's pretty obvious that the electron is akin to a photon going round and round. And pretty obvious that whilst photon momentum is resistance to change-in-motion for a wave moving linearly at c, electron mass is resistance to change-in-motion for a wave going round and round at c. Hence a radiating body loses mass. And in the case of electron-positron annihilation, it loses all of it.


text:
Q: Oracle Update based on join of 2 other tables I am in need of updating a huge table, >1 billion records (POS Data) with a key from a table based on a join with a third table. I can break the updates down based on dates since this goes back several years.
I basically need to replace the f.retail_sku_key in the table edw.f_pos_daily with the dedup.retail_sku_key when they are not the same.
Thanks!
select  F.POS_KEY, f.retail_sku_key , dedup.retail_sku_key dedup_key
from edw.f_pos_daily f,edw.d_retail_sku sku, edw.d_retail_sku_new dedup
where f.retail_sku_key = sku.retail_sku_key
and sku.retail_sku = dedup.retail_sku
and sku.mtd_item_number = dedup.mtd_item_number
and sku.retailer = dedup.retailer
and f.retail_sku_key <> dedup.retail_sku_key

A: While there's probably an UPDATE equivalent, I prefer using MERGE when a SQL statement is driving what rows need to be updated and generating the values to update with at the same time.
So, something like this? (I'm assuming that f.pos_key is a unique identifier on that f_pos_daily table. If that's not the case and the query returns more than one row for the same f_pos_key value, this will fail.)
MERGE INTO edw.f_pos_daily f_main
USING (
select f.pos_key -- this is for joining back to the rows that need to be updated...
     , dedup.retail_sku_key dedup_key -- ...and this is the value to update them with
  from edw.f_pos_daily f
     , edw.d_retail_sku sku
     , edw.d_retail_sku_new dedup
 where f.retail_sku_key = sku.retail_sku_key
   and sku.retail_sku = dedup.retail_sku
   and sku.mtd_item_number = dedup.mtd_item_number
   and sku.retailer = dedup.retailer
   and f.retail_sku_key <> dedup.retail_sku_key
    ) qry
ON (f_main.pos_key = qry.pos_key)
WHEN MATCHED THEN
   UPDATE SET f_main.retail_sku_key = qry.dedup_key
;

If you did need to break this up into separate updates, you can divide in conquer in two ways:
1) Isolate partitions in f_pos_daily in the internal query (assuming the table is partitioned by something other than retail_sku_key) e.g. FROM edw.f_pos_daily PARTITION (p_some_partition_name) and run the above statement once for every partition
2) Generate ranges of rows to update (again, using the f_pos_key=unique assumption) that will update, say, 10% of the rows each:
SELECT MIN(f_pos_key) c0,
PERCENTILE_DISC(0.1) WITHIN GROUP (ORDER BY f_pos_key) p1,
PERCENTILE_DISC(0.2) WITHIN GROUP (ORDER BY f_pos_key) p2,
PERCENTILE_DISC(0.3) WITHIN GROUP (ORDER BY f_pos_key) p3,
PERCENTILE_DISC(0.4) WITHIN GROUP (ORDER BY f_pos_key) p4,
PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY f_pos_key) p5,
PERCENTILE_DISC(0.6) WITHIN GROUP (ORDER BY f_pos_key) p6,
PERCENTILE_DISC(0.7) WITHIN GROUP (ORDER BY f_pos_key) p7,
PERCENTILE_DISC(0.8) WITHIN GROUP (ORDER BY f_pos_key) p8,
PERCENTILE_DISC(0.9) WITHIN GROUP (ORDER BY f_pos_key) p9,
MAX(f_pos_key) c4
FROM edw.f_pos_daily;

If the values ranged between 0 and 1000 (and some unknown number of rows), this will give you output like:
P0  P1  P2  P3  P4  P5  P6  P7  P8  P9  P10
0   104 183 319 402 512 607 723 810 914 1000

From here you just need to include another condition in the subquery to have
AND f.pos_key BETWEEN 0 AND 104

on the first run then
AND f.pos_key BETWEEN 105 AND 183

on the second run, and so on.


text:
Q: Reproduce normalization by tensorflow to keras actually i'm trying to reproduce a tensorflow model on keras, i'm really new on this topic.
I would like to reproduce those lines
embedding = tf.layers.conv2d(conv6, 128, (16, 16), padding='VALID', name='embedding')
embedding = tf.reshape(embedding, (-1, 128))
embedding = embedding - tf.reduce_min(embedding, keepdims =True)
z_n = embedding/tf.reduce_max(embedding, keepdims =True)

my actual code is:
def conv_conv_pool(n_filters,
                   name,
                   pool=True,
                   activation=tf.nn.relu, padding='same', filters=(3,3)):
    """{Conv -> BN -> RELU}x2 -> {Pool, optional}
    Args:
        input_ (4-D Tensor): (batch_size, H, W, C)
        n_filters (list): number of filters [int, int]
        training (1-D Tensor): Boolean Tensor
        name (str): name postfix
        pool (bool): If True, MaxPool2D
        activation: Activaion functions
    Returns:
        net: output of the Convolution operations
        pool (optional): output of the max pooling operations
    """
    net = Sequential()
    for i, F in enumerate(n_filters):
        conv = Conv2D(
            filters = F,
            kernel_size = (3,3),
            padding = 'same',
            )
        net.add(conv)
        batch_norm = BatchNormalization()
        net.add(batch_norm)
        net.add(Activation('relu'))

    if pool is False:
        return net

    pool = Conv2D(
        filters = F,
        kernel_size = (3,3),
        strides = (2,2),
        padding = 'same',
        )
    net.add(pool)
    batch_norm = BatchNormalization()
    net.add(batch_norm)
    net.add(Activation('relu'))
    return net

def model_keras():
    model = Sequential()
    model.add(conv_conv_pool(n_filters = [8, 8], name="1"))
    model.add(conv_conv_pool([32, 32], name="2"))
    model.add(conv_conv_pool([32, 32], name="3"))
    model.add(conv_conv_pool([64, 64], name="4"))
    model.add(conv_conv_pool([64, 64], name="5"))
    model.add(conv_conv_pool([128, 128], name="6", pool=False))
    return model

The normalization should be after layer 6.
I was thinking to use the lambda layer, is this correct? If yes how should I write it?

A: I believe you want to switch to tensorflow 2 which uses keras as the API. You will need to install/upgrade to tensorflow 2, then you could try this :
import tensorflow as tf

embedding = tf.keras.layers.conv2d(conv6, 128, (16, 16), padding='VALID',
            name='embedding')
embedding = tf.keras.layers.reshape(embedding, (-1, 128))
embedding = embedding - tf.math.reduce_min(embedding, keepdims =True)
z_n = embedding/tf.math.reduce_max(embedding, keepdims =True)

A: If you want to use the keras layer api you can create a custom layer, you can find the documentation how to do it here
 https://www.tensorflow.org/guide/keras/custom_layers_and_models,
you should end with something like this :
class NormalizationLayer(layers.Layer):

  def __init__(self, filters=128):
    super(NormalizationLayer, self).__init__()
    self.filters = filters

  def call(self, inputs):
    embedding = tf.keras.layers.conv2d(inputs, self.filters, (16, 16), padding='VALID',
            name='embedding')
    embedding = tf.keras.layers.reshape(embedding, (-1, self.filters))
    embedding = embedding - tf.math.reduce_min(embedding, keepdims =True)
    z_n = embedding/tf.math.reduce_max(embedding, keepdims =True)
    return zn

A: I use the normalization you introduced inside a Lambda layer. I also made a correction (min and max are calculated on the same input and not one on input and the other on the transformation), but you can also change it. norm_original normalize a 4D input with min and max calculated on ALL the channels and try to return a 2D output with a fixed number of features this will produce an error because you are modifying the batch dimension
def norm_original(inp):

    embedding = tf.reshape(inp, (-1, inp.shape[-1]))
    embedding = embedding - tf.reduce_min(inp)
    embedding = embedding / tf.reduce_max(inp)

    return embedding

inp = Input((28,28,3))
x = Conv2D(128, 3, padding='same')(inp)
x = Lambda(norm_original)(x)

m = Model(inp, x)
m.compile('adam', 'mse')
m.summary()

X = np.random.uniform(0,1, (10,28,28,3))
y = np.random.uniform(0,1, (10,128))

m.fit(X,y, epochs=3) # error

to avoid this error I propose two possibilities. I also made a change to operate a normalization by channel (I retain it more appropriate) but you can also modify it.
1) you can normalize the 4D input with min/max and then flatten the output putting all on the last dimension. this solution doesn't alternate the batch dim
def norm(inp):
    ## this function operate normalization by channels
    embedding = inp - tf.reduce_min(inp, keepdims=True, axis=[0,1,2])
    embedding = embedding / tf.reduce_max(inp, keepdims=True, axis=[0,1,2])

    return embedding

inp = Input((28,28,3))
x = Conv2D(128, 3, padding='same')(inp)
x = Lambda(norm)(x)
x = Flatten()(x)
x = Dense(128, activation='relu')(x)

m = Model(inp, x)
m.compile('adam', 'mse')

X = np.random.uniform(0,1, (10,28,28,3))
y = np.random.uniform(0,1, (10,128))

m.fit(X,y, epochs=3)

2) you can use a GlobalPooling layer to reduce the 4D dimension and reconduct to a 2D shape, preserving the feature dimension
inp = Input((28,28,3))
x = Conv2D(128, 3, padding='same')(inp)
x = Lambda(norm)(x)
x = GlobalMaxPool2D()(x) # u can also use GlobalAveragePooling2D

m = Model(inp, x)
m.compile('adam', 'mse')

X = np.random.uniform(0,1, (10,28,28,3))
y = np.random.uniform(0,1, (10,128))

m.fit(X,y, epochs=3)