text:
Q: Pandas Sorting and Regrouping Using Multiple Conditions This is the sample data -
Product     Type        Name    Time        Value
Product a   Medicare    CVS     2018-10-05  10
Product a   Medicare    Cigna   2018-10-05  20
Product a   Medicare    United  2018-10-05  30
Product a   Medicare    Humana  2018-10-05  40
Product a   Medicare    Centene 2018-10-05  50
Product a   Comm        CVS     2018-10-05  20
Product a   Comm        Cigna   2018-10-05  30
Product a   Comm        United  2018-10-05  40
Product a   Comm        Humana  2018-10-05  50
Product a   Comm        Centene 2018-10-05  60
Product a   Medicare    CVS     2019-10-03  30
Product a   Medicare    Cigna   2019-10-03  20
Product a   Medicare    United  2019-10-03  10
Product a   Medicare    Humana  2019-10-03  5
Product a   Medicare    Centene 2019-10-03  12
Product a   Comm        CVS     2019-10-03  87
Product a   Comm        Cigna   2019-10-03  43
Product a   Comm        United  2019-10-03  50
Product a   Comm        Humana  2019-10-03  30
Product a   Comm        Centene 2019-10-03  90

First I need to find the latest week in 'Time'.
In the table above it is 2019-10-03.
Now for that week, I need to sort/find the top 2 'Name' by value for each 'Type'.
Then, I need to create a dataframe like this below -
The top 2 'Name' for 'Medicare' for the week 2019-10-03 is CVS, and Cigna.
The top 2 'Name' for 'Comm' for the week 2019-10-03 is Centene, and CVS.
Product    Type         Name    Time       Value
Product a   Medicare    CVS     2018-10-05  10
Product a   Medicare    Cigna   2018-10-05  20
Product a   Comm        Centene 2018-10-05  60
Product a   Comm        CVS     2018-10-05  20
Product a   Medicare    CVS     2019-10-03  30
Product a   Medicare    Cigna   2019-10-03  20
Product a   Comm        Centene 2019-10-03  90
Product a   Comm        CVS     2019-10-03  87

A: IIUC, sort the dataframe first, then group by and use head:
df.sort_values('Value', ascending=False)\
  .groupby(['Product', 'Type', 'Time'])\
  .head(2)\
  .sort_index()

Output:
      Product      Type     Name        Time  Value
3   Product a  Medicare   Humana  2018-10-05     40
4   Product a  Medicare  Centene  2018-10-05     50
8   Product a      Comm   Humana  2018-10-05     50
9   Product a      Comm  Centene  2018-10-05     60
10  Product a  Medicare      CVS  2019-10-03     30
11  Product a  Medicare    Cigna  2019-10-03     20
15  Product a      Comm      CVS  2019-10-03     87
19  Product a      Comm  Centene  2019-10-03     90

A: First filter Product, Type and Name combination for latest datetime and then use merge for filter combinations for all datetimes:
df['Time'] = pd.to_datetime(df['Time'])

df1= (df[df['Time'].eq(df['Time'].max())]
      .sort_values('Value', ascending=False)\
      .groupby(['Product', 'Type'])\
      .head(2))
print (df1)
      Product      Type     Name       Time  Value
19  Product a      Comm  Centene 2019-10-03     90
15  Product a      Comm      CVS 2019-10-03     87
10  Product a  Medicare      CVS 2019-10-03     30
11  Product a  Medicare    Cigna 2019-10-03     20

df = (df.merge(df1[['Product','Type', 'Name']])
        .sort_values(['Product','Time','Type','Value'],
                     ascending=[True, True,True, False]))
print (df)
     Product      Type     Name       Time  Value
6  Product a      Comm  Centene 2018-10-05     60
4  Product a      Comm      CVS 2018-10-05     20
2  Product a  Medicare    Cigna 2018-10-05     20
0  Product a  Medicare      CVS 2018-10-05     10
7  Product a      Comm  Centene 2019-10-03     90
5  Product a      Comm      CVS 2019-10-03     87
1  Product a  Medicare      CVS 2019-10-03     30
3  Product a  Medicare    Cigna 2019-10-03     20


text:
Q: Configure sidekiq to work without brocker in development environment It would've been a nice feature to configure sidekiq to work synchronously on development environment - without installing and starting redis, no retrying and so on though I'm not saying that it is so hard to be done

For example celery has this feature as CELERY_ALWAYS_EAGER=True in settings

Does sidekiq have a support for this?

A: Yes, sidekiq supports this. From the sidekiq wiki:
require 'sidekiq/testing'
Sidekiq::Testing.inline!

That would run the jobs synchronously. If you want them to not run instead, you can use Sidekiq::Testing.fake!

A: The sidekiq developer says that he doesn't want to provide this feature.
Current sidekiq implementation puts a warning if you run it using the Testing.inline! mode outside test environment.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Minted \setminted is undefined control sequence I am trying to use minted to highlight some code in a Latex document.
I am trying to use the \setminted command to set a global, document wide, style.
But when I attempt to compile the document, I receive the error:
> ! Undefined control sequence. <recently
> read> \setminted

Relevant latex code:
\documentclass[12pt,a4paper,onecolumn,openright,oneside]{scrbook}
\usepackage{minted}
\setminted[python]{frame=lines,framesep=2mm,baselinestretch=1.2,bgcolor=LightGray,linenos}

Does anyone here know why the command \setminted is not a valid minted command despite being in the docs?
Thanks
EDIT: added { as to \setminted line, but results in the same error.

A: You are missing a { for the argument of the \setminted command. It should be \setminted[python]{frame=lines,framesep=2mm,baselinestretch=1.2,bgcolor=LightGray,linenos}.

A: Updating fixes the problem. Thank you to all who commented


text:
Q: handling different MGLPointAnnotation callouts i have two points 1 & 2 and each point has its own callout but when i try to use the taponcallout function
func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation ) {
it is reflected on both points which end up referring me to the same method
how can i make this function differentiate between the two points??
here is my code sample

let point = MGLPointAnnotation()
let point1 = MGLPointAnnotation()

 func mapView(_ mapView: MGLMapView, didFinishLoading style: MGLStyle) {

        // Create point to represent where the symbol should be placed

        point.coordinate = CLLocationCoordinate2D(latitude: 26.319735961914062, longitude: 50.14814726335609)
        point1.coordinate = CLLocationCoordinate2D(latitude: 26.319735961914062, longitude: 50.14414726335609)

        point.title = "big-bossman"
        point.subtitle = "very scary"

        point1.title = "smol-bossman"
        point1.subtitle = "smol scary"

        // Create a data source to hold the point data
        let shapeSource = MGLShapeSource(identifier: "marker-source", shape: point, options: nil)
        let shapeSource1 = MGLShapeSource(identifier: "marker-source1", shape: point1, options: nil)

        // Create a style layer for the symbol
        let shapeLayer = MGLSymbolStyleLayer(identifier: "marker-style", source: shapeSource)
        let shapeLayer1 = MGLSymbolStyleLayer(identifier: "marker-style1", source: shapeSource1)

        // Add the image to the style's sprite
        if let image = UIImage(named: "enemyImage") {
            style.setImage(image, forName: "home-symbol")
        }

        // Tell the layer to use the image in the sprite
        shapeLayer.iconImageName = NSExpression(forConstantValue: "home-symbol")
        shapeLayer1.iconImageName = NSExpression(forConstantValue: "home-symbol")

        // Add the source and style layer to the map
        style.addSource(shapeSource)
        style.addLayer(shapeLayer)

        style.addSource(shapeSource1)
        style.addLayer(shapeLayer1)

        mapView.selectAnnotation(point, animated: true, completionHandler: nil)
        mapView.selectAnnotation(point1, animated: true, completionHandler: nil)

    }

    func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
        true
    }

    func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation ) {

            transition()

    }

For example what i want is that if i click on the callout of point i get to transition() but if i click on point1 i get to transition1()

A: Unsure if you tried the above solution, but this accomplishes what you want. If you reference the annotation against your points within the tapOnCalloutFor method and then set the appropriate action, it should work fine. In the code below, I used the annotation and point titles:
       if annotation.title == point.title {
                //do something
       } else if annotation.title == point1.title {
                //do something else
       }


text:
Q: autonum, amsmath and \qedhere I have a weird behavior of the \qedhere command while using amsmath in combination with autonum.
Consider the minimal (not working) example below: In unreferenced equation with \qedhere (Theorem 2) the qed symbol is not shown at all. Not using the autonum package obviously resolves this issue, but then both equations are numbered. Is there a way to get \qedhere working with autonum?
Another (maybe related) problem occurs if the \usepackage{amsmath} - line is commented out. Now the second, unreferenced equation gets the right qed symbol but the referenced equation does not display correctly (the diamond is shown in front of the numbering "(1)" ).
\documentclass{article}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{thmtools}
\usepackage{autonum}

\declaretheoremstyle[qed=$\diamondsuit$]{myTheorem}
\declaretheorem[style=myTheorem]{theorem}

\begin{document}
Refer to equation \ref{eq:eq1}.
\begin{theorem}
\begin{equation}\label{eq:eq1}
a = b+c \qedhere
\end{equation}
\end{theorem}

\begin{theorem}
\begin{equation}
a = b+c \qedhere
\end{equation}
\end{theorem}

\end{document}

A: \documentclass{article}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{thmtools}
\usepackage{autonum}

\declaretheoremstyle[qed=$\diamondsuit$]{myTheorem}
\declaretheorem[style=myTheorem]{theorem}

\begin{document}
Refer to equation \ref{eq:eq1}.
\begin{theorem}
\begin{equation}\label{eq:eq1}
a = b+c \qedhere
\end{equation}
\end{theorem}

\begin{theorem}
\begin{equation}
\pushQED{\qed}
a = b+c \qedhere\popQED
\end{equation}
\end{theorem}

\end{document}

This is not ideal. But it partially allows for the possibility of manual adjusments of theorems ending in equations.


text:
Q: $http.post not acting as expected in AngularJS I've seen this topic discussed several times, but I'm still confused after reading every answer I've seen on this topic.
As many have before me, I'm trying to create this basic To Do app with CRUD features. I have the following (abridged to show relevant parts) code:
HTML:

            {{item.title}}

            {{item.details}}

            {{item.due}}

            <form>Mark Complete? <input type="checkbox" ng-model="item.complete" value="Y"></form>
            Edit this item

    <button ng-click="save()">Save changes</button>

JS in controller:
    $scope.save = function() {
    $http.post('js/services/items.json', $scope.items).success(function(data) {
        $scope.msg = 'Data saved' + JSON.stringify($scope.items);
    });
};

When I check a "Completed" box, and then "Save Changes", I get the data dump of the updated JSON but it never actually updated the JSON file on the server. That path is the same exact path I use to get the JSON in the first place. There are no errors thrown. It simply doesn't do it.
What am I missing here?

A: javascript is a client side language and doesn't have access to the server's file system, so angular itself can not update that file on the web server.
to do server side file manipulation, you need to use a server side language such as php or .net

A: Angular service to call service side
(function () {
    'use strict';

    angular
        .module('app')
        .factory('service', service);

    function service($http) {
        var url = 'api/todo';

        var service = {
            update: update
        };

        return service;

        function update(id, data, callback, errorCallback) {
            if (id) {
                $http({
                    method: 'PUT',
                    url: url + '/' + id,
                    data: data
                })
                .success(function (data, status, headers, config) {
                    if (callback) {
                        callback(status);
                    }
                })
                .error(function (data, status, headers, config) {
                });
            }
        };
    }
})();

Angular controller that uses service
(function () {
    'use strict';

    angular.module('app')
           .controller('controller', controller);

    function controller($scope, service) {

        $scope.save = function () {
            var person = {
                Id: $scope.item.id,
                Name: $scope.item.name
            };

            service.update(personId, person, function (status) {
                $scope.msg = 'Data saved';
            });
        };
    }
})();

In case you are using .NET infrastructure, your service can look like.
namespace App.Controllers.Api
{
    [Route("api/[controller]")]
    public class TodoController : Controller
    {
        [FromServices]
        public ITodoRepository Repository { get; set; }

        [HttpPut("{id}")]
        public IActionResult Update(int id, [FromBodyModels.TodoModel data)
        {
            if (data == null || data.Id != id)
            {
                return this.HttpBadRequest();
            }

            this.Repository.Update(data);

            return new NoContentResult();
        }
    }
}

*For update methods you need to use PUT method instead of POST
For more information about ASP.NET 5 (next version of ASP.NET) you can refer to http://docs.asp.net/en/latest/tutorials/your-first-aspnet-application.html


text:
Q: javascript recursive function callback how to identify when all function calls have ended   function transverse(element, result) {
        if (angular.isArray(element)){
            element.forEach(function (item) {
                { transverse(item, result); }
            });
        }

        else if ( angular.isObject(element)) {
            var transform;

            if (element.hasOwnProperty("dataMetrics")) {
                console.log(element);

            }

            if (element.hasOwnProperty("childNodes")) {
                transverse(element.childNodes, result);
            }
        }
    }

So I have a function written in javascript that traverses over a json object of tree structure. But i want to add a callback, once that function is over it should call that method.
How can this be accomplished?

A: Nothing in the code you have posted is executed asynchronously, including the forEach call.
For this reason, you don't need a callback. Simply continue with the code that should follow after the recursive traversal after the initial call of transverse.
Example, demonstrating the synchronous nature of forEach:

var input = [0, 1, 2, 3, 4];

input.forEach(function(item) {
  console.log(item);
});

console.log('done');


text:
Q: cannot send udp packets to remote host through wifi on android Here is the code: I'd like to send out a string to a remote host 192.168.1.3 at port 12345. But I cannot receive it at the remote host. Please let me know what's missing. thx
btw,I do can send information from android device to the remote host using netcat.  And i also invoked isReachable() and it showed that the remote host can be pinged.
try {
                socket = new DatagramSocket();

                socket.setBroadcast(false);
                DatagramPacket packet;
                String datas="adasdasdasd";
                packet = new DatagramPacket(datas.getBytes(), datas.length(),InetAddress.getByName("192.168.1.3"), 12345);

                socket.send(packet);
                System.out.println("sending");
            } catch (SocketException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
}

And the Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testclientnew"
    android:versionCode="1"
    android:versionName="1.0" >

        <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="10" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.testclientnew.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

A: I got the answer. It's simply because I did not open the netcat correctly at the receiver side. I should use nc -ul 12345. I missed the -u option which result in my failing in receiving UDP packets.


text:
Q: Getting API data via asynch-await instead of callback I am trying to get via the kraken-node api ticker data.
I tried the following ways:
import KrakenClient from "kraken-api";
const knex = require('knex')(require('../knexfile'))
const kraken = new KrakenClient();

//*********************
//ASYNCH AWAIT EXAMPLE*
//*********************

const tickerAsynch = async function() {
    // Get Ticker Info
    return kraken.api('Ticker', { pair: 'XXBTZUSD' });
};
tickerAsynch().then(data => console.log(data)).catch(err => console.log(err))

//*****************
//CALLBACK EXAMPLE*
//*****************
// Get Ticker Info

const tickerCallback = function() {
    kraken.api('Ticker', { "pair": 'XXBTZUSD' }, function(error, data) {
        if (error) {
            console.log(error);
        }
        else {
            console.log(data.result);
        }
    })
};

console.log("Callback: " + tickerCallback())

The ASYNCH AWAIT EXAMPLE just gives me the http request back:

Callback: undefined Request {   domain: null,   _events:     { error:
  [Function: bound ],
       complete: [Function: bound ],
       pipe: [Function] },   _eventsCount: 3,   _maxListeners: undefined,   method: 'POST',   headers:     { 'User-Agent': 'Kraken
  Javascript API Client',
       host: 'api.kraken.com',
       'content-type': 'application/x-www-form-urlencoded',
       'content-length': 13 },   timeout: 5000,   callback: [Function],   readable: true,   writable: true,   explicitMethod: true,   _qs:
  Querystring {
       request: [Circular],
       lib: { formats: [Object], parse: [Function], stringify: [Function] },
       useQuerystring: undefined,
       parseOptions: {},
       stringifyOptions: { format: 'RFC3986' } },   _auth:     Auth {
       request: [Circular],
       hasAuth: false,
       sentAuth: false,
       bearerToken: null,
       user: null,
       pass: null },   _oauth: OAuth { request: [Circular], params: null },   _multipart:     Multipart {
       request: [Circular],
       boundary: '839beaf0-e37d-459b-a879-0d1e2b22aab4',
       chunked: false,
       body: null },   _redirect:     Redirect {
       request: [Circular],
       followRedirect: true,
       followRedirects: true,
       followAllRedirects: false,
       followOriginalHttpMethod: false,
       allowRedirect: [Function],
       maxRedirects: 10,
       redirects: [],
       redirectsFollowed: 0,
       removeRefererHeader: false },   _tunnel:     Tunnel {
       request: [Circular],
       proxyHeaderWhiteList:
        [ 'accept',
          'accept-charset',
          'accept-encoding',
          'accept-language',
          'accept-ranges',
          'cache-control',
          'content-encoding',
          'content-language',
          'content-location',
          'content-md5',
          'content-range',
          'content-type',
          'connection',
          'date',
          'expect',
          'max-forwards',
          'pragma',
          'referer',
          'te',
          'user-agent',
          'via' ],
       proxyHeaderExclusiveList: [] },   setHeader: [Function],   hasHeader: [Function],   getHeader: [Function],   removeHeader:
  [Function],   localAddress: undefined,   pool: {},   dests: [],
  __isRequestRequest: true,   _callback: [Function],   uri:     Url {
       protocol: 'https:',
       slashes: true,
       auth: null,
       host: 'api.kraken.com',
       port: 443,
       hostname: 'api.kraken.com',
       hash: null,
       search: null,
       query: null,
       pathname: '/0/public/Ticker',
       path: '/0/public/Ticker',
       href: 'https://api.kraken.com/0/public/Ticker' },   proxy: null,   tunnel: true,   setHost: true,   originalCookieHeader: undefined,
  _disableCookies: true,   jar: undefined,   port: 443,   host: 'api.kraken.com',   body: 'pair=XXBTZUSD',   path: '/0/public/Ticker',
  httpModule:     { Server: { [Function: Server] super: [Object] },
       createServer: [Function: createServer],
       globalAgent:
        Agent {
          domain: null,
          _events: [Object],
          _eventsCount: 1,
          _maxListeners: undefined,
          defaultPort: 443,
          protocol: 'https:',
          options: [Object],
          requests: {},
          sockets: {},
          freeSockets: {},
          keepAliveMsecs: 1000,
          keepAlive: false,
          maxSockets: Infinity,
          maxFreeSockets: 256,
          maxCachedSessions: 100,
          sessionCache: [Object] },
       Agent: { [Function: Agent] super: [Object] },
       request: [Function: request],
       get: [Function: get] },   agentClass:     { [Function: Agent]
       super_: { [Function: Agent] super_: [Object], defaultMaxSockets: Infinity } },   agent:     Agent {
       domain: null,
       _events: { free: [Function] },
       _eventsCount: 1,
       _maxListeners: undefined,
       defaultPort: 443,
       protocol: 'https:',
       options: { path: null },
       requests: {},
       sockets: {},
       freeSockets: {},
       keepAliveMsecs: 1000,
       keepAlive: false,
       maxSockets: Infinity,
       maxFreeSockets: 256,
       maxCachedSessions: 100,
       _sessionCache: { map: {}, list: [] } } }

Whereas I get via the callback example the prices back:
{ XXBTZUSD:
   { a: [ '4347.99900', '1', '1.000' ],
     b: [ '4345.00000', '1', '1.000' ],
     c: [ '4354.97000', '0.19747745' ],
     v: [ '74.25674323', '10944.61634833' ],
     p: [ '4391.05837', '4290.88239' ],
     t: [ 314, 31776 ],
     l: [ '4264.00000', '4082.99500' ],
     h: [ '4468.00000', '4484.29000' ],
     o: '4349.98700' } }

Any suggestions what I am doing wrong within my asynch-await example?
I appreciate your replies!

A: I think kraken.api expects a callback and doesn't return a promise, you can always wrap a callback with a promise using the code below
function getKrakenPromise(){
  return new Promise(function(resolve, reject){
            kraken.api('Ticker', { "pair": 'XXBTZUSD' }, function(error, data) {
            if (error) {
                console.log(error);
                reject(error)
            }
            else {
                console.log(data.result);
                resolve(data);
            }
        })
  })
}

and then call getKrakenPromise() instead of the api


text:
Q: sql find newly loaded id's before dropping tabel Goodday,
I have a rather generic question which is more of an analytical question which requires a technical implementation.
I have table that gets renewed every day by dropping the table after which the same query as yesterday is being ran to repopulate the same tabel. each record does hold a unique id that gets loaded and a date at which it gets loaded (with sysdate).
now I wish to gather some analytical data to see how many records are loaded each day and how many new records are loaded that were not loaded yesterday. the latter question is where my question resides. Does anyone have any ideas?

A: You says that your table has a date field which records the date at which the row was inserted. You can simply fetch the rows using that date field.

*

*Fetch the rows using date of yesterday and today.

*Find the complement of their intersection.(Gives rows that were not updated yesterday as well as today of both days).

*Find the intersection of previous result with that of rows updated
today.(This eliminates the rows updated yesterday.).


text:
Q: Can it print anything in main Im writing a java app at the moment and nothing is being run! I can even print simple System.out.println("hi");
Below is the code. I can see the output window fine. No errors are being returned. Im using netbeans 8.0.2
public class BookingSystem{

public static void main(String[] args){
    System.out.print("hi");
    }
}

A: There should not be a problem in running the code you have posted. Make sure that you are running the BookingSystem class and not some other class. Use 'Run File' in Netbeans (or Shift+F6) to run the BookingSystem class.

A: Try the same code in notepad, compile and run the program in command prompt.


text:
Q: how to override gorm delete method for testing? I am writing a simple integration test where i intend to simulate  delete failure.
The controller simply pulls the record from database and deletes it as shown below.
def deleteItem(id){

    def item = Item.get(id)

    item.delete()

}

Now, i want to simulate delete failure with following code
void testDeleteItem_FailDeleteFlushSaveFail(){

    Item.metaClass.delete = { Map params ->

        throw new ValidationException("Failed!!")

    }

    def model = controller.deleteItem(mp.id)

    assertEquals controller.flash.message, "Sorry an error occured when deleting!!"

    GroovySystem.metaClassRegistry.removeMetaClass(Item.class)

}

But the test fails because the method is not replaced. i.e exception is not thrown on delete. I am guessing the problem is in my metaclass formulation. How can i make it so that exception is thrown when delete is called? I appreciate any help! Thanks!

A: This is because you should use
Item.metaClass.delete = {

        throw new ValidationException("Failed!!")

    }

rather than
Item.metaClass.delete = { Map params ->

        throw new ValidationException("Failed!!")

    }

A: First off, I don't think the question should have been down-voted.. It is a valid question for a scenario in which you are wanting to test how your program reacts to a failure.
There are a few things wrong here:

*

*Domain.delete does not throw validationExceptions. Also ValidationExceptions are constructed with two arguments (String msg, Errors error). You would need to add a custom error to your domain class and pass the domain class in. Again this doesn't make sense for delete because who needs to validate the object on delete?
Not sure what version you're running but here is the docs for 2.5.1 (Grails 2.5.1 docs -see 7.3.2 Deleting Objects)
def p = Person.get(1)
try {
    p.delete(flush: true)
}
catch (org.springframework.dao.DataIntegrityViolationException e) {
    flash.message = "Could not delete person ${p.name}"
    redirect(action: "show", id: p.id)
}

*Secondly, delete(failOnError: true). I'm not sure that does anything at all. Instead you should surround your delete method in a try catch and use the flush: true option.
try{
    item.delete(flush:true)
}catch(DataIntegrityViolationException e){
    flash.message = "Sorry an error occurred when deleting!!"
}

*Thirdly, where is mp.id coming from? Are we missing a portion of your test file. If not, your test appears to rely on data that is already existing. Even in an integration test it is wise to create your data separately for each test in some way to prevent test contamination and failed tests due to missing data.

*Finally, I have not been able to properly metaClass the Domain Class itself in my integration tests... so I would recommend you metaClass the domain instance in your test. Here is an example of that:
MetaClass Domain Instance method:
//creating test data
def item = new Item(name: 'testName')

def model = controller.deleteItem(item.id)

item.metaClass.delete = {Map params ->
    throw new DataIntegrityViolationException('Some error message')
}

assertEquals controller.flash.message, "Sorry an error occurred when deleting!!"

Edit 1 Note
I forgot to include the 'Map params ->' In the metaClass closure. (might not be required in all versions of grails due to the differences in how these methods are compiled through out the versions)

A: Try that using:
Item.metaClass.'static'.delete = { Map params ->
    throw new ValidationException("Failed!!")
}


text:
Q: setState with Firebase Promise in React How can i set state inside react component?
I`ve got error message:

Uncaught TypeError: Cannot read property 'setState' of null

here is the component code listing:
class MessageList extends React.Component {
 constructor(props){
 super(props);
 this.state = {
   messages: []
 };

 var firebaseRef = firebase.database().ref();
 firebaseRef.once('value')
  .then(function(dataSnapshot) {
      this.setState({
        messages: messages
      });
   });
 }

 render() { ... }

}

A: At, first I want to suggest you that you fetch your initial firebase data
in componentDidMount component life cycle and to fix your setState issue you can follow the below code in where I've change the self = this; line only,
class MessageList extends React.Component {
 constructor(props){
 super(props);
 this.state = {
   messages: []
 };

componentDidMount() {
 var self = this;
 var firebaseRef = firebase.database().ref();
  firebaseRef.once('value')
  .then(function(dataSnapshot) {
    self.setState({
      messages: messages
    });
  });
 }
}

render() { ... }

}

A: this is referring to the promise scope. Either use fat arrow functions (es6)
var firebaseRef = firebase.database().ref();
firebaseRef.once('value')
  .then((dataSnapshot) => {
      this.setState({
        messages: messages
      });
   });

Or create a copy of this before the promise
constructor(props){
 super(props);
 this.state = {
   messages: []
 };
 var that = this;
 var firebaseRef = firebase.database().ref();
 firebaseRef.once('value')
  .then(function(dataSnapshot) {
      that.setState({
        messages: messages
      });
 });

One last option, you could bind this to the promise:
firebaseRef.once('value')
 .then(function(dataSnapshot) {
     this.setState({
         messages: messages
     });
}).bind(this)


text:
Q: Design of notification events I am designing some events that will be raised when actions are performed or data changes in a system.  These events will likely be consumed by many different services and will be serialized as XML, although more broadly my question also applies to the design of more modern funky things like Webhooks.
I'm specifically thinking about how to describe changes with an event and am having difficulty choosing between different implementations.  Let me illustrate my quandry.
Imagine a customer is created, and a simple event is raised.
<CustomerCreated>
  <CustomerId>1234</CustomerId>
  <FullName>Bob</FullName>
  <AccountLevel>Silver</AccountLevel>
</CustomerCreated>

Now let's say Bob spends lots of money and becomes a gold customer, or indeed any other property changes (e.g.: he now prefers to be known as Robert).  I could raise an event like this.
<CustomerModified>
  <CustomerId>1234</CustomerId>
  <FullName>Bob</FullName>
  <AccountLevel>Gold</AccountLevel>
</CustomerModified>

This is nice because the schema of the Created and Modified events are the same and any subscriber receives the complete current state of the entity.  However it is difficult for any receiver to determine which properties have changed without tracking state themselves.
I then thought about an event like this.
<CustomerModified>
  <CustomerId>1234</CustomerId>
  <AccountLevel>Gold</AccountLevel>
</CustomerModified>

This is more compact and only contains the properties that have changed, but comes with the downside that the receiver must apply the changes and reassemble the current state of the entity if they need it.  Also, the schemas of the Created and Modified events must be different now; CustomerId is required but all other properties are optional.
Then I came up with this.
<CustomerModified>
  <CustomerId>1234</CustomerId>
  <Before>
    <FullName>Bob</FullName>
    <AccountLevel>Silver</AccountLevel>
  </Before>
  <After>
    <FullName>Bob</FullName>
    <AccountLevel>Gold</AccountLevel>
  </After>
</CustomerModified>

This covers all bases as it contains the full current state, plus a receiver can figure out what has changed.  The Before and After elements have the exact same schema type as the Created event.  However, it is incredibly verbose.
I've struggled to find any good examples of events; are there any other patterns I should consider?

A: You tagged the question as "Event Sourcing", but your question seems to be more about Event-Driven SOA.
I agree with @Matt's answer--"CustomerModified" is not granular enough to capture intent if there are multiple business reasons why a Customer would change.
However, I would back up even further and ask you to consider why you are storing Customer information in a local service, when it seems that you (presumably) already have a source of truth for customer.  The starting point for consuming Customer information should be getting it from the source when it's needed.  Storing a copy of information that can be queried reliably from the source may very well be an unnecessary optimization (and complication).
Even if you do need to store Customer data locally (and there are certainly valid reasons for need to do so), consider passing only the data necessary to construct a query of the source of truth (the service emitting the event):
<SomeInterestingCustomerStateChange>
  <CustomerId>1234</CustomerId>
</SomeInterestingCustomerStateChange>

So these event types can be as granular as necessary, e.g. "CustomerAddressChanged" or simply "CustomerChanged", and it is up to the consumer to query for the information it needs based on the event type.
There is not a "one-size-fits-all" solution--sometimes it does make more sense to pass the relevant data with the event.  Again, I agree with @Matt's answer if this is the direction you need to move in.
Edit Based on Comment
I would agree that using an ESB to query is generally not a good idea.  Some people use an ESB this way, but IMHO it's a bad practice.
Your original question and your comments to this answer and to Matt's talk about only including fields that have changed.  This would definitely be problematic in many languages, where you would have to somehow distinguish between a property being empty/null and a property not being included in the event.  If the event is getting serialized/de-serialized from/to a static type, it will be painful (if not impossible) to know the difference between "First Name is being set to NULL" and "First Name is missing because it didn't change".
Based on your comment that this is about synchronization of systems, my recommendation would be to send the full set of data on each change (assuming signal+query is not an option).  That leaves the interpretation of the data up to each consuming system, and limits the responsibility of the publisher to emitting a more generic event, i.e. "Customer 1234 has been modified to X state".  This event seems more broadly useful than the other options, and if other systems receive this event, they can interpret it as they see fit.  They can dump/rewrite their own data for Customer 1234, or they can compare it to what they have and update only what changed.  Sending only what changed seems more specific to a single consumer or a specific type of consumer.
All that said, I don't think any of your proposed solutions are "right" or "wrong".  You know best what will work for your unique situation.

A: Events should be used to describe intent as well as details, for example, you could have a CustomerRegistered event with all the details for the customer that was registered. Then later in the stream a CustomerMadeGoldAccount event that only really needs to capture the customer Id of the customer who's account was changed to gold.
It's up to the consumers of the events to build up the current state of the system that they are interested in.
This allows only the most pertinent information to be stored in each event, imagine having hundreds of properties for a customer, if every command that changed a single property had to raise an event with all the properties before and after, this gets unwieldy pretty quickly. It's also difficult to determine why the change occurred if you just publish a generic CustomerModified event, which is often a question that is asked about the current state of an entity.
Only capturing data relevant to the event means that the command that issues the event only needs to have enough data about the entity to validate the command can be executed, it doesn't need to even read the whole customer entity.
Subscribers of the events also only need to build up a state for things that they are interested in, e.g. perhaps an 'account level' widget is listening to these events, all it needs to keep around is the customer ids and account levels so that it can display what account level the customer is at.

A: Instead of trying to convey everything through payload xmls' fields, you can distinguish between different operations based on -
1. Different endpoint URLs depending on the operation(this is preferred)
2. Have an opcode(operation code) as an element in the xml file which tells which operation is to used to handle the incoming request.(more nearer to your examples)
There are a few enterprise patterns applicable to your business case - messaging and its variants, and if your system is extensible then Enterprise Service Bus should be used. An ESB allows reliable handling of events and processing.


text:
Q: Swift - How to get type of element of array in generic function I need to get type of element inside generic function
let array = [String].self          -> Array<String>.Type
let element = array.Element.self   -> String.Type
JSONDecoder().decode(element, from: data) -> works fine

func foo<T>(type: T.Type) where T: Decodable{
    let element = type.Element      ->   Error. How to get element here?
    JSONDecoder().decode(element, from: data)
}

foo(array)

How to get element type inside foo function in this example?

A: The code works only if T is constrained to Sequence, because only sequences have an Element type.
And you have to add .self after Element
func foo<T>(type: T.Type) where T: Decodable, T : Sequence {
    print(type)
    print(type.Element.self)
}

And if you want to decode that type you have to constrain Element to Decodable, too
... where T: Decodable, T : Sequence, T.Element : Decodable


text:
Q: Link com popup de video youtube Eu preciso criar um link em uma imagem onde qdo clicar na imagem abre um popup centralizado na tela com o video do youtube, esta funcionando mas o que eu fiz não sei se seria o correto, alguém pode me ajudar?
Link=>
<a

Script do popup =>


text:
Q: Server doesn't receive client Object java i have a server that work if change String with clients. Now,i want to use Object instead of String but the server doesn't receive anything and get stugged before the sout like the client doesn't sand anything...So, the problem is on the client or on the server?? Message is a class with interface Serializable and i called input before output in server and output before input in client.
Server:
public class ControllerServer {
   @FXML
   public ListView<Log> log_list;
   @FXML
   public MenuItem disconnect_button;
   @FXML
   public MenuItem connect_button;

   boolean connection = true;
   DataModel model;
   ObservableList<Log> list;
   Connection conn = new Connection();
   @FXML
   public void initialize() throws TransformerConfigurationException {
      if (this.model != null) {
         throw new IllegalStateException("Model can only be initialized once");
      }
      model = new DataModel();

      list = model.getLogList();
      log_list.setItems(list);

      log_list.getSelectionModel().selectedItemProperty().addListener((obs,oldLog,newLog) -> model.setCurrentLog(newLog));

      model.currentEmailProperty().addListener((obs, oldLog, newLog) -> {
         if (newLog == null) {
            log_list.getSelectionModel().clearSelection();

         } else {
            log_list.getSelectionModel().select(newLog);
         }
      });

      log_list.setCellFactory(lv -> new ListCell<Log>() {
         @Override
         public void updateItem(Log message, boolean empty) {
            super.updateItem(message, empty);
            if (empty) {
               setText(null);
            } else {
               setText(message.getContent());
            }
         }
      });
      conn.start();

   }

   public void disconnect(ActionEvent actionEvent)  {
      if(connection){
         connection = false;
         conn.cancel();
         if(disconnect_button!=null)disconnect_button.setVisible(false);
         if(connect_button!=null)connect_button.setVisible(true);
      }else System.out.println("The server is closed!");

   }

   public void connect(ActionEvent actionEvent) {
      if(!connection){
         conn.restart();
         connection = true;
         if(disconnect_button!=null)disconnect_button.setVisible(true);
         if(connect_button!=null)connect_button.setVisible(false);
      }
      else System.out.println("Already connected");
   }

   public class Connection extends Service<Void>{
      ServerSocket s;
      ExecutorService listeners = Executors.newCachedThreadPool();
      ArrayList<Socket> incomings_connection = new ArrayList<>();

      int id=1;
      @Override
      protected Task<Void> createTask() {
         return new Task<>() {
         @Override
         protected Void call() {
            System.out.println("Server Attivo");
               try {
                  s = new ServerSocket(8189);
                  while (!isCancelled()) {
                     Thread.sleep(500);
                     System.out.println("In attesa di connessione....");
                     Socket incoming = s.accept();
                     incomings_connection.add(incoming);
                     Task<Void> listener = new Task<Void>() {
                        @Override
                        protected Void call() throws Exception {
                           int id_task = id;
                           System.out.println("Connessione accettata! Client: "+id_task);

                           ObjectInputStream inStream = new ObjectInputStream(incoming.getInputStream());
                           ObjectOutputStream outStream = new ObjectOutputStream(incoming.getOutputStream());

                           Message request;
                           while (!isCancelled()){
                              Object obj = inStream.readObject();
                              try{
                                 request = (Message)obj;
                                 System.out.println("Arrivato: "+request.getMessage()+"  e: "+request.getAction());
                              }catch (ClassCastException e){
                                 e.printStackTrace();
                              }

                           }
                              return null;
                        }
                     };
                     listeners.submit(listener);
                     id++;
                  }
               }catch (SocketException ex){
                  System.out.println("Listener chiuso!");
               }
               catch (IOException | InterruptedException e) {
                  e.printStackTrace();
               }
            return null;
         }

            @Override
            protected void cancelled() {
               System.out.println("Closing server....");
               System.out.println("Done!");
                  try {
                     s.close();
                     try {
                        System.out.println("Connessioni chiuse: "+incomings_connection.size());
                        for(Socket conn: incomings_connection){
                           conn.close();
                        }
                     }catch (NullPointerException EX){
                        System.out.println("Non è stata stabilita nessuna connesione client prima della chiusura!");
                     }
                     model.closeLog();
                  }
                  catch (NullPointerException EX){
                     System.out.println("Server non inizializzato correttamente");
                  }
                  catch (IOException e) {
                     e.printStackTrace();
                  }

               super.cancelled();
            }

         };
      }

      private String login(String email) {
         String response = null;
         try {
            BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\Huawei\\OneDrive\\Desktop\\Università\\prog3\\Progetto\\Server\\src\\main\\resources\\Utenti\\"+email+"\\Info.txt"));
            response = reader.readLine();
         } catch (FileNotFoundException e) {
            response = "Error: user inesistente";
         } catch (IOException e) {
            e.printStackTrace();
         }

         return response;
      }
   }
}

Client
public class ControllerClient {

    Log log = new Log();
    Connection conn;
    @FXML
    public TextField email;
    @FXML
    public Button submit_button;
    @FXML
    public Label ConnectionFailureText;
    @FXML
    public Button try_connect;

    @FXML
    public void initialize() {
        connect();
    }

    private void connect() {
        conn = new Connection(log);
        conn.start();
    }

    public void re_connect(ActionEvent event){

    }

    public void login(ActionEvent actionEvent) {
        if(this.conn.isRunning()){
            if (email.getText()!=null && email.getText()!="" ){
                log.put(new Message("login",email.getText()));
            }else System.out.println("Inserisci la mail!");
        }
        else System.out.println("Connessione chiusa!");
    }

     class Connection extends Service<Void> {
        Log log;Socket s;
        public Connection(Log item){
            log = item;
        }
        @Override
        protected Task<Void> createTask() {
            return new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    try {
                        String nomeHost = InetAddress.getLocalHost().getHostName();
                        s = new Socket(nomeHost, 8189);
                        System.out.println("Ho aperto il socket verso il server");
                        try{

                            ObjectOutputStream outStream = new ObjectOutputStream(s.getOutputStream());
                            ObjectInputStream inStream = new ObjectInputStream(s.getInputStream());

                            System.out.println("Sto per ricevere dati dal socket server!");

                            Message message = null;

                            while (!isCancelled())  {
                                message = log.get();
                                if(message!=null){
                                    System.out.println("message: "+message.getMessage() + "  " +message.getAction());
                                    outStream.writeObject(message);
                                }

                            }
                        }catch(Exception e){
                            e.printStackTrace();
                            System.out.println("Connessione col server interrotta!");
                            s.close();conn.cancel();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        System.out.println("Errore di connessione!");

                    }
                    return null;
                }
            };
        }

         @Override
         protected void cancelled() {
             System.out.println("Connessione chiusa");
             super.cancelled();
         }
     }
}

class Log {
    private boolean available = false;
    private Message message = null;

    public synchronized Message get(){
        while (!available) {
            try {
                wait();
            } catch (InterruptedException e) {

            }
        }
        /* fondamentale notifyAll(), anziché notify(), per prevenire deadlock */
        available = false;
        notifyAll();
        return message;
    }

    public synchronized void put(Message value) {
        while (available) {
            try {
                wait();
            } catch (InterruptedException e) { }
        }
        message = value;
        available = true;
        notifyAll();
    }

}

Message:
public class Message implements Serializable {
    private String action;
    private String message;
    private Email email;

    public String getAction() {
        return action;
    }

    public void setAction(String action) {
        this.action = action;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Email getEmail() {
        return email;
    }

    public void setEmail(Email email) {
        this.email = email;
    }

    public Message(String action, String message){
        this.action=action;
        this.message=message;
    }
    public Message(String action, String message, Email email){
        this.action=action;
        this.message=message;
        this.email = email;
    }
}


text:
Q: set data-options html attribute I have the following HTML

I want to create this using js or jquery I have tried the following:
A.
var tabs = $('#tabPanelContainer').data("options","dxItem: { title:  "+tabId+" }");
$(tabs).append('

');

B.
var tabs = $('#tabPanelContainer').attr({ 'data-options': 'dxItem: { title: "+tabId+" }' });
$(tabs).append('

');

I have looked at multiple threads on how to do this and tried multiple things but nothing is working....
I have found this: How to set data attributes in HTML elements , and other similar threads but not quite the same or enough to figure it out.
This creates multiple grids but not the tabs. So to be clear if I create the HTML elements on the PHP file (hardcoded) then my tabs load correctly but if I try to dynamically create the tabs based on a for loop my tabs don't get created.

Instead of

A: You are setting the data attribute of #tabPanelContainer instead of each div element. Use this code instead:
var tabs = $("#tabPanelContainer"); //

var tab = $("
", { id: tabId }); //

tab.attr("data-options", "dxItem: { title: '" + tabId + "' }");
tab.append($("
", { id: gridId })); //

$(tabs).append(tab);


text:
Q: How to print a vector of objects from an archive in c++ My code is supposed to read a file and from the information on that file create objects of class Movie and
store them in a vector, How can I print those objects now that they are in the vector?
void Movie::loadFile(string file)
{
    ifstream inFile;

    inFile.open(file+".txt");
    try {
            if (!inFile)
                throw "UNABLE TO OPEN FILE";

            }catch (const char* msg)
            {
                cerr << msg << endl;
                exit(1);
            }

    while (inFile.good())
    {
        getline(inFile, id, ',');
        getline(inFile, name, ',');
        getline(inFile, tim, ',');
        getline(inFile, gen, ',');
        getline(inFile, rate, '\n');

        mov.push_back(new Movie(id, name, tim, gen, rate));
     }
    inFile.close();
    cout<<endl;
}

I have tried to do it by overloading an operator but I get the errors
error: 'std::vector<Movie*> Movie::mov' is protected within this context
error: 'ostream_iterator' was not declared in this scope
error: expected primary-expression before '>' token

ostream &operator <<(ostream& salida, const Movie& print)
{
    salida << print.id << endl;
    copy(print.mov.begin(), print.mov.end(), ostream_iterator<Video>(salida, " "));
    return salida;
}

I would really aprecciate the help :).

A: In order to use
copy(print.mov.begin(), print.mov.end(), ostream_iterator<Video>(salida, " "));

you need to implement the following overload.
std::ostream& operator<<(std::ostream&, Video const&);

From https://en.cppreference.com/w/cpp/iterator/ostream_iterator:

std::ostream_iterator is a single-pass LegacyOutputIterator that writes successive objects of type T into the std::basic_ostream object for which it was constructed, using operator<<.


text:
Q: Efficient way of checking for a value present in an object, from an array of objects I have an array of objects. There is a getCountry() in the object. I want to set a flag when the getCountry() is equal to say 'XXX'.
As of know, I am doing,
boolean isXXX=false;
if(custAcctArray != null)
{
    for(int index=0;index<custAcctArray.length;index++)
    {
        if(custAcctArray[i].getCountry().equalsIgnoreCase("XXX"))
        {
            isXXX=true;
        }
    }
}

if(isXXX)
{
    Do something about it....
}

I somehow don't like this logic when I assume the array is filled with some 100 or odd objects. Can someone throw or shed light at other ways of achieving the final output in an efficient way?
What I want: set a flag when getCountry()  == "XXX"

A: Maybe use a map instead of an array. The map should map from country to object. Then you will check whether the key exist in the map.
Another idea from the top of my head is to override the toString() method of that class and use Arrays.toString(custAcctArray).contains("XXX") (or maybe more reliable search using regexp). But it looks like a workaround. (This one is rather bad idea. Think about that as a tricky way to get rid of the loop in your code.)
Edit: To summarize my thoughts. Instead of a map, I think you should use a boolean flag (see my comment) if you know the value "XXX" when initializing the array or use a parallel set of country values. Use HashSet (efficiency O(1)), in this case you have to override equals() and hashCode() methods in your class. TreeSet is less efficient (O(log(n))) and still, here you use comparator or implement the interface Comparable in your class.
Edit: However, in this case we have String objects, so no need to implement anything (hashCode(), equals() and compareTo() are implemented there).

A: boolean isXXX=false;
if(custAcctArray != null)
{
    for(int index=0;index<custAcctArray.length;index++)
    {
        if(custAcctArray[i].getCountry().equalsIgnoreCase("XXX"))
        {
            isXXX=true;
            break;//<-------------you need to exit to be quick and true solution!!!!
        }
}
}

if(isXXX)
{
Do something about it....
}

Do you see the break; ? This exits the big loop as soon as possible. If you dont, the next iteration could set it to other value.
You can also use a "separate" array outside the object to access it quicker(1 less bounds checking)
A better way: when setting the country values, check that if "xxx" then set isXXX rightaway without needing to use a "check" algortihm :)


text:
Q: Proper way to retrieve the Request.Content from global error handler I have register a global exception handler, and it fires and contains all of the information I need with the exception of the Request.Content which is always empty...  I need the values that were passed in when I am debugging...
Public class MyExceptionLogger : ExceptionLogger
    {
        public override void Log(ExceptionLoggerContext context)
        {

            try
            {
                 ... other code

            var methodName = context.Request.Method.ToString();
            var errorUri = context.Request.RequestUri.ToString();
            var errorMessage = context.Exception.Message;
            var errorStackTrace = context.Exception.StackTrace.ToString();

            var payload = context.Request.Content.ReadAsStringAsync().Result;

            .....  other code

            }

       }
   }

What is the proper way to retrieve the Request.Content from global error handler ? In the code above the Content property has already been read by the model binders and as such is always empty.
How can I consistently get the posted body from an exception ?
Should I retrieve and save the posted body in a custom MessageHandler ?
Thanks
Greg

A: In experimenting with reading the buffer of the request.Content in a custom message handler.. It appears that if I read it with this code:
var payload = context.Request.Content.ReadAsStringAsync().Result;

and do NOTHING with it...  The buffer will not be emptied when the model binders read it, because its always there in my exception logger now... I don't know if this is by design or what but its exasperating !


text:
Q: CSS select every 1 3 4 6 nth child I have divs that are shown in a grid 3 x n.
What I'm looking to do is to select the 1st, 3rd of every row. Or a clearer example:
1 3, 4 6, 7 9, 10 12. Basically skipping the middle div in the grid.
I tried, but it breaks right after. I can't seem to find CSS selectors for more than 2 instances like I want.
.project:nth-child(1), .project:nth-child(2n+1) {
 //something
}

A: You can use 3n and 3n + 1 for every 1st, 3rd of every row.

.project:nth-child(3n),
.project:nth-child(3n+1) {
  color: red;
}

.wrapper {
  display: grid;
  grid-auto-flow: row;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(2, 1fr);
}

1

2

3

4

5

6

7

8

9

10

11

12


text:
Q: How to calculate throughput in SDN/OpenFlow Network using ryu controller How to get Throughput in OpenFlow Networks
We use OpenFlow 1.3 and Ryu Controller.

A: For Ryu Controller using OpenFlow, you may need to calculate based on  statistics data received  in OFPPortStats as part of  OPFPortStatsReply for which you may need to use OFPPortStatsRequest message, to request port statistics info. Similarly,  you can parse the OFPFlowStats of OPFFlowStatsReply  message for flow based statistics calculation which shall be  received as response for the request message OFPFlowStatsRequest.
OFPFlowStatsRequest can be used to get statistical information related to flow entry with switch. The requested target flow entry can be identified by conditions such as table ID, output port, cookie value and match but here all entries are made subject to the request.
OFPPortStatsRequest can be used to get port-related statistical information with switch. It is possible to specify the desired port number to acquire information from and OFPP_ANY can be specified to request information from all ports.
You may need to ceate an event handler that receives the PortStatsReply message. OPFPortStatsReply class's attribute body is the list of OFPPortStats. The OFPPortStats has statistical information such as port numbers, send/receive packet count, respectively, byte count, drop count, error count, frame error count, overrun count, CRC error count, and collision count.
You may need to define a stats thread that send above requests messages and parse reply messages periodically. Once the statistics data it available, iterate/parse through the statistics information and compute bandwidth usage .
There are many other kind of requests you can perform and operate on the responses for which you can refer to http://osrg.github.io/ryu-book/en/html/traffic_monitor.html.

A: Calculating throughput on mininet will just give you a simulated answer which may not be true. However, check out the iPerf tool and see how you can integrate it with mininet.


text:
Q: Transactions not being committed although I have "Commit Transaction" statement I'm using SQL Azure and trying to do conditional delete in batches for a large table, sample:
DECLARE
    @LargestKeyProcessed BIGINT =1,
    @NextBatchMax BIGINT,
    @msg varchar(max) ='';

WHILE (@LargestKeyProcessed <= 1000000)
BEGIN
 Begin Transaction
 SET @NextBatchMax = @LargestKeyProcessed + 50000;
  DELETE From mytable
  WHERE Id > @LargestKeyProcessed AND Id <= @NextBatchMax And some logic
  SET @LargestKeyProcessed = @NextBatchMax;
    set @msg=''+@LargestKeyProcessed;
  RAISERROR(@msg, 0, 1) WITH NOWAIT
  Commit Transaction
END

After the command gets executed successfully I close the tab but SSMS says there are uncomitted transactions although the commit statement is in every iteration. Also the database size seems to remain the same.
I kindly seek your support in explaining why this happens
Thank you very much

A: I think you can try to add SET IMPLICIT_TRANSACTIONS OFF to the sql. As follows to see if solved your issue.
DECLARE
    @LargestKeyProcessed BIGINT =1,
    @NextBatchMax BIGINT,
    @msg varchar(max) ='';

WHILE (@LargestKeyProcessed <= 1000000)
BEGIN
 SET IMPLICIT_TRANSACTIONS OFF
 Begin Transaction
 SET @NextBatchMax = @LargestKeyProcessed + 50000;
  DELETE From mytable
  WHERE Id > @LargestKeyProcessed AND Id <= @NextBatchMax And some logic
  SET @LargestKeyProcessed = @NextBatchMax;
    set @msg=''+@LargestKeyProcessed;
  RAISERROR(@msg, 0, 1) WITH NOWAIT
  Commit Transaction
END


text:
Q: Access Denied for someuser@localhost (Using password: YES) I'm in the process of learning PHP and MYSQL. I created a new user with the privileges select, insert, update, delete, create, alter, index, and drop and they are database specific. When I try to have this user log in I keep getting
ERROR 1045 (28000): Access denied for user 'bookorama'@'localhost' (using password: YES).
I can log in as root user and I'm not sure what I need to do to be able to let this user use the database. Any help would be greatly appreciated.

A: In the case that you've executed the GRANT command correctly, execute the command "FLUSH PRIVILEGES;" and try again.
If it fails again you'll have to check your GRANT command: http://dev.mysql.com/doc/refman/5.1/en/grant.html
An example:
GRANT ALL PRIVILEGES ON databasename.* TO 'bookorama'@'%' IDENTIFIED BY 'yourpassword';
FLUSH PRIVILEGES;


text:
Q: form a number using consecutive numbers I was puzzled with one of the question in Microsoft interview which is as given below:
A function should accept a range( 3 - 21 ) and it should print all the consecutive numbers combinations to form each number as given below:

3  = 1+2
5  = 2+3
6  = 1+2+3
7  = 3+4
9  = 4+5
10 = 1+2+3+4
11 = 5+6
12 = 3+4+5
13 = 6+7
14 = 2+3+4+5
15 = 1+2+3+4+5
17 = 8+9
18 = 5+6+7
19 = 9+10
20 = 2+3+4+5+6
21 = 10+11
21 = 1+2+3+4+5+6
could you please help me in forming this sequence in C#?
Thanks,
Mahesh

A: So here is a straightforward/naive answer (in C++, and not tested; but you should be able to translate). It uses the fact that
1 + 2 + ... + n = n(n+1)/2,
which you have probably seen before. There are lots of easy optimisations that can be made here which I have omitted for clarity.

void WriteAsSums (int n)
{
  for (int i = 0; i < n; i++)
  {
    for (int j = i; j < n; j++)
    {
      if (n = (j * (j+1) - i * (i+1))/2) // then n = (i+1) + (i+2) + ... + (j-1) + j
      {
        std::cout << n << " = ";
        for (int k = i + 1; k <= j; k++)
        {
          std::cout << k;
          if (k != j) // this is not the interesting bit
            std::cout << std::endl;
          else
            std::cout << " + ";
        }
      }
    }
  }
}

A: This is some pseudo code to find all the combinations if any exists:
function consecutive_numbers(n, m)
    list = [] // empty list
    list.push_back(m)
    while m != n
        if m > n
            first = list.remove_first
            m -= first
        else
            last = list.last_element
            if last <= 1
                return []
            end
            list.push_back(last - 1)
            m += last - 1
        end
    end
    return list
end

function all_consecutive_numbers(n)
    m = n / 2 + 1
    a = consecutive_numbers(n, m)
    while a != []
        print_combination(n, a)
        m = a.first - 1
        a = consecutive_numbers(n, m)
    end
end

function print_combination(n, a)
    print(n + " = ")
    print(a.remove_first)
    foreach element in a
        print(" + " + element)
    end
    print("\n")
end

A call to all_consecutive_numbers(21) would print:
21 = 11 + 10
21 = 8 + 7 + 6
21 = 6 + 5 + 4 + 3 + 2 + 1

I tested it in ruby (code here) and it seems to work. I'm sure the basic idea could easily be implemented in C# as well.

A: Here's something in Groovy, you should be able to understand what's going on. It's not the most efficient code and doesn't create the answers in the order you cite in your question (you seem to be missing some though) but it might give you a start.
def f(a,b) {

  for (i in a..b) {

    for (j in 1..i/2) {

      def (sum, str, k) = [ 0, "", j ]

      while (sum < i) {
        sum += k
        str += "+$k"
        k++
      }

      if (sum == i) println "$i=${str[1..-1]}"
     }
  }
}

Output for f(3,21) is:
3=1+2
5=2+3
6=1+2+3
7=3+4
9=2+3+4
9=4+5
10=1+2+3+4
11=5+6
12=3+4+5
13=6+7
14=2+3+4+5
15=1+2+3+4+5
15=4+5+6
15=7+8
17=8+9
18=3+4+5+6
18=5+6+7
19=9+10
20=2+3+4+5+6
21=1+2+3+4+5+6
21=6+7+8
21=10+11

Hope this helps. It kind of conforms to the tenet of doing the simplest thing that could possibly work.

A: I like this problem. Here is a slick and slightly mysterious O(n) solution:
void DisplaySum (int n, int a, int b)
{
  std::cout << n << " = ";
  for (int i = a; i < b; i++) std::cout << i << " + ";
  std::cout << b;
}

void WriteAsSums (int n)
{
  N = 2*n;

  for (int i = 1; i < N; i++)
  {
    if (~(N%i))
    {
      int j = N/i;
      if (j+i%2)
      {
        int a = (j+i-1)/2;
        int b = (j-i+1)/2;
        if (a>0 & a<b) // exclude trivial & negative solutions
          DisplaySum(n,a,b);
      }
    }
  }
}

A: if we slice a into 2 digit, then a = b + (b+1) = 2*b + (0+1)
if we slice a into 3 digit, then a = b + (b+1) + (b+2) = 3*b + (0+1+2)
...
if we slice a into n digit, then a = b + (b+1) +...+ (b+n) = nb + (0+1+n-1)
the last result is a = nb + n*(n-1)/2, a,b,n are all ints.
so O(N) Algorithm is:
void seq_sum(int a)
{
// start from 2 digits
   int n=2;
   while(1)
   {
      int value = a-n*(n-1)/2;
      if(value < 0)
         break;
// meet the quotation we deduct
      if( value%n == 0 )
      {
           int b=value/n;
// omit the print stage
           print("......");
      }
      n++;
   }
}


text:
Q: Empty $_GET params altough QSA flag next to rewrite rule in .htaccess I've tried various solutions posted here on stackoverflow, none of them seemed to work.
I really wonder what am I missing here, currently .htaccess looks like this:
RewriteEngine On
RewriteRule ^register/?$ ./register.php?reference=$1 [L,QSA]

I'm getting URL like this:
domain.com/register/ENIGMA-45
That's all good, but $_GET param don't pass.
I've tried to print_r($_GET) and print($_SERVER['QUERY_STRING]); both are empty.
VirtualHost config:
<VirtualHost 199.99.99.99:82>
    ServerName dot.magicaldomain.com
    ServerAlias www.dot.magicaldomain.com
    DocumentRoot /home/dot/public_html
    ServerAdmin webmaster@dot.magicaldomain.com
    ## User dot # Needed for Cpanel::ApacheConf
    <IfModule mod_userdir.c>
        Userdir disabled
        Userdir enabled dot
    </IfModule>
    <IfModule mod_suphp.c>
        suPHP_UserGroup dot dot
    </IfModule>
    <IfModule !mod_disable_suexec.c>
        <IfModule !mod_ruid2.c>
           SuexecUserGroup dot dot
        </IfModule>
    </IfModule>
    <IfModule mod_ruid2.c>
       RUidGid dot dot
    </IfModule>
    CustomLog /usr/local/apache/domlogs/dot.magicaldomain.com-bytes_log "%{%s}t %I .\n%{%s}t %O ."
    CustomLog /usr/local/apache/domlogs/dot.magicaldomain.com combined
    Options -ExecCGI -Includes
    RemoveHandler cgi-script .cgi .pl .plx .ppl .perl
</VirtualHost>

A: To capture:
domain.com/register/ENIGMA-45

You can use this:
Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

RewriteRule ^register/?([^/]*|)/?$ /register.php?reference=$1 [L]

Add this to your virtualhost:
<Directory "/home/dot/public_html">
    Options -Indexes FollowSymLinks +ExecCGI
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>


text:
Q: Laravel Eloquent relation between models I need help with querying the result of relation between models. Two models are defined, User and Role model.
User:
public function roles()
{
    return $this->belongsToMany('App\Role', 'role_users');
}

public function hasAccess(array $permissions) : bool
{
    foreach ($this->roles as $role) {
        if ($role->hasAccess($permissions)) {
            return true;
        }
    }

    return false;
}

public function inRole(string $slug)
{
    return $this->roles()->where('slug', $slug)->count() == 1;
}

Role:
public function users()
{
    return $this->hasMany('App\User', 'role_users');
}

public function hasAccess(array $permissions) : bool
{
    foreach ($permissions as $permission) {
        if ($this->hasPermission($permission)) {
            return true;
        }
    }

    return false;
}

private function hasPermission(string $permission) : bool
{
    return $this->permissions[$permission] ?? false;
}

Also, a pivot table called role_users is defined. In the roles database several roles are pre-defined by seeding (Admin, Editor, Author).
I want to query the users by its roles, for example,
$editors = App\User::roles(2)->orderBy('name', 'asc')->get()

where in roles database the id of editor is 2. I got the error
PHP Deprecated:  Non-static method App/User::roles()

How to solve this? Note: I'm using Laravel 5.6 and new to Laravel and framework. I tried to refer to docs but it confused me.
Thanks in advance.

A: You have to use whereHas(..):
$editors = \App\User::whereHas('roles', function ($q) {
    $q->where('id', 2);
})->orderBy('name', 'asc')->get()

A: @devk is correct but here you have another way to get the data of user by role.
\App\Role::where('id', 2)->with('users')->get();


text:
Q: Anti-aliasing not working when resizing a UIWebView I'd like to add a Web View to my app at 60% scale (like seen in Safari in the browse other windows view):

Notice how the content looks nice and Aliased!
If I try and add the same Web view to my app:
NSURL *url = [NSURL URLWithString:@"http://www.google.co.uk?q=hello"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];
webView.delegate=self;
[webView loadRequest:request];
[self.view addSubview:webView];

Using the following transformation:
[webView setTransform:CGAffineTransformMakeScale(0.6, 0.6)];

..the scale is really bad quality and there appears to be no anti-aliasing.
Does anyone know why this is happening or have a suggestion on how it could be fixed?
Thanks!
Nick.

A: I figured out a solution!
Take a snapshot of the webview, add it to a UIImageView and resize that insted!
UIGraphicsBeginImageContext(webView.bounds.size);
[webView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(webView.bounds.x, webView.bounds.y, webView.frame.size.width, webView.size.height)];
imageView.image = viewImage;
[self addSubview:imageView];
[imageView release];

webView.hidden = YES;

Seems to work fine!
One point to note.. if you want to do this as soon as the WebView has loaded, you need to defer the action by some period (I chose a 10th of a second!)
Like so:
-(void)deferLoading
{
    webViewHasActuallyLoaded = YES;
    [self setNeedsLayout];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [NSTimer scheduledTimerWithTimeInterval: 1.0/10.0 target:self selector:@selector(deferLoading) userInfo:nil repeats:NO];
}

Cheers for suggestions abovee!
Nick.

A: Why not just make the web view smaller? It should render the content in high quality at the smaller size.
If you need to animate the change in size, you can set the minificationFilter on the web view's layer to get reasonable quality:
[[webView layer] setMinificationFilter:kCAFilterLinear];

A: In your UIViewController override

*

*(void)placeViewItems: (UIInterfaceOrientation)interfaceOrientation

And make your UIWebView's frame.origin.x & frame.origin.y integer values.
See if that is the result you are looking for.


text:
Q: $W_p(\mu,\mu_{\epsilon})\to 0$ when $\mu_{\epsilon}$ is a mollified version of $\mu$. I would like to show that the Wasserstein distance between a probability measure $\mu$ (in $\mathbb{R}^d$) and a mollified version of it $\mu_{\epsilon}:=\mu\ast\rho_\epsilon$ where $\mu\ast\rho_\epsilon(x):=\int \rho_{\epsilon}(x-y)d\mu(y)$ goes to 0, i.e. $$\lim\limits_{\epsilon\to 0}W_p(\mu,\mu_{\epsilon}).$$ I was told that to do this I can show that $$W_p(\mu,\mu_{\epsilon})\le\epsilon m_p(\rho)$$ where $m_p(\rho):=\left(\int d(x,x)^p\rho(x)dx\right)^{1/p}$ denotes the $p$-th moment. I think I have to come up with a particular transport plan between $\mu$ and $\nu$. I tried with the most obvious one to me, i.e. the product measure $\mu\times\mu_{\epsilon}$ but I didn't arrive to the desired conclusion.
edit
Using the plan $\mu\times\mu_{\epsilon}$ I get
\begin{align}
W_p^p(\mu,\mu_{\epsilon})&\le \int d(x,y) d\mu(x)d\mu_\epsilon(y)\\ &= \int d(x,y)\mu\ast\rho_{\epsilon}(y)d\mu(x) dy\\ &= \int d(x,y)\left(\int\rho_{\epsilon}(y-z)d\mu(z)\right)d\mu(x) dy
\end{align}
But now I a am stuck

A: The problem with using the product measure $\mu \otimes \mu_{\epsilon}$ is it does not use the form of $\mu_{\epsilon}$ at all.  Convolutions have a very specific probabilistic interpretation, as do couplings, and the $p$-th moment you wrote also frequently appears in probabilistic computations.  Hence a second guess is to exploit this connection.
Recall that if $Y$ is a random vector with distribution $\mu$ and $X_{\epsilon}$ is a random variable with distribution $\rho_{\epsilon}(x) \, dx$, and if $Y$ and $X_{\epsilon}$ are independent, then $X_{\epsilon} + Y$ has distribution $\rho_{\epsilon} * \mu = \mu_{\epsilon}$.  Accordingly, if $\nu$ is the distribution of the pair $(X_{\epsilon} + Y,Y)$, then the first marginal $\pi_{1*} \nu$ equals $\mu_{\epsilon}$ and the second marginal $\pi_{2*}\nu$ equals $\mu$.  In particular, $\nu$ is a coupling of $\mu_{\epsilon}$ and $\mu$.
Also, I'm assuming that $d(x,y) = \|x - y\|$, where $\|\cdot\|$ is the Euclidean norm.  However, all that is really necessary is that $d$ is translationally invariant (i.e. $d(x + z, y + z) = d(x,y)$ for all $x,y, z \in \mathbb{R}^{d}$).  In particular, other norms would also work.
With the coupling $\nu$ in hand, let's try to bound $W_{p}(\mu_{\epsilon},\mu)$.  I will use the random variables to do the computation since it is much clearer.  If that's not your style, it would be a good exercise to write down a purely analytic proof.  We find:
\begin{align*}
W_{p}(\mu_{\epsilon},\mu)^{p} &\leq \int_{\mathbb{R}^{d} \times \mathbb{R}^{d}} \|x - y\|^{p} \, \nu(dx \otimes dy) \\
&= \mathbb{E}(\|(X_{\epsilon} +Y) - Y\|^{p}) \\
&= \mathbb{E}(\|X_{\epsilon}\|^{p}) \\
&= \int_{\mathbb{R}^{d}} \|x\|^{p} \rho_{\epsilon}(x) \, dx \\
&= \epsilon^{p} \int_{\mathbb{R}^{d}} \|\epsilon^{-1} x\|^{p} \rho(\epsilon^{-1}x) \, \frac{dx}{\epsilon^{d}} \\
&= \epsilon^{p} M_{p}(\rho),
\end{align*}
where the $p$th moment of $\rho$ is $M_{p}(\rho) = \int_{\mathbb{R}^{d}} \|y\|^{p} \rho(y) \, dy$.
It is worth noting (and can be used to simplify the computation above somewhat) that $X_{\epsilon}$ has the same distribution as $\epsilon X$, where $X$ has distribution $\rho(x) \, dx$.  In this sense, what we are doing in the last three lines above is simply computing $\mathbb{E}(\|\epsilon X\|^{p}) = \epsilon^{p} \mathbb{E}(\|X\|^{p})$ --- another indication that the probabilistic interpretation is very convenient here.
Hint to "un-probability" the computation above:  Let $\nu = \nu_{\epsilon}$ be the probability measure on $\mathbb{R}^{d} \times \mathbb{R}^{d}$ given by its action on $f \in C_{c}(\mathbb{R}^{d} \times \mathbb{R}^{d})$ by
\begin{equation*}
\int_{\mathbb{R}^{d} \times \mathbb{R}^{d}} f(x,y) \nu_{\epsilon}(dx \otimes dy) = \int_{\mathbb{R}^{d}} \left( \int_{\mathbb{R}^{d}} f(y' + x',y') \rho_{\epsilon}(x') \, dx' \right) \mu(dy').
\end{equation*}
Check that $\nu_{\epsilon}$ as defined is really a coupling of $\mu$ and $\mu_{\epsilon}$.  It is also worth verifying that $\nu_{\epsilon}$ can be rewritten as
\begin{equation*}
\int_{\mathbb{R}^{d} \times \mathbb{R}^{d}} f(x,y) \nu_{\epsilon}(dx \otimes dy) = \int_{\mathbb{R}^{d}} \left( \int_{\mathbb{R}^{d}} f(y' + \epsilon x', y') \rho(x') \, dx' \right) \mu(dy').
\end{equation*}
Hence $\nu_{\epsilon}$ is looking very close to the diagonal.  Finally, check that
\begin{equation*}
\int_{\mathbb{R}^{d} \times \mathbb{R}^{d}} \|x-y\|^{p} \nu_{\epsilon}(dx \otimes dy) = \int_{\mathbb{R}^{d}} \|x'\|^{p} \rho_{\epsilon}(x') \, dx'
\end{equation*}
and complete the argument as in the answer above.
Edit:  The product measure will not give a useful estimate.  To see this, consider the case when $\mu$ is Gaussian, that is, $\mu(dx) = (2 \pi)^{-d/2}\exp(-\|x\|^{2}/2) \, dx$ and let $\rho$ also be Gaussian:
\begin{equation*}
\rho(x) = (2 \pi)^{-d/2} \exp(-\|x\|^{2}/2).
\end{equation*}
One can then check that $\mu \otimes \mu_{\epsilon}$ is nothing other than two independent Gaussians, the second with variance $1 + \epsilon^{2}$:
\begin{equation*}
(\mu \otimes \mu_{\epsilon})(dx \otimes dy) = (2 \pi)^{-d} \epsilon^{-d} \exp \left(- \|x\|^{2}/2 - \|y\|^{2}/2(1+\epsilon^{2})\right) \, dx dy.
\end{equation*}
Now in the easy case when $p = 2$, writing $\|x - y\|^{2} = \|x\|^{2} + \|y\|^{2} - 2 \langle x,y \rangle$ and eliminating the cross term leads to
\begin{equation*}
\int_{\mathbb{R}^{d} \times \mathbb{R}^{d}} \|x - y\|^{2} (\mu \otimes \mu_{\epsilon})(dx \otimes dy) = \int_{\mathbb{R}^{d}} \|x\|^{2} \mu(dx) + \int_{\mathbb{R}^{d}} \|y\|^{2} \mu_{\epsilon}(dy) = 2 + \epsilon^{2}.
\end{equation*}


text:
Q: Xcode Error , The operation couldn't be completed. No such process. React Native I am trying to build my app on iPhone simulator with m1 mac, but I get this error alert from xcode,
"The operation couldn't be completed. No such process",
Details
The operation couldn't be completed. No such process
Domain: NSPOSIXErrorDomain
Code: 3
Failure Reason: No such process
User Info: {

    DVTErrorCreationDateKey = "2022-09-15 08:54:55 +0000";

    IDERunOperationFailingWorker = IDELaunchiPhoneSimulatorLauncher;

}

Analytics Event: com.apple.dt.IDERunOperationWorkerFinished : {

    "device_model" = "iPhone14,2";

    "device_osBuild" = "15.2 (19C51)";

    "device_platform" = "com.apple.platform.iphonesimulator";

    "launchSession_schemeCommand" = Run;

    "launchSession_state" = 1;

    "launchSession_targetArch" = arm64;

    "operation_duration_ms" = 2091;

    "operation_errorCode" = 3;

    "operation_errorDomain" = NSPOSIXErrorDomain;

    "operation_errorWorker" = IDELaunchiPhoneSimulatorLauncher;

    "operation_name" = IDERunOperationWorkerGroup;

    "param_consoleMode" = 0;

    "param_debugger_attachToExtensions" = 0;

    "param_debugger_attachToXPC" = 1;

    "param_debugger_type" = 3;

    "param_destination_isProxy" = 0;

    "param_destination_platform" = "com.apple.platform.iphonesimulator";

    "param_diag_MainThreadChecker_stopOnIssue" = 0;

    "param_diag_MallocStackLogging_enableDuringAttach" = 0;

    "param_diag_MallocStackLogging_enableForXPC" = 1;

    "param_diag_allowLocationSimulation" = 1;

    "param_diag_gpu_frameCapture_enable" = 0;

    "param_diag_gpu_shaderValidation_enable" = 0;

    "param_diag_gpu_validation_enable" = 0;

    "param_diag_memoryGraphOnResourceException" = 0;

    "param_diag_queueDebugging_enable" = 1;

    "param_diag_runtimeProfile_generate" = 0;

    "param_diag_sanitizer_asan_enable" = 0;

    "param_diag_sanitizer_tsan_enable" = 0;

    "param_diag_sanitizer_tsan_stopOnIssue" = 0;

    "param_diag_sanitizer_ubsan_stopOnIssue" = 0;

    "param_diag_showNonLocalizedStrings" = 0;

    "param_diag_viewDebugging_enabled" = 1;

    "param_diag_viewDebugging_insertDylibOnLaunch" = 1;

    "param_install_style" = 0;

    "param_launcher_UID" = 2;

    "param_launcher_allowDeviceSensorReplayData" = 0;

    "param_launcher_kind" = 0;

    "param_launcher_style" = 0;

    "param_launcher_substyle" = 0;

    "param_runnable_appExtensionHostRunMode" = 0;

    "param_runnable_productType" = "com.apple.product-type.application";

    "param_runnable_swiftVersion" = "5.6.1";

    "param_runnable_type" = 2;

    "param_testing_launchedForTesting" = 0;

    "param_testing_suppressSimulatorApp" = 0;

    "param_testing_usingCLI" = 0;

    "sdk_canonicalName" = "iphonesimulator15.5";

    "sdk_osVersion" = "15.5";

    "sdk_variant" = iphonesimulator;

}

--
System Information

*

*macOS Version 12.5.1 (Build 21G83)

*Xcode 13.4.1 (20504) (Build 13F100)

*Timestamp: 2022-09-15T10:54:55+02:00
I tried to upgrade IOS version of the app from "ios 10" to "ios 12" but it didn't work


text:
Q: Display all constants in 'Digest' I would like to know how to see every constant available on the Digest module in advance programmatically. The behaviour seen below is due to const_missing used here:
require 'digest'

Digest.constants
#=> [:Class, :REQUIRE_MUTEX, :Instance, :Base]

Digest::MD5
Digest.constants
#=> [:Class, :REQUIRE_MUTEX, :Instance, :Base, :MD5]

Digest::SHA1
Digest.constants
#=> [:Class, :REQUIRE_MUTEX, :Instance, :Base, :MD5, :SHA1]

Given that they are metaprogramming in possible digests, how can I know all possible available digests?
For knowledge, the ones that appear to be available in Ruby 2.4.1 should be [:SHA256, :SHA384, :SHA512, :SHA1, :SHA2, :MD5, :RMD160]

A: Here's a code snipped from the current master branch of ruby:
module Digest
  def self.const_missing(name) # :nodoc:
    case name
    when :SHA256, :SHA384, :SHA512
      lib = 'digest/sha2.so'
    else
      lib = File.join('digest', name.to_s.downcase)
    end

    begin
      require lib
    rescue LoadError
      raise LoadError, "library not found for class Digest::#{name} -- #{lib}", caller(1)
    end
    unless Digest.const_defined?(name)
      raise NameError, "uninitialized constant Digest::#{name}", caller(1)
    end
    Digest.const_get(name)
  end

  # ...
end

...So, you can't really list all constants without knowing them already! You need to either require the necessary file, or reference the constant directly (which will load the file dynamically, as seen above).
Any workaround solution I could give would only be guaranteed to work for a specific version of ruby. You'd be better off to just read the documentation and load each library explicitly, unfortunately!


text:
Q: I can not right click in Delphi7 IDE, because when i click , occur error message I using Delphi 7. Until recently, it worked fine.
But now, every time i do right click, I get an error that message is

"Access violation at address 735f5e37 in module 'MSVCR90.dll'. Write
  of address 00000000"

So, I can not do anything in delphi7 IDE for development.
Also, When I left click at menu (such as file, edit, run, tool.. etc) occur same error message.
So, I reinstall delphi7. But same occurs these error message.
Why is this happening?


text:
Q: Unable to deserialize ZonedDateTime using Jackson I am using Jersey with Jackson as JSON provider. I am able to serialize ZonedDateTime to JSON but when I want to deserialize it gives me error as follows.
Could you please help me tell the exact configuration required to get this deserialization work.

Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class java.time.ZonedDateTime] from String value ('2016-01-21T21:00:00Z'); no single-String constructor/factory method

My mapper configuration is as follows:
@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
    private final ObjectMapper MAPPER;

    public ObjectMapperContextResolver() {
        MAPPER = new ObjectMapper();
        //This would add JSR310 (Datetime) support while converting date to JSON using JAXRS service
        MAPPER.registerModule(new JavaTimeModule());
        //Below line would disable use of timestamps (numbers),
        //and instead use a [ISO-8601 ]-compliant notation, which gets output as something like: "1970-01-01T00:00:00.000+0000".
        MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return MAPPER;
    }
}

A: I found the problem, actually issue was not with Deserialization using standard jackson provider. In my case, I was using Jersey client to get JSON and then deserialize using readEntity method.
Problem was that jersey client was not aware of the jsr310 module, so by registering the contextresolver where jsr310 has been added solved the issue. So in nutshell, you don't need to do anything for seralization and deserialization of ZonedDateTime if using normal jackson provider.
Below is the reference code which I am referring here, to get better clarity.
public class RESTClientImpl{

    /*
     * ***This is very important, JacksonJsonProvider is the implementation of
     * MessageBodyWriter/Reader which is required for "readEntity" method,
     * else it would throw MessageBodyWriter/Reader not found exception
     *
     * https://jersey.java.net/documentation/latest/message-body-workers.html#mbw.ex.client.mbr.reg
     *
     * Registering of ObjectMapperContextResolver is important as we have registered JSR310 module there and without registering this,
     * Jersey client is not aware of JSR310 module, so it will not be able to de-serialize ZonedDateTime
     */
    private final Client client = ClientBuilder.newClient(new ClientConfig().register(LoggingFilter.class)).register(JacksonJsonProvider.class)
            .register(ObjectMapperContextResolver.class);

    public User get(URI uri) {
        WebTarget webTarget = client.target(uri);

        Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
        Response response = invocationBuilder.get();
        User user = response.readEntity(User.class);
        return user;
    }
}

@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
    private final ObjectMapper MAPPER;

    public ObjectMapperContextResolver() {
        MAPPER = new ObjectMapper();
        //This would add JSR310 (Datetime) support while converting date to JSON using JAXRS service
        MAPPER.registerModule(new JavaTimeModule());
        //Below line would disable use of timestamps (numbers),
        //and instead use a [ISO-8601 ]-compliant notation, which gets output as something like: "1970-01-01T00:00:00.000+0000".
        MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addDeserializer(Object.class, new ZonedDateTimeDeserializer());
        MAPPER.registerModule(simpleModule);
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return MAPPER;
    }
}


text:
Q: How to change output from binary to ascii? I want to make a small change in one C code,in order to double-check some results.Just few relevant lines
 FILE           *f1_out, *f2_out;

/* open files */
if ((f1_out = fopen(vfname, "w")) == (FILE *) NULL)
{
   fprintf(stderr, "%s: Can't open file %s.\n", progname, vfname);
   return (-1);
}

Then goes some calculations and
yes = fwrite(vel, nxyz*sizeof(float), 1, f1_out);

How to change the last line to get the ascii output?

A: Assuming that your vel is an array of floats, and your nxyz is the number of floats in that array, and that you want the output on the standard output and not on the file you opened:
for (int i = 0; i < nxyz; ++i) {
    printf("vel[%d] = %f\n", i, vel[i]);
}

A: Instead of yes = fwrite(vel, nxyz*sizeof(float), 1, f1_out);, use
for(i = 0; i < nxyz; ++i) {
  yes &= (fprintf(f1_out, "%d:\t%f\n", i, vel[i]) > 0);
}

A: To see all meaningful digits in a float as text use printf("%*e", some_precision, some_float)
#include <float.h>
fprintf(f1_out, "%.*e\n", FLT_DECIMAL_DIG - 1, *vel);


text:
Q: Deploy jars in gemfire cache I am studying gemfire and getting my hands dirty. I came across this concept of deploying jars into gemfire.
My question is why and what type of jars would one deploy in to gemfire cache that would become native to gemfire.
Can you list some scenarios that would clarify this concept of deploying jars in to gemfire ?

A: You can write Functions that can be executed within the Geode server process. Functions are a quick way of iterating over the data in Geode in parallel OR implementing your custom aggregate.
You can also implement CacheLoaders to load data into Geode and CacheListeners/AsyncEventListeners to write data from Geode into another data source.
Your functions, Listeners, Writers can be bundled in a jar and then deployed on the Geode servers.


text:
Q: In Struts2, how do I persist data between 2 actions? I have a Struts 2 page with 2 DisplayTag tables on there, each having a List<T>. This List<T> is populated in code-behind and can be a couple of thousand entries long. On the page, I can select rows of either of the tables and press a button to move them from one table to the other. This can be done multiple times before finally pressing another button to save the contents of one of the tables in the database. I want to do both of these things in the action through AJAX.
userGroupEditmembers.jsp (apologies for the excess whitespace, remnant of using block selection in eclipse)

                <s:text name="overview.groupMembers" />

            <s:set name="groupMembers" value="groupMembers" scope="request" />
            <display:table name="groupMembers" uid="row" excludedParams="*" cellspacing="1" cellpadding="1">
                <%-- include localized messages for the table's banner --%>
                <%@ include file="/jsp/includesstruts2/displayTagBanner.jsp"%>

                <display:column sortable="false" headerClass="listHeader">
                    <s:checkbox name="groupMemberOids" fieldValue="%{#attr.row.oid}"  theme="simple" />
                </display:column>
                <%-- User Name --%>
                <display:column property="userId" titleKey="label.user.userId" headerClass="listHeader" />

                <%-- User Name --%>
                <display:column property="name" titleKey="label.user.name" headerClass="listHeader" />

                <%-- Whether the User is archived --%>
                <display:column titleKey="label.user.archived" headerClass="listHeader"
                    class="iconColumn">
                    <s:if test="%{#attr.row.archived}">
                        <img src="<s:url value='/images/checkedWarning.gif'/>" border="0" />
                    </s:if>
                </display:column>
            </display:table>

            <%-- 'Remove Users from Group' button --%>
            <input value=">>" type="button" id="removeUsersButton" />

            <%-- The 'Refresh' button. Used to reload the issueTrackingSystemEditDialog.jsp --%>
            <input value="<<" type="button" id="addUsersButton" />

                <s:text name="overview.nonGroupMembers" />

            <s:set name="nonGroupMembers" value="nonGroupMembers" scope="request" />

            <display:table name="nonGroupMembers" uid="row" excludedParams="*"
                cellspacing="1" cellpadding="1">
                <%-- include localized messages for the table's banner --%>
                <%@ include file="/jsp/includesstruts2/displayTagBanner.jsp"%>

                <display:column sortable="false" headerClass="listHeader">
                    <s:checkbox name="nonGroupMemberOids" fieldValue="%{#attr.row.oid}"
                        theme="simple" />
                </display:column>
                <%-- User Name --%>
                <display:column property="userId" titleKey="label.user.userId"
                    headerClass="listHeader" />

                <%-- User Name --%>
                <display:column property="name" titleKey="label.user.name"
                    headerClass="listHeader" />

                <%-- Whether the User is archived --%>
                <display:column titleKey="label.user.archived" headerClass="listHeader"
                    class="iconColumn">
                    <s:if test="%{#attr.row.archived}">
                        <img src="<s:url value='/images/checkedWarning.gif'/>" border="0" />
                    </s:if>
                </display:column>
            </display:table>

<s:token />

<s:hidden name="oid" />
<s:hidden name="version" />
<s:hidden name="groupMembersJson" />
<s:hidden name="nonGroupMembersJson" />

UserGroupEditMembersAction.java:
private Integer oid;
private Integer version;

private List<UserView> groupMembers;

private List<UserView> nonGroupMembers;

private String groupMembersJson;

private String nonGroupMembersJson;

private Integer[] groupMemberOids;

private Integer[] nonGroupMemberOids;

private Boolean showArchived;

/**
 * method for DisplayUserGroupEdit action.
 *
 * @return
 * @throws Exception
 */
public String display() throws Exception {
    if (showArchived == null) {
        showArchived = false;
    }
    UserService userService = (UserService) ServiceFactory.getInstance().createService(UserService.class);
    List<List<UserView>> usersForUserGroup = userService.getUsers(oid, showArchived);
    groupMembers = usersForUserGroup.get(0);
    nonGroupMembers = usersForUserGroup.get(1);
    groupMembersJson = serializeToJsonString(groupMembers);
    nonGroupMembersJson = serializeToJsonString(nonGroupMembers);

    return SUCCESS;
}

public String addMembers() throws Exception {
    groupMembers = (List<UserView>) deserializeFromJsonString(groupMembersJson);
    nonGroupMembers = (List<UserView>) deserializeFromJsonString(nonGroupMembersJson);
    UserService userService = (UserService) ServiceFactory.getInstance().createService(UserService.class);
    for (Integer userOid : nonGroupMemberOids) {
        UserView userview = userService.getUser(userOid);
        groupMembers.add(userview);
        for(int i = 0; i< nonGroupMembers.size(); i++){
            UserView view = nonGroupMembers.get(i);
            if(view.getOid().equals(userOid)){
                nonGroupMembers.remove(i);
                break;
            }
        }
    }
    groupMembersJson = serializeToJsonString(groupMembers);
    nonGroupMembersJson = serializeToJsonString(nonGroupMembers);
    return SUCCESS;
}

public String removeMembers() throws Exception {
    groupMembers = (List<UserView>) deserializeFromJsonString(groupMembersJson);
    nonGroupMembers = (List<UserView>) deserializeFromJsonString(nonGroupMembersJson);
    UserService userService = (UserService) ServiceFactory.getInstance().createService(UserService.class);
    for (Integer userOid : groupMemberOids) {
        UserView userview = userService.getUser(userOid);
        nonGroupMembers.add(userview);
        for(int i = 0; i< groupMembers.size(); i++){
            UserView view = groupMembers.get(i);
            if(view.getOid().equals(userOid)){
                groupMembers.remove(i);
                break;
            }
        }
    }
    groupMembersJson = serializeToJsonString(groupMembers);
    nonGroupMembersJson = serializeToJsonString(nonGroupMembers);
    return SUCCESS;
}

The problem I have is that when I'm moving elements from one List to the other List, I need access to the lists that are currently used in the tables. Because Struts2 actions are stateless, I need to persist these lists between 2 actions.

*

*I've tried just having the lists in a <s: hidden /> block, but that can't be converted back easily.

*My current attempt is by serializing them to JSON through the JSONUtil.serialize and JSONUtil.deserialize methods, but for some reason that deserializes them to List<HashMap> instead of List<T>.

*I've suggested my coworker we use the Session, but he's concerned about performance losses.

What's the best way to handle this?

A: Action chaining is the correct way. I am using annotation so code looks like this.
@Action(
            value = "/loginAction",
            results = {
                    @Result(name = "car_user", type="chain", params = {"actionName", "getAllUserAction", "loginUser", "${loginUser}"}),

....................
Where loginUser is the variable having setter getter in loginAction class and the chain attion class which has actionName getAllUserAction will receive it in loginUser Variable in that class which has setter getter for the same.


text:
Q: How do I overlay a transparent image on a swiper and still be able to swipe? I have an iPad image with a transparent background so that the swiper images are within it.
Codepen here.
The issue I'm having is that when I have the iPad image outside of the swiper-container div, it looks great, but I can no longer click on the images in the swiper to move/swipe them..

When I put it the iPad image inside the swiper-container div it works great, but it doesn't overlap the images as I need it to. The swiper-container crops it.

Any ideas on how to wrap the image-slider with the iPad transparent background while still being able to swipe the images?

A: Adding pointer-events: none; for .ipad-frame will allow to swipe the image


text:
Q: maskedtextbox alignment I am working on a VB.Net Windows application. I am trying to use MaskedTextBox. My mask is 999999, RightToLeft is true, TextAlign is right. It is not letting me enter characters from the right. It is entering them from the left. When I type 1234 and save I get 1234____ when I expect to get ____1234.
Please tell me what I am missing.

A: This worked for me. The code is in the Form's load event.
MaskedTextBox1.Mask = "999999"
MaskedTextBox1.RightToLeft = RightToLeft.Yes
MaskedTextBox1.TextAlign = HorizontalAlignment.Right


text:
Q: Push vertices of an OBJ file- Edit .obj I have a .obj 3D model where I want to move some of the surface vertices for a given length.
How can I get to do this.
For smaller files I can just open it in the notepad and edit the vertices position. But when the model gets bigger this becomes impossible.
Matlab? Tried to load a 3D model which is kinda big using a toolbox. It takes a lot of time :(
Meshlab maybe? -Couldn't find
Thanks in advance.

A: With meshlab, you could write a plugin to manipulate yout mesh vertex.
So if you search a progamming solution, it could be a good choice.