text:
Q: Micro services REST with Javascript user authentication/authorization I am fairly new to the microservice architecture. I am trying to build a web application in this kind of way. After some research online about microservices and having experience with Spring and Angular I want to build a web application with a separate front-end and multiple (separate) back-end REST API's.
How i want to design my application is a javascript/html/css front end (developed by me, no external clients). The front end will communicate via an API gateway (Reverse proxy) to my backend REST API's. The REST API's will be different microservices. I want the user to sign in once (SSO) to be authenticated and authorized for the REST API's. Some API's will be public, but some must be protected. Also this could be on different levels (admin and user API's).
Front end -> API Gateway --> Authorization server
                         |-> User REST API (User and Admin)
                         |-> Statistics REST API (User and Admin)
                         |-> Admin user overview REST API (Admin only)

The thing that worries me is the user authentication/authorization. (Its a big deal in my app). This is where i got lost. I did some research online for this and there are a lot of people recommending Oauth2 for this. Altough i tought Oaut2 is for application to application authorization there seems to be a authorization flow for javascript based web apps (The implicit flow). I want the user to log in in the front end, no social authentication or anything. Complete own developed system.
It is actually language agnostic (Almost each language can implement OAuth2). I am ooking for the best way to implement security authentication and authorization.
But i was wondering is OAuth2 is the right thing for this architecture.
Is the Oauth2 implicit flow good enough for my own developed front end? Or could/should i use the password flow?
If Oauth is not suitable for this goal, what should be used then? I read about JWT but i am not sure if that is what i need. And if Oauth2 is suitable for my situation, should i use the Implicit or Password flow?
I hope you guys can help me decide and explain things a bit.
Thanks!

A:
I want the user to log in in the front end, no social authentication or anything.

There is nothing social in OpenID/OAuth2. Basically, the benefit of OpenID and OAuth2 is for the developer to rely on an external system to handle all the authentication in the first case, and authorization in the second case.
For the developer, this means that:

*

*The developer doesn't take the risk of introducing bugs which would, ultimately, allow a hacker to gain access to the system as a different user, or tamper with user's credentials.

*The system doesn't store any hashed passwords, which makes the system much less interesting to hack for someone who wants to get users' passwords.

*The developer add extra providers with ease.

*When a provider starts supporting an additional security feature, such as Two Factor Authentication, you get it for free.
For the user, this means that:

*

*There is one password less to remember if the user is already registered on the third-party website which provides OpenID/OAuth2 service.

*Or, there is one more account to create if the user is not registered on the third-party website. This could be an issue when the user doesn't want to register on that third-party website. For instance, if you make it mandatory to have a Facebook account to use your product, I won't be among your customers.

*The overall user experience becomes slightly poorer, due to multiple redirects, as well as the loss of context ("Why am I redirected to Facebook? Is this a error?")
The actual OpenID and OAuth2 provider could be anything: while it is true that many social websites also do let you use their OpenID/OAuth2, they are not alone. Non-social providers include SalesForce, PayPal and Amazon.

Complete own developed system.

Why would you do that?
As explained above, the benefit of OpenID/OAuth2 is to mitigate the risk by moving complex code and sensitive data out of your servers. Let experts from Amazon or Google handle this thing. Don't put yourself and your users at risk. Unless, of course, you are the expert and you've worked for the last decade on authentication systems, in which case, go for it.

But i was wondering is OAuth2 is the right thing for this architecture. Is the Oauth2 implicit flow good enough for my own developed front end? Or could/should i use the password flow?

OpenID is the password flow. Open Developer's Tools panel in your browser and track the network stream; you'll see there is no magic there. For your web application, it will be pretty straightforward to set up OpenID or OAuth2, depending on the maturity of thir-party libraries which are available for your language of choice.
However, when it comes to accessing the APIs from the client, you'll have problems either way: at some moment, the web application would need to tell the API that a specific user with a specific key and secret will need to access it.
Basically, at some point, either the app or the API will need to generate a key-secret pair which will then be used by the browser when doing AJAX requests to that API. The app would also need to tell the API that a given key is associated with a given user: this way, the user will be able to access her data, but not the data of somebody else.
This mechanism is independent of the choice between OpenID/OAuth2 and a home-made system. The scope of authentication is the web application; APIs don't authenticate users; they authenticate other applications, would it be your own web app, or a third-party.

A: Rest is about leveraging the already existing mechanisms of the internet. The web already gives you several http authentication mechanisms.BASIC, Digest etc. Consider using basic auth over ssl.


text:
Q: Can serverless express be used with sails.js apps Strange that google does not have any info for this...
I want to use aws lambda for an upcoming project. I would like to build it with sails.js. I know that there is aws-serverless-express that allows to run express apps on lambda. Does this also apply to sails or would this not work?

A: I'm using waterline.js successfully with express and serverless on AWS Lambda. Waterline is the ORM component of Sails.js.
Under the hood of Sails it uses express so it would be possible to with serverless. Although as Manuel mentions it may be too fat for Lambda.
const PGAdapter = require('sails-postgresql');
const Waterline = require('waterline');

const conf = {
  "adapters":{
    "sails-postgresql": PGAdapter
  },
  "datastores":{
    "default":{
      "adapter":"sails-postgresql",
      "port":5432,
      "poolSize":1,
      "ssl":false,
      "database":"development",
      "host":"localhost",
      "user":"***",
      "password":"****"
    }
  },
  "models":{
    "User":{
      "tableName":"users",
      "attributes":{
        "email":{
          "type":"string",
          "required":true
        },
        "first_name":{
          "type":"string"
        },
        "last_name":{
          "type":"string"
        }
      }
    }
  },
  "defaultModelSettings":{
    "primaryKey":"id",
    "datastore":"default",
    "attributes":{
      "id":{
        "type":"number",
        "autoMigrations":{
          "autoIncrement":true
        }
      }
    }
  }
}

And before my express routes I create a middleware function that hooks on my models to the app.
app.use((req, res, next) => {
  let waterline = conf;
  Waterline.start(waterline, function(err, orm) {
    if(err) {
      console.error('Could not start up the ORM:\n',err);
      return process.exit(1);
    }
    app.models = {
      User: Waterline.getModel('user', orm)
    }
    next();
  });
});

The result in use.
app.get('/', function (req, res) {
  app.models.User.findOne({ id: 2 }).exec(function (err, result){
    console.log('err:', err);
    console.log('result:', result);
    res.json(result);
  });
});

With some tweaking you can house your models in external files and autoload them in. And swap out database details based on environment. Here is the configuration function I use.
const PGAdapter = require('sails-postgresql');

function createWaterlineConf(db, models) {
  const defaults = {
    adapter:    'sails-postgresql',
    port: 5432,
    poolSize: 10,
    ssl: true
  };
  const databaseConf = Object.assign(defaults, db);

  const waterlineConf = {

    adapters: {
      'sails-postgresql': PGAdapter
    },

    datastores: {
      default: databaseConf
    },

    models: models,

    defaultModelSettings: {
      primaryKey: 'id',
      datastore: 'default',
      attributes: {
        id: { type: 'number', autoMigrations: { autoIncrement: true } },
      }
    }

  };
  return waterlineConf;
}

module.exports.createWaterlineConf = createWaterlineConf;

A: I am using sails.js, but I wouldn't put it into a Lambda function as it is too fat, needs seconds to boot and that works against the usage profile of a Lambda function. Of course, I understand that it would be nice to have your already implemented models and services in a Lambda function - I will also run into this.
If you still want to try it, you can

*

*strip down the Lambda sails.js (disable as much as possible in .sailsrc and disable as many middlewares as possible) and

*try to use Lambda's same-container strategy (Example how MongoDB does it)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why can I still access vector data after resizing? The following code doesn't throw an error:
int main()
{
typedef std::vector<int> intstack;

intstack mystack;

mystack.push_back(7);
mystack.push_back(8);
mystack.push_back(9);

mystack.pop_back();
std::cout << mystack.size(); //prints 2
std::cout << mystack[2]; // prints 9
return 0;
}

I would have thought the line std::cout << mystack[2] would throw an error because the vector has been resized by the pop_back operation. Why is the data still accessible? Is it because the data in the underlying array is still there and the vector pop_back operation only modifies the iterators?

A: std::vector operator[] does not perform range checks.
the at() member function does.
Your line std::cout << mystack[2] has undefined behavior.


text:
Q: How to inject a dependency into a custom attribute with StructureMap (4.0)? MVC5 project I'm pretty much wanting to do what this guy describes (passing a dependency into a custom attribute):
How to use dependency injection with an attribute?
however, I want to do it with StructureMap 4.0, not Ninject.
My project is set up with the custom attribute in my Data Layer dll, and I already have StructureMap installed and working with my controllers in my UI Layer.
I have determined I probably have to do Setter injection with StructureMap:
http://docs.structuremap.net/ConstructorAndSetterInjection.htm
however, it is not working correctly for me with my custom attribute in the data layer.
I figured that in order to make things work that I should install Structuremap into my data layer as well, and put this in IoC.cs:
        public static IContainer Initialize()
    {
        Container container = new Container(x =>
        {

            x.ForConcreteType<My_AuthorizeADAttribute>().Configure.Setter<My_AppDataContext>().IsTheDefault();  //not sure about this line
        });

        return container;
    }

oh.. my custom Attribute:
public class My_AuthorizeADAttribute : AuthorizeAttribute
{
    public IMy_Data_Context _dataContext;

    [SetterProperty]
    public IMy_Data_Context DataContext
    {
        get { return _dataContext; }
        set { _dataContext = value;  }
    }

Is this the right thing to do?  I'm thinking I left out a step.  (but then again, I haven't really set up Structuremap on multiple dlls in the same project.  Wondering if multiple projects with StructureMap needs something more.
At present, the app will run, but the Property in the Custom Attribute won't populate.
Update:  This StackOverflow question has been helpful:
How do I get StructureMap working with an AngularJs / MVC5 and WebApi2 web project

A: It is indeed the line you are unsure of.
x.ForConcreteType<My_AuthorizeADAttribute>().Configure.Setter<My_AppDataContext>().IsTheDefault();  //not sure about this line

This should instead specify what you actually want to inject into the setter on instantiation, like so:
x.ForConcreteType<My_AuthorizeADAttribute>().Configure.SetterDependency<IMy_Data_Context>().Is(new My_AppDataContext());

This will inject your concrete implementation of IMy_Data_Context, My_AppDataContext, into the type My_AuthorizeADAttribute. If you had multiple properties of the IMy_Data_Context type on your attribute you may need to worry about how to assign multiple defaults using the default syntax you were working off of, but that doesn't appear to be your use case.

A: I responded to you in the StructureMap Gitter room, but I'll do it here too. Are you calling Container.BuildUp(object) against your attribute object after it's created? StructureMap isn't building the attribute objects at runtime, it can only apply setters afterward. See the bottom section of this: http://structuremap.github.io/setter-injection/ for more information on BuildUp().

A: ok, after much research, apparently this is the best option for me now. it means the Attribute has a dependency on StructureMap, but then again, [SetterProperty] would have it as well.
Asp.Net MVC Custom Validation Attribute With StructureMap


text:
Q: can a python dictionary replace only what it finds? The following works fine:
line = "Hello %(firstname)s %(lastname)s, how are you?"
print line % dict (firstname = "Mike", lastname="Kane")

and prints:

Hello Mike Kane, how are you?

But if I don't have a value for lastname, I still want this to work:
line = "Hello %(firstname)s %(lastname)s, how are you?"
print line % dict (firstname = "Mike")

I want it to just ignore the lastname key and print:

Hello Mike , how are you?

A: You can use a defaultdict
from collections import defaultdict

line = "Hello %(firstname)s %(lastname)s, how are you?"
print line % defaultdict(str, firstname = "Mike")

Explanation: the first argument to the defaultdict initializer must be a callable that returns the default value. str is callable that returns an empty string (try str()).

A: You can use make a subclass of dictionary that supplies defaults for missing values:
>>> class Dict(dict):
        def __missing__(self, key):
            # supply a default value for a given key
            return key

>>> d = Dict(firstname = 'Mike')
>>> print "Hello %(firstname)s %(lastname)s, how are you?" % d
Hello Mike lastname, how are you?

The techniques gives you complete control over what is returned.  Here are some variants:
return '--missing--'       returns a default string
return key.upper()         highlight the missing key
return ''                  return an empty string

A: class MyDict(dict):
    def __missing__(self, key):
        return ""
print("Hello %(firstname)s %(lastname)s, how are you?"
      % MyDict(firstname = "Mike"))

prints
Hello Mike , how are you?


text:
Q: Selecting with PreparedStatements in clojure I am using Clojure.java.jdbc for database operations.
I want to select some rows using Clojure prepared statements.
I did it like this,
(jdbc/db-do-prepared db "select * from `users` where name='?'" ["hari"])

but throws an error like,
Caused by: java.sql.BatchUpdateException: Can not issue executeUpdate() for SELECTs

So what can I do about it?

A: db-do-prepared can only return an update count, and  is meant for doing prepared mutations like update. It doesn't accept queries that return a resultset, like select.
In [org.clojure/java.jdbc "0.3.3"], the latest version, query is used for queries that return a resultset. For prepared values, quoting within the query is not necessary. Also, in the new version, you don't need a vector with values.
(jdbc/query db
            ["select * from users where name=? and surname=?" "hari" "krishnan"])


text:
Q: How To send a GenericList Items To Controller I Have a Modle like:
public class Invoice
{
int Code{get;set;}
List<InvoiceItem> InvoiceItems{get;set;}
}

I fill InvoiceItems in a Table and  I want Get Table Item as InvoiceItems in Controller
  [HttpPost]
        public virtual ActionResult Create(Invoice model)
        {
           //Save Invoice
            return View();
        }

How Can I fill InvoiceItems and send it to controller?

A: The outcome of your html should look something like this

    <input type="text" name="Code" value=""/>
    ...

                #
                Name

                1
                <input type="hidden" name="InvoiceItems[0].Name" value="InvoiceItem1"/>

                2
                <input type="hidden" name="InvoiceItems[1].Name" value="InvoiceItem2"/>

                3
                <input type="hidden" name="InvoiceItems[2].Name" value="InvoiceItem3"/>

    <button type="submit">Submit</button>
</form>

This way you can use plain form submission or ajax
// assuming you have only one form. otherwise use more specific selector
var $form = $("form");
var data = $form.serializeArray();
var url = $form.attr("href") || document.URL;
$.post(url, data, yourCallbackFunction);

The rest is done by ModelBinder. The key part is to maintain InvoiceItems indexes. They must start from 0 and be sequential. i.e. 0,1,2,3 etc.. If you skip some index, modelbinder will end binding your list where indexes are broken.

A: lists can be represented by quasi-2-dimensional-arrays:
$arr =
    array(
        array(
            {
                "key":"value",
                "key2":"value2"
            },
            {
                "key":"value",
                "key2":"value2"
            }
        ),
        array(
            {
                "key":"value",
                "key2":"value2"
            },
            {
                "key":"value",
                "key2":"value2"
            }
        )
    );

(json_encode)
can be read e.g. with $val = $arr["0"]["0"]["key2"];
this is just an example > use and combine Array-, Object- and Json-Syntax to get your list match your needs. working with json is very handy and features very "sourced" and object-oriented coding and easy data handling.
ps: to me your question seems rather unclear, dont know what you are exactly aiming at...


text:
Q: Flask-SQLAlchemy connect to RDS-proxy over IAM I have an application which needs to connect to and RDS (postgres) proxy with IAM. It makes use of the create_app method.
def create_app():
    connex_app = connexion.App(__name__, specification_dir=base_apispec_dir)
    connex_app.add_api("swagger.yaml", strict_validation=True)

    app = connex_app.app
    app.config.from_object(get_configuration())

    ma.init_app(app)
    db.init_app(app)

    return connex_app

In this post there is an example of how to do this with SQLalchemy, but how do we connect with Flask-SQLAlchemy. In the example they use the @event.listen_for() event from SQLalchemy, but for that I need the engine, which I do not have.
It is possible to get it from the SQLalchemy object, but this gives to following error: No application found. Either work inside a view function or push.
Does anyone know how to make this connection working so the IAM-token can be refreshed every time it expires or just before that?


text:
Q: How does a process terminate after it tries to execute an illegal instruction? When a process executes an illegal instruction (like division by zero, or trying to access a forbidden memory space), this is detected by the CPU, then the
CPU saves what it has to save and changes the IP (instruction pointer) to the adress of the OS routine which is in charge of that particular error. Then the process abnormally terminates (or not?).
I would like to know two things:
1. Does the process that tries to execute illegal instruction always abnormally terminate?
2. Is the termination carried out by the OS or CPU?

A: *

*No.

*Exception occurs in CPU, then CPU transfer the control to OS.

We call this event an "exception". DivisionByZero is a typical exception.
CPU operates with opcodes, not with complete process/software. OS transfers
the next opcode to the CPU. If the CPU response is an exception, OS handles what will follow next: termination, or run forward. Also process can set up OS to manage the exceptions itself, in this case the CPU exception received by the OS and forwarded to process, and process can manage the next step.
But this is a very composite topic, hard to sum it in few words.


text:
Q: Как вывести ListView с картинками из базы данных SQLite? В приложении Android есть база SQLIte, в которой хранятся данные в 4 столбцах, по примеру: "_id", "https://example.com/dataimage/136.970.jpg", "text1", "text2".
Естественно, данные в каждой строке относятся друг к другу. Нужно из этих данных собрать ListView, чтобы каждый пункт содержал в себе свою картинку из колонки, где указан адрес картинки, типа - "https://example.com/dataimage/136.970.jpg".
Выводить из SQLite cursor и собирать адаптером text1 и text2 это просто, а вот как быть с картинками?
Адрес картинки, а также text1 и text2 я получаю из json, распарсивая его AsyncTask и записывая в SQLite.
Прошу вас просто намекнуть мне - где искать, и как это проще реализовать.
Спасибо.

A: Вам нужна одна из библиотек для загрузки-кэширования-отображения картинок из сети. Например UIL или Picasso
В первом случае код будет такой:
ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleton instance
imageLoader.displayImage(imageUri, imageView);

Во втором так:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);


text:
Q: Which driver messes with media keys on Dell 9550? System info
Dell XPS 15 9550 with Windows 10 19043.
Problem
I made the mistake of unnecessarily updating drivers with the program Snappy Driver Installer. It changed about 30 drivers. The problem is that the media keys — the keys on the function row, F1-F12 — no longer work properly. This shows itself in 4 ways:

*

*using volume keys no longer shows a volume popup window.

*using screen brightness keys no longer shows a brightness popup
window.

*the brightness keys change the brightness in large, discrete
steps of 10% (before it was a smooth change). sometimes when pressing the brightness keys the right-click
a popup menu appears.

*pressing the play/pause, next or previous buttons no longer
shows a media popup.

Some wrong driver causes the problem. Which one is it?
Attempted solutions
Already tried using Dell SupportAssist, Dell Update, Windows Update. Tried reinstalling HID, display, Realtek audio drivers.

A: First, please don't ever use that kind of shitty software/driver updater, always use Windows/Manufacturers.
Try to use System Restore. If it is disabled or you don't have a valid restore point, try to uninstall Snappy Driver Installer from Control Panel/Programs and Features.

*

*If you see anything weird or related to that shit as drivers, go
ahead and remove all you can find installed on the same date.

*Restart Windows, and let it load default Windows 10 drivers.

*Then go this.

*Register/Login and download the proper drivers and tools for your
device.

If that doesn't work, backup all your stuff, and reinstall with a clean Windows 10 using Create Windows 10 installation Media downloaded from Microsoft and using Rufus to create a Bootable Media (USB stick).

A: From your list of drivers, I would guess that these are to blame:
26. Logicool HID Keyboard Power Key
27. Logitech HID-Compliant Keyboard
28. Logicool HID Keyboard Consumer Controls
29. Logicool HID-compliant Cordless Mouse

These are all Logitech drivers, so pertain to the keyboard and mouse.
You need to remove them from the computer.

*

*Run Device Manager

*Click on the View menu and turn on "Show Hidden Devices"

*Expand the node that represents the type of device to uninstall,
perhaps "Human Interface Devices"

*Right-click the device entry for the device to uninstall and select Uninstall

*On the "Confirm Device Removal" dialog box, to also remove the
driver package in addition to uninstalling the device,
select "Delete the driver software for this device".

*Click OK.

*Repeat for other likely devices, keeping the mouse to the last.

*Reboot the computer - after this the keyboard and mouse might become
unusable, and in that case press once the Power button to shutdown
the computer.

*On the next boot Windows will install its own drivers.

*If the media keys are not yet functional, search for a driver on
the Dell website.

Create a System Restore point before starting, for backup.

A: Deleting the program DroidCam made the brightness and media popups reappear. This program had 2 audio device drivers. Strange, because the problem clearly started after using the driver program and I didn't do anything with or related to DroidCam in the meantime.


text:
Q: Find and manage all YouTube uploads by app My app upload videos to YouTube using "direct upload".
I use version 3.
i need that after the user uploaded his video I (app owner) and the user will be able to manage the videos (delete or edit the video), all this through the website of YOUTUBE(At the entrance to the URL,video list appear ). Currently only the user can edit or delete his videos.
In addition user will  find the videos (all videos uploaded by the app) by a URL (like a playlist) this list will Sort by views  or by rating.
Maybe the answer is a playlist, or channel???, whether i will use channel or playlist the users  Be allowed to add their videos to my playlist or to my channel? the users Be allowed to delete their video?
I received An answer, to my earlier questionbut, but I do not understand how categoryID is unique  to my application?

A: According to YouTube v2.0 You can delete it if you have access token and developer key.
Like this:
DELETE /feeds/api/users/default/uploads/VIDEO_ID HTTP/1.1
Host: gdata.youtube.com
Content-Type: application/atom+xml
Authorization: Bearer ACCESS_TOKEN
GData-Version: 2
X-GData-Key: key=DEVELOPER_KEY

So deleting by user request is not a problem. Deleting by your own need to be tested, it depends if you can obtain application access token using some kind of app secret.
Parhaps YouTube API v2.0 - OAuth 2.0 Authorization will give you the answer.


text:
Q: How to convert data type of different columns in a dataframe without using pandas or numpy functions? I'm new to python, and trying to work through some problems. I have a dataset.csv loaded to jupyter. After running through some functions I'm trying to change some columns from str to float, some from str to int and replace empty fields with None. I don't know how to apply it to the entire column. I think this code is just applying to the header, but it doesn't make sense because the actual values of the header are all strings, ie. age itself is a string, but I need the following rows of data to change the age column from str to float, or int.
I've done this:
[input]
new_type = []
last = str(last)
first = str(first)
sex = str(sex)
age = float(age)
sibsp = int(sibsp)
pclass = int(pclass)
fare = float(fare)
survived = int(survived)

#empty sting to none conversion
res = [str(i or None) for i in new_type]

[output]
[['Braund', ' Mr. Owen Harris', 'male', '22', '1', '3', '7.25', '0'], ['Cumings', ' Mrs. John Bradley (Florence Briggs Thayer)', 'female', '38', '1', '1', '71.2833', '1'], ['Heikkinen', ' Miss. Laina', 'female', '26', '0', '3', '7.925', '1']]

Any help or suggestions would be greatly appreciated.


text:
Q: XAMPP 1.7.3 and MSSQL 2016 connection I'm using an old version of XAMPP (1.7.3) to run a PHP old script on many MSSQL databases (2008,2012,2014).
when tried to connect MSSQL 2016 and 2017 I'm getting connection errors "Warning: mssql_connect() [function.mssql-connect]: Unable to connect to server"
the log doesn't have any data related to this error to debug.


text:
Q: How to explicitly write out the conditional expectation of the expected absorption time in first step analysis of a Markov Chain? A Markov chain $X_0,X_1,X_2,\ldots$ has the transition probability matrix
$$P=
        \begin{bmatrix}
        1 & 0 & 0 \\
        \alpha & \beta & \gamma \\
        0 & 0 & 1
        \end{bmatrix}
$$
where the first row corresponds to $X_n = 0$ and the second row $X_n = 1$, and third row corresponds to $X_n = 2$.
We define $T = \min\{n\geq0: X_n=0 \ \ \text{or} \ \ X_n = 2\}$
I would like to find $v= E[T|X_0=1]$.
This question appears in the textbook Stochastic Modeling by Pinksy, and their explanation is: "Weighting these contingencies by their respective probabilities, we obtain for $v$":
$$
v = 1+\alpha\cdot (0)+\beta\cdot (v)+\gamma\cdot (0) = 1+\beta v
$$
My question is two-fold:
1) What is the explicit notation for what is going on above? When they "weight" the probabilities, are they doing $E[T|X_0=1] = \sum_{k=0}^2 E[T|X_0=1, X_1=k]$?
2) What is a good way to see why there is the $1$ added above? I know the usual explanation is that the absorption time $T$ is always at least $1$, but how does it come out in the math?

A: The equation should be
$
\begin{align*}
E(T\mid X_0=1)&=\sum_{k=0}^2 E(T\mid X_0=1,X_1=k)P(X_1=k\mid X_0=1) \\
&=E(T\mid X_0=1,X_1=0)\alpha+E(T\mid X_0=1,X_1=1)\beta+E(T\mid X_0=1,X_1=2)\gamma.
\end{align*}
$
The first and last expectations on the right become $1$ since we have hit $\{0,2\}$ in one time step. For the second expectation on the right, think of $\{X_1,X_2,\dots\}$ as a new Markov chain starting at $1$. The transition probabilities from $X_1$ to $X_2$ to $X_3$ (and so on) do not depend on the original starting point $X_0$, but only on the new starting point $X_1$. Since $X_1$ is still $1$, the new Markov chain $\{X_1,X_2,\dots\}$ can be thought of as restarting original one $\{X_0,X_1,\dots\}$ and so $E(T\mid X_0=1,X_1=1)=1+E(T\mid X_0=1)$. The $1$ on the right is due to the fact that we have still expended one time unit to 'reset' our Markov chain. Putting everything together gives $$E(T\mid X_0=1)=1\alpha+(1+E(T\mid X_0=1))\beta+1\gamma=1+E(T\mid X_0=1)\beta.$$


text:
Q: How can I handle audio messages in pyTelegramBotAPI? I'm using pyTelegramBotAPI as framework to create a telegram bot.
I'm having some troubles with handle audio messages and I can't understand where I am wrong.
Here my code:
# If user send an audio and it's a private chat
@bot.message_handler(content_types=["audio"])
def react_to_audio(message):
    if message.chat.type == "private":
        bot.reply_to(message, """What a nice sound! I'm not here to listen to some audio, tho. My work is to wish a good night to all members of a group chat""")

Can anyone help me?

A: i don't specifically know well how to use pyTelegramBotAPI because also i got problems i couldn't solve so i abandoned it for python-telegram-bot which is better documented in comparison to pyTelegramBotAPI, has a bigger community, is more actively developed and also have an active Telegram group where you can directly ask for help from other developers using this wrapper.
So if you are interested to change to python-telegram-bot, the code for your bot would look something like this:
from telegram import Update
from telegram.ext import Updater, MessageHandler, Filters

token = "" #Insert your token here

def message_handler(update, context):
    update.message.reply_text("Hello")

def audio_handler(update, context):
    if update.message.chat.type == "private": #Checks if the chat is private
        update.message.reply_text("What a nice sound! I'm not here to listen to some audio, tho. My work is to wish a good night to all members of a group chat")

def main():
    """Start the bot."""
    updater = Updater(token, use_context=True)

    # Get the dispatcher to register handlers
    dispatcher = updater.dispatcher

    # on noncommand i.e message
    # Use this if you want to handle also other messages
    dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, message_handler))

    dispatcher.add_handler(MessageHandler(Filters.audio & ~Filters.command, audio_handler))

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

if __name__ == '__main__':
    main()

Here are also some official examples of bots made with this wrapper and the that you can use to better understand the wrapper, if you want more info regard this feel free to DM me on telegram @Husnainn.


text:
Q: functions and if statements Does anyone know how I could echo rconresults and if its not rconresults to call rconresults1 or rconresults2? The only one that works at the moment is echo rconresults(); function at the bottom, I am new to this :P
<?php
define('INCLUDE_CHECK',true);
include("../classes/functions2.php");
include("../classes/functions.php");
require '../classes/q3status.php';
require '../classes/q3rcon.php';
include("rconform.php");
include("rconresults.php");
include("rconresults1.php");
include("rconresults2.php");
$theme = $_COOKIE['currenttheme'];?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"../templates/$theme/style.css\" media=\"screen\" />"; ?>

<?php
echo "
";
echo rconform();
echo '
close window';
echo "
";
echo rconresults();

?>

Rconresults calls this file and I have 3 with different requests
   <?php
    function rconresults() {
include "../classes/config_inc.php";
$server3 = mysql_real_escape_string($_REQUEST['rconserver']);
$say = mysql_real_escape_string($_REQUEST['say']);
echo "
";
if ($server3 != "") {
$server3 = addslashes($server3);
mysql_connect("$db_host", "$db_user", "$db_pass") or die(mysql_error());
mysql_select_db("$db_database") or die(mysql_error());
$result = mysql_query("select * from {$db_prefix}_servers where `id`='{$server3}'");
if (!$result) {
    die("No Server Available with id {$server3}");
}

$fields_num = mysql_num_fields($result);

// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry

$r = new q3rcon($row['ip'], $row['port'], $row['rconpass']);
$data = explode(" ", $say);
if ($data[0] == "clientkick" && count($data) > 2) {
    $data = explode(" ", $say, 3);
    $r->send_command("".$data[0]." ".$data[1]." \"".$data[2]."\"");
} else {
    $r->send_command("say " . $say);
}
$out = $r->get_response();

$out2 = explode("\n", $out);
echo "

";
if ($out == '') {
    echo "Command Sent!";
}
foreach($out2 as $line) {
    if ($line != '') {
        echo "".strip_gtlt(strip_colors($line))."
";
    }
}
echo "

";
}
echo "
";
    }
    ?>

I think you mean this? When you click the button then it restarts the map?
<?php
function rconform()
{
include("../classes/config_inc.php");
echo "<form method='post' action=''>

";
echo "

Run RCON Command

Server:

";
echo "<select name='rconserver'><option selected='selected'>Select</option>";
mysql_connect("$db_host", "$db_user", "$db_pass") or die(mysql_error());
mysql_select_db("$db_database") or die(mysql_error());
$sql="SELECT * FROM `".$db_prefix."_servers` where `Status`='Online' order by `order` ASC";
$result =mysql_query($sql);
while ($data=mysql_fetch_assoc($result)){
$svname = $data['name'];
$svname = stripslashes($svname);
$svid = $data['id'];
if ($svname == $server3) {
$selected = "selected=\"$svname\"";
} else {
$selected = "";
}
echo "<option value =\"$svid\" $selected>$svname</option>";
}
echo "</select>

Console:

<input type='text' placeholder='Say something..' name='say'>

<input type='submit' value='Execute'>

</form>";
echo "</select>

Change Map:

<input type='text' placeholder='mp_harbor' name='map'>

<input type='submit' value='Execute'>

</form>";
echo "</select>

<input type='submit' value='Restart Map' name='map_restart'>

</form>";

}

?>

A: It depends what rconresults is returning.
If it's a boolean condition, the code below will run rconresults if it's true, and run rconresults2 if it's false.
It will all depend on the condition.
if ( $_REQUEST['option'] == "rconresults2" ) {
    echo rconresults2();
} else {
    echo rconresults();
}

Update.

A: I think you are a bit confused about how includes work. It seems that you want something like this:
if (some condition {

   include("rconform.php");

} else if (some other condition) {

   include("rconresults.php");

} else if ( a different condition) {

    include("rconresults1.php");

} else {
    include("rconresults2.php");
}

But you didn't say what the conditional was. If you could tell us a bit more about what you want to accomplish, we could provide some guidance.


text:
Q: linux cluster + want to unlock but from clusvcadm -l I get locked I have linux cluster
when I do
  clusvcadm -u

I get
Resource groups unlocked
but in order to verify I do
clusvcadm -S

but I get:
Resource groups locked
why?
in fact the linux is realy lock -:(


text:
Q: Inject a splitter that never aggregates Camel ver 2.17.3:  I want to insert a splitter into a route so that split messages remain split. If I have a "direct" route with a splitter, when control returns from the inner route, I no longer have split messages, only the original.
from("direct:in")
.transform(constant("A,B,C"))
.inOut("direct:inner")
.log("RET-VAL: ${in.body}");

from("direct:inner")
.split()
.tokenize(",")
.log("AFTER-SPLIT ${in.body}")
;

Based on the answer to a similar question, and Claus's comment below, I tried inserting my own aggregator and always marking the group "COMPLETE". Only the last (split) message is being returned to the outer route.
from("direct:in")
.transform(constant("A,B,C"))
.inOut("direct:inner")
.log("RET-VAL: ${in.body}");

from("direct:inner")
.split(body().tokenize(","), new MyAggregationStrategy())
.log("AFTER-SPLIT ${in.body}")
;

public static class MyAggregationStrategy implements AggregationStrategy
{
  @Override
  public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
    System.out.println("Agg called with:"+newExchange.getIn().getBody());
    newExchange.setProperty(Exchange.AGGREGATION_COMPLETE_CURRENT_GROUP, true);
    return newExchange;
  }
}

How do I get the messages to stay split, regardless of how routes are nested etc.?

A: See this EIP
http://camel.apache.org/composed-message-processor.html
with the splitter only example.
And in the AggregationStrategy you combine together all those splitted sub-messages into one message which is the result you want, eg the outgoing message of the splitter when its done. How you do that depends on your messages and what you want to keep. For example you can put together the sub messages in a List or maybe its XML based and you can append the XML fragments, or something.


text:
Q: Angular - How to import googleapis library? I'm trying to incorporate the Google Drive API into one of my projects. The Node.js quick start guide requires me to import file-reading and googleapis libraries. However, when I try to do so, I run into issues when importing it into app.module.ts or any components:
Components import code:
import { Injectable } from '@angular/core';
import {google, drive_v3} from 'googleapis'
const drive = google.drive({version: 'v3'});
@Injectable({
  providedIn: 'root'
})
export class SubscriptionService {
  constructor () {}
}

Error:
ERROR in ./node_modules/google-auth-library/build/src/auth/googleauth.js
Module not found: Error: Can't resolve 'child_process' in '...\node_modules\google-auth-library\build\src\auth'
ERROR in ./node_modules/google-auth-library/build/src/crypto/node/crypto.js
Module not found: Error: Can't resolve 'crypto' in '...\node_modules\google-auth-library\build\src\crypto\node'
ERROR in ./node_modules/jwa/index.js
Module not found: Error: Can't resolve 'crypto' in '...\node_modules\jwa'
ERROR in ./node_modules/google-auth-library/build/src/auth/googleauth.js
Module not found: Error: Can't resolve 'fs' in '...\node_modules\google-auth-library\build\src\auth'
ERROR in ./node_modules/google-p12-pem/build/src/index.js
Module not found: Error: Can't resolve 'fs' in '...\node_modules\google-p12-pem\build\src'
ERROR in ./node_modules/googleapis-common/build/src/discovery.js
Module not found: Error: Can't resolve 'fs' in '...\node_modules\googleapis-common\build\src'
ERROR in ./node_modules/gtoken/build/src/index.js
Module not found: Error: Can't resolve 'fs' in '...\node_modules\gtoken\build\src'
ERROR in ./node_modules/agent-base/patch-core.js
Module not found: Error: Can't resolve 'https' in '...\node_modules\agent-base'
ERROR in ./node_modules/https-proxy-agent/index.js
Module not found: Error: Can't resolve 'net' in '...\node_modules\https-proxy-agent'
ERROR in ./node_modules/google-auth-library/build/src/auth/googleauth.js
Module not found: Error: Can't resolve 'os' in '...\node_modules\google-auth-library\build\src\auth'
ERROR in ./node_modules/google-auth-library/build/src/auth/googleauth.js
Module not found: Error: Can't resolve 'path' in '...\node_modules\google-auth-library\build\src\auth'
ERROR in ./node_modules/gaxios/build/src/gaxios.js
Module not found: Error: Can't resolve 'stream' in '...\node_modules\gaxios\build\src'
ERROR in ./node_modules/google-auth-library/build/src/auth/oauth2client.js
Module not found: Error: Can't resolve 'stream' in '...\node_modules\google-auth-library\build\src\auth'
ERROR in ./node_modules/googleapis-common/build/src/apirequest.js
Module not found: Error: Can't resolve 'stream' in '...\node_modules\googleapis-common\build\src'
ERROR in ./node_modules/jws/lib/data-stream.js
Module not found: Error: Can't resolve 'stream' in '...\node_modules\jws\lib'ERROR in ./node_modules/jws/lib/sign-stream.js
Module not found: Error: Can't resolve 'stream' in '...\node_modules\jws\lib'ERROR in ./node_modules/jws/lib/verify-stream.js
Module not found: Error: Can't resolve 'stream' in '...\node_modules\jws\lib'ERROR in ./node_modules/https-proxy-agent/index.js
Module not found: Error: Can't resolve 'tls' in '...\node_modules\https-proxy-agent'

How do I properly import the googleapis library in Angular? I've tried adding the following script import to index.html as lots of people online suggest, but it doesn't seem to work (see comments).
<script src="https://apis.google.com/js/api.js"></script>
I have also made sure to perform the following installs:
npm install --save @types/gapi
npm install --save @types/gapi.auth2
npm install --save @types/gapi.client.drive

A: googleapis (and google-auth-library) is a NodeJS library. You can't use it in front-end projects as is. There're some workarounds - see https://medium.com/angular-in-depth/google-apis-with-angular-214fadb8fbc5 (but I didn't try it personally so can't recommend).
The other lib you mentioned - https://apis.google.com/js/api.js - is the right one, it's for front-end, but it's not modularized, it's just one big script that you need to load via script tag. That's because you cannot import it via import. To make TS compiler happy (providing you already installed types @types/gapi*) add this import in a file where you accessing gapi global object:
/// <reference types="gapi.client. drive" />


text:
Q: Hyperbolic structures on once punctured tori I've been working on a problem about billiards in ideal hyperbolic polygons and I was thinking about how the problem for ideal quadrilaterals relates to closed geodesics on once punctured tori.
My questions have to do with constructing a general hyperbolic punctured torus.  I would like to think of it as the quotient of an ideal quadrilateral. I have not been able to find a description of the space of hyperbolic structures on the once punctured torus from this perspective.
The tori that come up in the problem are constructed as follows:  Let $Q$ be an ideal quadrilateral.  Let $L_1$ be the geodesic orthogonal to a pair of opposite sides $a_1$ and $a_2$.  Let $L_2$ be the geodesic orthogonal to the other pair of opposite sides $b_1$ and $b_2$.  Now let $A$ be the loxodromic isometry with axis $L_1$ taking $a_1$ to $a_2$ and let $B$ be the loxodromic isometry with axis $L_2$ taking $b_1$ to $b_2$.  Let $G$ be the group of isometries generated by $A$ and $B$.  Then the quotient of the hyperbolic plane by $G$ gives us a punctured torus.  With this construction, there is a positive real number which determines the hyperbolic structure:   the length, $y$, of the geodesic segment $L_1 \cap Q$, which determines the shape of $Q$.  I understand that the space of hyperbolic structures on a once punctured torus has two real dimensions and can be identified with the upper half plane.  This construction gives us hyperbolic structures parametrized by a single positive real number $y$.  I guess that it corresponds to the positive imaginary axis in the upper half plane.
Question 1:  Does the set of hyperbolic once punctured tori constructed as above have a name?
My next question has to do with what the other hyperbolic structures look like when thinking of them as the quotient of an ideal quadrilateral.  Instead of just using the isometries $A$ and $B$ above, we can compose $A$ with a loxodromic isometry $C$ having axis $a_2$ (which is a side of $Q$).  Call this composition $A'$.  We want a loxodromic isometry $B'$ that identifies $b_1$ with $b_2$ such that the commutator of $A'$ and $B'$ is parabolic.  My guess is that, given $A'$, there is a unique $B'$ such that the commutator of $A'$ and $B'$ is parabolic.  This would mean that the hyperbolic structures could be parametrized by two real numbers $x$ and $y$.  The number $y$ is a positive real number that determines the shape of $Q$ and the number $x$ is a real number that determines the translation length of the isometry $C$.
Question 2:  Does this make sense and, if so, is it a reasonable way to think about the space of hyperbolic structures on once punctured tori?

A: Question 1: I would call them "rectangular", because they are conformally equivalent to gluing opposite sides of a Euclidean rectangle by Euclidean translation and then removing the point obtained by gluing the four corners.
Question 2: I believe this is true. The way to prove it would be to cut the quadrilateral into two ideal triangles. Each of side of each ideal triangle has a "foot" which is the base of the perpendicular ray going out to the opposite ideal vertex. For each of the three matched pairs of sides of this pair of triangles you have a "shearing coordinate" which is a real number giving the displacement from the foot of that side in one triangle to the foot of that side in the other triangle. This gives three shearing coordinates $a$, $b$, $c$, and the "completeness condition" or "parabolicity condition" is simply the equation $a+b+c=0$, and this is well known to be a parameterization of the Teichmuller space of the punctured torus by a plane in $a$, $b$, $c$ space (see for instance Penner's paper "The decorated Teichmüller space of punctured surfaces" which may contain this exact statement but if not contains the ideas needed to verify it).
Edit: Here's a bit more detail, since this seems pretty simple. Choosing the shape of the quadrilateral determines and is determined by one of the coordinates $a$. Then, having chosen that, choosing the translation along your side labelled $a_2$ determines and is determined by the second coordinate $b$. Finally, and the third coordinate $c=-a-b$ determines and is determined by the translation along your side labelled $b_2$.


text:
Q: Google Calendar API Event color not set Using following request the event is created like a charm but the color is not set. Does anyone see what I'm doing wrong?
{
   "summary":", Meier, Test Musterfirma GmbH",
   "location":"Musterstrasse 8, 8000 Zurich",
   "description":"Test Musterfirma GmbH",
   "start":{
      "dateTime":"2016-03-31T11:00:00",
      "timeZone":"Europe/Zurich"
   },
   "end":{
      "dateTime":"2016-03-31T12:00:00",
      "timeZone":"Europe/Zurich"
   },
   "visibility":"private",
   "ColorId":"10",
   "transparency":"opaque"
}


text:
Q: iOS Bonjour Over the Internet I know that iOS's Bonjour implementation (NSNetService, NSNetServiceBrowser) work out of the box on local networks.
The documentation says it is possible to set up a Bonjour DNS server to allow connecting users over the internet, so my questions are:

*

*What is the Bonjour DNS server interface? is there a sample I can start from?

*Does the DNS Server responsible for the initial hand-shaking\connection of the peers and the rest (send\rec data) will be directly between the peers?

*Does the DNS Server provide a NAT hole-punching mechanism?

Thanks!

A: Bonjour local service discoveryis based on "multicast DNS". whenever some client wants to find out anything about the network or services on the network it uses the multicast address 224.0.0.251, meaning only clients within that multicast group can use bonjour together.
the 244.0.0/24 IP-Address space is defined as "Local Network Control Block" by RFC5771 and will not be forwarded out of your local network.
BUT really, Bonjour is just a DNS-based method - you can tell NSServiceBrowser to search in a non-local domain, which just requires the DNS server to respond to specific requests (as described in Manually Adding DNS-SD Service Discovery Records to an Existing Name Server)
This allows service discovery over the internet and even service registration if you get DNS Update working (Setting up a Bonjour Name Server), but nothing more - you have to care about hole-punching yourself.

So get yourself a BIND-server and start trying ;)


text:
Q: Jackson JsonMappingException: Can not deserialize instance of class out of START_ARRAY token Unable to read value of image arr. How can I read the value of Image arr using jackson json mapper .
JSON
{
  query: "rann of kutch",
  response: {
    image: [
      "http://www.ouralaskancruise.com/wp-content/uploads/2010/05/Princess_Denali_Express_Rail.jpg"
    ],
    source: "chatbot",
    text: "Very interesting.",
    time: 5572
  },
  uid: "11222"
}

Code:
String responseJson = null;
            try {
                responseJson = Utils.executeHttpGet(url);
            } catch (Exception e) {

                if (e != null) {
                    error = e.getMessage();
                    e.printStackTrace();
                }

            }

Classes
public class ResponseDetails {

    public String query;
    public String uid;
    public Response response;

}
public class Response {
    public Image image;
    public String source;
    public String text;
    public long time;

}
public class Image {
    public ArrayList<String> urls;
//public    String url;
}

Exception:
11-07 18:48:34.321: W/System.err(15921): com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.Travel.TravelChat.DataClasses.Image out of START_ARRAY token
11-07 18:48:34.321: W/System.err(15921):  at [Source: java.io.StringReader@417fbc70; line: 4, column: 5] (through reference chain: com.Travel.TravelChat.DataClasses.ResponseDetails["response"]->com.Travel.TravelChat.DataClasses.Response["image"])
11-07 18:48:34.341: W/System.err(15921):    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:575)
11-07 18:48:34.341: W/System.err(15921):    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:569)
11-07 18:48:34.341: W/System.err(15921):    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromArray(BeanDeserializerBase.java:1121)
11-07 18:48:34.341: W/System.err(15921):    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:148)
11-07 18:48:34.341: W/System.err(15921):    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:123)
11-07 18:48:34.341: W/System.err(15921):    at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:464)
11-07 18:48:34.341: W/System.err(15921):    at com.fasterxml.jackson.databind.deser.impl.FieldProperty.deserializeAndSet(FieldProperty.java:107)
11-07 18:48:34.341: W/System.err(15921):    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:295)
11-07 18:48:34.341: W/System.err(15921):    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
11-07 18:48:34.341: W/System.err(15921):    at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:464)
11-07 18:48:34.341: W/System.err(15921):    at com.fasterxml.jackson.databind.deser.impl.FieldProperty.deserializeAndSet(FieldProperty.java:107)
11-07 18:48:34.341: W/System.err(15921):    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:295)
11-07 18:48:34.341: W/System.err(15921):    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
11-07 18:48:34.341: W/System.err(15921):    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
11-07 18:48:34.341: W/System.err(15921):    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
11-07 18:48:34.341: W/System.err(15921):    at com.Travel.TravelChat.Helpers.Utils.readResponseDetailsJson(Utils.java:97)
11-07 18:48:34.341: W/System.err(15921):    at com.Travel.TravelChat.Helpers.GetResponseTask.doInBackground(GetResponseTask.java:46)
11-07 18:48:34.341: W/System.err(15921):    at com.Travel.TravelChat.Helpers.GetResponseTask.doInBackground(GetResponseTask.java:1)
11-07 18:48:34.341: W/System.err(15921):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
11-07 18:48:34.341: W/System.err(15921):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-07 18:48:34.341: W/System.err(15921):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-07 18:48:34.341: W/System.err(15921):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
11-07 18:48:34.341: W/System.err(15921):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-07 18:48:34.341: W/System.err(15921):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-07 18:48:34.341: W/System.err(15921):    at java.lang.Thread.run(Thread.java:856)
11-07 18:48:34.341: W/dalvikvm(15921): threadid=11: thread exiting with uncaught exception (group=0x40c18a68)
11-07 18:48:34.351: E/AndroidRuntime(15921): FATAL EXCEPTION: AsyncTask #1

I have gone through the following links :
JsonMappingException: out of START_ARRAY token
Cannot deserialize instance of object out of START_ARRAY token in Spring 3 REST Webservice
Please help .
Thanks!

A: If you want to keep you object model, your json should look like this :
{
    query: "rann of kutch",
    response: {
        image : {
            urls: ["http://www.ouralaskancruise.com/wp-content/uploads/2010/05/Princess_Denali_Express_Rail.jpg"]
        },
        source: "chatbot",
        text: "Very interesting.",
        time: 5572
    },
    uid: "11222"
}

edit
As the JSON can't be changed, like @Chaosit said, change your bean definition to
public class Response
{
    public List<String> image;
    public String source;
    public String text;
    public long time;
}

}

A: The problem is actually that you're trying to deserialize an instance of Image class when you have an array of strings. Try declaring a Response class in the following way:
public class Response {
@JsonProperty("image")
public List<String> images;
public String source;
public String text;
public long time;

}
You can find these annotations here: https://github.com/FasterXML/jackson-annotations

A: If , we send one object then no need JSON.stringifyIf else make an ajax call Like this to send group of objects.
data : "data=" + JSON.stringify(data)

then it works.


text:
Q: How to get multiple regex matches capture group I am trying to access all matches of my first capture group ([^ ]+) in an array so I can foreach it, however I don't see it in the output:
$input = "Row 1:
Computer: xxx
Last Heartbeat: 4/9/2020 11:27:24 AM

Row 2:
Computer: yyy
Last Heartbeat: 4/9/2020 11:27:37 AM"

$matches = ([regex]'Computer: ([^ ]+)').Matches($input)
$matches

Yields:
Groups   : {0, 1}
Success  : True
Name     : 0
Captures : {0}
Index    : 7
Length   : 13
Value    : Computer: xxx

Groups   : {0, 1}
Success  : True
Name     : 0
Captures : {0}
Index    : 66
Length   : 13
Value    : Computer: yyy

Admittedly I have a lot to learn about the data structures and how to access them.

A: Before we get to the real answer, please consider renaming your variables - both $Matches and $Input are automatic and can be overwritten by the runtime.

In order to grab the value of the first capture group, you'll want to address index 1 in the Groups property or index 0 in the Captures property of each match:
$string = "Row 1:
Computer: xxx
Last Heartbeat: 4/9/2020 11:27:24 AM

Row 2:
Computer: yyy
Last Heartbeat: 4/9/2020 11:27:37 AM"

$results = ([regex]'Computer: ([^ ]+)').Matches($string)
$results | ForEach-Object { $_.Groups[1].Value }
# or
$results | ForEach-Object { $_.Captures[0].Value }


text:
Q: Auto refresh in javascript I want to create a project which have a function that will refresh the browser automatically every 5 seconds . But I don't know what to do?
I know that I have to put code in a
Setinterval block like this:
setinterval(()=>{
// auto refresh code in here
}

A: As you say settimeout will only work once u need to define it simpe script (only)so everytime page load it works or better to increase intervel time some time due to network issue your page does not load properly your javascript doeasnot load also
<script type="text/javascript">
setTimeout(function(){
   window.location.reload(1);
}, 5000);
</script>


text:
Q: Getting user id from facebook I wonder is it still possible to get Facebook user ID if I got 'only' the user's profile (profile username/link)?
For instance:
https://www.facebook.com/zuck

I've tried to do this with SDK and Graph API but it seems that all previous solutions don't work. Could you please give me a hint? I would like to go further but I'm not sure which way is correct.

A: You can do it with Excel. I put the macros that I use. You have to put the name in the first column and it will generate the id in the second column when you run the GenerateFaceIds macro. (You need to be logged into Facebook in IExplorer)
Sub GenerateFaceIds()
  Dim total As Long
  total = 1

   Do Until IsEmpty(Cells(total, 1)) = True
   If (Cells(total, 2) = "") Then
       Call faceId(total)
    End If
    total = total + 1
   Loop

    MsgBox ("OK")
End Sub

Sub faceId(row As Long)
    On Error GoTo ErrHandler

    Dim appIE As Object
    Set appIE = CreateObject("internetexplorer.application")

    Dim id As String
    id = Cells(row, 1)

    With appIE
        .Navigate "https://www.facebook.com/" + id
        .Visible = False
    End With

    Do While appIE.Busy
    DoEvents
    Loop

    Text = appIE.Document.Body.innerHTML

    posinter = InStr(Text, "profile_owner")
    profile_owner = Mid(Text, posinter + 16, 15)

    posinter2 = InStr(profile_owner, """")
    If posinter2 > 0 Then
        profile_owner = Left(profile_owner, posinter2 - 1)
    End If

    Cells(row, 2) = profile_owner

    appIE.Quit
    Set appIE = Nothing

ExitSub:

    Exit Sub

ErrHandler:
    'MsgBox "Something's wrong"

    appIE.Quit
    Set appIE = Nothing

    Resume ExitSub
    Resume

End Sub

Result:
zuck    4


text:
Q: Yii2 use runAction() within beforeAction method I have a MainController which extends Controller. All my app's controllers extend from MainController which includes various methods and properties which need to be accessible from any Controller.
Within my MainController is beforeAction, which does several things:

*

*Checks for redirects held in the database and performs them if the URL matches one in the DB.

*Generates <head> data for each controller

*Gets the language and country the user is looking at based on cookie and slug of the URL. (i.e. http://example.com/netherlands).

*Will render a generic page from a template if URL matches one from the database's pages table.

It's the last that I am struggling with. In my MainController I have this:
/**
* Before action, check all $this->before_actions satisfy. If no head_data provided, try and fill in some basics
*/
public function beforeAction( $action )
{

    // Run parent method first
    if (!parent::beforeAction($action))
        return false;

    // Check redirects
    $this->checkRedirects();

    if( $this->checkPages() )
    {

        // If not error page, loop through before methods
        if( $action->id !== 'error' )
        {

            // Loop through actions to peform and do them
            foreach ( $this->before_actions as $before_method )
                $this->$before_method();
        }
        return true;
    }

}

Where $this->checkPages() contains the following:
/**
* Check for pages
*/
public function checkPages()
{

    // Attempt to find page for this request
    $page = Page::find()->where( [ 'permalink' => trim( str_replace( getBaseUrl() , "", getCurrentUrl() ), "/" ) ] )->one();

    // If found, load it instead
    if( !empty( $page ) )
        return Yii::$app->runAction( "pages/show", [ 'id' => $page->id ] );

    // Else, return
    return true;

}

The issue I am having is that if I go to http://example.com/story, because there is no StoryController, the returns a 404 error although the action does run and the view "views/story/show" is output.
How can I prevent this?
EDIT:
To add, the log shows that it first says:
"Unable to resolve the request 'story/index'".
But then additional logs show:
"Route to run: pages/show" ... "Running action: app\controllers\PagesController::actionShow()"
..
Rendering view file: /Users/stefandunn/Documents/Local Machine Development/views/pages/show.php
So I am guessing it's the first log result causing the 404 status

A: Add one last route that can catch any pattern and redirect to custom action.
'urlManager' => [
    'class' => 'yii\web\UrlManager',
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        //...
        '<any:.*>' => 'site/index'
    ],
],


text:
Q: How to replace values in dataframe by id? df <- data.frame(id = 1:10, key = 1:10)
replace_key <- c(2,5)
replace_id <- c(9,3)

I want to replace the key values into the values in replace_key by replace_id
required effect:
id key
1 1
2 2
3 5
4 4
5 5
6 6
7 7
8 8
9 2
10 10

A: Assuming you have unique ids, then you can use match to find out the row index where the keys need to be replaced and then assign the replace_key to these positions for the key column. Corresponding elements will be replaced in order:
df$key[match(replace_id, df$id)] <- replace_key

df
#   id key
#1   1   1
#2   2   2
#3   3   5
#4   4   4
#5   5   5
#6   6   6
#7   7   7
#8   8   8
#9   9   2
#10 10  10

A: We can use mapply over the two vectors replace_id and replace_key find the respective key and assign the respective values with <<-
mapply(function(x, y) df$key[df$id == x] <<- y, replace_id, replace_key)

df
#   id key
#1   1   1
#2   2   2
#3   3   5
#4   4   4
#5   5   5
#6   6   6
#7   7   7
#8   8   8
#9   9   2
#10 10  10

A: One can also do this operation using dplyr package.
df %>% mutate(key = replace(key, match(replace_id, id), replace_key))

A: Here is a join option with data.table
library(data.table)
setDT(df)[data.frame(id = replace_id, val= replace_key), key := as.integer(val), on = "id"]
df
#    id key
# 1:  1   1
# 2:  2   2
# 3:  3   5
# 4:  4   4
# 5:  5   5
# 6:  6   6
# 7:  7   7
# 8:  8   8
# 9:  9   2
#10: 10  10


text:
Q: Apple keychain private/public key issue I accidentally deleted the private and public key pair of my certificate, but I can't find anything helpful to undo or add those to my certificate again.
Actually the developement certificate has expired, so i redownloaded the new one.
Than I wanted to add the private/public key to my new certificate. And there it happend, i deleted it.
How can I get these and set them to my actual certificate again.

A: I had this issue two days ago.
Open Keychain Access
What you have to do is make backups of all your certificates and then go and delete all the private and public keys and certificates on your machine relevant to apple.
Then in Keychain Access click on Keychain Access(Menu Bar) and in the menu select Certificate Assistant -> Request a certificate from a certificate authority.
Enter your details and make sure Saved to disk and Let me specify key chain pair is selected.
Save it.
On the next screen: These values must be:
Key Size: 2048 bits
Algorithm: RSA
You then need to log into the Provisioning Portal on apple's website and revoke all certificates there.
Then click distribution and say Add Certificate and select the file you created earlier.
You can then request all certificates again. Re-download all certificates, once you start opening the downloaded certificates your new key pair and certificate will be in Keychain Access.
If you have any questions check out http://developer.apple.com/ios/manage/distribution/index.action


text:
Q: Quartz : Dynamic job scheduling I'm scheduling quartz job dynamically and one of the issue that I came across is, I couldnt find an option to programmatically set the job to "PersistJobDataAfterExecution" and "DisallowConcurrentExecution" as both are annotation. Can any of you please suggest whats the equivalent while scheduling a job programmatically ( not declarative )

A: Since you are scheduling dynamically you should be passing a JobDetail to the Scheduler.  You should be able to create your own JobDetail implementation or extends the base implementation then return whatever you want for the corresponding methods.


text:
Q: Apache camel multicast FreeMarker I need to send two different XMLs (by FreeMarker) to two different endpoints.
i.e.
.to("freemarker:templates/xml1.ftl").to("file://C:\\testXmls1")

and
.to("freemarker:templates/xml2.ftl").to("file://C:\\testXmls2")

I had a look at the multicast() function but I don't know how to apply it when there are two .to
Could anyone please help me?

A: Yes you can specify multiple endpoints in the same .to(uri1, uri2, ...) then it becomes as a single "eip".
multicast()
  .to(uri1a, uri1b)
  .to(uri2a, uri2b)
.end() // to end multicast

Otherwise you would have to enclose it using the pipeline eip.
multicast()
  .pipeline().to(uri1a).to(uri1b).end() // to end this pipeline
  .pipeline().to(uri2a).to(uri2b).end() // to end this pipeline
.end() // to end multicast


text:
Q: I got a data(token from server) on one controller, and want to use that data(token) in another controller in Angular js? i am getting data from server in form of token in controller named "adminSearchCtrl" and want to use that token  to another controller named "adminViewCtrl"  how to do that??
adminSearchCtrl.js
$scope.getUserDetails = function(selectedUser){
        console.log(selectedUser, userToken.token);
        AdminSearchService.getUserDetails(selectedUser, userToken.token)
        .then(function(response){
            $scope.switchUserToken = response.switchToken.token;
        })
        .catch(function(err){
            $scope.error = err.message;
        });
    }

i want to use this token "$scope.switchUserToken" to another controller named "adminViewCtrl" I have put to $scope also but when i am using "$scope.switchUserToken" to my "adminViewCtrl" it is giving undefined can any body help me out??

A: Each controller has its own $scope, you can't access them from one to another, and you shouldn't.
The solution is to create a service to share this data between controllers. Here you have a JSBin with an example.


text:
Q: Screen brightness reverts to max after returning from `xset dpms` display suspend I'm running the openbox window manager and using this line in my autostart.sh to control display power management:
xset dpms 0 60 0

This works nicely, causing the display to suspend after 60 seconds of inactivity.
However, when the display reawakens in response to a mouse movement, keypress, etc., the screen is at full brightness.  This is wasteful of power and sometimes blinding.  If I use the laptop's brightness control keys (Fn + <-/->) to adjust the brightness, the first press will restore the brightness to what it was before the display was suspended.
What I'd like is for the screen to be at the pre-suspend brightness as soon as the display is reawakened, i.e. without having to hit one of the brightness control keys.
I'm running ubuntu 10.10 on an Acer Aspire 5742.

A: If you're setting the brightness beforehand (in autostart.sh for example), you could simply keep checking the brightness and setting it to whatever value you want in a continuous while true; loop.
This works only if you always a constant value (because if you decide you want it brighter for a bit, it will automatically dim).
Another possible (but not probable) option is if xset has some kind of callback or hook that you can grab a hold of. In that case you can make it call another script when it resumes.

A: A little late but this comes up as the top result on google. The following worked for me on Manjaro:
xbacklight -set 10

I wrote 2 scripts to help with brightness increase/decrease which you'll find here.


text:
Q: call function within ajax success I am trying to call a function from within an AJAX success handler, but it is being ignored
$.ajax({
    url: '../ajax/create_audit_standard_carosel.php',
    type:'POST',
    data: 'audit_id='+audit_id+'&user_id='+user_id,
    dataType: 'json',
    success: function(response){
        $('#num').html(response.standards_count);
        $('#standards_list').html(response.output);
            jQuery(function($) {
                $("#selected_standards").touchCarousel({
                   itemsPerPage: 4,
                   scrollbar: true,
                   scrollbarAutoHide: true,
                   scrollbarTheme: "dark",
                   pagingNav: false,
                   snapToItems: true,
                   scrollToLast: true,
                   useWebkit3d: true,
                   loopItems: false
                });
            });
     }, // End of success function of ajax form
    error:function (xhr, ajaxOptions, thrownError){
      alert(thrownError);
    }
}); // End of ajax call

The responses are correct and the contents of #standards_list are amended with the correct content so I know that the AJAX call is working correctly, but the function within the success call is completely ignored.

A: If you mean the function beginning directly after where you update the #standards_list element, it's because you are trying to bind to an event that has long since fired.
Passing a function to the global jQuery function is a shortcut for binding to the document.ready event. This event is fired when the page loaded and will not fire again as a result of the AJAX call.
Just remove the wrapping function and call the touchCarousel method after updating the #standards_list element, e.g:
$.ajax({
    url: '../ajax/create_audit_standard_carosel.php',
    type:'POST',
    data: 'audit_id='+audit_id+'&user_id='+user_id,
    dataType: 'json',
    success: function(response){
        $('#num').html(response.standards_count);
        $('#standards_list').html(response.output);
        $("#selected_standards").touchCarousel({
            itemsPerPage: 4,
            scrollbar: true,
            scrollbarAutoHide: true,
            scrollbarTheme: "dark",
            pagingNav: false,
            snapToItems: true,
            scrollToLast: true,
            useWebkit3d: true,
            loopItems: false
        });
    }, // End of success function of ajax form
    error:function (xhr, ajaxOptions, thrownError){
        alert(thrownError);
    }
}); // End of ajax call`


text:
Q: Error executing action `start` on resource 'service[nginx]' I am trying to install nginx on AMI machine using yum cookbook as dependancy.
This is what my nginx/recipe/default.rb looks like,
include_recipe "yum"

yum_repository 'epel' do
    mirrorlist 'http://mirrors.fedoraproject.org/mirrorlist?repo=epel-7&arch=$basearch'
    description 'Extra Packages for Enterprise Linux 7 - $basearch'
    enabled true
    gpgcheck true
    gpgkey 'https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-7'
end

yum_repository "nginx" do
    name 'nginx_repo'
    baseurl  'http://nginx.org/packages/rhel/7/$basearch/'
    enabled true
    gpgcheck true
    #gpgkey      'http://nginx.org/keys/nginx_signing.key'
    action :create
end

package "nginx" do

      action :install
end

template "nginx.conf" do
      source "nginx.conf.erb"
      path "#{node['nginx']['dir']}/nginx.conf"
      action  :create
      mode 0644
end

template "default.conf" do
      source "default.conf.erb"
      path "#{node['nginx']['dir']}/conf.d/default.conf"
      action :create
      mode 0644
end

service 'nginx' do
      #supports :restart => :true
      action [:enable, :start]
end

Also, I have added ' depends "yum" ' in metadata.rb
On trying to run 'sudo chef-client' on client server, I get the following error:
[2014-12-17T08:53:03+00:00] WARN:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
SSL validation of HTTPS requests is disabled. HTTPS connections are still
encrypted, but chef is not able to detect forged replies or man in the middle
attacks.

To fix this issue add an entry like this to your configuration file:

````
# Verify all HTTPS connections (recommended)
ssl_verify_mode :verify_peer

# OR, Verify only connections to chef-server
verify_api_cert true
````

To check your SSL configuration, or troubleshoot errors, you can use the
`knife ssl check` command like so:

```
knife ssl check -c /etc/chef/client.rb
```

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Starting Chef Client, version 11.16.4
resolving cookbooks for run list: ["yum", "nginx"]
Synchronizing Cookbooks:
  - nginx
  - yum
Compiling Cookbooks...
Converging 7 resources
Recipe: yum::default
* yum_globalconfig[/etc/yum.conf] action create
* template[/etc/yum.conf] action create (up to date)
 (up to date)
Recipe: nginx::default
* yum_repository[epel] action create
* template[/etc/yum.repos.d/epel.repo] action create (up to date)
* execute[yum-makecache-epel] action nothing (skipped due to action :nothing)
* ruby_block[yum-cache-reload-epel] action nothing (skipped due to action :nothing)
 (up to date)
* yum_repository[nginx_repo] action create
* template[/etc/yum.repos.d/nginx_repo.repo] action create (up to date)
* execute[yum-makecache-nginx_repo] action nothing (skipped due to action :nothing)
* ruby_block[yum-cache-reload-nginx_repo] action nothing (skipped due to action :nothing)
 (up to date)
* package[nginx] action install (up to date)
* template[nginx.conf] action create (up to date)
* template[default.conf] action create (up to date)
* service[nginx] action enable (up to date)
* service[nginx] action start

================================================================================
Error executing action `start` on resource 'service[nginx]'
================================================================================

Mixlib::ShellOut::ShellCommandFailed
------------------------------------
Expected process to exit with [0], but received '1'
---- Begin output of /sbin/service nginx start ----
STDOUT: Starting nginx: [FAILED]
STDERR: nginx: [emerg] invalid log level "pid" in /etc/nginx/nginx.conf:5
---- End output of /sbin/service nginx start ----
Ran /sbin/service nginx start returned 1

Resource Declaration:
---------------------
# In /var/chef/cache/cookbooks/nginx/recipes/default.rb

 53: service 'nginx' do
 54:   #supports :restart => :true
 55:   action [:enable, :start]
 56: end
 57:

Compiled Resource:
------------------
# Declared in /var/chef/cache/cookbooks/nginx/recipes/default.rb:53:in `from_file'

service("nginx") do
  action [:enable, :start]
  supports {:restart=>false, :reload=>false, :status=>true}
  retries 0
  retry_delay 2
  guard_interpreter :default
  service_name "nginx"
  enabled true
  pattern "nginx"
  cookbook_name "nginx"
  recipe_name "default"
end

Running handlers:
[2014-12-17T08:53:05+00:00] ERROR: Running exception handlers
Running handlers complete
[2014-12-17T08:53:05+00:00] ERROR: Exception handlers complete
[2014-12-17T08:53:05+00:00] FATAL: Stacktrace dumped to /var/chef/cache/chef-stacktrace.out

Chef Client failed. 0 resources updated in 2.259546529 seconds

[2014-12-17T08:53:05+00:00] ERROR: service[nginx] (nginx::default line 53) had an error:      Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received '1'
---- Begin output of /sbin/service nginx start ----
STDOUT: Starting nginx: [FAILED]
STDERR: nginx: [emerg] invalid log level "pid" in /etc/nginx/nginx.conf:5
---- End output of /sbin/service nginx start ----
Ran /sbin/service nginx start returned 1
[2014-12-17T08:53:05+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited  unsuccessfully (exit code 1)

A: The log is quite clear I think:
STDERR: nginx: [emerg] invalid log level "pid" in /etc/nginx/nginx.conf:5
your nginx.conf.erb file as somewhere a problem as it writes a log_level = pid instead of info/error.

A: This has not much to do with Chef. The important detail is:

nginx: [emerg] invalid log level "pid" in /etc/nginx/nginx.conf:5


text:
Q: What strategy to adopt to handle connection loss in WCF We have a lot(~15) WCF services on the same server. To connect to them, we have a class(which I named ClientConnection). This class manage all the different service on the client side to one particular server.
This class is responsible of creating the Channel(and their bindings) for every service that is asked(and cache them).
Now, what if the connection broke(let's imagine that one switch was down, or one server is too busy to answer), I would like to have a fallback strategy.
It means to detect that it brokes, and then try to restore the connection.
Currently I've a "watchdog" in this class that verify that it can reach the remote service, if not it raise an event.
When I get this event, what should I do? Refresh the channel? Dispose it and create a new one? Also, since I've 10-15 active services to the same server, should I restore them anyway?
I think I should not be the first one to have this issue, but I struggle to find a good strategy on how to manage all thoses issues

A: This sounds like a good fit for the Circuit Breaker Pattern
The long and short of it is that you essentially have something that tolerates failures with retry behaviour up to a point, and then has a back-off behaviour to gradually try to re-establish the connection.


text:
Q: Changes in AngularJS 1.3 I've just started with AngularJS and I was going through a set of Hello World examples and I can't get them running on branch 1.3 of the the library.
HTML code

    <input ng-model='greeting.text'>

{{greeting.text}}, World

controller.js
function HelloController($scope) {
  $scope.greeting = { text: 'Hello' };
}

This works fine in 1.2.
I couldn't find the changes that have been made in 1.3 that cause this.

A: Since Angular 1.3 beta 15, $controller does not look for controllers anymore on window. The AngularJS changelog explains in a clear manner what precisely has changed (scroll to the 'Breaking Changes' section).


text:
Q: Copy/Paste of a custom managed object in core data I am having a very hard time getting copy/paste to work on my custom managed object Person. The object contains properties and relationships. The object should provide the objectID. I intend to implement pasting generating a new object and then filling in the information from the copied Person.
Copying the objectID probably does work. I am certain that pasting does not work. I have the following methods implemented in my Person class, in an attempt to copy/paste an object:
#pragma mark --- Copy functionality

-(id)pasteboardPropertyListForType:(NSString *)type
{
    if ( [type isEqualToString:@"my.company.person"])
    {
        NSManagedObjectID *oid = self.objectID;
        NSURL *uidURL = [oid URIRepresentation];
        return [uidURL absoluteString];
    }
    return nil;
}

-(NSArray *)writableTypesForPasteboard:(NSPasteboard *)pasteboard
{
    return @[@"my.company.person"];
}

+ (NSPasteboardWritingOptions)writingOptionsForType:(NSString *)type pasteboard:(NSPasteboard *)pasteboard
{
    if ( [type isEqualToString:@"my.company.person"])
    {
        return NSPasteboardWritingPromised;
    }
    return nil;
}

and to do the pasting:
#pragma mark --- Paste functionality

+(NSArray *)readableTypesForPasteboard:(NSPasteboard *)pasteboard
{
    return @[@"my.company.person"];
}

+ (NSPasteboardReadingOptions)readingOptionsForType:(NSString *)type pasteboard:(NSPasteboard *)pasteboard
{
    if ( [type isEqualToString:@"my.company.person"])
    {
        return NSPasteboardReadingAsString;
    }
    return nil;
}

- (id)initWithPasteboardPropertyList:(id)propertyList ofType:(NSString *)type
{
    if ( [type isEqualToString:@"my.company.person"])
    {
        ...
    }
    return nil;
}

How should I proceed here? I am at a loss, reading many stackoverflow Q&A's (e.g. Peter Hosey's great answer to NSPasteboard and simple custom data), as well as the Apple docs, still have me stumped on this one.

A: Have you already seen this:
Using Managed Objects?
I'm not sure what you mean about 'I need to return a Person object but I don't have a managed object context.'  Your context is your scratch pad to create things.


text:
Q: how to merge a multiIndex dataframe with a singleIndex dataframe, and keep the resulting dataframe multiIndexed how to merge a multiIndex dataframe with a singleIndex dataframe, and keep the resulting dataframe multiIndexed
so i have dfA and dfB
dfA:
fir    A      B    C
sec    Aa Ab  Ba   Ca  Cb
ind
1      1  2   2    2   1
2      1  2   2    2   1
4      1  2   2    2   1

dfB
ind
1
2
3
4
5

I want the result to be multiIndexed like:
fir    A      B    C
sec    Aa Ab  Ba   Ca  Cb
ind
1      1  2   2    2   1
2      1  2   2    2   1
3      0  0   0    0   0
4      1  2   2    2   1
5      0  0   0    0   0

I did a simple merge
dfA = pd.merge(dfB,dfA,how='left',on='ind').fillna(0)

I would have the result dfA as:
   ind (A,Aa)(A,Ab)(B,Ba)(C,Ca)(C,Cb)
0   1    2     2     2     2     1
1   2    2     2     2     2     1
2   3    0     0     0     0     0
3   4    2     2     2     2     1
4   5    0     0     0     0     0

the columns got flatten,i want to keep them multiIndexed

A: Just reindex dfA on axis=0:
dfA.reindex(dfB['ind'], fill_value=0)

Output:
fir  A     B  C
sec Aa Ab Ba Ca Cb
ind
1    1  2  2  2  1
2    1  2  2  2  1
3    0  0  0  0  0
4    1  2  2  2  1
5    0  0  0  0  0


text:
Q: Infinite dimensional central simple algebras When constructing the Brauer group of a field, only the finite-dimensional central simple algebras are considered (because of Artin-Wedderburn's characterization).
But what happens to the infinite-dimensional ones? (I.e., to simple algebras which are infinite-dimensional over their centers).

*

*Is there an analogue for the Brauer group?

*Is there some structure theorem like Artin-Wedderburn's?

*What can be said about cross products of these algebras?

A: Perhaps one approach to thinking about this question would be Dixmier-Douady theory (as described in Brylinski's book "Loop Spaces, Characteristic Classes and Geometric Quantization"). This involves considering certain Banach algebras over the complex numbers as infinite dimensional analogs of central simple algebras, and leads to some useful notions generalizing bundles of central simple algebras over topological spaces.
The point of view here starts with the correspondence between bundles of central simple $\mathbb C$-algebras over a topological space $X$ and torsion elements of the second cohomology $H^2(X, \underline{\mathbb C}^*)$. This comes from the identification of isomorphism classes degree $n$ algebra bundles with $H^1(X, \underline{PGL_n})$ and the nonabelian short exact sequence:
$$ 1 \to \underline{\mathbb C}^* \to \underline{GL_n} \to \underline{PGL_n} \to 1$$
(here I'm using the underline to denote the corresponding sheaves of continuous functions).
Now, when you do this, you find that those classes which come from $H^1(X, \underline{PGL_n})$ (i.e. from degree $n$ central simple algebra bundles) are necessarily $n$-torsion in $H^2(X, \underline{\mathbb C}^*)$. what Dixmier-Doady theory does is identify all the elements of this $H^2$ as arising from infinite dimensional algebras.
A little more precisely, assuming paracompactness of $X$, on fixes some separable Hilbert space $E$, and defines $\mathcal K$ to be the Banach algebra of compact operators on $E$. It then turns out that one can naturally identify the whole of
$H^2(X, \underline{{\mathbb C}^\ast})$
 with the set of isomorphism classes of locally trivial Banach algebra bundles with fiber isomorphic to $\mathcal K$. What makes this really work is an analog of the above sequence
$$ 1 \to {\mathbb C}^\ast \to {\mathcal L}^\ast \to {\mathcal L}^\ast/{\mathbb C}^\ast \to 1 $$
where $\mathcal L$ is the Banach algebra of bounded (sup-norm) operators on $E$ (which incidentally happens to have center $\mathbb C$), and one uses an identification $\mathcal L^\ast/\mathbb C^\ast \cong Aut(\mathcal K)$.

A: I only know a little bit about this, so for your sake I hope someone more knowledgeable comes along...
As for your first question:
It is not hard to see that the tensor product of any two central simple algebras over a field is again a central simple algebra over that field: see e.g. Theorem 79 of these notes.  So for any field $K$ and any infinite cardinal number $\kappa$, the set of isomorphism classes of central simple $K$-algebras of cardinality at most $\kappa$ forms a commutative monoid.  I don't know what can be said about the structure of these monoids.
However in this case it's not clear to me that there is some natural equivalence relation to impose here such that the quotient under this relation forms a group (as in the finite-dimensional case).  One perspective on Brauer equivalence of finite dimensional CSAs is that it is a special case of Morita equivalence.  I would tend to doubt that considering infinite dimensional central simple algebras under Morita equivalence will give a group: perhaps some expert can confirm this.  Failing this, it seems that the burden is on you to come up with some natural equivalence relation and explain why it generalizes the Brauer group in the classical case.  On the other hand I know people who like to think of categorical analogues of the Brauer group, so possibly this is a fruitful way to go here.
As to your second question:
No, definitely not.  Among other things, Wedderburn's Theorem shows that any Artinian simple algebra is "almost" a division algebra (in fact is Morita equivalent to a division algebra).  But the class of non-Artinian simple algebras over a field $K$ is far larger than the class of division algebras over a field $K$, and there is no reasonable classification of one in terms of the other.  For some examples of this, see Chapter 1 in the notes linked to above, and then see Lam's First Course on non-commutative algebra for much more in this direction.
I have nothing to offer on your third question.

A: I am very far from an expert, so I hope my answer is useful for you, but I hope also that people who know more than I do will supplement or correct my answer.
Let me fix a commutative ring (or...) $k$.  The first thing to recall is that the Brauer group of $k$ is very close to the etale homology group $\mathrm H^2(\operatorname{spec} k, \mathbb G_m)$.  For example, when $k$ is a field, then etale homology is group homology for the Galois group, and (writing $k^s$ for the separable closure of $k$) one has $\text{Brauer} = \mathrm H^2(\operatorname{Gal}(k^s/k),(k^s)^\times)$, where $(k^s)^\times$ is the group of units in $k^s$.  Grothendieck asked (and at least in some cases answered, but I don't know the history) whether one actually has Brauer=H^2 in general, where "Brauer" is defined by Azumaya algebras and corresponds geometrically to projective bundles over $\operatorname{spec} k$ (modulo proj(vector bundles)).  The answer is that one does have an inclusion of Brauer into H^2, but it is not onto in general.  First, every Azumaya algebra represents a torsion element in H^2, and in general H^2 has non-torsion part.  But in fact there can be torsion in H^2 that also is not in Brauer.  To fix these problems, see for example Heinloth and Schröer, "The bigger brauer group and twisted sheaves", 2009.  (Sorry, I don't have an arXiv number, but I can email the pdf if you can't find it online.)  Perhaps these are the infinite-dimensional algebras you're looking for.  If memory serves, I learned this story from Pete L. Clark here on MathOverflow.  (If memory has misserved me, I apologize!)
There is a story I have told myself, but I don't know a reference or let alone a precise statement.  Let me be imprecise about some list of "nice categorical properties", and wrap everything up into the word "green".  ("green" may include words like "presentable" or "abelian" or ....)  Then for example the category $K = \text{Mod}_k$ of right $k$-modules is a green category.  Because $k$ is commutative, $K$ has a natural structure as symmetric-monoidal category.  For any algebra $A$ over $k$, one can also consider the green category $\text{Mod}_A$ of right $A$-modules.  Any such module is also a left $k$-module, and so there is an operation of $k$-modules on $A$-modules, and this makes $\text{Mod}_A$ into some categorified version of left $K$ module.  In general, we can consider a 2-category whose objects are green categories equipped with the structure of left $K$-module; I will call this 2-category $_K\text{MOD}$.
Then since $K$ is symmetric monoidal, $_K\text{MOD}$ carries a natural structure as symmetric monoidal 2-category.  After you've decided what "green" means, a natural question to ask is: What are the "units" in $_K\text{MOD}$?  For comparison, the group of units in $K = \text{Mod}_k$ are precisely the line bundles over $\operatorname{spec} k$, i.e. the Picard group $\mathrm H^1(\operatorname{spec} k,\mathbb G_m)$.  So this is a sort of "2-Picard group", and the "0-Picard group" is $\mathbb G_m(k) = \mathrm{GL}_1(k) = \mathrm H^0(\operatorname{spec} k,\mathbb G_m)$.
When "green" means "is the representation theory of an algebra", probably this "2-Picard group" is the classically-defined Brauer group on the nose.  What you would like to believe (but as I said, I have no theorem to this effect) is that for the correct definition of "green", the 2-Picard group is precisely $\mathrm H^2(\operatorname{spec} k,\mathbb G_m)$.  Then the answer to your question is that rather than looking for infinite-dimensional algebras that extend the Brauer group, what you should be asking for are representation theories that behave as if they were representations of an "infinite-dimensional" central simple algebra.  And you should believe that the story continues for the correct categorification of "green".
But then I think that even for the correct definition of "green", over a field you don't get anything new.  That's because we already have Brauer = H^2 on the nose, and so you should believe that all reasonable definitions of "green" have the same group of units.  Most generally, there is a weakening of "unit" to "dualizable object" and probably when $k$ is a field, all reasonable definitions of "green" give the same class of dualizable objects in $_K\text{Mod}$.  But I'm starting to digress far from your original question, and so I will stop.


text:
Q: JIRA Plugin: Where to start I was asked to create a simple JIRA plugin that combines Workflow + Custom Fields + Conditional Steps
I just started installing JIRA and finally managed to create a run a simple Hello World Plugin.
I am already confused with how huge this interface is, and cannot seem to be able to grasp the big picture
Could any of you send me to the right direction? An idea on what could include all these?

A: It might be a good idea to start with the scriptrunner plugin. This enables you to write custom groovy scripts for workflow conditions, validators, post-functions, listeners and many more.
The advantage is that the learning curve for simple groovy scripts is not as steep as for "real" plugins. That way you can accomodate with the jira api and then when you hit the point where you can't help yourself with groovy anymore switch over to normal plugin mechanics.

A: The Introduction to the Atlassian Plugin SDK is actually quite good.
The get your head around try to focus on the type(s) of plugin you want to have:

*

*customfield - calculated or not?

*workflow plugins - validators, conditions

Within each plugin, find out what information you need and then see where from the API you can get that information.

A: Script Runner is easier to learn and it does exactly what you are asking for. A SR script can become also a JIRA plugin if you want to install it in other instances (SR plugin must be available).
Learning Script Runner helps you to understand better how to develop JIRA plugins, in any case it's not time wasting because you can easily switch between native JIRA plugins and SR (SR uses JIRA components so the main logic is still the same, it just hides most of the annoying and repetitive stuff).
You can start with this template:
https://bitbucket.org/jamieechlin/sr-scripts-plugin/overview


text:
Q: Is it still possible to programme in LISP 1/1.5? All of the resources online I find are for Common Lisp, even when I try to search specifically for original LISP resources.  I suspect that Common is probably a lot easier, but I thought it might be fun to try Lisp out from the beginning of it's history as a language.

A: Yes, and it's easy in fact.  This person has a tarball which lets you run Lisp 1.5 on the SIMH emulator for the IBM 7094, which must have, I think, been the system Lisp 1.5 was ported to from the 704 (the 7094 is a transistor machine, the 704 was valve (tube)). Here is a link to the slides from a talk given by Norman Richards at the March 2015 Clojure meetup where he must have demonstrated all this working.
Example
I did this on a scratch Ubuntu 20.04 machine.

*

*Get SIMH, with aptitude install simh or whatever you are using.

*Get the above tarball and unpack it.

*unpack the utils-1.1.8.tar.gz tarball inside it and build txt2bcd;

*put txt2bcd somewhere in your PATH;

*profit.

The tarball includes a factorial program, inevitably, and here's a transcript of it running:
ts$ i7094 lisptape.ini factorial.txt

IBM 7094 simulator V3.8-1
MTA: unit is read only
MTA: unit is read only
LPT: creating new file

HALT instruction, PC: 10524 (TRA 10523)
Goodbye
ts$ cat sys.log
             TEST  FACTORIAL

  THE TIME ( 0/ 0  000.0) HAS COME, THE WALRUS SAID, TO TALK OF MANY THI
NGS .....   -LEWIS CARROLL-
 EVALQUOTE OPERATOR AS OF 1 MARCH 1961.    INPUT LISTS NOW BEING READ.

  THE TIME ( 0/ 0  000.0) HAS COME, THE WALRUS SAID, TO TALK OF MANY THI
NGS .....   -LEWIS CARROLL-
  FUNCTION   EVALQUOTE   HAS BEEN ENTERED, ARGUMENTS..
 DEFINE

 (((FACTORIAL (LAMBDA (X) (COND ((EQUAL X 0) 1) (T (TIMES X (FACTORIAL (
SUB1 X)))))))))

 END OF EVALQUOTE, VALUE IS ..
 *TRUE*

  FUNCTION   EVALQUOTE   HAS BEEN ENTERED, ARGUMENTS..
 FACTORIAL

 (10)

 END OF EVALQUOTE, VALUE IS ..
 3628800

  THE TIME ( 0/ 0  000.0) HAS COME, THE WALRUS SAID, TO TALK OF MANY THI
NGS .....   -LEWIS CARROLL-
 END OF EVALQUOTE OPERATOR
             FIN      END OF LISP RUN

So it's that easy: I was amazed, having spent much longer than this trying to get MACLISP to run.  I think later systems are harder because they assume terminal types and so on as there is more interactivity.
Some other links
Some other links which might be useful (some from my original comment):

*

*a listing of Lisp 1.5 for (I presume) the IBM 7094);

*an IBM 704 emulator for Windows if you wanted to go even further back;

*The SIMH software kits list lists Lisp for the PDP-1, which is what is described here and which is also very early.


text:
Q: Symlink command in Dockerfile doesn't create the link in the container In my Dockerfile I have this line:
RUN ln -s /var/www/html/some_file /var/www/html/another_file
When running docker build all the steps are executed including the creation of the symbolic link, but when I start a container using the image created and check the folder /var/www/html/ I don't see the link there.
I tried searching online if this is something supported by docker and couldn't find an answer.
The content of the container is already available by another container image I am using with the FROM instruction, so the file /var/www/html/some_file is not on my machine.
No Volumes are involved. This is the Dockerfile:
FROM piwik:3.2.1-apache

RUN apt update

RUN ln -s /var/www/html/some_file /var/www/html/another_file

CMD [ "apache2-foreground" ]

A: The Dockerfile for that image (three and a half years old and not getting any updates!) has the line:
VOLUME /var/www/html

This will prevent any subsequent RUN instructions from making any changes to that directory, even if it's in a derived image.
There's no way to un-VOLUME a directory, so if you need this symlink to exist, you either need to create a new image from a base PHP image installing the software yourself, or wrap its entrypoint script with your own that creates the symlink at startup time.


text:
Q: When does a SBT package get downloaded/built? I want to use http://dispatch.databinder.net/Dispatch.html .
The site indicates I must add this to project/plugins.sbt:
libraryDependencies +=  "net.databinder.dispatch" %% "core" % "0.9.1"

which I did. I then restarted the play console and compiled.
Importing doesnt work:
import dispatch._

Guess I have been silly, but then I never used a build system when using Java.
How must I trigger the process that downloads/builds the package? Where are the jars (or equivalent) stored; can I reuse them? When is the package available for use by the Play application?

A: It doesn't say you should add it to project/plugins.sbt. That is the wrong place. It says to add to the build.sbt file, on the root of your project. Being a Play project, project/Build.scala might be more appropriate -- I don't know if it will pick up settings from build.sbt or not.
To add the dependency in your Build.scala:
val appDependencies = Seq(
  "net.databinder.dispatch" %% "core" % "0.9.1"
)

A: You probably need to run sbt update.
From the sbt Command Line Reference:
update Resolves and retrieves external dependencies as described in library dependencies.