text:
Q: Having RecyclerView inside a NestedScrollView calls onBindView for all the items I have two RecyclerViews placed vertically in a LinearLayout. I need to make both of them scrollable and that is why I have put the LinearLayout inside NestedScrollView
This is the my layout file.
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:scrollbars="none">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/featured_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/all_topic_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Also, I am disabling nested scrolling in Java code.
disableNestedScrolling(findViewById(R.id.all_topic_list));
disableNestedScrolling(findViewById(R.id.featured_list));

My RecylerView library version is 26.1.0
This works fine perfectly, but then onBindViewHolder method is getting called for all the items in the list. Ideally it should only be called for the visible items in the list.
I think the issue is happening because I am giving wrap_content to the RecyclerView. A lot of answers on this question suggest that the issue is solved in v23.2.1, but I am already using v26.1.0. How to solve this issue?

A: I had exactly the same problem. RecyclerViews are not meant to be placed inside scroll containers with the same scroll direction. The view recycling only works when the height is set to MATCH_PARENT.
Depending on the complexity of the content inside of the NestedScrollView and the anticipated amount of RecyclerView items:

*

*Ignore the problem. If there are only a few simple items, you may
not need view recycling at all.
When I hit the problem, I analysed the layouts of other popular apps: For example, WhatsApp only uses RecyclerViews (or ListViews with view recycling) in some parts of their app.
Particularly, this group settings screen with hundreds of possible items is made of multiple ListViews wrapped by a ScrollView, without any view recycling.

*Replace the NestedScrollView with a single
ReyclerView with multiple item types and put all of your scrollable content inside of it. This is the way to go if you need view recycling.
Beware that you also have to convert all the other content in the NestedScrollView (headers and footers, spacing) to RecyclerView items with their own ViewHolders.
If the setup is rather simple, I would recommend you to implement it without additional libraries, following the link above.

There are a few different libraries available to solve your problem (all of them follow the second approach with a single RecyclerView), but most come with a lot of extra features which you may not need:
RendererRecyclerViewAdapter
It comes with a ViewRenderer/ViewModel interface, which works like a
"partial" RecyclerView for a single item type. You would create one
for every item type and then register them in a single adapter.
Epoxy
A library/framework create by airbnb and used heavily in their app.
   They have a lot of scrollable content (similar to a web page) with a
   lot of different item types. Epoxy also helps with the composition of
   the different items on a page, and it handles animations when the
   content or its order changes. Too much if you only need it for a single screen.
Litho
A complete UI framework created by Facebook which comes with it's own rendering engine, a replacement for xml layouts and much more. As far as I understand, it allows you to do to handle large amounts of items (like the Facebook timeline) and the view recycling is handled automatically. Like Epoxy, you would only use this if your app includes things like endless scrolling with a lot of different item types and you really need the performance.

I tried Epoxy and RendererRecyclerViewAdapter, but after all I created my own multiple item type adapter. It can be created in less than 100 lines of code.

A: Starting from RecyclerView:1.2.0-alpha04 we can use ConcatAdapter to solve this problem
https://developer.android.com/reference/androidx/recyclerview/widget/ConcatAdapter

A: I tried your problem by adding 20 items in each recyclerview, with NestedScrollView application called onBindViewHolder method 40 times. As you disabling nested scrolling in Java code i suggest to use Scrollview. By using ScrollView application called onBindViewHolder 33 times.

If you fix your recyclerView's height to specific size instead of "match-parent" it will reduce call to onBindViewHolder greatly.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="false">

<android.support.v7.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.vishal.my2.MainActivity">
<android.support.v7.widget.RecyclerView
    android:id="@+id/featured_list"
    android:layout_width="match_parent"
    android:layout_height="300dp" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/all_topic_list"
    android:layout_width="match_parent"
    android:layout_height="300dp" />
</android.support.v7.widget.LinearLayoutCompat>
</ScrollView>

If Specifying hardcoded value to recyclerView's height does not meet your application requirement then you can try using ListView instead of recyclerView. pardon me if i am wrong, This was my first time answering any question.

A: Add this to nested scroll view android:fillViewport="false"


text:
Q: Synchronizing content with divs on multiple pages I am trying to make my workflow easier. This is why I am looking for a possibilty to have one HTML or JavaScript file that loads into the sidebar of each of my pages.
I am thinking of creating a file called for example: "sidebar.html" or "sidebar.js".
And on my normal pages (about.html, music.html, etc...) I have a div with id and/or class "sidebar". This div is the exact same on each page. How can I make the sidebar.html/sidebar.js load into those divs?
That way when I want to update my sidebar, I would only have to change the sidebar.html/sidebar.js and would not have to open each page and manually change it.
Thank you for your help!

A: HTML files dont have an include feature as you are expecting. However there are many options.
in your about.html have your div

, now send an ajax request to sidebar.html and append the response in you div.
Other option is to have an iframe in your div

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to execute sp_send_dbmail while limiting permissions Is there a way to provide access to users in my database to execute  msdb.dbo.sp_send_dbmail without needing to add them to the MSDB database and the DatabaseMailUserRole?
I've tried this:
ALTER PROCEDURE [dbo].[_TestSendMail]
(
  @To NVARCHAR(1000),
  @Subject NVARCHAR(100),
  @Body NVARCHAR(MAX)
)
WITH EXECUTE AS OWNER
AS
    BEGIN
        EXEC msdb.dbo.sp_send_dbmail @profile_name = N'myProfile',
            @recipients = @To, @subject = @Subject, @body = @Body
    END

But I get this error:
The EXECUTE permission was denied on the object 'sp_send_dbmail', database 'msdb', schema 'dbo'.

Thanks!

A: Your approach is OK, but your wrapper proc must be in the msdb database.
Then, you execute "EXEC msdb.dbo._TestSendMail"
This still leave the issue of permissions on dbo._TestSendMail in msdb.
But public/EXECUTE will be enough: it only exposes the 3 parameters you need.
If in doubt, add WITH ENCRYPTION. This is good enough to stop anyone without sysadmin rights viewing the code
USE msdb
GO
CREATE PROCEDURE [dbo].[_TestSendMail]
(
  @To NVARCHAR(1000),
  @Subject NVARCHAR(100),
  @Body NVARCHAR(MAX)
)
-- not needec WITH EXECUTE AS OWNER
AS
    BEGIN
        EXEC dbo.sp_send_dbmail @profile_name = N'myProfile',
            @recipients = @To, @subject = @Subject, @body = @Body
    END

A: You actually can do it with a certificate signed stored procedure and it doesn't have to be in msdb to do so:
CREATE DATABASE TestDBMail
GO

USE [TestDBMail]
GO

CREATE PROCEDURE [dbo].[TestSendMail]
(
        @To NVARCHAR(1000),
        @Subject NVARCHAR(100),
        @Body NVARCHAR(MAX)
)
WITH EXECUTE AS OWNER
AS
BEGIN
        EXEC msdb.dbo.sp_send_dbmail
                        @profile_name = N'Database Mail Profile',
                        @recipients = @To,
                        @subject = @Subject,
                        @body = @Body
END
GO

-- This should fail
EXECUTE [dbo].[TestSendMail] 'someemail@domain.com', 'test', 'body'

-- Create a certificate to sign stored procedures with
CREATE CERTIFICATE [DBMailCertificate]
ENCRYPTION BY PASSWORD = '$tr0ngp@$$w0rd'
WITH SUBJECT = 'Certificate for signing TestSendMail Stored Procedure';
GO

-- Backup certificate so it can be create in master database
BACKUP CERTIFICATE [DBMailCertificate]
TO FILE = 'd:\Backup\DBMailCertificate.CER';
GO

-- Add Certificate to Master Database
USE [master]
GO
CREATE CERTIFICATE [DBMailCertificate]
FROM FILE = 'd:\Backup\DBMailCertificate.CER';
GO

-- Create a login from the certificate
CREATE LOGIN [DBMailLogin]
FROM CERTIFICATE [DBMailCertificate];
GO

-- The Login must have Authenticate Sever to access server scoped system tables
-- per http://msdn.microsoft.com/en-us/library/ms190785.aspx
GRANT AUTHENTICATE SERVER TO [DBMailLogin]
GO

-- Create a MSDB User for the Login
USE [msdb]
GO
CREATE USER [DBMailLogin] FROM LOGIN [DBMailLogin]
GO

-- Add msdb login/user to the DatabaseMailUserRole
EXEC msdb.dbo.sp_addrolemember @rolename = 'DatabaseMailUserRole', @membername = 'DBMailLogin';
GO

USE [TestDBMail]
GO

-- Sign the procedure with the certificate's private key
ADD SIGNATURE TO OBJECT::[TestSendMail]
BY CERTIFICATE [DBMailCertificate]
WITH PASSWORD = '$tr0ngp@$$w0rd';
GO

-- This will succeed
EXECUTE [dbo].[TestSendMail] 'someemail@domain.com', 'test', 'body'

/*
-- Cleanup
USE [msdb]
GO
DROP USER [DBMailLogin]
GO
USE [master]
GO
DROP LOGIN [DBMailLogin]
DROP CERTIFICATE [DBMailCertificate]
DROP DATABASE [TestDBMail]

-- Delete the certificate backup from disk

*/

A: One possible solution is to encapsulate the mailing as a stored procedure e.g. mail_error_as_MAILER (wich you will later call)
and another stored procedure
e.g.

ALTER PROCEDURE [dbo].[mail_error](@error_ID int)
SET NOCOUNT ON
declare @rc int
declare @object int
declare @src varchar(255)
declare @desc varchar(255)
declare @osql_cmd varchar(1000)
-- create shell object
exec @rc = sp_oacreate 'wscript.shell', @object out
if @rc0
  begin
    exec sp_oageterrorinfo @object, @src out, @desc out
    return
  END

  DECLARE @user VARCHAR(50)
  DECLARE @password VARCHAR(50)
  DECLARE @database VARCHAR(50)
  DECLARE @server VARCHAR(50)
  DECLARE @sql varchar(200)
 SET @user=MAILER,@password=XXXXXX,@database=XXXXXX,@server=XXXXX
SET @sql= 'EXEC mail_ERROR_as_MAILER @error_ID=' + CAST(@error_id as varchar(10))
set @osql_cmd='osql -U'+@user+' -P'+@password+' -d'+@database+' -S"'+@server+'"  -Q"'
  +@sql+'"'

exec @rc= sp_oamethod @object, 'run', null, @osql_cmd
--print @rc
if @rc0
  begin
    exec sp_oageterrorinfo @object, @src out, @desc out
    return
  end
-- destroy shell object
exec sp_oadestroy @object

But this requires:
* hardcoding password (make sure users cannot view definition of stored procedure ...)
* giving users access to sp_oacreate etc... (opens up other security problems e.g. DOS)
that way they can only use the mail the way you want to without giving them permission to mail other things.
Or safer,
let users put mail in some kind of mail_queue(wich you can control what they can put in) and have an agent acount send these mails periodically
Or: give them permission to mail but take a big club with rusted spikes on abuse


text:
Q: Subtracting two IPv6 Addresses Gives Wrong Value I have an IP address stored in two 64-bit array. I've noticed least significant bits are in the first byte-little endian.
I'm subtracting two IPv6 addresses which can differ only by 64 bits. So basically, I need to subtract only addr_end[1]-addr_begin[0] to get the result.
However the result is not correct.
This is the code I'm trying:
struct m128bit {
    union {
        uint8_t  val8[16];
        uint16_t val16[8];
        uint32_t val32[4];
        uint64_t val64[2];
    } u;
};
//Overflows 64 bit, too big range (little endian representation)
if (local_begin.u.val64[0] != local_end.u.val64[0]) {
    cout<<"Range is too big!"<<endl;
    return 0;
}
else {
    return (local_end.u.val64[1])-(local_begin.u.val64[1]);
}

The result is 0xb.
I'm passing in the following IPs:
2001:0db8:85a3:0000:0000:8a2e:0370:7335 -2001:0db8:85a3:0000:0000:8a2e:0370:7340
The result should be 5.
What am I missing? I tried applying htobe64() while subtracting the addresses but that didn't work either (I get 0xb, instead of 0xb00000000000000).
Thanks in advance!

A: In hex the number of elements between 7335 to 7340 is as follows.
7335,7336,7337,7338,7339,733a,733b,733c,733d,733e,733f,7340
So when you subtract 7335 from 7340 you will get 11 in base 10 i.e. 0xb in hex and thats what you are getting 0xb and is expected.

A:
The result should be 5.

Nope.  The numbers in those IPv6 addresses are all in hex.
0x7340 - 0x7335 is 0xb
In base 10
29504 - 29493 is 11.


text:
Q: Why is parent's public member only accessible within a method definition but not the class that derived from it? If I have these two classes
class Car
{
    public int maxSpeed;
}

class Minivan : Car
{
    maxSpeed = 100; //error

    public void Test()
    {
        maxSpeed = 100;//ok!
    }
}

Why it's only permitted to use the public  member of the base class within a method not the class body?

A:
Why it's only permissible to use public member of the base class within a method not the class body?

You are thinking about this the wrong way.
It is not the accessibility rules that make this illegal; it would be illegal regardless of the accessibility.
The rule you are violating is that a statement must appear within the body of a method, property, constructor, destructor, indexer, operator or event.  In your first code sample the statement appears outside of all of those, and in the second, it appears inside a method.
Again, this rule has nothing whatsoever to do with accessibility. It's a grammatical rule of the language that you are violating, not a semantic rule.
That should answer your question, but let's take a look at your code. The better way to write this would be:
abstract class Car
{
  public abstract double MaximumSpeed { get; }
}
class Minivan : Car
{
  public override double MaximumSpeed { get { return 100.0; } }
}

Why is this better?

*

*Public fields are a bad idea. Represent things that are logically properties as properties.

*The property is now read-only. You don't want just anyone to be able to change the value!

*Use good naming conventions.

*Car is abstract, so you cannot create a vehicle that is just a car.

*The maximum speed is a "physics" quantity, so it should be double, not int. There is no requirement that speed be quantized to an integer.

A: class Minivan : Car
{
maxSpeed=100; //error
}

Doesn't fit anywhere, it's not a member of the class, it doesn't even have a type. What is it?
If you want to initialize the property of base class in a child class you can use a constructor for that.
class Car
{
    Car()
    {
        maxSpeed = 100;
    }
}

If you need to pass a value for maxSpeed to every car you create you can create multiple constructors and chain them

A: What you define in the class are the fields and what you declare inside the methods are the variables. They may look same but there is a difference between them. like you can't use access modifiers with variables but you can do with fields. Also there is a slit difference between fields and properties, Properties exposes fields marked private in a container like class. So you can not use them interchangeably, that means you can't use fields in place of variable. In your case maxspeed is a field and you are using it like a variable.
class Minivan : Car
    {
        //Inside a method
        public void Test()
        {
            maxSpeed = 100;
        }

        //Inside a constructor
        public Minivan(int _maxSpeed)
        {
            maxSpeed = _maxSpeed;
        }

        //Inside a property
        public int MaxSpeed
        {
            get { return maxSpeed; }
            set { maxSpeed = value; }
        }
    }

So if you want to use the field use it inside a method or constructor or inside a property.Hope it helps. Please feel free to comment if any doubt.


text:
Q: Creating Document in CosmosDB with postman Error I am able to create the DB and the collection via postman, however when I try to create a document I get this error.
{
    "code": "BadRequest",
    "message": "Message: {\"Errors\":[\"The collection cannot be accessed with this SDK version as it was created with newer SDK version.\"]}\r\nActivityId: e0cbc782-c764-48c8-bce4-8e1d5bf21da4, Request URI: /apps/06f97901-5530-4c65-a094-ceac7aeba20b/services/742a131c-0991-499c-bd7c-1e899c09b61c/partitions/45855936-11ca-4b85-b2b5-a69e6c0d1f11/replicas/132816360009752188p/, RequestStats: \r\nRequestStartTime: 2021-11-17T15:22:27.7739709Z, RequestEndTime: 2021-11-17T15:22:28.8039391Z,  Number of regions attempted:1\r\n{\"systemHistory\":[{\"dateUtc\":\"2021-11-17T15:21:25.4530841Z\",\"cpu\":0.744,\"memory\":52690489344.000,\"threadInfo\":{\"isThreadStarving\":\"False\",\"threadWaitIntervalInMs\":0.0204,\"availableThreads\":32764,\"minThreads\":52,\"maxThreads\":32767}},{\"dateUtc\":\"2021-11-17T15:21:35.4632206Z\",\"cpu\":1.625,\"memory\":50108911616.000,\"threadInfo\":{\"isThreadStarving\":\"False\",\"threadWaitIntervalInMs\":0.0137,\"availableThreads\":32743,\"minThreads\":52,\"maxThreads\":32767}},{\"dateUtc\":\"2021-11-17T15:21:45.4733865Z\",\"cpu\":0.886,\"memory\":50303107072.000,\"threadInfo\":{\"isThreadStarving\":\"False\",\"threadWaitIntervalInMs\":0.02,\"availableThreads\":32765,\"minThreads\":52,\"maxThreads\":32767}},{\"dateUtc\":\"2021-11-17T15:22:05.4836759Z\",\"cpu\":0.658,\"memory\":50759467008.000,\"threadInfo\":{\"isThreadStarving\":\"False\",\"threadWaitIntervalInMs\":0.0174,\"availableThreads\":32765,\"minThreads\":52,\"maxThreads\":32767}},{\"dateUtc\":\"2021-11-17T15:22:15.4937953Z\",\"cpu\":1.056,\"memory\":50995646464.000,\"threadInfo\":{\"isThreadStarving\":\"False\",\"threadWaitIntervalInMs\":0.0166,\"availableThreads\":32762,\"minThreads\":52,\"maxThreads\":32767}},{\"dateUtc\":\"2021-11-17T15:22:25.5038872Z\",\"cpu\":2.251,\"memory\":50450370560.000,\"threadInfo\":{\"isThreadStarving\":\"False\",\"threadWaitIntervalInMs\":0.0215,\"availableThreads\":32765,\"minThreads\":52,\"maxThreads\":32767}}]}\r\nRequestStart: 2021-11-17T15:22:27.7739709Z; ResponseTime: 2021-11-17T15:22:27.7739709Z; StoreResult: StorePhysicalAddress: rntbd://cdb-ms-prod-westus2-fd22.documents.azure.com:14093/apps/ad7b049e-a5b5-477b-ad5c-689b7e77e42a/services/c39381b9-f255-469c-a031-699608b1c00c/partitions/32e095ed-ac4c-48d3-a03a-9fbf0ee34219/replicas/132814791013059696p/, LSN: -1, GlobalCommittedLsn: -1, PartitionKeyRangeId: , IsValid: False, StatusCode: 410, SubStatusCode: 0, RequestCharge: 0, ItemLSN: -1, SessionToken: , UsingLocalLSN: False, TransportException: null, BELatencyMs: , ActivityId: e0cbc782-c764-48c8-bce4-8e1d5bf21da4, TransportRequestTimeline: {\"requestTimeline\":[{\"event\": \"Created\", \"startTimeUtc\": \"2021-11-17T15:22:27.7739709Z\", \"durationInMs\": 0.0105},{\"event\": \"ChannelAcquisitionStarted\", \"startTimeUtc\": \"2021-11-17T15:22:27.7739814Z\", \"durationInMs\": 0.009},{\"event\": \"Pipelined\", \"startTimeUtc\": \"2021-11-17T15:22:27.7739904Z\", \"durationInMs\": 0.097},{\"event\": \"Transit Time\", \"startTimeUtc\": \"2021-11-17T15:22:27.7740874Z\", \"durationInMs\": 0.4853},{\"event\": \"Received\", \"startTimeUtc\": \"2021-11-17T15:22:27.7745727Z\", \"durationInMs\": 0.0257},{\"event\": \"Completed\", \"startTimeUtc\": \"2021-11-17T15:22:27.7745984Z\", \"durationInMs\": 0}],\"requestSizeInBytes\":1137,\"requestBodySizeInBytes\":635,\"responseMetadataSizeInBytes\":56,\"responseBodySizeInBytes\":75};\r\n ResourceType: Document, OperationType: Create\r\nRequestStart: 2021-11-17T15:22:28.8039391Z; ResponseTime: 2021-11-17T15:22:28.8039391Z; StoreResult: StorePhysicalAddress: rntbd://cdb-ms-prod-westus2-fd37.documents.azure.com:14034/apps/06f97901-5530-4c65-a094-ceac7aeba20b/services/742a131c-0991-499c-bd7c-1e899c09b61c/partitions/45855936-11ca-4b85-b2b5-a69e6c0d1f11/replicas/132816360009752188p/, LSN: 1, GlobalCommittedLsn: 1, PartitionKeyRangeId: 0, IsValid: True, StatusCode: 400, SubStatusCode: 0, RequestCharge: 0, ItemLSN: -1, SessionToken: 1, UsingLocalLSN: False, TransportException: null, BELatencyMs: 0.298, ActivityId: e0cbc782-c764-48c8-bce4-8e1d5bf21da4, TransportRequestTimeline: {\"requestTimeline\":[{\"event\": \"Created\", \"startTimeUtc\": \"2021-11-17T15:22:28.8039391Z\", \"durationInMs\": 0.0101},{\"event\": \"ChannelAcquisitionStarted\", \"startTimeUtc\": \"2021-11-17T15:22:28.8039492Z\", \"durationInMs\": 0.0099},{\"event\": \"Pipelined\", \"startTimeUtc\": \"2021-11-17T15:22:28.8039591Z\", \"durationInMs\": 0.1055},{\"event\": \"Transit Time\", \"startTimeUtc\": \"2021-11-17T15:22:28.8040646Z\", \"durationInMs\": 0.8552},{\"event\": \"Received\", \"startTimeUtc\": \"2021-11-17T15:22:28.8049198Z\", \"durationInMs\": 0.041},{\"event\": \"Completed\", \"startTimeUtc\": \"2021-11-17T15:22:28.8049608Z\", \"durationInMs\": 0}],\"requestSizeInBytes\":1137,\"requestBodySizeInBytes\":635,\"responseMetadataSizeInBytes\":173,\"responseBodySizeInBytes\":112};\r\n ResourceType: Document, OperationType: Create\r\n, SDK: Microsoft.Azure.Documents.Common/2.14.0"
}

The x-ms-version header is the same for all my requests.
Here is an image of the headers and call I use for creating a collection.

for creating a document I change my url to:
https://<url>.documents.azure.com/dbs/volcanodb2/colls/testcol2/docs

for the body I use the examples found on the msft docs:
https://learn.microsoft.com/en-us/rest/api/cosmos-db/create-a-document

This is my pre-request script:
var today = new Date();
var str = today.toUTCString();
pm.environment.set("time", str);

// I need these to generate a token
var verb = 'POST';
var resourceType = "docs";
var resourceId = 'dbs/volcanodb2/colls/testcol2';
var text = (verb || "").toLowerCase() + "\n" + (resourceType || "").toLowerCase() + "\n" + (resourceId || "") + "\n" + str.toLowerCase() + "\n" + "" + "\n";

//Hash and Encode by using the masterkey.
var key = CryptoJS.enc.Base64.parse("<my token here>");
var signature = CryptoJS.HmacSHA256(text, key).toString(CryptoJS.enc.Base64);
var MasterToken = "master";
var TokenVersion = "1.0";
var authToken = encodeURIComponent("type=" + MasterToken + "&ver=" + TokenVersion + "&sig=" + signature);

// Save it to parameter to use in HTTP header
pm.environment.set("authToken", authToken);

UPDATE: SS to repsonse.

The body I am using is, I also tried the one posted in the docs:
{
  "id": "AndersenFamily"
}

A: Can you try passing few headers which are missing in your screenshot?
Accept : application/json
x-ms-documentdb-partitionkey : ["yourPK"]
x-ms-verison : 2016-07-11


text:
Q: "Dysfunctional" vs. "disfunctional"
Possible Duplicate:
Which is the proper spelling: "disfunction" or "dysfunction"?

What's the rationale behind dysfunctional being spelled dys- and not dis-?

A: From WordReference.com on Dysfunction vs. Disfunction:

dys- is a Greek prefix meaning "bad", "abnormal", "difficult", or
  "impaired".
dis- is a Latin prefix with none of the above meanings.
dys- has the right meaning, but function is a Latin word. Hence the
  confusion.

Latin dis- can mean "lack of", "not", "opposite of", "away from".
This all explains why something dys-functional has a bad or abnormal function, rather than a lack of function that dis-functional implies.

A: There is no rationale, it's just one of the countless quirks of natural language.
The dis- prefix comes from Latin, dys- from Greek. They have some overlap in meaning, and with -functional, both could be used.
Now, function has Latin roots, so disfunctional would make more sense, in the way that both prefix and suffix come from Latin. However, dysfunctional has come to be the more commonly used spelling, disregarding the different roots of prefix and suffix.

A: The Oxford English Dictionary records disfunctional as a variant spelling of (the more usual) dysfunctional.


text:
Q: "If value exists in table" - Is there such a thing? I'm new to mysql and I need some help.
I want to select all the rows from a table where a value exists, but not select that value:
For example:
ID           ITEM
--------------------
1             AA
1            22S
1             AB
2            F45
2             BB
3             1
3             1
3             AA
3            F45
3            F67
3             A
......

something like: SELECT ID, ITEM FROM TABLE1 IF Item "AA" is present except "AA"
and that would return:
1  225,AB
3  1,1,F45,F67,A

What is the actual query for doing this? Thank you

A: You can get the list using group_concat():
SELECT ID, group_concat(case when ITEM <> 'AA' then ITEM end)
FROM TABLE1
group by id
having sum(item = 'AA') > 0;

The case statement ensures that the value is not included in the final list.  group_concat() ignores NULL values.
The having clause makes sure that there is at least one 'AA' value for the returned row.
EDIT:
Thanks to Praveen:
Fiddle here

A: This query will give you a list of ids that are associated with the AA item:
SELECT DISTINCT(id) FROM table WHERE item = 'AA'

You can use it as a subquery (embed it into a larger query) to get the desired result by considering only rows with ids that have an AA item, except those that have the AA item themselves:
SELECT id, GROUP_CONCAT(item) FROM table
WHERE id IN (SELECT DISTINCT(id) FROM table WHERE item = 'AA')
  AND item != 'AA'
GROUP BY id

A: SELECT tbl.id,
    GROUP_CONCAT(tbl.item) AS item
FROM tbl
INNER JOIN (
    SELECT id,
        item
    FROM tbl
    WHERE item = 'AA'
) tmp ON
    tmp.id = tbl.id
WHERE item <> 'AA'

Try the above code.

A: Here, 'id' appears to be a foreign key to another table (since id usually implies identity). If you have such a table the the data you seek is returned by:
SELECT y.id, y.item
FROM yourtable y
INNER JOIN othertable o
ON y.id=o.id
INNER JOIN yourtable a
ON a.id=o.id
WHERE a.item='AA'
AND y.item<>'AA'

But this will return multiple rows (e.g. 2 entries for id 1 - 1,225 and 1,AB). To consolidate the results into a single line (usually very bad practice - sionce the result set is not reusable in queries):
SELECT y.id, GROUP_CONCAT(y.item)
FROM yourtable y
INNER JOIN othertable o
ON y.id=o.id
INNER JOIN yourtable a
ON a.id=o.id
WHERE a.item='AA'
AND y.item<>'AA'
GROUP BY y.id

If you don't have another table, then it's still possible by recreating a represnetation of the missing table:
SELECT y.id, GROUP_CONCAT(y.item)
FROM yourtable y
INNER JOIN (
     SELECT DISTINCT a.id
     FROM yourtable a
     WHERE a.item='AA'
) o
ON y.id=o.id
WHERE y.item<>'AA'
GROUP BY y.id

BTW mixing different types of data in the same column is a bad idea too.


text:
Q: Is it bad practice to put application specific modules into a second node_modules? I'm trying to restructure some of my application components to make them more easily available inside of my project. (eg. not having to stack '../../../' in my requires). I have set up a second node_modules folder at the second level of my project hierarchy where I want to put my application specific modules into, that I use frequently from any point of the project (eg. a module providing my app's config values).
Now I wonder if this is to be considered a bad practice as node modules inside node_modules folders are meant to be independent, global modules, to be used in any project. Is this true? Is there a better approach to this?


text:
Q: Prefill redux-form form for an update I'm new to React. I'm using redux-form for my app, as suggested by a tutorial.  How do you do the 'U' in CRUD with this plugin?  For an update, I call my posts_create class.  If I detect an id on this.props.params, then I assume it is an update, fetch the data, and the initialValues get set because of this function:
function mapStateToProps(state){
console.log ("in mapStateToProps")
console.log (state)
return {
    initialValues:state.posts.post
}

}
If not, it must be a create, and I don't do the fetch. Well, everything works, kinda.  After one update, the next time I go to 'New', the data from the previous update is still in the form.  I am not fetching the data.  I have tried the following in componentWillMount(), but the reset doesn't seem to work.  And this seems clumsy anyway:
    componentWillMount(){
    if (this.props.params.id){
        this.props.fetchPost(this.props.params.id)
        this.isNew = false;
    }
    else {
        console.log ("reseting form")
        this.props.resetForm();
        this.isNew = true;
    }
    console.log ("isNew: " + this.isNew)
}

Thanks for any help.

A: I ended up creating a new action for the purpose of clearing  props.initialValues.  I pass the action this.props.fields, it returns an object in the correct structure, but with all of the fields properties set to empty string.  This seems convoluted, but it does work.

A: One Solution of it is to pass enableReinitialize={true} from parent of redux-form container class. code should look like below in Parent Class where we call redux-form container class.
<ReduxFormContainerClass enableReinitialize={true} />


text:
Q: Congruence of square-free numbers Let $m$ be a square-free number.  I want to prove that, given some $b \in \mathbb{Z}^+$, where $\gcd(b,m)>1$, that
$\qquad b^{\,c\,\phi(m) + 1} \equiv b \pmod m,\ $ for some $c \in \mathbb{Z}^+$.
I've verified this with a bunch of different values of $m$ and $b$, but I'm really stuck on how to prove it.

A: Let $b=p_1^{a_1}p_2^{a_2}\ldots p_k^{a_k}$, where $p_1, p_2, \ldots p_k$ are prime divisors of b. We'll prove there exist $c$ (actually every natural number works), such that:
$$p_1^{a_1(c\phi(m)+1)} \equiv p_1^{a_1} \pmod {m}$$
$$p_2^{a_2(c\phi(m)+1)} \equiv p_2^{a_2} \pmod {m}$$
$$\cdots$$
$$p_k^{a_k(c\phi(m)+1)} \equiv p_k^{a_k} \pmod {m}$$
Get the first relation and divide with $p_1^{a_1}$ since $m$ is square integer, one is the highest power $p_1$ that devides it. Now we get:
$$p_1^{a_1c\phi(m)} \equiv 1 \pmod n$$
where $n=\frac m{gcd(m,p_1)}$, obviously $(n,p_1) = 1$ since m is squarefree integer. Now use the fact that the Euler Totient Function is multiplicative for relatively prime numbers and that $p_1^{\phi(n)} \equiv 1 \pmod n$:
$$p_1^{a_1c\phi(m)} \equiv p_1^{a_1c\phi(n) \phi(p_1)} \equiv (p_1^{\phi(n)})^{a_1c\phi(p_1)} \equiv 1^{a_1c\phi(p_1)}  \equiv 1 \pmod n$$
Simularly we prove for each of the congruence relations.
Now just multiply all the congruence relations and we have:
$$(p_1^{a_1}p_2^{a_2}\ldots p_k^{a_k})^{c\phi(m) + 1} \equiv p_1^{a_1}p_2^{a_2}\ldots p_k^{a_k} \pmod m$$
$$b^{c\phi(m) + 1} \equiv b \pmod m$$
Hence the proof.

You can directly prove this by using a nice lemma that another MSE user has proved: here. Subsitute $e=c\phi(m) + 1$ in his answer and use that $p-1 = \phi(p)$ and the fact that $m$ is squarefree.


text:
Q: Delete top message from MQQueue I am constructing a messaging system using MQSeries. For some reason, when I perform q.get(...), I am getting an exception thrown (I don't know the specific MQException). Below is the code causing the error:
private static MQGetMessageOptions GMO = new MQGetMessageOptions();
private static int GMO_OPTIONS = MQC.MQGMO_SYNCPOINT | MQC.MQGMO_WAIT;
GMO.options = GMO.options | GMO_OPTIONS;
GMO.waitInterval = MQC.MQWI_UNLIMITED;

MQEnvironment.hostname = args[0];
MQEnvironment.channel = args[2];
MQEnvironment.port = Integer.parseInt(args[1]);
MQQueueManager queueManager = new MQQueueManager(args[3])

MQMessage msg = new MQMessage();
MQQueue q = queueManager.accessQueue("qName1",MQC.MQOO_OUTPUT);
q.get(msg, GMO);

My plan is, when this error occurs, skip the message and delete it. To perform the delete I will call the following function:
private void deleteMsg(MQQueueManager queueManager, String queueName) throws MQException {
    MQGetMessageOptions tempGmo = new MQGetMessageOptions();
        tempGmo.options |= MQC.MQGMO_WAIT;
        tempGmo.waitInterval = 1000;
    MQQueue remover = queueManager.accessQueue(queueName, MQC.MQOO_INPUT_AS_Q_DEF);
        remover.get(new MQMessage(), tempGmo);
        queueManager.commit();
}

Would the remover.get() in my deleteMsg function also, in this specific scenario, fail for the same reason? Or does the option used to construct the MQQueue(MQC.MQOO_INPUT_AS_Q_DEF vs MQC.MQOO_OUTPUT) prevent it from also failing? If I am having trouble accessing my queue's message, how do I discard the top message and move to the next?
To shorten my question:
If I am unable to perform a get() on a given queue to retrieve a message, how can we delete that corrupt message on the same queue?
Thank you!

A: OMG!
MQQueue q = queueManager.accessQueue("qName1",MQC.MQOO_OUTPUT);
q.get(msg, GMO);

Your are opening a queue for output (writing) but you are trying to get a message.  You have your shoes on the wrong feet!!  Secondly, why aren't you catching the MQException that MQ would be throwing??  The exception would have included the reason code which would have given you the exact explanation to your issue.
Here's how you should be opening the queue for reading:
try
{
   int oo = MQC.MQOO_INPUT_SHARED + MQC.MQOO_FAIL_IF_QUIESCING;
   MQQueue q = queueManager.accessQueue("qName1",oo);
   MQGetMessageOptions gmo = new MQGetMessageOptions();
   gmo.options = MQC.MQGMO_NO_WAIT + MQC.MQGMO_FAIL_IF_QUIESCING;
   q.get(msg, gmo);
}
catch (MQException e)
{
   System.err.println(e.getLocalizedMessage() );
   System.err.println("CC = " + e.completionCode + " - RC = " + e.reasonCode);
}

Also, make sure you use the appropriate "Fail if quiescing" option for the particular MQ API call.
Finally, look up "backout queue".  If your application is having an issue with a message then the message should be moved to a backout queue and not simply deleted.

A: I do not why what you are doing does not work for you but I wonder why are you using proprietary API of MQ Series instead of using JMS API. In JMS terms remove top message just means receive the message, so call of session.receieve() does the work.
Using common JMS API has a lot of advantages. The main of them is that you can easily move from MQ Series to any other messaging solution without changing even one line of your code.

A: I wonder if the program compiled because there is no option called GMO_OPTIONS. All MQ constants are prefixed MQC


text:
Q: Intel MPI mpirun does not terminate using java Process.destroy() My Intel MPI version is impi/5.0.2.044/intel64 installed on a RHEL machine.
I am using java to invoke an MPI program using the following code:
ProcessBuilder builder = new ProcessBuilder();
builder.command("mpirun ./myProgram");
builder.redirectError(Redirect.to(new File("stderr")));
builder.redirectOutput(Redirect.to(new File("stdout")));
Process p = null;
try {
    p = builder.start();
} catch (IOException e) {
    e.printStackTrace();
}
// Process has started here
p.destroy();
try {
    // i = 143
    int i = p.exitValue();
} catch( IllegalThreadStateException e){
}

But even after the exitValue() is known without throwing exception, ps aux still shows a bunch of ./myProgram, and the program is still writing result files as if it is not being killed, terminating only after it finishes all its calculation.
Currently, the only way I find successful to terminate ./myProgram is to terminate the java using Ctrl+C in the console to the java program.
My intention is to stop the calculation immediately and let the java program schedule some other calculation. Is there any walkaround to force all mpi instances to terminate, or at least guarantee a termination in small, definite amount of time (e.g. 30s or 1 min of polling)?

A: The problem is that the JDK implementation of destroy sends SIGTERM, which shuts down mpirun hard.
See here for the relevant JDK source.
You need to send SIGINT to give MPI a chance to shut down gracefully.
E.g. Runtime.getRuntime().exec("kill -9 <pid>");
You can get the PID by invoking mpirun with --report-pid. (read the man-page)
edit
You can alternatively use reflection to figure out the PID of a process you started under a UNIX-like OS (stolen from here). As we are talking about kill and signal, that should not be a restriction.
if(process.getClass().getName().equals("java.lang.UNIXProcess")) {
  /* get the PID on unix/linux systems */
  try {
    Field f = process.getClass().getDeclaredField("pid");
    f.setAccessible(true);
    pid = f.getInt(p);
  } catch (Throwable e) {
  }
}


text:
Q: \hrule with vertical margin Is it possible to specify a vertical margin for \rule or \hrule?
When I say
abc
\hrule
def

the line "touches" the text above and below, so I would like it to have a margin of about 1mm.

A: TeX doesn't insert interline glue around rules. You need to add the vertical space yourself
abc

\vskip1mm
\hrule
\vskip1mm

def


text:
Q: UIWebView is crashing when trying to load a local html file The code I am using in my view controller viewDidLoad method:
NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest* request = [[NSURLRequest requestWithURL:url] autorelease];
[webView loadRequest:request];

I get EXE_BAD_ACCESS

A: requestWithURL: will give you an autoreleased object so you don't need to autorelease it again.


text:
Q: Query data from current user in arrowdb how can i query the checkin from a specific user in the api? Like a join with the user and filter by the user_id? It because checkin does not have user_id property.

A: Just did a workaround putting the owner_id as a custom_field in the checkin creation.

A: You should be able to use user_id in query checkins API, like following example:
curl -c cookies.txt -b cookies.txt -X GET --data-urlencode 'where={"user_id":"56207d2616d4b1e2de4bbba8"}' "https://api.cloud.appcelerator.com/v1/checkins/query.json?key=myOwnAppKey&pretty_json=true&show_user_like=true&count=true"
{
  "meta": {
    "code": 200,
    "status": "ok",
    "method_name": "queryCheckins",
    "count": 1
  },
  "response": {
     "checkins": [
      {
        "id": "56e67fb3550a680912694e17",
        "created_at": "2016-03-14T09:09:07+0000",
        "updated_at": "2016-03-14T09:09:07+0000",
        "place_id": "56e67edda778ca09086b8ff1",
        "user_id": "56207d2616d4b1e2de4bbba8"
      }
    ]
  }
}


text:
Q: Flask, Apache, CentOS, and Permission Denied on the datastore I've setup up a flask project on a CentOS 6.4 machine, with python 2.7.6 and mod_wsgi 3.x that I built myself on the box.
The app uses a file based database for storing RDF data, and I'm getting an Error 13 on the folder containing the datastore.
from genometry import app as application
File "/opt/genometry/software/genometry.py", line 125, in <module>
db, classes, user_datastore, security = create_db(app)
File "/opt/genometry/software/genometry.py", line 101, in create_db
db.store.open(app.config['db'])
"build/bdist.linux-x86_64/egg/rdflib/plugins/sleepycat.py", line 89, in open
db_env = self._init_db_environment(homeDir, create)
File "build/bdist.linux-x86_64/egg/rdflib/plugins/sleepycat.py", line 66, in     _init_db_environment
mkdir(homeDir)
OSError: [Errno 13] Permission denied: 'store.kb'

I've tried everything I can think of.  Changed the /opt and everything under it to be owned by apache:apache.  Changed /opt and everything under it to be 777, and yet still a permissions error.  How can that be?  What's the best way to setup the permission on folder "store.kb"

A: It turns out the problem was that Apache was looking for the store.kb in /var/www due to the rdfalchemy db uri.  I updated it to:
app.config['rdfalchemy_dburi'] = 'sleepycat:////{0}/store.kb'.format(PROJECT_ROOT)

and now everything works fine


text:
Q: is async really making sense here? NpgSQL with F# I have the following transaction:
let insertPositionsAsync accountId timestamp (positions: PositionInfo list) : Async<Result<int, ExchangeError>> =
    async {
        try
            use connection = getConnection location
            do! connection.OpenAsync()

            use writer =
                connection.BeginBinaryImport(
                        $"COPY {accountId}.{tablePositionsName} (ts,instrument,average_price,leverage,unrealized_pnl,side,initial_margin,maintenance_margin,position_initial_margin,open_order_initial_margin,quantity,max_notional)
                        FROM STDIN (FORMAT BINARY)"
                    )

            for t in positions do
                do! writer.StartRowAsync()                                                     |> Async.AwaitTask
                do! writer.WriteAsync(timestamp,                       NpgsqlDbType.Timestamp) |> Async.AwaitTask
                do! writer.WriteAsync(t.Instrument.Ticker,             NpgsqlDbType.Varchar)   |> Async.AwaitTask
                do! writer.WriteAsync(t.AveragePrice,                  NpgsqlDbType.Double)    |> Async.AwaitTask
                do! writer.WriteAsync(t.Leverage,                      NpgsqlDbType.Integer)   |> Async.AwaitTask
                do! writer.WriteAsync(t.UnrealizedPnl,                 NpgsqlDbType.Double)    |> Async.AwaitTask
                do! writer.WriteAsync(t.Side.ToString().ToLower(),     NpgsqlDbType.Varchar)   |> Async.AwaitTask
                do! writer.WriteAsync(t.InitialMargin,                 NpgsqlDbType.Double)    |> Async.AwaitTask
                do! writer.WriteAsync(t.MaintenanceMargin,             NpgsqlDbType.Double)    |> Async.AwaitTask
                do! writer.WriteAsync(t.PositionInitialMargin,         NpgsqlDbType.Double)    |> Async.AwaitTask
                do! writer.WriteAsync(t.OpenOrderInitialMargin,        NpgsqlDbType.Double)    |> Async.AwaitTask
                do! writer.WriteAsync(t.Quantity,                      NpgsqlDbType.Double)    |> Async.AwaitTask
                do! writer.WriteAsync(t.MaxNotional,                   NpgsqlDbType.Double)    |> Async.AwaitTask

            let! c = writer.CompleteAsync()
            return Ok (int c)

        with ex ->
            error $"insertPositionsAsync {ex.Humanize()}"
            return Error (ServiceException ex)
    }

my understanding is that the loop:
            for t in positions do
                do! writer.StartRowAsync()                                                     |> Async.AwaitTask
                do! writer.WriteAsync(timestamp, NpgsqlDbType.Timestamp) |> Async.AwaitTask
                ...

            let! c = writer.CompleteAsync()

is happening in the driver and it's just collecting data in some local storage. Does it make sense to have all these async blocks then? (performance wise).
But the async API must exist for some reason. What could I be missing?

A: It's true that in many (even most) cases, the APIs on NpgsqlBinaryImporter will complete synchronously, since they simply write to Npgsql's memory buffer. This is true not just for individual value writing (WriteAsync), but for StartRowAsync as well - none of these APIs perform I/O unless the internal buffer is full.
So in effect, you're streaming out an arbitrarily long stream of data to PostgreSQL, via a memory buffer. Given enough data (after all, this is a "bulk import"), at some point the buffer will be exhausted and the API will flush; the question is whether that flush should block the calling thread or happen asynchronously.
So yes, it does make sense to use the async APIs, if you want I/O to happen asynchronously (even if most calls don't result in I/O). There should be very little overhead for calling the async methods (as opposed to the sync ones), so the async ones should generally be the default; but measure the overhead yourself to get the full picture.

A: As with any performance related question, the only meaningful answer is  measure it and see for yourself!
More generally, async makes it possible to do the communication with the database without blocking an operating system thread. This may or may not have performance implications - but it depends on what else is happening in your program.

*

*If you just have a single logical process communicating with the database, it makes no difference whether you do this in a synchronous or asynchronous bit of code.

*If you want to write data to a database, you could do this from multiple concurrent writers. In this case, async would make a difference as you could create more concurrent writters. But I think it would likely not help much - because the database will probably not be able to write faster when you have excessive number of writer threads.

*A more interesting case is when you are doing something else in your program. For example, if you have a web server than needs to handle many concurrent requests, it makes sense to use asynchronous communication with a database - because it will not block threads that you need to handle other web requests.
The summary is, you should measure the performance - but it will likely depend on what else is going on in your program. I do not think changing a single threaded writer script to async would make any difference (aside form adding some small overhead).

A: There's a discussion of this API here. It starts with someone saying:

It would be helpful to have asynchronous versions of BeginBinaryImport and BeginBinaryExport so they can be used from e.g. api endpoints without blocking the server.
For Import, given the write happens on Close/Dispose I'm guessing the write methods would not become async

However, one one of the developers then comments that:

Write can also block. So you need WriteAsync too.


text:
Q: How to get activerecord associations via reflection For normal columns, you can get at them via the columns class method. However, associations may be named something quite different if the foreign_key option is set in the relationship method. For example, given
class Post
  has_many :comments, :foreign_key => :message_id # this is a contrived example
end

if I did Post.column_names I could get at message_id, but is there any way to get comments?

A: Model.reflections gives information about a model's associations. It is a Hash keyed on the association name. e.g.
Post.reflections.keys # => ["comments"]

Here is an example of some of the information it can be used to access:
Post.reflections["comments"].table_name # => "comments"
Post.reflections["comments"].macro # => :has_many
Post.reflections["comments"].foreign_key # => "message_id"

Note: this answer has been updated to cover Rails 4.2 based on MCB's answer and the comments below. In earlier versions of Rails the reflection's foreign_key was accessed using primary_key_name instead, and the keys for the reflections may be symbols instead of strings depending on how the association was defined e.g. :comments instead of "comments".

A: For future Googlers in Rails 4 the answer would now be:
Post.reflections[:comments].foreign_key # => "message_id"

Taken from here: https://stackoverflow.com/a/15364743/2167965
EDIT:
reflections, as of 4.2, now takes strings instead of symbols which is a fun bug to track down. If you want to keep using symbols you should switch to reflect_on_association(:assoc_name). Also note reflections are actually the public api which will keep reporting things like HABTM, even though it's all has many through under the hood. The reflections Rails is actually using are now in _reflections

A: For an ActiveRecord object I use:
object._reflections

So, I can manipulate the Hash returned. For instance:
object._reflections.keys.each do |key|
    object.public_send(key).destroy_all
end

The above example delete all the relationships from database.


text:
Q: Object* or Object *? All programming languages I am familiar to (C/C++, Java, C#, Objective C) accept both notations. So I want to know which is semantically correct: Object* myObj or Object *myObj?

A: Well, it depends. Both are correct but I generally use the Object*, because the pointer itself can be considered a type and it is more readable.
But there is a problem with that. The pointer in C, by real, is just a modification of a type, and not a real type. If you declare multiple variables in one single line as this:
Object *a, b;

You will have a as a pointer to Object and b as one instance of Object, so I imagine that the correct way is to put the pointer with the variable.

A:
Which is semantically correct?

Semantically they are identical. Therefore which you use is a matter of taste.

Which taste should you prefer?  Well, you can write object* a, b and think that you have declared two pointers. Of course you have not, you have declared a to be a pointer and b as an object.
So you should certainly prefer object *a, b to object* a, b. However, I believe it is better still to have a single line for each variable declaration:
object *a;
object b;

This approach has no scope for confusion and is recommended by many coding style guidelines.


text:
Q: Симплекс метод. Командная строка ожидает ввод символа Пишу программу реализующую решение задачи на максимум симплекс методом. Столкнулся с проблемой, при входе в цикле while в методе getPlane программа останавливается, по сути она должна выводить как минимум матрицу при завершении 1 итерации цикла, но и этого не происходит, может кто знает, в чем проблема?
#include "stdafx.h"
#include <iostream>

using namespace std;

class Simplex{
int num_x; // кол-во переменных
int num_r; // кол-во ограничений
double *func;
double **syst;
short int *sign; //
double *x;
double *rez;
int strs, cols;
public:
void inpValues();
void printMatrix();
bool check();
void getPlane();
};

void Simplex::inpValues(){
cout << "Vvedite kol-vo ogranichenii v syst: "; cin >> num_r;
cout << "Vvedite kol-vo x: "; cin >> num_x;
func = new double[num_x];
strs = num_r + 1;
cols = num_x + num_r + 2;
syst = new double *[strs];
for (int i = 0; i < strs; i++)
    syst[i] = new double[cols];
func = new double[num_x];
cout << "Vvedite koefficienti v glavnom urovnenii: \n";
for (int i = 0; i < num_x; i++){
    cout << "x" << i + 1 << " = "; cin >> func[i];
    syst[0][i] = func[i] * (-1);
}
sign = new short int[num_r];
x = new double[num_x];
rez = new double[num_r];
for (int i = 0; i < num_r; i++){
    cout << "Vvedite znak v " << i + 1 << "-m uravnenii systemi 0 - <=; 1 - >=:";cin >> sign[i];
    cout << "Vvedite koefficienti pri peremennih i rezultat dlya " << i + 1 << "-go uravneniya systemi: \n";
    for (int j = 0; j < num_x; j++){
        cout << "x" << j + 1 << " = "; cin >> x[j];
        if (sign[i] == 0) syst[i + 1][j] = x[j];
        else syst[i + 1][j] = x[j] * (-1);
    }
    cout << "rez = "; cin >> rez[i];
    if (sign[i] == 0) syst[i+1][cols-2] = rez[i];
    else syst[i + 1][cols - 2] = rez[i] * (-1);
}
syst[0][cols-2] = 0;
for (int i = 0, temp = 0; i < strs; i++, temp++){
    syst[i][cols - 1] = 0;
    for (int j = num_x; j < cols-2; j++){
        if (j == num_x + temp - 1 && i != 0) syst[i][j] = 1;
        else syst[i][j] = 0;
    }
}
printMatrix();
}

void Simplex::printMatrix(){
cout << "\n";
for (int i = 0; i < strs; i++){
    for (int j = 0; j < cols; j++)
        cout << syst[i][j] << " ";
    cout << "\n";
}
}

bool Simplex::check(){
bool temp = false;
for (int i = 0; i < cols - 1; i++){
    if (syst[0][i] < 0){ temp = true; break;}
}
return temp;
}

void Simplex::getPlane(){
int i_str, i_col, i , j, last_str = 0;
double  min, atd, min_atd;
int iter = 0;
while (check()){
    ++iter;
    cout << "Iteraciia: "<< iter << "\n";

    min = 1;
    // находим разрешающий столбец
    for (i = 0; i < cols; i++){
        if (syst[0][i] < 0 && syst[0][i] < min){ min = syst[0][i];  i_col = i; }
    }
    min_atd = syst[1][cols - 2] / syst[1][i_col];
    // нахоидим разешающую строку
    for (i = 1; i < strs; i++){
        atd = syst[i][cols - 2] / syst[i][i_col];
        if (i != last_str && atd <= min_atd){ min_atd = atd; i_str = i; }
    }
    // Длим элементы строки с разрешающим эл-том на разреш. элем.
    for (i = 0; i < cols; i++)
        if (i != i_col) syst[i_str][i] = syst[i_str][i] / syst[i_str][i_col];
    syst[i_str][i_col] = 1;
    // находим остальные элементы строки
    for (i = 0; i < strs; i++){
        if (i != i_str){
            for (j = 0; j < cols - 1; i++){
                if (j != i_col) syst[i][j] = (syst[i_str][j] * (-1) * syst[i][i_col]) + syst[i][j];
            }
        } else continue;
        syst[i][i_col] = (syst[i_str][j] * (-1) * syst[i][i_col]) + syst[i][i_col];
    }
    printMatrix();
}
 }

void main(){
Simplex *obj = new Simplex();
obj->inpValues();
obj->getPlane();
system("pause");
}

A: for (j = 0; j < cols - 1; i++)

Детская ошибка: i вместо j.


text:
Q: Slope of line tangent to function at point.
I hope the picture's quality isn't too bad,
but the question was  slope of line tangent to $y^2 + (xy +1) ^3 = 0$ at point $(2,-1)$.
I tried two ways where one was trying to  find the derivative right away- is this way wrong? especially the second part where I put $2(xy + 1) ^2$ ?
The second way I tried was actually multiplying it out because I was sort of hopeless.
Bot hare wrong answers, and the slope was $\frac34$.
Please help me.

A: Function: $y^2 + (xy +1) ^3 = 0$
Differentiate implicitly:
\begin{align*}
y^2 + (xy +1) ^3 &= 0\\
\implies \frac{d}{dx}y^2 + (xy +1) ^3 &= 0\\
\implies 2y\frac{dy}{dx}+3(xy+1)^2\left(y+x\frac{dy}{dx}\right)&=0
\end{align*}
Now substitute $(x,y)$ and $\dfrac{dy}{dx}$ the subject.
Alternatively, you could make $y$ the subject in your original function.
Key Fact:
$$\frac{d}{dx}y^2=\frac{dy}{dx}\frac{d}{dy}y^2=\frac{dy}{dx}2y$$
Edit (Chain rule and implicit differentiation):
\begin{align*}
\frac{d}{dx} (xy +1) ^3 &= 0\\
3(xy+1)^2\times\frac{d}{dx}(xy+1)&= 0
\end{align*}
Note that for the chain rule, you just bring down the power from outside the bracket and reduce the power by one then perform the differentiation on the inside.


text:
Q: Change JComboBox colours WITHOUT renderer I can change the ComboBox background color using:
UIManager.put("ComboBox.background", Color.RED);

and it works.
But to change the [selected].background, having a look at Nimbus Defaults the property is called ComboBox:"ComboBox.listRenderer"[Selected].background, so I tried with:
UIManager.put("ComboBox:\"ComboBox.listRenderer\"[Selected].background", Color.RED);

but it doesn't work.
I want to do this with a renderer (which I have tried and gives many problems into a long code I even hadn't written myself, and rendering the comboboxes into the JFileChoosers is an extra problem if I go that way). So, is there any solution to fix this using UIMAnager.put()?

A: set different Color, without using Nimbus defaluts
1/ for separate JComboBox
((JTextField) myJComboBox.getEditor().getEditorComponent())
#setBackground(Color.xxxx);

2/ for JFileChooser

*

*extract all JComponents from JFileChooser (compound JComponents) as sugested here, same way as is described for JList and JScrooPane

*safiest way by extract all JComponents from JFileChooser as suggested in your previous post about that here
3/ by using NimbusDefalut find defalut for

*

*JTextField and as suggested in my add No.1

*JComboBox's DropDown List from defaluts for JList, HighLighter for selection from JTable
EDIT:
code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.basic.BasicComboPopup;

public class DisabledEditableCombo extends JFrame {

    private static final long serialVersionUID = 1L;
    private String comboList[] = (new String[]{"-", "London", "New York", "Sydney", "Tokyo"});
    private JComboBox cmb = new JComboBox(comboList);
    private JComboBox cmb1 = new JComboBox(comboList);
    private JComboBox cmb2 = new JComboBox(comboList);
    private JComboBox cmb3 = new JComboBox(comboList);
    private JList list;
    private JCheckBox checkBox = new JCheckBox("Combo enabled", false);

    public DisabledEditableCombo() {
        JLabel lbl = new JLabel("Editable JComboBox");
        cmb.setEditable(true);
        ((JTextField) cmb.getEditor().getEditorComponent()).setDisabledTextColor(Color.red);
        ((JTextField) cmb.getEditor().getEditorComponent()).setBackground(Color.green);
        cmb.setSelectedItem("Just Editable");
        JLabel lbl1 = new JLabel("Non-Editable JComboBoxes");
        //UIManager.put("ComboBox.disabledForeground", Color.red.darker().darker());
        cmb1.setSelectedItem("Sydney");
        cmb1.setRenderer(new DefaultListCellRenderer() {//  ListCellRenderer

            private static final long serialVersionUID = 1L;

            @Override
            public void paint(Graphics g) {
                setBackground(cmb1.getBackground());
                setForeground(Color.red);
                super.paint(g);
            }
        });
        cmb2.getEditor().getEditorComponent().setForeground(Color.blue);
        ((JTextField) cmb2.getEditor().getEditorComponent()).setDisabledTextColor(Color.red);
        cmb2.setSelectedItem("London");
        cmb3.setSelectedItem("Sydney");
        checkBox.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                boolean selected = checkBox.isSelected();
                cmb.setEnabled(selected);
                cmb1.setEnabled(selected);
                cmb2.setEnabled(selected);
                cmb2.setEditable(!cmb2.isEnabled());
                cmb2.setForeground(selected ? Color.blue : Color.red);
                if (cmb2.getEditor() != null) {
                    ((JTextField) cmb2.getEditor().getEditorComponent()).setDisabledTextColor(Color.red);
                }
                cmb3.setEnabled(selected);
                Object child = cmb3.getAccessibleContext().getAccessibleChild(0);
                BasicComboPopup popup = (BasicComboPopup) child;
                list = popup.getList();
                if (list != null) {
                    if (selected) {
                        list.setForeground(Color.blue);
                    } else {
                        list.setForeground(Color.red);
                    }
                }
            }
        });
        cmb.setEnabled(false);
        cmb1.setEnabled(false);
        cmb2.setEnabled(false);
        cmb3.setEnabled(false);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(300, 300));
        setLocation(150, 100);
        setLayout(new GridLayout(7, 0, 10, 10));
        add(lbl);
        add(cmb);
        add(lbl1);
        add(cmb1);
        add(cmb2);
        add(checkBox);
        add(cmb3);
        pack();
        setVisible(true);
    }

    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                DisabledEditableCombo disabledEditableCombo = new DisabledEditableCombo();
            }
        });
    }
}


text:
Q: Is converting a defensive copy to a stream still thread-safe? I have the following class (bulk code omitted):
public class SimpleEventBus implements EventBus {
    private final static Set<EventHandler> EMPTY_SET = Collections.emptySet();
    private final static EventHandler[] EMPTY_ARRAY = new EventHandler[0];
    private final static Supplier<Set<EventHandler>> CONCURRENT_SET_SUPPLIER =
            () -> Collections.newSetFromMap(new ConcurrentHashMap<>());

    private final ConcurrentMap<Class<?>, Set<EventHandler>> eventMapping = new ConcurrentHashMap<>();
    private final Class<?> eventClassConstraint;

    public SimpleEventBus() {
        this(Object.class);
    }

    public SimpleEventBus(final Class<?> eventClassConstraint) {
        this.eventClassConstraint = Objects.requireNonNull(eventClassConstraint);
    }

    ...

    @Override
    public void executeEvent(final Object event) {
        if (eventClassConstraint.isAssignableFrom(event.getClass())) {
            getCopyOfEventHandlers(event.getClass()).forEach(eventHandler -> eventHandler.invoke(event));
        }
    }

    ...

    private Stream<EventHandler> getCopyOfEventHandlers(final Class<?> eventClass) {
        Set<EventHandler> eventHandlers = eventMapping.get(Objects.requireNonNull(eventClass));
        return (eventHandlers == null)
                ? Stream.empty()
                : Arrays.stream(eventHandlers.toArray(EMPTY_ARRAY));
    }

    ...

}

I am wondering if getCopyOfEventHandlers here still returns a thread safe copy of the set. I know it would if I would write it as such:
private EventHandler[] getCopyOfEventHandlers(final Class<?> eventClass) {
    Set<EventHandler> eventHandlers = eventMapping.get(Objects.requireNonNull(eventClass));
    return (eventHandlers == null)
            ? EMPTY_ARRAY
            : eventHandlers.toArray(EMPTY_ARRAY);
}

But I am wanting to benefit from Java 8 as much as possible, hence I decided to do it like this:
private Stream<EventHandler> getCopyOfEventHandlers(final Class<?> eventClass) {
    Set<EventHandler> eventHandlers = eventMapping.get(Objects.requireNonNull(eventClass));
    return (eventHandlers == null)
            ? Stream.empty()
            : Arrays.stream(eventHandlers.toArray(EMPTY_ARRAY));
}

Is this still thread-safe as streams use lazy initialization? Does this mean that the resulting array (from eventHandlers.toArray(EMPTY_ARRAY) gets stored in memory (blocked from GC) implicitely?

A: eventHandlers.toArray(EMPTY_ARRAY) does create an array immediately - only the stream is lazy. So your two versions are essentially identical from a thread safety perspective.


text:
Q: Create a 'close/exit' option for a child frame that is created using tkinter in python I have created a script using tkinter, that brings up a child frame when you press a button. The  frame occupies the full screen size on my mac laptop. Now I need to create an option to exit/ or close this new frame. What is the best option to do that?
-Thanks
from Tkinter import *
import tkFont
class App(Frame):
  def __init__(self, *args, **kwargs):
    Frame.__init__(self, *args, **kwargs)
    self.apple = Button(self,
                     text="Apple", command=self.write_apple)
    self.apple.pack(side=LEFT)

def write_apple(self):
    self.customFont = tkFont.Font(family="Helvetica", size=80)
    t = Toplevel(self)
    t.overrideredirect(True)
    t.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))
    l = Label(t, text="This is a green apple.",font=self.customFont)
    l.pack(side="top", fill="both", expand=True)

if __name__ == "__main__":
    root = Tk()
    main = App(root)
    main.pack(side="top", fill="both", expand=True)
    root.mainloop()

A: This solution handles the case that multiple instances of Toplevel are created:
from Tkinter import *
import tkFont
class App(Frame):
    def __init__(self, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs)
        self.apple = Button(self,
                            text="Apple", command=self.write_apple)
        self.apple.pack(side=LEFT)
        self.top_dict = dict()

    def destroy_top(self, event):
        # event.widget is the instance of Label that was clicked
        # Get the instance of Toplevel
        top = self.top_dict[event.widget]
        # Destroy the instance of Toplevel
        top.destroy()
        # Remove the instance of Toplevel from the list
        del self.top_dict[event.widget]

    def write_apple(self):
        self.customFont = tkFont.Font(family="Helvetica", size=80)
        # Create an instance of Toplevel
        top = Toplevel(self)
        top.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))
        label = Label(top, text="This is a green apple.",font=self.customFont)
        label.pack(side="top", fill="both", expand=True)
        # Bind the destroy_top method to the mouse-button-1 click
        label.bind('<Button-1>', self.destroy_top)
        # Save the instance of Toplevel using the label as the key
        self.top_dict[label] = top

if __name__ == "__main__":
    root = Tk()
    main = App(root)
    main.pack(side="top", fill="both", expand=True)
    root.mainloop()

NOTE: As @Bryan Oakley noted, removing the call to overrideredirect adds window decorations to the instance of Toplevel.


text:
Q: Weak convergence of measures and Regularized optimal transport Let W_p be the Wasserstein metric on the space of probability measures on $\mathcal{X}$, a compact subset of $\mathbb{R}^n$. I know that $\mu_k \rightarrow \mu$ (under weak convergence of measures) iff $W_p(\mu_k, \mu) \rightarrow 0$. Now instead of working with $W_p$, I am using the entropic regularized version of $W_p$, call it $W_{p, \lambda}$ as introduced in https://papers.nips.cc/paper/2013/file/af21d0c97db2e27e13572cbf59eb343d-Paper.pdf. Due to some pathological properties of $W_{p, \lambda}$, let us assume that the sequence $\mu_k$ is not constant and also the number of samples drawn from our measures are arbitrarily large. Then my question is: Is it still true that
$\mu_k \rightarrow \mu$ iff $W_{p, \lambda}(\mu_k, \mu) \rightarrow 0$

A: So I've found the answer. [This article by Feydey et al][1] proves that for a compact metric space $X$, and a Lipschitz cost $c$. Then the Sinkhorn Divergence does metrize the weak convergence, i.e $\tilde W_{p,\epsilon}(\mu_n,\mu)\to 0 \iff \mu_n \rightharpoonup \mu$.
Just note that the Sinkhorn divergence is an unbiased version of the regularized cost, where:
$$
\tilde W_{p,\epsilon}(\alpha, \beta)^p =
2W_{p,\epsilon}(\alpha,\beta) -W_{p,\epsilon}(\alpha,\alpha)-W_{p,\epsilon}(\beta,\beta)
$$
[1]: https://hal.archives-ouvertes.fr/hal-01898858/document


text:
Q: Не могу обратиться к атрибуту класса Cython Решил перевести программу из Python3 в Cython, а тут такая проблема. Есть python-класс:
class Device:
    def __init__(self, name, delay, tabl):
        self.name = name
        self.delay = delay
        self.speed_to = tabl

    def upd(self, u):
        self.speed_to.update(u)
        return 0

В Cython абсооютный новичок, поэтому перевёл в cython-класс по примерам, которые смог найти:
cdef class Device:
    cdef str name
    cdef long double delay
    cdef dict speed_to

    def __init__(self, str names, long double delays, dict tabls):
        self.name = names
        self.delay = delays
        self.speed_to = tabls

    cpdef upd(self, dict u):
        self.speed_to.update(u)
        return 0

Выглядит (для меня) так, что должно работать, но при обращении к любому атрибуту объекта вроде Device('name', 123456, {1:2, 2:3}).name выдаёт ошибку:
AttributeError: 'cget_time.Device' object has no attribute 'name'

Действительно, dir() этого объекта показывает ['__class__', ...magic methods..., '__subclasshook__', 'upd'], то есть, атрибутов он не видит.
В чём проблема и как можно исправить?

A: По умолчанию поля extension type приватные и видимы только для методов. Это можно исправить с помощью модификаторов readonly и public:
cdef class Device:
    cdef public str name
    ...


text:
Q: refine merge-sort to count number of inversions I'm working on an improved version of merge sort so that it counts the number of inversions.
Note: I don't want you to get my homework done, but I have some ideas about this and would love to know whether they make sense at all.
As merge-sort is O(nlogn I need to adjust it without worsing its overall performance. I think to this I have to insert a test that takes constant time (1)
(1) I test for inversion (upper) with A[i] > A[j] given that i<j
To find the appropriate spot to insert the test I am asking myself: when during the execution of merge sort is guaranteed that the test runs unrelated to n?
I think the only spot where this is true is when the list is split into one-element lists
Hence, I would propose the following algorithm adjustment
use divide-and-conquer and split the list to one elements lists
test A[i] > A[j] as i<j is true for two adjacent lists

Does this make sense at all?
Eventually, I have to carry with the count of inversions until the algorithm terminates. Could someone give me a hint with regard to this problem?
(Intuitively I would give the count to the merge part as the algorithm terminates when merging is complete.)
Cheers,
Andrew

A: If you only count when the array size is 1, you're only looking at pair-wise inversions. I think you just want to keep a counter throughout all the recursive calls, and increment it whenever, during the merge step, you compare an element from the left subarray to one from the right subarray and the one from the right is smaller (assuming you're sorting in ascending order).


text:
Q: Unable to install package I'm trying to install a few packages, the command is :
sudo apt-get install nginx-extras passenger

But I'm getting an error afterward:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 nginx-extras : Depends: nginx-common (= 1:1.6.2-9.5.0.4~trusty1) but it is not going to be installed
                Depends: perl (>= 5.18.2-2ubuntu1) but 5.14.2-21+deb7u2 is to be installed
                Depends: perlapi-5.18.2 but it is not installable
                Depends: libc6 (>= 2.14) but 2.13-38+deb7u8 is to be installed
                Depends: libgd3 (>= 2.1.0~alpha~) but it is not installable
                Depends: libperl5.18 (>= 5.18.2) but it is not installable
                Recommends: passenger (< 5.0.5) but 1:5.0.4-1~trusty1 is to be installed
 passenger : Depends: libc6 (>= 2.14) but 2.13-38+deb7u8 is to be installed
             Recommends: passenger-doc (= 1:5.0.4-1~trusty1)
             Recommends: passenger-dev (= 1:5.0.4-1~trusty1) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I don't exactly know what to do with this problem, I do believe I need to install some packages, but all of those?
Thanks in advance!

A: I had the same error and I fixed it.
I guess you followed the same guide as me (https://gorails.com/deploy/ubuntu/14.04) and this one only works if you are using 14.04. What version and distribution are you using?. You can find it if you execute cat /etc/*-release.
If you look on like with VERSION, it look like this on VERSION="7 (wheezy)".
Next ting you need to do is edit /etc/apt/sources.list.d/passenger.list as root. So you can to sudo vim /etc/apt/sources.list.d/passenger.list and than change
deb https://oss-binaries.phusionpassenger.com/apt/passenger trusty main

to
deb https://oss-binaries.phusionpassenger.com/apt/passenger <Your version> main

in my case
deb https://oss-binaries.phusionpassenger.com/apt/passenger wheezy main

Than do `sudo apt-get update' Now you should be able to install nginx-extras passenger


text:
Q: how to change the title of Title Bar on the left up corner of the screen with code I create a android project with Bottom Navigation  Activity template, then I get three default fragment,
in the method: onCreateView of  DashboardFragment ,i added  getActivity().setTitle("Important");
but the titile (on the left up corner of the screen)  is still "Dashboard",it didn't change to "Important" why?
I want to change the title with code ,I want to change it when running the app,not just config it in the mobile_navigation.xml
thanks.
here is mobile_navigation.xml
here is   mobile_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mobile_navigation"
    app:startDestination="@+id/navigation_home">

    <fragment
        android:id="@+id/navigation_home"
        android:name="com.example.testfragmentjump.ui.home.HomeFragment"
        android:label="@string/title_home"
        tools:layout="@layout/fragment_home" />

    <fragment
        android:id="@+id/navigation_dashboard"
        android:name="com.example.testfragmentjump.ui.dashboard.DashboardFragment"
        android:label="@string/title_dashboard"
        tools:layout="@layout/fragment_dashboard" />

    <fragment
        android:id="@+id/navigation_notifications"
        android:name="com.example.testfragmentjump.ui.notifications.NotificationsFragment"
        android:laabel="@string/title_notifications"
        tools:layout="@layout/fragment_notifications" />
</navigation>

A: First you have to remove the title of Dashboard Fragment to check where it is in XML or Code class,then by code your able to change the title as per your selection of fragment!


text:
Q: Creating a dynamic class instance programmatically in PHP with variable arguments? I've some code that creates ad instance with a dynamic class (i.e. from a variable):
$instance = new $myClass();

Since the constructor has different argument count depending on $myClass value, How do I pass a variable list of arguments to the new statement? Is it possible?

A: class Horse {
    public function __construct( $a, $b, $c ) {
        echo $a;
        echo $b;
        echo $c;
    }
}

$myClass = "Horse";
$refl = new ReflectionClass($myClass);
$instance = $refl->newInstanceArgs( array(
    "first", "second", "third"
));
//"firstsecondthird" is echoed

You can also inspect the constructor in the above code:
$constructorRefl = $refl->getMethod( "__construct");

print_r( $constructorRefl->getParameters() );

/*
Array
(
    [0] => ReflectionParameter Object
        (
            [name] => a
        )

    [1] => ReflectionParameter Object
        (
            [name] => b
        )

    [2] => ReflectionParameter Object
        (
            [name] => c
        )

)
*/

A: The easiest route would be to use an array.
public function __construct($args = array())
{
  foreach($array as $k => $v)
  {
    if(property_exists('myClass', $k)) // where myClass is your class name.
    {
      $this->{$k} = $v;
    }
  }
}

A: I don't know why but i don't like using the new operator in my code.
Here is a static function to create an instance of a class called statically.
class ClassName {
    public static function init(){
        return (new ReflectionClass(get_called_class()))->newInstanceArgs(func_get_args());
    }

    public static function initArray($array=[]){
        return (new ReflectionClass(get_called_class()))->newInstanceArgs($array);
    }

    public function __construct($arg1, $arg2, $arg3){
        ///construction code
    }
}

If you are using it inside a namespace you need to escape ReflectionClass like so: new \ReflectionClass...
Now you can call the init() method with a variable number of arguments and it will pass it on to the constructor and return an object for you.
Normal way using new
$obj = new ClassName('arg1', 'arg2', 'arg3');
echo $obj->method1()->method2();

Inline way using new
echo (new ClassName('arg1', 'arg2', 'arg3'))->method1()->method2();

Static call using init instead of new
echo ClassName::init('arg1', 'arg2', 'arg3')->method1()->method2();

Static call using initArray instead of new
echo ClassName::initArray(['arg1', 'arg2', 'arg3'])->method1()->method2();

The nice thing about the static methods is that you can run some pre construction operations in the init methods such as constructor argument validation.


text:
Q: Understanding Hierarchy of the $scope in AngularJS? When I create a object and navigate through the _proto__ property of it I get to know that it has been inherited from Object

Now when I create a new object and inherit the obj object, then I get the inheritance structure like this

Here i can understand that the object obj1 is being inherited from the object obj and the object obj is being inherited from the object Object, which is the global object.
Now my question is, when i debug in my console i get both obj and obj1 as Object but the when i debug the $scope of angularJS i get something like this

Why is the $scope returning b instead of Object which can be seen in all the two images above, what is so different in angularJS, am i missing something.
UPDATE 1
when I make a object of the constructor in javascript I get the function name in the constructor as shown in the image below

But in the case of the $scope i see no constructor function, why is that? am i missing something, please let me know

A: This is because you're debugging minified application.
$scope is an instance of internal Scope or ChildScope class.
In minified Angular bundle the class is called something like b.

A: When you inspect an object in console, it is referenced by this object's class name, for example:
function Scope() {}
var s = new Scope();

In your case, instead of function Scope() {}, in the minified version the code looks like this  function b() {} and new b() is used instead of new Scope()


text:
Q: Receive delegate method calls from multiple view controllers I have an app with a SplitViewController. The MasterViewController is a UITableViewController. And the DetailViewController is a UIViewController with a MapView.

I'm calling an API to get a list of events. In the tableView, I want to display the names and the addresses of the events. And in the mapView, I want to mark the locations of those events.
I have a class called DataLoader in which I call the API, parse the JSON object and create Event objects and put them in an array successfully.
import Foundation
import SwiftyJSON

@objc protocol DataLoaderDelegate {
    func eventDataReceived(items: [Event]?, error: NSError?)
}

public class DataLoader {

    private let api = ApiClient()

    var delegate: DataLoaderDelegate?

    init() { }

    public func fetchEvents() {
        api.getEvents({ (data) -> Void in
            let json = JSON(data)
            self.processEventData(json["data"])
        }, failure: { (error) -> Void in
            println("Error fetching events: \(error?.localizedDescription)")
            self.delegate?.eventDataReceived(nil, error: error)
        })
    }

    private func processEventData(data: JSON) {
        var events = [Event]()

        if let eventsArray = data.array {
            for eventObj in eventsArray {
                let event = Event(
                    id: eventObj["id"].int!,
                    type: EventType(rawValue: eventObj["type"].int!)!,
                    location: eventObj["location"].string!,
                    status: EventStatus(rawValue: eventObj["status"].int!)!
                )
                event.allDay = eventObj["allDay"].int!
                event.title = eventObj["title"].string
                event.description = eventObj["description"].string
                event.latitude = eventObj["lat"].double
                event.longitude = eventObj["lng"].double
                event.startDate = NSDate(string: eventObj["start"].string!)
                event.endDate = NSDate(string: eventObj["end"].string!)
                event.createdAtDate = NSDate(string: eventObj["created_at"].string!)
                event.updatedAtDate = NSDate(string: eventObj["updated_at"].string!)
                event.creatorEmail = eventObj["creatorEmail"].string
                event.organizerEmail = eventObj["organizerEmail"].string
                event.googleCalendarId = eventObj["google_cal_id"].string!
                event.googleEventId = eventObj["google_event_id"].string!
                event.htmlLink = eventObj["htmlLink"].string!

                events.append(event)
            }

            // Order the events by the startDate value
            events.sort({ $0.startDate!.timeIntervalSince1970 < $1.startDate!.timeIntervalSince1970 })

            self.delegate?.eventDataReceived(events, error: nil)
        }
    }
}

I have a delegate called DataLoaderDelegate with a method called func eventDataReceived(items: [Event]?, error: NSError?) which is called after all the event objects are inserted into an array so I can pass it through that method.
I need this method implemented in both the ListViewController where I populate the tableView and MapViewController where I populate the mapView. So I have implemented the eventDataReceived delegate method in both view controllers in order to get the events objects.
ListViewController.swift
import UIKit

class ListViewController: UITableViewController, DataLoaderDelegate {

    let loader = DataLoader()

    private var events = [Event]()

    override func viewDidLoad() {
        super.viewDidLoad()

        loader.delegate = self
        loader.fetchEvents()
    }

    // MARK: - Table view data source
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return events.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

        let event = events[indexPath.row]
        cell.textLabel?.text = event.title
        cell.detailTextLabel?.text = event.location

        return cell
    }

    // MARK: - DataLoaderDelegate
    func eventDataReceived(items: [Event]?, error: NSError?) {
        println("ListViewController got \(items?.count) events")
        if let events = items {
            self.events = events
            tableView.reloadData()
        }
    }
}

MapViewController.swift
import UIKit

class MapViewController: UIViewController, DataLoaderDelegate {

    let loader = DataLoader()

    override func viewDidLoad() {
        super.viewDidLoad()

        loader.delegate = self
    }

    // MARK: - DataLoaderDelegate
    func eventDataReceived(items: [Event]?, error: NSError?) {
        println("MapViewController got \(items?.count) events")
    }
}

But here's the problem. Only the implementation in the ListViewController gets executed. I think the reason is I create a new instance of DataLoader class in the MapViewController.
What should I do to have one instance of DataLoader across the entire application and receive its delegate method calls from all view controllers?
I've uploaded a demo project to my Dropbox if you need to run it to get a better idea.
Thanks.

A: This is a best-practice case for a Singleton-pattern
Your DataLoader should implement a static let holding the reference to the same object of self.
static let sharedInstance = DataLoader()

When you want the reference to constantly the same singleton-object. Call it with DataLoader.sharedInstance
Make sure to always use .sharedInstance then and do not forget to wipe any calls of the standard initializer of the class, because it will still make new instances unless you block this behavior programmatically.
Explained
Only inserting the singleton constant (shown above) will NOT make DataLoader class always return the singleton instance. The existing initializer calls like:
   var myDataLoader = DataLoader()

will still instanciate a new object, everytime they are called. The singleton instance is reached with:
   var mySingletonDataLoader = DataLoader.sharedInstance

You could change your standard (non singleton) initializers like:
init() {
NSLog("No instances allowed, please use .sharedInstance for a singleton")
}

Complete solution
The singleton is only one piece to solve the whole problem. The used delegate-pattern works great for sending information from one object to another and therefore delegating the work.
The problem from the questioner needs another broadcasting mechanism from one object to many other object. Therefore he decided to implement the Observer-pattern with NSNotificationCenter


text:
Q: Applying class decorator to staticmethod: takes 1 positional argument but 2 were given I am trying to apply a class decorator to each of its methods. But staticmethod and classmethod are not working for me. I got this:
import functools
import re

def decor(cls):
    def decorator(f):

        if isinstance(f, type):
            for attr in f.__dict__:
                if callable(getattr(f, attr)) and not re.match(r"__\w*__", attr):
                    setattr(f, attr, decorator(getattr(f, attr)))
            return f

        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            return f(*args, **kwargs)

        return wrapper

    return decorator(cls)

@decor
class MyClass:

    def printer1(self, string):
        print(string)

    @classmethod
    def printer2(cls, string):
        print(string)

    @staticmethod
    def printer3(string):
        print(string)

MyClass().printer1("foo")  # this works
MyClass().printer2("foo")  # this does not work
MyClass.printer2("foo")    # this works
MyClass().printer3("foo")  # this does not work
MyClass.printer3("foo")    # this works

# the error is the following:
TypeError: printer() takes 1 positional argument but 2 were given

Basically every time I instantiate the class, I get the error when calling a staticmethod and a classmethod.

A: You don't seem to understand the working principle of staticmethod and classmethod. This is a link about the working principle of classmethod. The working principle of the staticmethod is similar to that of the classmethod. The difference is that when accessing the staticmethod, the class will not be bound to the function, but simply return the function.

There are two problems:

*

*The decorator also wraps the class and returns a function instead of a class, which prevents staticmethod and classmethod from working properly.

*For staticmethod and classmethod, getattr will get the result returned after the descriptor triggers the __get__ method, not necessarily the function itself. And here you only use wrapper to wrap, and do not restore them to the corresponding special methods.

Here is a working example:
def decorator(cls_or_func):
    if isinstance(cls_or_func, type):
        cls = cls_or_func
        for name, attr in cls.__dict__.items():
            if isinstance(attr, (staticmethod, classmethod)):
                setattr(cls, name, type(attr)(decorator(attr.__func__)))
            elif callable(attr) and not re.match(r"__\w*__", name):
                setattr(cls, name, decorator(attr))
        return cls

    func = cls_or_func

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)

    return wrapper


text:
Q: Is there a function in perl to check if 2 arrays contain the same contents(although NOT necessarily the same order)? I know you could go one element at a time, but that would be really inefficient. Is there a better way?.
e.g
my @end_list =qw(
VDD1_DDR1_S2[2:1]
VDD2_DDR3_S2[5:1]
VDD1_DDR3_S2[2:1]
VDD2_DDR1_S2[5:1]
VDD2_DDR2_S2[5:1]
VDD1_DDR2_S2[2:1]
VDD1_DDR0_S2[2:1]
VDD2_DDR0_S2[5:1]
);

and
my @expected_list =qw(
                      VDD1_DDR0_S2_[2:1]
                      VDD2_DDR0_S2_[5:1]
                      VDD1_DDR1_S2_[2:1]
                      VDD2_DDR1_S2_[5:1]
                      VDD1_DDR2_S2_[2:1]
                      VDD2_DDR2_S2_[5:1]
                      VDD1_DDR3_S2_[2:1]
                      VDD2_DDR3_S2_[5:1]
      );

would be the same in spite of the contents being in a different order.

A: Since we're talking about strings,
my %counts;
++$counts{$_} for @m;
--$counts{$_} for @n;
die "Different" if grep $_, values(%counts);

While not relevant here, you can even use this function with things other than strings by using a key function that returns the same string for values you consider identical and different strings for value you consider different.
For example, if you wanted to support undef as well as strings, and if you wanted the comparisons to be case-insensitive, you could use the following:
sub key { defined($_[0]) ? '1'.fc($_[0]) : '0' }

my %counts;
++$counts{key($_)} for @m;
--$counts{key($_)} for @n;
die "Different" if grep $_, values(%counts);

Either way, O(M + N) speed and memory.

A: Using perm from Array::Compare on CPAN ignores order:
use warnings;
use strict;
use Array::Compare qw();

my @end_list =qw(
VDD1_DDR1_S2[2:1]
VDD2_DDR3_S2[5:1]
VDD1_DDR3_S2[2:1]
VDD2_DDR1_S2[5:1]
VDD2_DDR2_S2[5:1]
VDD1_DDR2_S2[2:1]
VDD1_DDR0_S2[2:1]
VDD2_DDR0_S2[5:1]
);

my @expected_list =qw(
                      VDD1_DDR0_S2[2:1]
                      VDD2_DDR0_S2[5:1]
                      VDD1_DDR1_S2[2:1]
                      VDD2_DDR1_S2[5:1]
                      VDD1_DDR2_S2[2:1]
                      VDD2_DDR2_S2[5:1]
                      VDD1_DDR3_S2[2:1]
                      VDD2_DDR3_S2[5:1]
      );

my $comp = Array::Compare->new();

if ($comp->perm(\@end_list, \@expected_list)) {
    print "Arrays are perms\n";
}
else {
    print "Nope. Arrays are completely different\n";
}

Note: I removed the _ before the [ in each item in @expected_list.
This outputs:
Arrays are perms


text:
Q: Artificial gravity on free falling objects Assume the following scenario:
-two objects in constant velocity free fall side by side to each other (imagine two astronauts in orbit)
-one of the two astronauts is inside a non rotating ring structure (imagine space station in orbit) but not connected to the structure in any way
-space station is also moving at constant velocity so that there is no relative motion between the three objects
-only thing separating the two astronauts is the wall of the ring structure
If the ring begins to spin about its axis without otherwise changing its constant velocity or relative motion to the two astronauts, will the astronaut inside the ring nonetheless experience centripetal forces and thus "artificial gravity" and be forced toward the outer wall of the ring whereas the other astronaut does not experience any relative force?
From reading and seeing this basic premise in science materials (and in science fiction films no less like Interstellar, Martian, 2001), this should be the expected outcome, but this seems like "spooky action at a distance" as well.
How does the spinning of the ring suddenly create a force that acts on the astronaut in free fall inside the ring whereas the astronaut immediately adjacent to but just outside the ring wall not feel any force?

A: No, the spinning of the ring itself does not suddenly create a force on the astronaut. It is the tangential velocity of the astronaut that makes him hit the ring, as he can not continue traveling straight due to the ring being in front of him, which ultimately leads to a change in direction and a corresponding force to make that change.
In short, astronaut will experience a force only if he is connected to the rotating ring. And to simplify even more, their rotational speeds should mach.


text:
Q: Nested #include and error : fatal error: map : No such file or directory I wrote a multiple files program in C/C++ and create library.h and put all of *.h in library.h, Then #include "library.h" same the following code :
#ifndef LIBRARY_H_
    #include "library.h"
#endif

My library.h is here:
#ifndef LIBRARY_H_
#define LIBRARY_H_

#include <map>
#include <fstream>
#include <string>
#include <string.h>
#include <cstdio>
#include <iostream>
#include <ncurses.h>
#include <stdlib.h>
//#include <termios.h>

using namespace std;

#include "structs.h"

#include "globals.h"
#include "typedef.h"

#include "readfile.h"
#include "writefile.h"
#include "tui.h"

#endif /* LIBRARY_H_ */

Please note that I get the following error:

fatal error: map: No such file or directory

and map is first #include file. I commented it, then map changed to fstream (next of map).
When I remove #include "library.h" from tui.h everything is ok! tui.h is here:
#ifndef TUI_H_
#define TUI_H_
#ifndef LIBRARY_H_
    #include "library.h"
#endif

//#endif    LIBRARY_H_
//BEGIN_C_DECLS
    void print_menu(WINDOW *menu_win, int highlight);
    void menu();
//END_C_DECLS

#endif /* TUI_H_ */

How can I solve it?