text:
Q: Use USB Tethering for local router as internet Gateway I want to use a local router as a node for all devices to connect to internet instead of Android Hot-Spot.
Reason: Because connecting to Android requires manipulating the NAT on multiple phones just to connect two devices with each other and there are multiple devices.
Attempted Solution 1:

*

*Connected a phone to WiFi that has internet (to act as internet gateway for the router instead of of the regular cable)

*Connected the same phone to the router using USB-Tethering from phone, the USB Port is working fine (the LED is giving green color indicate that) but the internet LED gives red color (Indication that it is trying to detect internet gateway) but it never turns green.

What am I missing or should look up at the internet because I failed drastically?
Similar Problems to mine:

*

*Using cell phone as Internet provider for router

*Cell phone as data feed to wireless router

*Use Smartphone as gateway to internet for my local network (Not smartphone hotspot!)
Some Information that might be helpful or relevant:

*

*I have multiple PCs that can only be connected via LAN (They are far from each other to the extent that not even a Wi-Fi Module can connect them to the router)

*Router Type: ZXHN H168 V3.1

*Thought of making a device act as the gateway but then, I am not sure if the devices are going to communicate with each other nicely (without needing to manually edit the NAT) & do not know how to do so and not to mention that the only device capable of doing this is a laptop because it has both Wi-Fi and LAN.

*Image of the entire connection described above
(update) Attempted Solution 2: (Inspired from this site)
Tried to use my Linux Laptop to be the WAN gateway.

*

*The router detects the connection.

*Pinging the Laptop from other devices gives me From 192.168.1.1 icmp_seq=1 packet filtered.

*The laptop does not see any device on the local network (I used sudo arp-scan --interface=enp7s0 --localnet & Tried to access the router page using my browser but the laptop does not see the router (Error 404 when loading 192.168.1.1)).

A: There is unfortunately a lot of different protocols that could be used to provide networking over USB – some devices use a generic protocol like CDC ECM or CDC EEM or CDC NCM, Android phones in "USB tethering" mode provide RNDIS, and of course there are many USB-Ethernet products requiring custom drivers.
But 3G modems might use none of the above as their primary interface; if your router claims "3G WAN" support, it's likely that it expects the USB device to provide a serial port for AT communications, much like dial-up modems (and pre-smartphone GPRS/HSPA tethering) in the past. The router would ask the modem to "dial" *99# for Internet access.
(And for 4G modems, it would be a serial port for MBIM/QMI; they do provide an ECM network interface alongside, but it only becomes active once specific "connect" commands are sent via MBIM first.)
Of course, the router could support several kinds of USB network interfaces, but it's very likely that the manufacturer had focus on AT-based 3G modems specifically, and didn't even think about including support for RNDIS that's required for Android USB tethering.


text:
Q: Lua - table length seems invalid a = {}
a[1] = 1
a[2] = nil -- does nothing, as a[2] is already nil
a[3] = 14

print(#a)

prints 1
a = {}
a[1] = 1
a[2] = nil -- does nothing, as a[2] is already nil
a[3] = 14
a[4] = 5

print(#a)

prints 4
What does the # operator really return?

A: If the table is not a proper sequence, the return value of the # operator applied to that table is undefined.
In both of your cases, a is not a proper sequence because a[2] == nil and a[3] ~= nil.
The # operator returns the length of proper sequences.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Serialization "isolation level" in MongoDB, or the lost-update problem I realize MongoDB is a NoSQL solution, but I was wondering if it had some sort of equivalent to serialization-level transaction isolation level.
If not, how would you solve the lost-update problem in MongoDB?
I want to keep the revision history of some data in Mongo and each revision has to point to the one before it. How can I make sure no more than one latest revision exists for my data, and on the other hand that no revision is lost due to concurrent updates?
** Edit **
Oops, RTFM, it is indeed possible: http://www.mongodb.org/display/DOCS/Atomic+Operations
Not sure if I should close the question since the knowledge might be relevant to other people..

A: Yes, this is possible, so long as you keep the history in a single document.  MongoDB supports atomic updates within the scope of a document, but not across multiple documents in a collection.
So, you could embed the history in an array, using a schema something like this:
{
    _id: 12345,
    value: "Apple",
    history:
    [
        { revisionid: 2, value: "Orange" },
        { revisionid: 1, value: "Pear" }
    ]
}

For example, you could insert a new document:
db.things.insert( { _id: 123, value: "Apple" } )

Then update it in one atomic operation:
db.things.update( { _id: 123 },
    {
        $set: { value: "Orange" },
        $push : { history : { revisionid: 1, value: "Apple" } }
    }
)


text:
Q: How to get difference between two excel columns Column A contains active user's name, and column B contains all user's name. How can I get the difference between the two lists (inactive users)?

A: In column C1 you can use:
=if(countif(A:A, B1)<1, "Inactive", "")

And copy that down for every name in column B and it will add the word "Inactive" on any records where the name in B is not found in column A.
You can then sort by Column C to group them all together. Or autofilter. Or pivot table.


text:
Q: EntityFramework connection to SQL server I have exactly the same configuration in app.config files in two projects in different solutions.
One is an old solution where I deleted the old migrations, changed the DB and started getting connection errors with the new DB.
I reinstalled EF, deleted migrations, re-enabled them etc. Nothing works.
I created a new solution, installed EF, copied my model classes into it and tried the same. It works! The migration codes generated are exactly the same.
So the same configuration for the same code are in two different solutions on the same computer. One gets the below error while the other one works.

*

*Enable-Migrations -> works fine

*Add-Migration -> created migration files

*Update-Database -> gets the below error:

System.Data.SqlClient.SqlException (0x80131904): A network-related or
  instance-specific error occurred while establishing a connection to
  SQL Server. The server was not found or was not accessible.

A network-related or instance-specific error occurred while establishing
  a connection to SQL Server. The server was not found or was not
  accessible. Verify that the instance name is correct and that SQL
  Server is configured to allow remote connections. (provider: SQL
  Network Interfaces, error: 26 - Error Locating Server/Instance
  Specified)

It's not the same error with the other question mentioned in the comments.  Different exceptions.
Edit: I copy the project files and add it to a brand new solution. And it works! I restarted the old solution, restarted my computer, reinstalled all packages in the project. Nothing works. I really need to make it work on that solution.


text:
Q: Are reducible Integral Binary Quadratic Forms equivalent? By an integral binary quadratic form (IBQF for short) I mean an $$f(x,y) = ax^2 + bxy + cy^2$$ with $a,b,c \in \mathbb{Z}$. Note that I am not assuming that they are all coprime.
Such an $f$ is said to be reducible if it factors as the product of two linear forms; equivalently, if its discriminant, defined as $\Delta(f) := b^2 - 4ac$, is a square in $\mathbb{Z}$.
I would like to say that, if two IBQFs $f$ and $g$ are reducible and have the same discriminant, then they must be equivalent, by which I mean that there exists a matrix $\gamma \in SL_2(\mathbb{Z})$ such that $$\gamma f = g.$$
Is this true?

A: That was fun. It turns out that, for discriminant $0$ and primitive, the two $SL_2 \mathbb Z$ classes are $f(x,y) = x^2$ and $g(x,y) = -x^2.$ For discriminant $1,$ the only class is $f(x,y) = xy.$
For discriminant $D = B^2$ with integer $B > 1,$ the count of classes is given by the Euler totient $\varphi(B),$ because all the distinct classes are given by taking $B > 0,$ also $\gcd(A,B) = 1$ and $1 \leq A < B,$ for each $A$ the class is given by
$$ f(x,y) = Ax^2 + B xy.   $$
Notice that there is no $y^2$ term. Also note that, with $B \geq 2,$ taking $A=0$ would give an imprimitive form, namely $Bxy,$ so we exclude that. Oh, it turns out that there is no need to have $B = - \sqrt D,$ requires proof but it is all elementary manipulations of how elements of $SL_2 \mathbb Z$ act on forms.
GO FIGURE

A: $$ f(x,y) = x^2 - y^2  $$
$$ g(x,y) = 2 x y  $$
A different pair:
$$ f(x,y) = x^2 - 9y^2  $$
$$ g(x,y) = -x^2 + 9 y^2 $$
Here is a good one;
$$ f(x,y) = x^2 - 36y^2  $$
$$ g(x,y) = 9x^2 - 4 y^2. $$
While $9-4 = 5,$ we can easily check $x^2 - 36 y^2 \neq 5,$ either because $5$ is not a quadratic residue $\pmod 3,$ or by solving $(x+6y)(x-6y) = 5$ where each factor needs to be $\pm 1, \pm 5,$ and we find, in four possible ways, $x= \pm 3, y= \pm \frac{1}{3}.$


text:
Q: Understanding Java Generics sub-typing
Picture from http://docs.oracle.com/javase/tutorial/java/generics/subtyping.html
How can List<? super Number> be sub type of List<? super Integer> ?

A: That is because a List<? super Integer> is capture convertible to all the lists that can be capture converted from List<? super Number>.
Let's see what all types are capture-convertible from List<? super Number>:

*

*List<Number>

*List<Object>

*List<Serializable>
A List<? super Integer> is capture-convertible to all the above types. So you can safely assign a List<? super Number> to a List<? super Integer>, without any compiler error.
Just in case you're thinking what is capture-conversion, it means, you can assign a List<Number> to a List<? super Number>.

A: Any super of Number is also a super of Integer.
As mentioned below the instanceof example I gave would not compile. It probably wasn't the best way of showing it.


text:
Q: What is the size of the kth Superabundant Number? Utilizing the data generated by T.D. Noe for the first $10^6$ terms of A004394, a plot of $k$ against $log_{10}(S(k))$ where S(K) is the $k^{th}$ Superabundant Number shows a strong linear relationship which suggests the following:
$$S(k)\approx e^{0.242692k}$$
Is this a known result and does this relationship hold past $k=10^6$? Can the exact value of the constant be determined?


text:
Q: Sort an array of strings starting by numbers I'm trying to sort an array of objects by name in Symfony. But I don't know how to do that, because the strings start with numbers so the order is not good.
I tried with a queryBuilder in my repository:
 $qb = $this->createQueryBuilder('arrondissement')
            ->addOrderBy('arrondissement.nom', 'ASC');
        $query = $qb->getQuery();
        return $query->execute();

And a sort() function in the controller,
But as you can see it's not totaly that. I wnat something like : 1er arrondissement, 2e ...., 20e..., Paris

A: You can use php natsort for example :
$arr = [
            '10e arrondrissement',
            '1e arrondrissement',
            '8e arrondrissement',
            '2e arrondrissement',
            '5e arrondrissement',
 ];
 natsort($arr);
 print_r($arr);

Will return :
Array (
[1] => 1e arrondrissement
[3] => 2e arrondrissement
[4] => 5e arrondrissement
[2] => 8e arrondrissement
[0] => 10e arrondrissement
)

A: in this case IMHO you SHOULD NOT alter the ordering via PHP but use the database sorting for that.
Here is my proposal to modify your query builder:
 $qb = $this->createQueryBuilder('arrondissement')
            ->add( 'orderBy', 'CAST(arrondissement.nom AS UNSIGNED), arrondissement.nom')
        $query = $qb->getQuery();
        return $query->execute();

A: you can't sort strings/objects by natural order easily in doctrine. but you could sort it in php:
$result = $query->getResult();
$nomSort = function($a, $b) :int {
    return strnatcmp($a->getNom(), $b->getNom());
}
usort($result, $nomSort);
// $result is now sorted

strnatcmp will compare according to "natural sort", which interprets "1" < "2" < "10" < "20", even if some more letters are appended.
usort can apply a custom sort function to an array - which is required here, since you want to access a sub-element (nom) of your array-element (an object). - Otherwise you could have just used natsort.
If you really need to sort in database for whatever reason, have a look at this related question: Natural Sort in MySQL (assuming mysql here)


text:
Q: Equation of Plane in a unit cube given the normal and volume enclosed I know the normal and volume enclosed by the plane. I am interested in finding out the equation of the plane. The volume enclosed is with respect to origin. The plane can have any random orientation.How should I approach this problem ?
$ n_xx+n_yy+n_zz + d =0 $
How can I calculate the 'd' ?


text:
Q: How to perform incremental retrieval on NetSuite API? Using the WebService API of NetSuite (using C#/.NET), I would like to retrieve all SalesOrder(s) and all PurchaseOrder(s) using some incremental data retrieval pattern where not all data get redownloaded each time; only the data that have actually changed. It's unclear to me how to achieve this with the NetSuite search feature.
Any hint?

A: Assuming no records are created during the search duration,
Use Transaction Searches to fetch data and keep the result sorted on internalId.
Next time you fetch the data add a filter internalid greater than, this way you can incrementally fetch the data.


text:
Q: Timeout ignored by AspNet Identity and OWIN I hope someone can help me. We are writing an MVC app and we are using AspNet Identity and OWIN and we are trying to set the timeout to 4 hours. However, it seems like no matter what we set the timeout to the site times out in 30 minutes and we get redirected to the login page.
As an aside, this is an MVC app in EpiServer, but the mechanism for using AspNet Identity and OWIN is the same.
In our web.config, we have the following settings:
<authentication mode="None">
</authentication>

and
 <sessionState mode="InProc" timeout="240" />

and, in appSettings,
<add key="SessionTimeout" value="240" />

In our OWIN startup class, we have the following code:
public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        CookieAuthenticationProvider provider = new CookieAuthenticationProvider();
        Action<CookieApplyRedirectContext> originalHandler = provider.OnApplyRedirect;

        provider.OnApplyRedirect = context =>
        {
            context.RedirectUri = $"{new PathString(Global.LoginPath)}/?session_expired=1";
            originalHandler.Invoke(context);
        };

        provider.OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager<PortalDirectApplicationUser>, PortalDirectApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user));

        app.SetupPortalDirectAspNetIdentity<PortalDirectApplicationUser>();

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            CookieName = "OurCookie",
            LoginPath = new PathString(Global.LoginPath),
            Provider = provider,
            SlidingExpiration = true,
            ExpireTimeSpan = TimeSpan.FromMinutes(int.Parse(ConfigurationManager.AppSettings["SessionTimeout"]))
        });
    }
}

So the timeout in the startup class is also 240 minutes.
Can anyone point me in the right direction as to why the site times out in 30 minutes? I have searched for answers and I'm obviously not setting something correctly.
Thanks!


text:
Q: File to list, split by newlines (python 3.5.0) How can I convert a fasta file in python to a list, split by two newlines?
So, this is how the file looks like:
Subject1...
Subject1...
Subject1...
[Enter]
[Enter]
Subject2...
Subject2...
Subject2...

I need something like this, in a list:
[Subject1
Subject1
Subject1,
Subject2
Subject2
Subject2]

So, every few lines of one 'subject' should be one item together, so that I can remove or print all lines of one specific subject.
Thanks!

A: Simple:
Read the file into memory:
text = myfile.read()

Split the text:
subjects = text.split("\n\n")

A quick demo:
In [2]: text = """Subject1...
   ...: Subject1...
   ...: Subject1...
   ...:
   ...: Subject2...
   ...: Subject2...
   ...: Subject2...
   ...:
   ...: Subject3...
   ...: Subject3...
   ...: Subject3..."""

In [3]: text.split("\n\n")
Out[3]:
['Subject1...\nSubject1...\nSubject1...',
 'Subject2...\nSubject2...\nSubject2...',
 'Subject3...\nSubject3...\nSubject3...']


text:
Q: How to create JSON using Entity to POST in Swift3 iOS? I am newly to Swift programming. I have to send below JSON request to server using httpRequest in Swift3.
{
    "CompanyId": 162,
    "RollupYear": 2018,
    "UserId": 1609,
    "datarollup": [{
            "Name": "Thank You Cards",
            "RollupYear": 2018,
            "DataRollupColumnID": 210,
            "CurrentValue": 520
        },
        {
            "Name": "Prospecting Calls",
            "RollupYear": 2018,
            "DataRollupColumnID": 212,
            "CurrentValue": 1300
        }
    ],
    "Seasonalitylist": [{
            "CompanyPeriodId": 386,
            "UserId": 1609,
            "Seasonality": 25
        },
        {
            "CompanyPeriodId": 387,
            "UserId": 1609,
            "Seasonality": 25
        }
    ]
}

So, in order to send JSON in this format I have created an Entity Class with name 'RequestModel' :
import Foundation

class RequestModel {

    var CompanyId: Int? = 0
    var RollupYear: Int? = 0
    var UserId: Int? = 0

    var dataRollupArr = NSMutableArray()
    var seasonalityArr = NSMutableArray()
}

class DataRollupModel {
    var Name: String? = ""
    var CurrentValue: Float? = 0.0
    var RollupYear: Int? = 0
    var DataRollupColumnID: Int? = 0
}

class SeasonalityModel {

    var CompanyPeriodId: Int? = 0
    var UserId: Int? = 0
    var Seasonality: Int? = 0
}

I have all my values, Can anyone suggest me how to add my Entity values to required JSON.
Note:
Here is my code to send JSON request to server for Login :
func login(email:String, password:String, completion:@escaping (NSDictionary) -> ()) {
        if let url = NSURL(string: baseurl+"login") {
            let request = NSMutableURLRequest( url: url as URL)

            let signInDict = ["UserName":email,"Password":password]

            print(signInDict)

            let jsonData = try! JSONSerialization.data(withJSONObject: signInDict, options: JSONSerialization.WritingOptions.init(rawValue: 0))

            request.httpMethod = "POST"

            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.setValue("732rguiqfw9237ryu4k2141", forHTTPHeaderField: "KEY")

            request.httpBody = jsonData
            let task = URLSession.shared.dataTask(with: request as URLRequest) {
                data, response, error in
                do{
                    if let data = data,
                        let jsonString =  try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
                        , error == nil {
                        completion(jsonString)
                    } else {
                        print("error=\(error!.localizedDescription)")
                        let errorDict = ["error_status":true,"message":error!.localizedDescription] as [String : Any]
                        completion(errorDict as NSDictionary)

                    }
                }
                catch{
                    print("error=\(error.localizedDescription)")
                    let errorDict = ["error_status":true,"message":error.localizedDescription] as [String : Any]
                    completion(errorDict as NSDictionary)

                }

            }
            task.resume()
        }
    }

A: Hi first of all you don't have to create object if you already have a dictionary of the data you can directly convert it to json as shown here
I would suggest you to use object mapper as thats the easiest way if you still want to use object models
Object mapper widely used
The structs or objects that inherit the mappable class they have direct function to convert object to jsonString or the dictionary

A: Using Swift 4 Codable, #simple like
class RequestModel: Codable {

    var CompanyId: Int? = 0
    var RollupYear: Int? = 0
    var UserId: Int? = 0

    var datarollup = [DataRollupModel]()
    var Seasonalitylist = [SeasonalityModel]()

    class DataRollupModel: Codable {
        var Name: String? = ""
        var currentValue: Float? = 0.0
        var RollupYear: Int? = 0
        var DataRollupColumnID: Int? = 0
        var CurrentValue: Int? = 0
    }

    class SeasonalityModel: Codable {

        var CompanyPeriodId: Int? = 0
        var UserId: Int? = 0
        var Seasonality: Int? = 0
    }

}

extension Encodable {
    func toJSONData() -> Data? {
        return try? JSONEncoder().encode(self)
    }
}

Use
let instance = RequestModel()
let jsonData = instance.toJSONData()


text:
Q: timeout in sql server and attachment of db in sql express 2005? Intro.
i have made a application in vs 2008 using c# and at back end i am using sql express 2005.
Application background:
just like report tool in which user select some parameters and get results in cube
after she can import that result into excel or in any formats.
problem:

*

*user mostly processing 15 to 70 months report which takes 45 mints to 1.25 hours to
complete but sometime result generated for 9 months and sometime 11 months not as
selected months -- show alert: timeout....

*how to attach and deattach my database file when my software is installing
(or after installation) as my application installer installs my apps.
and sql express 2005

A: Use sp_attach_db to attach a database to a SQL server: http://msdn.microsoft.com/en-us/library/ms179877.aspx
If you're connecting to the server using a SqlCommand object, then you can set the CommandTimeout to 0 for indefinite execution. That is not advised though!
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout.aspx


text:
Q: Angular component, different content depending on Element I have a list
*ngFor="let h of list"

Depending on the type of the item "h.type" I want to use a different component to display details. How do I load the component?

A: Here is how you could do it with an NgSwitch:
<div *ngFor="let h of list" [ngSwitch]="h.type">
  <ng-container *ngSwitchCase="'x'">
    <component-x>
  </ng-container>
  <ng-container *ngSwitchCase="'y'">
    <component-y>
  </ng-container>
</div>

You might be able to skip the ng-container but I haven't tested that:
<div *ngFor="let h of list" [ngSwitch]="h.type">
    <component-x  *ngSwitchCase="'x'">
    <component-y  *ngSwitchCase="'y'">
</div>

A: You can use ng-template for that. E.g.
<div *ngFor="let h of list">
  <ng-container *ngIf="h.type === 'FIRST'">
    <ng-container *ngTemplateOutlet="firstTemplate"></ng-container>
  </ng-container>

  <ng-container *ngIf="h.type === 'SECOND'">
    <ng-container *ngTemplateOutlet="secondTemplate"></ng-container>
  </ng-container>
</div>

<!-- now define the two templates -->
<ng-template #firstTemplate>
  <my-first-component/>
</ng-template>
<ng-template #secondTemplate>
  <my-second-component/>
</ng-template>

A: You can accomplish this by using *ngIf
And load components with their selectors directly in html.
<component1 *ngIf="h.type == 'car'"></component1>
<component2 *ngIf="h.type == 'truck'"></component2>

Component 1 is going to be displayed when h.type is car and component 2 is going to be displayed when h.type is truck.


text:
Q: Why is this a Dynkin system: $\{A \in \mathcal{A} \colon E[X1_A]=E[Y1_A]\}$ Let $X,Y$ be two random variables on $(\Omega, \mathcal{A},P)$.
Why is the set $\mathcal{D}:=\{A \in \mathcal{A} \colon E[X 1_A] = E[Y 1_A]\}$ a Dynkin system?
Suppose $A \in \mathcal{D}$. Then $E[X1_A] = E[Y1_A]$.
All I could think of was the following:
Therefore $E[X 1_{A^c}]= E[X(1-1_A)]=E[X]-E[X1_A] = E[X]-E[Y1_A]$
But this is not what we need.
Also if $A_i \in \mathcal{D}$ for $A_i$ pairwise disjoint.
Then $E[X 1_{\bigcup_i A_i}] = E[X \sum_{i} A_i]= \sum_i E[X A_i] = \sum_i E[Y A_i] = E[Y 1_{\bigcup_i A_i}]$.
But here I am not sure whether I can change the sum and the Expectation. Is this possible due to Monotone convergence theorem?

A: Because $\Omega \in \mathcal{D}$ is a necessary condition for $\mathcal{D}$ to be a Dynkin system, we got to have $E[X] = E[Y]$ or $\mathcal{D}$ will not be a Dynkin system.
Let $A \in \mathcal{D}$. Then
$$E[X 1_{A^c}]= E[X(1-1_A)]=E[X]-E[X1_A] = E[Y]-E[Y1_A] = E[Y 1_{A^{c}}]$$
So $A^{c} \in \mathcal{D}$.
Now let's look at a sequence $(A_n) \in \mathcal{D}$ with $A_i \cap A_j = \emptyset $ if $i \neq j$. Let $A = \cup_{i=1}^{\infty} A_i$. We now want to show that we may interchange taking the expectation with summation. Let $X^{+}$ be the positive part of $X$. Define $$ X_n^{+} := X^{+}1_{\cup_{i=1}^{n} A_i}.$$ We trivially have $X_n^{+} \leq X_{n+1}^{+}$, so the monotone convergence theorem yields
$$\lim_{n\to\infty} E[X_{n}^{+}] = E[\lim_{n\to\infty} X_{n}^{+}]$$
The same argument applied to the negative part of $X$ shows that we have
$$\lim_{n\to\infty} E[X_{n}] = E[\lim_{n\to\infty} X_{n}] = E[X1_{A}]$$
with $X_n := X1_{\cup_{i=1}^{n} A_i}$. We can of course carry out the same argument with $Y$. Thus we obtain
\begin{align} E[X1_{A}] &= E[\lim_{n\to\infty} X_n] = \lim_{n\to\infty} E[X_n] = \lim_{n\to\infty} E\left[\sum_{i=1}^{n} X1_{A_i}\right] = \lim_{n\to\infty} E\left[\sum_{i=1}^{n} Y1_{A_i}\right] \\ &=\lim_{n\to\infty} E[Y_n] = E[\lim_{n\to\infty} Y_n] = E[Y1_{A}] \end{align}
Which shows $A \in \mathcal{D}$.


text:
Q: What the equivalent of "this" (as in Java or C++) in S4 object system in R Now I understand that the S4 object system of R is very different from C++ or Java.
However I had the question is there anything similar to the "this" in S4

A: Methods are defined on generics and dispatch on class, rather than on classes. So this is always the object being dispatched on.
.A = setClass("A", slots = c(a = "integer"))

setGeneric("foo", function(x) standardGeneric("foo"))

setMethod("foo", "A", function(x) {
   x@a        # 'x' is the object that `foo()` dispatches on, i.e., 'this'
})

Usage:
> y = .A(a=1:5)
> foo(y)
[1] 1 2 3 4 5


text:
Q: Spree commerce - Edit User object properties I'm new to spree and also still learning Rails
I don't completely understand how can I add new properties to the Spree::User object, so that I can set more data to the users that are registering to my site.
According to the not-so-clear documentation, I understand that I should create a User class and add preferences:
class User < ActiveRecord::Base
  preference :hot_salsa, :boolean
  preference :dark_chocolate, :boolean, :default => true
  preference :color, :string
  preference :favorite_number, :integer
  preference :language, :string, :default => "English"
end

But I'm not sure where should I save this file or how to name it at all.
Am I on the correct path?

A: You can do it using a decorator. You can create the decorator as app/models/spree/user_decorator.rb and add your code in it.
Spree::User.class_eval do
  preference :hot_salsa, :boolean
  preference :dark_chocolate, :boolean, :default => true
  preference :color, :string
  preference :favorite_number, :integer
  preference :language, :string, :default => "English"
end

Find documentation for overidding or extending code here.

A: The fields you are adding should not be used as preferences as the value for preferences are serialised and then stored which will not be useful if you want to do some filtering/querying on these fields.
Rather these should be

*

*separate attributes of user model (columns of spree_users table).

*attributes of a separate new table may be spree_user_details (belongs_to :user) with has_one association from user model.


text:
Q: Fastest / most efficient way to combine heterogeneous csv files in Python I have 1000 csv files with size varying from 8MB to 17MB. Each file has a portion of 6 metrics. Examples are below:
File1 (columns): key, metric1, metric2, metric3
File1 (values):  k1, m1, m2, m3
File2 (columns): key, metric4, metric5, metric6
File2 (values):  k1, m4, m5, m6
File3 (columns): key, metric2, metric4, metric5, metric6
File3 (values):  k2, m2, m4, m5, m6

All methods I tried today combined files into the output below:
Output (columns): key, metric1, metric2, metric3, metric4, metric5, metric6
Output (values):  key1, m1,   m2,   m3,   null, null, null
                  key1, null, null, null, m4,   m5,   m6
                  key2, null, m2,   null, m4,   m5,   m6

What I really need is also consolidate rows by key column:
Output (columns): key, metric1, metric2, metric3, metric4, metric5, metric6
Output (values):  key1, m1,   m2, m3,   m4, m5, m6
                  key2, null, m2, null, m4, m5, m6

I know pandas could do it; however, it may take forever to finish 1000 files.

A: It's a bit unclear what your format is, but I think this will work:
 df = pd.DataFrame(expected_metrics)
 for filename in filelist:
       current_data = pd.read_csv(filename,index_col = 'key')
       current_columns = current_data.columns
       current_row = current_data.index[0]
       df.loc[current_row,current_columns] = current_data

Notes:
-This requires you know ahead of time what metrics will be present so you can initialize expected_metrics. You could instead replace the last line with:
 for column in current_columns:
      df.loc[current_row,column] = current_data[column]

This would probably take longer
-If a particular (key, metric) combination shows up more than once, only the last one will be recorded.
-The result will have key as the index. If you want it as a data column, you'll have to do df['key'] = df.index.
I wouldn't expect this to take "forever"; a thousand files should take at worst a few minutes unless you have a very large number of metrics.
You could also do:
 data = {}
 for filename in filelist:
       current_data = pd.read_csv(filename,index_col = 'key')
       current_columns = current_data.columns
       current_row = current_data.index[0]
       data[current_row] = {column:list(current_data[column])[0] for column in current_columns}

This will give a dictionary where each key is a key from your data, and the value is a dictionary representing the row for that key.
EDIT:
A third option would be to take the output you already have and do df.groupby(by='key').max() This will create a dataframe where each entry is the maximum metric for all the rows with the same key. So, again, if you have only one value for each (key,metric) combination, this should give you what you want. If you have more than one value, all but the largest will be ignored.


text:
Q: Maven: Building another project from current pom.xml My project structure is simply:
P1(pom.xml)
P2(pom.xml)
I want to build P2 first and include it's jar as dependency to P1, and build P1 to get a war.
Please Help!


text:
Q: Trying to draw full-width rectangles but there are white spaces at the image's borders, why? Summary

*

*Context

*Actual results (the problem revealed)

*Expected results (if the problem is solved)

*Clues to help you to help me

*Minimal and Testable Executable Code

*

*Prerequisites

*Sources

Context
I want to draw full-width colored rectangle in a 515x515 image. What I get is:

Actual results (the problem revealed)
If you open it in Paint, you will see that the right and bottom borders of the image contain white pixels. It means that in fact, my rectangles are not full-width. Moreover, top and left borders contain colors different than the rectangles' ones. Also, the color between two consecutive rectangles is differerent than the rectangles' colors.
Expected results (if the problem is solved)
What I would want is: to make the image contain only the colors of the rectangles (1 rectangle = 1 color of course), and no other color ; to know why there are white pixels ; to know why there are colors that are different than the rectangles' ones between two consecutive rectangles. And, of course: how to replace any color that is not a rectangle's one by the correct rectangle's one?
Clues to help you to help me
In my other computer, I don't have these problems. Perhaps the issue is bound to the way I use DPI unit, in the call to my function open_eps? See the following code.
Minimal and Testable Executable Code
Prerequisites

*

*To reproduce this bug, you can, normally (it seems to depend on your computer and/or screen I don't know), execute the above code in your Python interpreter. No input data is required for the execution, you can launch the script alone. It should be easy to reproduce the bug I think (tell me if it's not the case).

*Python Interpreter: you can use 3.7 as I do but I think it's not required ; By the way, I'm on Windows so you can change files paths if you use UNIX or some other reasons.
Sources
Here is the code that generates these images ; just execute this code (there is randomness, at each execution a different image could be drawn ; the bug will be always present):
 import io
 import math
 import random
 from tkinter import Canvas, Tk

 import PIL.Image

def open_eps(ps, dpi=300.0):
    img = PIL.Image.open(io.BytesIO(ps.encode('utf-8')))
    original = [float(d) for d in img.size]
    scale = dpi / 72.0
    if dpi is not 0:
        img.load(scale=math.ceil(scale))
    if scale != 1:
        img.thumbnail([round(scale * d) for d in original])
    return img

def generate_terrain():
        canvas_width = 512
        canvas_height = 512
        root = Tk()
        canvas = Canvas(root, width=canvas_width, height=canvas_height)
        canvas.pack()
        canvas.create_rectangle(0, 0, canvas_width, canvas_height / 3, fill='#9ceedd', outline='#9ceedd', width=3)
        clouds = random.randint(0, 1)
        layout = 0
        ground = random.randint(0, 1)
        plants = random.randint(0, 2)
        if layout == 0:
            if clouds == 0:
                canvas.create_rectangle(0, 0, canvas_width, 50, fill='#696969', outline='#696969', width=3)
            if ground == 0:
                ground = '#6e6e28'
            if ground == 1:
                ground = '#999900'
            canvas.create_rectangle(0, 2 * (canvas_height / 3), canvas_width, canvas_height, fill=ground,
                                    outline=ground, width=3)
            if plants == 0:
                plants = '#7bc800'
            if plants == 1:
                plants = '#760000'
            if plants == 2:
                plants = '#a8c832'
            canvas.create_rectangle(0, (canvas_height / 3), canvas_width, 2 * (canvas_height / 3), fill=plants,
                                    outline=plants, width=3)
        canvas.update()
        ps = canvas.postscript()
        root.destroy()
        img = open_eps(ps, dpi=95.5)
        img.save("C:/Users/x/Desktop/a/b/test.png")

generate_terrain()

A: Well. I tried another way to save the image (a workaround) and now it works. However you can still answer this question, of course.
I have replaced width=6 with: width=3.
I have replaced img = open_eps(ps, dpi=95.5) with: img = PIL.Image.open(io.BytesIO(ps.encode('utf-8'))).


text:
Q: Give child class based on parent class only on target container Im trying to give an element (.item) a class based on a childclass - but I want to keep it to the target container. Below you can see the script im trying - this give all of my elements with the class .left an extra class based on the .item class. I only want this to happen to the container that actually have this class. How do I do this?
HTML:

script:
$(document).ready(function () {
    if($(".item").hasClass("itemonlypicture")) {
        $(".container").addClass("image");
    }
});

A: Use closest to get the first ancestor matching the passed selector.
$('.itemonlypicture').closest('.container').addClass('myClass');

$('.itemonlypicture').closest('.container').addClass('myClass');
.myClass {
  color: green;
  font-weight: bold;
}

1

2

3

4

5

6

A: Try below JS

  $(document).ready(function() {
    $('.item').each(function(){
    if($(this).hasClass("itemonlypicture"))
    {
      $(this).closest(".container").addClass("image");
    }
    });
  });

  <--- give class


text:
Q: Selenium / Python - how to mock server responses? I've written a tool that automates interaction with a slow web service that's outside of my control. In order to test certain features, I'd like to avoid Selenium making repeated requests to the real service. For this I wanted to use unit tests and mocking.
Is there a way to mock out responses from a real server? Ideally I'd like to be able to define a mapping of:
mock_responses = {
  'http://server/path1': 'path1.html',
  'http://server/pathN': 'pathN.html',
}

so that when the URL in key is requested, instead of issuing a real request, Selenium would just treat the local static HTML file as if it came from the live web service.
PS. I'm not looking for solutions involving standing up a test webserver returning static pages.

A: As you are planning to keep local copy of static htmls (responses), you can load required response html as and when required using Selenium (webdriver) get() method.
For example, you have stored all the response HTMLs in "C:/responces/" (you can store response htmls as part of your automation framework), then you can load required response as below:
driver.get("file://C:/responces/path1.html");
driver.get("file://C:/responces/pathN.html");


text:
Q: For every set S of at most n people, there is at least one person outside of S who is friends with everyone in S. Let $n$ be a positive integer. In a group of $2n + 1$ people, each pair is classified as friends or
strangers. For every set $S$ of at most $n$ people, there is at least one person outside of $S$ who is friends with everyone in $S$. Prove that at least one person is friends with everyone else.

A: Take two disjoint sets of $n$ persons $A$ and $B$ such that the number of friendships between $A$ and $B$ is the minimum possible. Suppose that call the remaining dude $x$ and suppose that $x$ doesn't know everyone in $A$. Notice that if we swap the dude in $B$ that knows everyone in $A$ with $x$ we get even less friendships between $A$ and this new set. Hence we conclude $x$ knows everyone in $A$ and analogously $x$ knows everyone in $B$

A: The same is true for a group of $2n$ people. In general, given a (finite) set $V$ of people, if for every set $S\subseteq V$ with $|S|\le\frac12|V|$ there is a person in $V\setminus S$ who is friends with everyone in $S$, then somebody in $V$ is friends with everyone else.
It will be convenient to restate the proposition in terms of graph theory. Recall that a dominating set in a graph $G$ is a set $S$ of vertices such that every vertex not in $S$ is adjacent to a vertex in $S$; the domination number $\gamma(G)$ is the minimum number of vertices in a dominating set.
Let us consider the "stranger graph" $G=(V,E)$: the vertex set $V$ is the set of people, and two people are joined by an edge iff they are strangers. The condition "somebody not in $S$ is friends with everyone in $S$" means that $S$ is not a dominating set; and the statement "somebody is friends with everybody else" means that there is an isolated vertex. Hence the generalized version of your problem, for an odd or even number of people, is equivalent to the following simple fact about the domination number of a graph:
Theorem. If a graph $G=(V,E)$ has no isolated vertices, then $\gamma(G)\le\frac12|V|$.
Proof. Let $H$ be a spanning subgraph of $G$ which is minimal with the property of having no isolated vertices. In the graph $H$, each edge is incident with a leaf (vertex of degree one), otherwise we could remove it and still have no isolated vertices. Now it is clear that $H$ is an acyclic graph, i.e. a forest, every connected component is a tree. Moreover, it is easy to see that a tree, in which each edge is incident with a leaf, is a star; so $H$ is a forest of stars. By picking a central vertex from each of those stars, we get a set $S$ which is a dominating set for $H$ and therefore also for $G$; and $|S|\le\frac12|V|$ since each of those stars has at least two vertices.


text:
Q: Apply custom and complex 2d gradient to WPF 3d Objects What I would like to do is simple to describe:
I want to map an UV map like in this question on a cube:
WPF Texture mapping of a cube .
But with an higher level of complety: I want to generate the 2d gradient on the fly (from N points coloured in N different ways).
I've read somewhere that wpf cannot create 2d gradient: is it still true? Is there any way to create this gradient, avoiding complex solution such as mixing N linear gradients?
Maybe using something like a 2d mesh or some external library?
Thank you.

A: 2D gradients aren't supported, but if you can deconstruct it down to some alpha-blended or additive combination of two 1d gradients then it can still be done. Check out my answer to this question for an example.
Anything more complex and you'll have to generate the shading yourself. The easiest way to do this is to create a 2D texture manually and apply that to your geometry. Plenty of examples on the net showing how to do that.
If you don't want to generate a texture then your only remaining option is to use a custom shader. This is not a trivial topic, but I'll give you the general idea. You start with your shader fx code, which you then compile to a ps file:
float4 main(float2 uv : TEXCOORD) : COLOR
{
    return float4(uv.x, uv.y, 0, 1);
}

Obviously this is just a very simple shader that sets red along the x axis and green along y, in your example you'd probably want to pass both axis in as 1D textures containing your gradient stops. Either way, you compile it down, add it as a resource and load it with a class based on ShaderEffect:
public class MyShader : ShaderEffect
{
    public MyShader() => this.PixelShader = new PixelShader { UriSource = new Uri("/MyApp;component/MyShader.ps", UriKind.Relative) };
}

With that out of the way, you now need to apply it to geometry. WPF doesn't directly support 3d texture shaders, but since you've loaded your shader as an effect you can create a 2d VisualBrush and apply it like that instead:
<Viewport3D>
    <Viewport3D.Camera>
        <PerspectiveCamera Position="0 0 10" LookDirection="0 0 -1"/>
    </Viewport3D.Camera>
    <ModelVisual3D>
        <ModelVisual3D>
            <ModelVisual3D.Content>
                <AmbientLight Color="White" />
            </ModelVisual3D.Content>
        </ModelVisual3D>
    </ModelVisual3D>
    <ModelVisual3D>
        <ModelVisual3D.Content>
            <GeometryModel3D>
                <GeometryModel3D.Geometry>
                    <MeshGeometry3D
                        Positions="-1 -1 0  1 -1 0  -1 1 0  1 1 0"
                        TextureCoordinates="0 1  1 1  0 0  1 0"
                        TriangleIndices="0 1 2  1 3 2" />
                </GeometryModel3D.Geometry>
                <GeometryModel3D.Material>
                    <DiffuseMaterial>
                        <DiffuseMaterial.Brush>
                            <VisualBrush>
                                <VisualBrush.Visual>
                                    <Image Source="texture.png"> <!-- placeholder texture -->
                                        <Image.Effect>
                                            <local:MyShader />
                                        </Image.Effect>
                                    </Image>
                                </VisualBrush.Visual>
                            </VisualBrush>
                        </DiffuseMaterial.Brush>
                    </DiffuseMaterial>
                </GeometryModel3D.Material>
            </GeometryModel3D>
        </ModelVisual3D.Content>
    </ModelVisual3D>
</Viewport3D>

The result is 3D geometry mapped with your custom shader output:


text:
Q: Rails: Access record instance inside of serializer I'm trying to encrypt some JSON data with a custom column serializer in rails. Because the encryption needs to be reversible I am using AES 256 CBC with a cipher key and initialization vector (IV).
I want the key and iv to be unique to each record which has instance methods to provide those two values. The problem I'm having right now is that I can't access the record instance inside of the serializer/coder so I'm not sure how to pass those values to it.
Here's some pseudo code:
class MyModel
  serialize :keys, EncryptedJSON

  def data_encryption_key
    Digest::SHA2.new(256).hexdigest("#{user.id}:#{user.created_at.utc.to_i}:#{ENV["SOME_SECRECT_KEY_VALUE"]}")
  end

  def data_encryption_iv
    Digest::SHA2.new(256).hexdigest(user.created_at.utc.to_i)
  end
end

class EncryptedJSON
  require 'openssl'

  # decode, decrypt and convert to json
  def self.load(encrypted)
    return if encrypted.nil?

    decipher = OpenSSL::Cipher::AES.new(256, :CBC)

    decipher.decrypt

    # I want this to use: record.data_encryption_key()
    decipher.key = Digest::SHA2.new(256).hexdigest("123")

    # I want this to use: record.data_encryption_iv()
    decipher.iv = Digest::SHA2.new(256).hexdigest("123")

    encrypted = Base64.decode64(encrypted)
    decrypted = decipher.update(encrypted) + decipher.final

    JSON.parse(decrypted)
  end

  # convert to string, encrypt and encode
  def self.dump(data)
    return if data.nil?

    cipher = OpenSSL::Cipher::AES.new(256, :CBC)

    cipher.encrypt

    # I want this to use: record.data_encryption_key()
    cipher.key = Digest::SHA2.new(256).hexdigest("123")

    # I want this to use: record.data_encryption_iv()
    cipher.iv = Digest::SHA2.new(256).hexdigest("123")

    encrypted = cipher.update(data.to_s) + cipher.final

    Base64.encode64(encrypted)
  end
end

A: Unfortunately since serialize is a class method, there is no way to pass a reference to an instance.  In order to do what you need to do, you are going to have to manually handle serialization and deserialization by overwriting the getter and setter methods for keys.
class MyModel < ActiveRecord::Base
  def keys=(json)
    write_attribute(:keys, EncryptedJSON.dump(json, self))
  end

  def keys
    EncryptedJSON.load(read_attribute(:keys), self)
  end
end


text:
Q: how to enable check box single checked when i click on item of list view item public class SingleListAdapter extends BaseAdapter {
    public Context ctx;
    LayoutInflater lInflater;
    List<String> data;

    public SingleListAdapter(Context context, List<String> data) {
        ctx = context;
        this.data = data;
        lInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            view = lInflater.inflate(R.layout.single_choice_items, parent, false);
        }

        ((TextView) view.findViewById(R.id.singleitemId)).setText(data.get(position));

        return view;
    }
}

This is my adapter class :
String[] data = {"10-11 Am", "11-12Am", "12-2Pm", "2-4PM", "4-6Pm"};

List<String> list = new ArrayList<String>();

        for (int i = 0; i < data.length; i++) {
            list.add(data[i]);
        }

        SingleListAdapter     adapter = new SingleListAdapter(this, list);

        listview.setAdapter(adapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                valueoflist=   data[i];

            }
        });

this is my lsitview itemclick function i have  textview and checkbox in listview adapter i am printing value in a textview   and i am able to get data of Particular item on listview item click i want when i click on item list then that particular check box should enable please suggest me how we can do this like and i want single choice checked item click please help me suggest me how we can do this .

A: In onItemClick method you can call your checkBox object and you can work with it.
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            valueoflist=   data[i];
            CheckBox chk = (CheckBox)view.findViewById(R.id.your_check_box_id);
            chk.setChecked(true);
        }
    });

I hope it will help you
Try this:
listview.setOnItemClickListener(new OnMyItemClickListener());

and declare:
private class OnMyItemClickListener implements
        ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
            valueoflist=   data[i];
            CheckBox chk = (CheckBox)view.findViewById(R.id.your_check_box_id);
            chk.setChecked(true);
    }
}

But.. a question.. can you show the listview initialize?


text:
Q: Trying to find a short sci-fi/horror story featuring another dimension with a god that feeds on pain/fear This is going to be a long example so bear with me.
Years ago I read a story online where an army (along with our main guy) from our dimension are sent into another to help the natives who are humanoid psychics that are physically weak by killing a being which has been attacking them. The being feeds on their pain (either pain or fear) and leaves them brain dead so they can't kill it themselves. When the army ventures into this world they come across a really out of place hotel and decide to enter one of them gets attacked by the thing and is tortured horribly, and experiences great pain in front of main guy.
Later the main guy and the rest of the army are captured by fleshy blobs with mechanical spider-like legs, captured in big nets on their underside, the main guy manages to cut himself out by stabbing the blob. He then follows the trail of the spider things to the mouth of a cave. He enters the cave (as you do), it's dark, and he has to trail his hand along the side of the cave; after a while he realizes the wall is no longer rock and is instead flesh... etc.
There's more I know but I just realized I obviously don't have to give all the story. You'd think I'd be able to find it easily considering I remember so much, but I've had no such luck :(
Also I hope this wasn't just a story I dreamt.
Please help me!
P.S. a quote from it was used on TvTropes for the first example on the Madness Mantra page


text:
Q: Webservice call in Play2 Scala I want to do something apparently simple: calling a webservice and saving the result in the database.
I'm inside an Akka Actor code and what I do is to call an object method:
object Service {
  def run {
    val response = WS.url("http://api.server.com/rest/")
    .withAuth("test", "test", com.ning.http.client.Realm.AuthScheme.BASIC)
    .get.value.get.get.body
  }
}

How do I parse the body? I tried to print it on the console but I got NotSuchElement exception.
Any idea, thought? How do I parse arrays, attributes, elements of the XML ?
I'm in the play version 2.1.0

A: Things have changed a bit since the previous version. Play 2.1.0 depends on the scala.concurrent package instead of their own classes:

*

*A Play Promise is now a Scala Future

*A Play Redeemable is now a Scala Promise
I didn't have time to test it, but from the documentation I gathered it should be something like this:
import play.api.libs.ws.WS
import play.api.libs.concurrent.Execution.Implicits._
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.language.postfixOps

object WebserviceCallParseXML {

  val responseFuture = WS.url("http://api.server.com/rest/")
    .withAuth("test", "test", com.ning.http.client.Realm.AuthScheme.BASIC)
    .get()

  val resultFuture = responseFuture map { response =>
    response.status match {
      case 200 => Some(response.xml)
      case _ => None
    }
  }

  val result = Await.result(resultFuture, 5 seconds)

  println(if (result.isDefined) result.get else "No result found" )

}

The documentation about Future.value:

If the future is not completed the returned value will be None. If the future is completed the value will be Some(Success(t)) if it contains a valid result, or Some(Failure(error)) if it contains an exception.


text:
Q: How to replace keys to values in DataFrame? I have the dictionary and the dataframe. I would like to replace keys to values in column 'x_kod'. How can I do that?
lookup_x_kod = {
    'BUBD01': 'budynki mieszkalne jednorodzinne',
    'BUBD02': 'budynki o dwóch mieszkaniach',
    'BUBD03': 'budynki o trzech i więcej mieszkaniach',
    'BUBD04': 'budynki zbiorowego zamieszkania',
    'BUBD05': 'budynki hoteli',
    'BUBD06': 'budynki zakwaterowania turystycznego, pozostałe',
    'BUBD07': 'budynki biurowe',
    'BUBD08': 'budynki handlowo-usługowe',
    'BUBD09': 'budynki łączności, dworców i terminali',
    'BUBD10': 'budynki garaży',
    'BUBD11': 'budynki przemysłowe',
    'BUBD12': 'zbiorniki, silosy i budynki magazynowe',
    'BUBD13': 'ogólnodostępne obiekty kulturalne',
    'BUBD14': 'budynki muzeów i bibliotek',
    'BUBD15': 'budynki szkół i instytucji badawczych',
    'BUBD16': 'budynki szpitali i zakładów opieki medycznej',
    'BUBD17': 'budynki kultury fizycznej',
    'BUBD18': 'budynki gospodarstw rolnych',
    'BUBD19': 'budynki przeznaczone do sprawowania kultu religijnego i czynności religijnych',
    'BUBD20': 'obiekty budowlane wpisane do rejestru zabytków i objęte indywidualną ochroną konserwatorską oraz nieruchome, archeologiczne dobra kultury',
    'BUBD21': 'pozostałe budynki niemieszkalne, gdzie indziej nie wymienione',
}

A: Use series.map:
df['x_kod'] = df['x_kod'].map(lookup_x_kod)

A: You can use the look_x_kod dictionary
import pandas as pd

>>> lookup_x_kod = {
...     'BUBD01': 'budynki mieszkalne jednorodzinne',
...     'BUBD02': 'budynki o dwóch mieszkaniach',
...     'BUBD03': 'budynki o trzech i więcej mieszkaniach',
...     'BUBD04': 'budynki zbiorowego zamieszkania',
...     'BUBD05': 'budynki hoteli',
...     'BUBD06': 'budynki zakwaterowania turystycznego, pozostałe',
...     'BUBD07': 'budynki biurowe',
...     'BUBD08': 'budynki handlowo-usługowe',
...     'BUBD09': 'budynki łączności, dworców i terminali',
...     'BUBD10': 'budynki garaży',
...     'BUBD11': 'budynki przemysłowe',
...     'BUBD12': 'zbiorniki, silosy i budynki magazynowe',
...     'BUBD13': 'ogólnodostępne obiekty kulturalne',
...     'BUBD14': 'budynki muzeów i bibliotek',
...     'BUBD15': 'budynki szkół i instytucji badawczych',
...     'BUBD16': 'budynki szpitali i zakładów opieki medycznej',
...     'BUBD17': 'budynki kultury fizycznej',
...     'BUBD18': 'budynki gospodarstw rolnych',
...     'BUBD19': 'budynki przeznaczone do sprawowania kultu religijnego i czynności religijnych',
...     'BUBD20': 'obiekty budowlane wpisane do rejestru zabytków i objęte indywidualną ochroną konserwatorską oraz nieruchome, archeologiczne dobra kultury',
...     'BUBD21': 'pozostałe budynki niemieszkalne, gdzie indziej nie wymienione',
... }
>>>
>>> df = pd.DataFrame(data=['BUBD01','BUBD01','BUBD16','BUBD04','BUBD05','BUBD12','BUBD21','BUBD10'],columns=['x_kod'])
>>> df['x_kod_value'] = df['x_kod'].apply(lambda x:lookup_x_kod[x])
>>> df
    x_kod                                        x_kod_value
0  BUBD01                   budynki mieszkalne jednorodzinne
1  BUBD01                   budynki mieszkalne jednorodzinne
2  BUBD16       budynki szpitali i zakładów opieki medycznej
3  BUBD04                    budynki zbiorowego zamieszkania
4  BUBD05                                     budynki hoteli
5  BUBD12             zbiorniki, silosy i budynki magazynowe
6  BUBD21  pozostałe budynki niemieszkalne, gdzie indziej...
7  BUBD10                                     budynki garaży
>>>


text:
Q: Can I populate LDAP accounts using a table of username/passwords from a different database? Our users' web passwords/usernames/firstname/lastname/etc are in the dbo.contacts table in our CRM. This is great for CRM and our CRM compatible apps, but I would love to query these accounts with software that can only query LDAP.
Is it possible to tell openldap, "Hey, create logins using this table*" and to update this information periodically as obviously information changes over time? My scripting-fu isn't very strong but I've worked with php and webservices and would just like to get ldap talking to this table so I can get serious with single-sign-on.
Thanks.
*This can be a live connection to the CRM db via odbc/ado, a csv file, or connection via webservices.

A: This has nothing to do with OpenLDAP. LDAP clients can use the add request to add entries, assuming the client's authorization state allows adding users under the base object chosen by client. There is a standalone modify client called ldapmodify. Please "LDAP: Mastering ldapmodify" for more information.
Be aware that the some versions of the openldap ldapmodify tool are broken in that it incorrectly allows values with trailing spaces (which is illegal). The directory server base 64 encodes these values, which is probably not what was intended.


text:
Q: Is there anyway to bring up the color picker in VSCode when writing JS/JSX files? When using React, it would be nice to be able to have access to a color picker with hex code when using inline styling. Any extensions or settings out there to remedy this?

A: I ran into this problem myself, so I built Color Pick.

A: I've created an extension that uses macOS native color picker, and it works well with inline styles and any file formats, as long as the selected color is in a CSS compliant notation (hex, rgba(...) etc)


text:
Q: service get killed when screen is off in some devices I have seen many pages about this problem but didn't help me.
I have a service that should run in background even when the screen is off.
but some android devices (like many huawei phones) have battery care stuff that can kill service when screen is off, and android 6 has that option (keep running after screen off) but user should give that permission himself.
I see that telegram service get killed too, but how whatsapp service doesn't stop even when the screen is off.
this is my service in androidManifest
<service android:name=".myservice" />

is there any option in manifest that can keep service running when the screen is off? I can't use sticky-services because it runs over and over after screen turns on but my service should start once!
or any other solution for this problem?? thanks!


text:
Q: RabbitMQ: Connection issue while publishing message to multiple queues I have messages in Map - key as a Queue Name and value as a List of messages.
Whenever I publish the multiple message to queue server throws an exception as user has reached the maximum number of sign-ins permitted.
while publishing messages to 1 queue. Below is code which executes:
public class MessageManager {

public static void publish(String exchange, HashMap<String, List<String>> queueNameWithMessages) throws IOException {
    ...
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(Constants.HOST_NAME);
    factory.setUsername(Constants.USER_NAME);
    factory.setPassword(Constants.PASSWORD);
    factory.setPort(Constants.PORT);
    Connection connection = factory.newConnection();
    Channel ch = connection.createChannel();
    Channel ch1 =  connection.createChannel();
    try {
        for(Entry<String, List<String>> entry : queueNameWithMessages) {
            String routingKey = entry.getKey();
            for(String  messageToBeSent : entry.value()) {
                ch.basicPublish(exchange, routingKey, true, MessageProperties.PERSISTENT_BASIC,  messageToBeSent.getValue().getBytes());
            }
            ExecutorService threadExecutor = Executors.newFixedThreadPool(5);
            String responseKey = props.getProperty(routingKey);
            if(!CLAMUtility.workingListnerToRespnseQueue.contains(responseKey)) {
                Worker fast = new Worker(0, threadExecutor, ch1,responseKey, routingKey);
                CLAMUtility.workingListnerToRespnseQueue.add(responseKey);
            }
        }
        ch.close();
        System.out.println("Message published successfully!\n \n");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

A: We discover that this issue is not related to Rabbit MQ. Message consumer system has some user interaction related limitations that is not handled properly.
Thanks!


text:
Q: Send a POST message with UTF-8 special char with Wininet I want to send a message on a PHP page using Wininet. My code is actually incompatible with UTF-8 special char like €, é, à. How to convert it ? I search a long time and I don't find the solution. I tried to use wstring but it the same problem. This is the source code :
void sendHello()
{
    LPCSTR header = "Content-Type: application/x-www-form-urlencoded; charset=utf-8";
    std::string dataStr = "message=ééàà€€";
    LPVOID myMessage = (LPVOID)dataStr.c_str();
    HINTERNET hInternet = InternetOpenA("InetURL/1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    HINTERNET hConnection = InternetConnectA(hInternet, "127.0.0.1", 80, " ", " ", INTERNET_SERVICE_HTTP, 0, 1);
    HINTERNET hRequest = HttpOpenRequestA(hConnection, "POST", "/SendMessage.php", NULL, NULL, NULL, 0, 1);
    HttpSendRequestA(hRequest, header, strlen(header), myMessage, dataStr.size());
}

I post a new question because a similar question has been posted by someone but the problem is not solved and solution pruposed doesn't works. (It's a StackOverflow recommandation to open a new question).
Thanks to @Barmak, @Shemirani, @Unheilig, @Daniel Widdis to keep it opened.

A: Thanks all, this is the final solution :
void sendHello()
{
    LPCSTR header = "Content-Type: application/x-www-form-urlencoded; charset=utf-8";
    std::string dataStr = u8"message=ééàà€€";
    LPVOID myMessage = (LPVOID)dataStr.c_str();
    HINTERNET hInternet = InternetOpenA("InetURL/1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    HINTERNET hConnection = InternetConnectA(hInternet, "127.0.0.1", 80, " ", " ", INTERNET_SERVICE_HTTP, 0, 1);
    HINTERNET hRequest = HttpOpenRequestA(hConnection, "POST", "/SendMessage.php", NULL, NULL, NULL, 0, 1);
    HttpSendRequestA(hRequest, header, strlen(header), myMessage, dataStr.size());
}

A: You are not url-encoding the string data correctly. Non-ASCII and reserved characters need to be charset encoded to bytes and then the resulting bytes encoded in %HH format.
The UTF-8 encoded form of ééàà€€ is bytes

C3 A9 C3 A9 C3 A0 C3 A0 E2 82 AC E2 82 AC

So change this
std::string dataStr = "message=ééàà€€";

To this
std::string dataStr = "message=%C3%A9%C3%A9%C3%A0%C3%A0%E2%82%AC%E2%82%AC";`


text:
Q: Multi Selection using Angular js I am having the requirement in AngularJS on Multi Select fields.
I have 2 multi select drop-downs and I need to pass the data between them through 3 buttons. I tried sample in JSFiddle but I was unable to succeed. Please find the details in the below link.
Here is the link
HTML CODE

<select multiple="true" ng-model="selectedDetails" ng-options="c.name+' ('+c.id+')' for c in rule"></select>
<button ng-click='moveSelectedToRight(selectedDetails)'>></button>
 <button ng-click='moveAllSelected(selectedDetails)'>>></button>
<button ng-click='moveSelectedToLeft(selectedDetails)'><</button>
<select multiple="true" ng-model="selectedDetailsCopied" ng-options="c.name+' ('+c.id+')' for c in selectedDetailsCopied"></select>

Selected Details: {{selectedDetails }}

Copied Details: {{selectedDetailsCopied}}

JS CODE
    var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.selectedDetails = [];
    $scope.selectedDetailsCopied=[];
    $scope.rule = [{
        name: 'Rock',
        id: '0'},
    {
        name: 'white',
        id: '1'},
    {
        name: 'Test',
        id: '2'},
    {
        name: 'Fun',
        id: '3'},
    {
        name: 'Laaa',
        id: '4'
    }];
$scope.moveSelectedToRight = function(selectedDetails){
        $scope.selectedDetailsCopied = angular.copy(selectedDetails);
    }
    $scope.moveAllSelected = function(selectedDetails){
        $scope.selectedDetailsCopied = angular.copy($scope.rule);
    }
     $scope.moveSelectedToLeft = function(selectedDetails){
        $scope.selectedDetailsCopied = [];
    }

}

A: Look this

var myApp = angular.module('myApp', []);

    function MyCtrl($scope) {
        $scope.selectedDetails = [];
        $scope.selectedDetailsCopied = [];
        $scope.rule = [{
               name: 'Rock',
               id: '0'},
           {
               name: 'white',
               id: '1'},
           {
               name: 'Test',
               id: '2'},
           {
               name: 'Fun',
               id: '3'},
           {
               name: 'Laaa',
               id: '4'
           }];

            $scope.moveSelectedToRight = function(){
                angular.forEach($scope.selectedDetails, function(value, key) {
                    var indexEl = $scope.geIndex($scope.rule, value);
                    $scope.selectedDetailsCopied.push($scope.rule[indexEl]);
                });

                angular.forEach($scope.selectedDetails, function(value, key) {
                    var indexEl = $scope.geIndex($scope.rule, value);
                    $scope.rule.splice(indexEl, 1);
                });

                while($scope.selectedDetails.length > 0)
                    $scope.selectedDetails.splice(0, 1);
            }
            $scope.moveAllSelected = function(){
                angular.forEach($scope.rule, function(value, key) {
                    $scope.selectedDetailsCopied.push(value);
                });

                while($scope.rule.length > 0)
                    $scope.rule.splice(0, 1);
            }
            $scope.moveSelectedToLeft = function(){
                angular.forEach($scope.selectedDetailsMoved, function(value, key) {
                    var indexEl = $scope.geIndex($scope.selectedDetailsCopied, value);
                    $scope.rule.push($scope.selectedDetailsCopied[indexEl]);
                });

                angular.forEach($scope.selectedDetailsMoved, function(value, key) {
                    var indexEl = $scope.geIndex($scope.selectedDetailsCopied, value);
                    $scope.selectedDetailsCopied.splice(indexEl, 1);
                });
            }

            $scope.geIndex = function(arr, idElement){
                var itemIndex = {};
                angular.forEach(arr, function(value, key) {
                    if(value.id == idElement || value == idElement){
                        itemIndex = key;
                        return false;
                    }
                });
                return itemIndex;
            }
        }

    <select multiple="true" ng-model="selectedDetails" ng-options="c.id as c.name for c in rule"></select>
    <button ng-click='moveSelectedToRight(selectedDetails)'>></button>
    <button ng-click='moveAllSelected(selectedDetails)'>>></button>
    <button ng-click='moveSelectedToLeft(selectedDetailsMoved)'><</button>
    <select multiple="true" ng-model="selectedDetailsMoved" ng-options="c.id as c.name for c in selectedDetailsCopied"></select>

Selected Details: {{selectedDetails }}

Copied Details: {{selectedDetailsCopied}}


text:
Q: Is there a way to choose/ stay in one specific flutter version for one app? With Flutter 2 just released, I want to upgrade the SDK to the latest stable version, but I won't do it, since there will be compatibility issue with some of the plugin that I use. Is there a way to choose/ stay in a specific flutter version for one app so that when I upgrade my SDK it won't disrupt my existing app? Any answers will be appreciated.

A: I believe fvm is what you need. I am also looking into this so might have more info soon. According to info from pubdev it can "Configure and use Flutter SDK version per project" Check the pubdev for more info
https://pub.dev/packages/fvm

A: No, currently you cannot do that. You should just upgrade your SDK after about a month or so when support for Flutter 2.0 would be out for most packages I guess


text:
Q: Method overload. How the compiler decide which to use? I have 2 methods.
    1. public void Log(object tolog, string Instance)
    2. public void Log(params object[] tolog)

And I call Log like this, where tolog1 is a object
Log(tolog1,"Hello")

I'm confused as to why the compiler has chosen the second overload. What conditions would cause this?

A: Your call Log(tolog1,"Hello") would use the method Log(object tolog, string Instance) that is because of Overloading Resolution Rules (7.4.2).
Given the list of arguments your first method overload  Log(object tolog, string Instance) is a more suitable/closer candidate and compiler can determine that because of the rules specified:
Overloading Resolution Rules (7.4.2)

*

*Given the set of applicable candidate function members, the best    function member in that set is located.

*If the set contains only one function member, then that function    member is the best function member.

*Otherwise, the best function member is the one function member that  is better than all other function members with respect to the given argument list, provided that each function member is compared to all   other function members using the rules in Section 7.4.2.2.

*If there is not exactly one function member that is better than all    other function members, then the function member invocation is
  ambiguous and a compile-time error occurs

Under Section 7.4.2.2 You will see:

Given an argument list A with a set of argument types {A1, A2, ...,
  AN} and two applicable function members MP and MQ with parameter types
  {P1, P2, ..., PN} and {Q1, Q2, ..., QN}, MP is defined to be a better
  function member than MQ if

*

*for each argument, the implicit conversion from AX to PX is not worse    than the implicit conversion from AX to QX, and

*for at least one argument, the conversion from AX to PX is better    than the conversion from AX to QX.

  When performing this evaluation, if MP or MQ is applicable in its
  expanded form, then PX or QX refers to a parameter in the expanded
  form of the parameter list.

A: In short, the compiler chooses the type which is closer i.e. the object that is at highest level of Hierarchy / Inheritance.
In your case, Log(tolog1,"Hello"), tolog1 satisfies both the overloads
Log(params object[] tolog) and Log(object tolog, string Instance) but in case of second parameter "Hello" the compiler chooses Log(object tolog, string Instance) As System.String is closer to "Hello" than System.Object


text:
Q: Jar file doesn't work on the web server I have an Jar file that is working perfectly fine on my Mac using console:
 MacBook-Pro-Pavel:PDFparser pavelpigalev$ java -jar PDFparser.jar
 Usage: java PDFparser <input-pdf> -p1 <password> -c1 -i0 -s1
    -p1 : PDF password
    -c1 : write JSON to console
    -i0 : don't extract images
    -s1 : take page screenshots [WARNING: currently in beta]
 MacBook-Pro-Pavel:PDFparser pavelpigalev$ java -jar PDFparser.jar f5.pdf
 MacBook-Pro-Pavel:PDFparser pavelpigalev$

It creates a folder and puts out images that I need in that folder.
But if I use it on the web server (also using console) it gives me this error:
 [root@somesite.com pdfparser]$ ls
ffive.pdf  lib  PDFparser.jar  README.TXT
[root@somesite.com pdfparser]$ java -jar "PDFparser.jar"
Usage: java PDFparser <input-pdf> -p1 <password> -c1 -i0 -s1
    -p1 : PDF password
    -c1 : write JSON to console
    -i0 : don't extract images
    -s1 : take page screenshots [WARNING: currently in beta]
[root@somesite.com pdfparser]$ java -jar "PDFparser.jar" ffive.pdf
Exception in thread "main" java.lang.ClassNotFoundException: javax.vecmath.Vector2d not found in gnu.gcj.runtime.SystemClassLoader{urls=[file:PDFparser.jar], parent=gnu.gcj.runtime.ExtensionClassLoader{urls=[], parent=null}}
   at java.net.URLClassLoader.findClass(libgcj.so.10)
   at java.lang.ClassLoader.loadClass(libgcj.so.10)
   at java.lang.ClassLoader.loadClass(libgcj.so.10)
   at java.lang.reflect.Field.getType(libgcj.so.10)
   at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.excludeField(ReflectiveTypeAdapterFactory.java:56)
   at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:111)
   at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:72)
   at com.google.gson.Gson.getAdapter(Gson.java:353)
   at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:52)
   at com.google.gson.Gson.getAdapter(Gson.java:353)
   at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.<init>(ReflectiveTypeAdapterFactory.java:82)
   at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:81)
   at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:118)
   at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:72)
   at com.google.gson.Gson.getAdapter(Gson.java:353)
   at com.google.gson.Gson.toJson(Gson.java:578)
   at com.google.gson.Gson.toJson(Gson.java:565)
   at com.google.gson.Gson.toJson(Gson.java:520)
   at com.google.gson.Gson.toJson(Gson.java:500)
   at pdfparser.PDFparser.main(PDFparser.java:163)

I didn't make this Jar file, I don't really know much about Java. I work with PHP and I really need this program working well on server. Can someone help me with that?

A: Place vechmath .jar in your class path
Or - Add your supporting .jars to the classpath
export CLASSPATH=$CLASSPATH:/path/to/vecmath.jar
Or - Supply at the Runtime
java -cp vecmath-xxx.jar -jar Yourjar.jar

Importance of Classpath

A: You're not using the same JVM that the one in your macbook. You're using GNU JVM as seen in not found in gnu.gcj.runtime.SystemClassLoader
Try a java -version to confim that and then change your JVM

A: Try to find vecmath-1.3.1.jar file on you Mac and place it in the same dir as PDFparser.jar is located. Try to run. If no success then try to run as follow:
 java -cp vecmath-1.3.1.jar -jar "PDFparser.jar"


text:
Q: Are the results of Apple Photos processing shared between my computers? I have a MacBook and and Mac mini with same Apple ID. My photo library size is 55,109 photos, 3,670 videos, 68 items.  photoanalysisd has been running for 7 days on my MacBook.  It doesn't appear to be running on the Mac mini.  On the Mac Mini, Photos.app is not running (and thus should not be pausing photoanalysisd).

*

*Do both computers share the analysis results, or does each computer repeat the analysis?

*If the information is shared, is there a way I can coerce photoanalysisd to only process on the Mac mini, to make processing faster using the two computers?

A: No. In general, all photo library generated metadata is not strictly shared from iCloud to iCloud on macOS Mojave 10.14 and iOS 12 but some of the overall categories / extracted data does sync. (So it's pretty confusing / grey area at the moment)
Most of the AI training models to identify photos by subject, finding faces, making memories run locally on each device and only after you name a face, save or customize a memory or make an album does that higher level data sync.
You might need to erase the long running library and let it redownload or better, engage apple support for iCloud and give the engineers permission to look at the sync logs server side and submit some local diagnostics if the process can't catch up.
I've don't that in the past to get excellent support and a precise fix. Sometimes the algorithm gets stuck and you need an assist rather than just restarting the OS or downloading a clean copy from iCloud to one Mac (assuming that Mac isn't your "source of truth" or master copy of photos for you).


text:
Q: When does the closure capture the variable value (defined in an outer function) in javascript: when nested function is defined or executed? I understand that scope is created when a function is defined. But I am not sure if I comprehend correctly if the variable value (defined in a function & referenced in inner function, aka closure) is captured also when the nested function is defined , Or, when it is executed.
In the well known closure in loop Scenario, the closure seems to capture the "i" value when the loop finishes. Assuming loop through 5 times, then "i" would be 4. Hence "i" would be captured as 4. Therefore it looks like "i" is only captured when nested function is executed?
It would be appreciated if someone can point out where the capture is happening.
Scenario 1
var fnName = function(x){
    return function(){ return ++x; };   // (is x value captured here?)
};
var fnName1 = fnName(0);
fnName1();              // x=1 (is x value captured here?)
fnName1();              // x=2

Scenario 2
var fnName = function(){
var x = 0;
    return function(){ return ++x; };   // (is x value captured here?)
};
var fnName1 = fnName();
fnName1();              // x=1 (is x value captured here?)
fnName1();              // x=2

Scenario 3
var fnName = function(){
    var x = 0;
    function runFn(){ return x++; };    // (is x value captured here?)
    runFn();
};
fnName();               // x=0
fnName();               // x=0

A: The variable is captured when it is declared. The value isn't captured (which is why it can change).
var fnName = function(x){ // Here
    return function(){ return ++x; };
};

var fnName = function(){
var x = 0;  // Here (but remember that hoisting exists)
    return function(){ return ++x; };
};


text:
Q: Giving Value to Python3 Count String I am running a loop equation that divides or subtracts. Every time it divides I want it to represent each division with the # 2 and every time it subtracts I want it to represent the subtractions with a 1. I then want that count string to be a value that I can manipulate with some basic math. Basically it'll look like this: 20/2 = 10 (2) 10/2 = 5 (2) 5/2 = 2.5 (2) 2.5-.5 = 2 (1) 2/2 = 1 (2)
22212 <=== that I want to make a new value but with the way I have it coded, it's not working. I think it may have something to do with the end='' in the code.
I've tried giving the value of the string = to a int value and tried joining the string but no luck so far.
num = 20
while num >= 1.5:
        num /= 2
        v = 1
        print(v, end='')
        if int(num) != num:
            num -= .5
            v = 2
            print(v, end='') #trying to make the output here a value
            nv = ''.join(str(int(v)))
            nv = int(v) #trying to give the joined strs of nv a value
print(nv) #trying to get this to print the combined valued of v to something that math can be applied to.
print('')

The code doesn't give any errors I just can't figure out how to make the output and actual number that I can manipulate.

A: you are printing v = 1 after your division. In your post you said you want a 2 for division, I am assuming what you wrote in the post is the result you want.
a = ""
num = 20
while num >= 1.5:
    num /= 2
    a +=  "2"
    if int(num) != num:
        num -= .5
        a += "1"
print(a)

now a is a string with your desired result. You can always convert that String to an int to do some math with it.


text:
Q: Mapping lookup/junction table entity in many-to-many relationship I'm attempting to map a many-to-many relationship and include the lookup/junction table entity and I'm having some trouble.  Here are my (basic) models:
public class User
{
    public int UserId { get; set; }
    public IList<UserGroupCode> Codes { get; set; }
}

public class Group
{
    public int GroupId { get; set; }
    public IList<UserGroupCode> Codes { get; set; }
}

public class UserGroupCode
{
    public int UserGroupCodeId { get; set; }
    public int UserId { get; set; }
    public int GroupId { get; set; }
    public string Value { get; set; }
}

Here is the configuration for User I've been working with
HasMany(p => p.Codes).WithMany().Map(m =>
{
    m.ToTable("UserGroupCodes");
    m.MapLeftKey("UserId");
    m.MapRightKey("UserGroupCodeId");
});

I've seen a lot of articles on how to map many-to-many relationships which don't include the lookup table as an entity (the classic example is User-Roles relationships).  But, as you can see, I have a Value property on my UserGroupCode relationship which necessitates that relationship being an actual entity.
Thanks in advance.

A: I ended up coming across this article.  I added navigation properties to my UserGroupCode model for User and Group.
public class UserGroupCode
{
    public int UserGroupCodeId { get; set; }
    public int UserId { get; set; }
    public User User { get; set; }
    public int GroupId { get; set; }
    public Group Group { get; set; }
    public string Value { get; set; }
}

The only configuration required for the relationship is on the UserGroupCode entity:
HasRequired(p => p.User).WithMany(p => p.Codes).HasForeignKey(p => p.UserId);
HasRequired(p => p.Group).WithMany(p => p.Codes).HasForeignKey(p => p.GroupId);


text:
Q: Gson with FileWriter doesn't write complete file I am creating an instance of Gson and writing with the following:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Writer writer = new FileWriter(location);
gson.toJson(data, writer);

This does write to the file, but the JSON object is incomplete and ends at line 7197 like this:
...
{
    "type": "RockCell"
},
{
    "type": "Flo

I have tried deleting and rerunning the code and it always stops writing at line 7197 in this exact way.
If I change the value of data, it ends at a different point (line 7182) but again does so consistently.
In both cases, the files are 106,496 bytes in size. This issue still occurs if pretty printing is disabled, but the files are always 49,152 bytes.


text:
Q: Ember Data pluralizing url endpoints when using store.find I got an error with
GET http://localhost:63342/people 404 (Not Found)
and
Assertion failed: Error while loading route:....
Why does this error http://localhost:63342/people 404 appears? I don't have this route.
here is my js code:
window.Models = Ember.Application.create();

Models.Router.map(function () {
    //匹配路由后显示person_list模板
    this.resource('persons', { path: '/' });
});

Models.PersonsRoute = Ember.Route.extend({
    model:function(){
        return this.store.find('person');
    },
    setupController:function(controller, model){
        controller.set('content', model)
    }
});

Models.Person = DS.Model.extend({
    name: DS.attr('string'),
    description:DS.attr('string')
});

Models.Person.FEATURES = [{
    name:'Kratos Zhang',
    description:'a c# coder in 7agree.'
}]

and template


text:
Q: JSON Web Request string to parsed data with JSON.NET I am using .net to call to a webservice then parse it to usable data.
Right now I am experimenting with this call: http://www.reddit.com/r/all.json
Which returns: http://pastebin.com/AbV4yVuC
This is put in to a string, which I called jsontxt.
I am using JSON.NET to parse the information but it doesn't seem to be working.  I initially tried to deserialize it as an object and it didn't work as nothing is put in to the variable
Then I tried to deserialize it as a dataset and I'm having no luck again.  My error was

An unhandled exception of type 'Newtonsoft.Json.JsonException' occurred in Newtonsoft.Json.dll

MY CODE:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace tutorialresult1
{

class Program
{
    static void Main(string[] args)
    {
        using (var webClient = new System.Net.WebClient())
        {
            var jsontxt = webClient.DownloadString("http://www.reddit.com/r/all.json");
           // Console.Write(json);

            // -----Deserializing by Object--------------
            //MediaEmbed account = JsonConvert.DeserializeObject<MediaEmbed>(jsontxt);
            //Console.WriteLine(account.width);   //COMES OUT TO NULL

            // -----Deserializing by DataSet--------------
            DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(jsontxt);
            DataTable dataTable = dataSet.Tables["Children"];
            Console.WriteLine(dataTable.Rows.Count);
        }

    }

    public class MediaEmbed
    {
        public string content { get; set; }
        public int width { get; set; }
        public bool scrolling { get; set; }
        public int height { get; set; }
    }
.... //rest of classes here for each json which were generated with http://json2csharp.com/
    }
}

I'm just trying to make the JSON easily accessible by parsing it.

A: You are trying to deserialize a json-string into a dataset-object. But the json-string doesn't have the format of a dataset. So you need to create a class which matches the json or deserialize it into a dictionary or sth. like this.

A: Using json2charp I generated the following set of classes. Using those you should be able to deserialize the JSON into RootObject using JSON.NET.
var account = JsonConvert.DeserializeObject<RootObject>(jsontxt);

.
public class MediaEmbed
{
    public string content { get; set; }
    public int? width { get; set; }
    public bool? scrolling { get; set; }
    public int? height { get; set; }
}

public class Oembed
{
    public string provider_url { get; set; }
    public string description { get; set; }
    public string title { get; set; }
    public string url { get; set; }
    public string type { get; set; }
    public string author_name { get; set; }
    public int height { get; set; }
    public int width { get; set; }
    public string html { get; set; }
    public int thumbnail_width { get; set; }
    public string version { get; set; }
    public string provider_name { get; set; }
    public string thumbnail_url { get; set; }
    public int thumbnail_height { get; set; }
    public string author_url { get; set; }
}

public class SecureMedia
{
    public Oembed oembed { get; set; }
    public string type { get; set; }
}

public class SecureMediaEmbed
{
    public string content { get; set; }
    public int? width { get; set; }
    public bool? scrolling { get; set; }
    public int? height { get; set; }
}

public class Oembed2
{
    public string provider_url { get; set; }
    public string description { get; set; }
    public string title { get; set; }
    public int thumbnail_width { get; set; }
    public int height { get; set; }
    public int width { get; set; }
    public string html { get; set; }
    public string version { get; set; }
    public string provider_name { get; set; }
    public string thumbnail_url { get; set; }
    public string type { get; set; }
    public int thumbnail_height { get; set; }
    public string url { get; set; }
    public string author_name { get; set; }
    public string author_url { get; set; }
}

public class Media
{
    public string type { get; set; }
    public Oembed2 oembed { get; set; }
}

public class Data2
{
    public string domain { get; set; }
    public object banned_by { get; set; }
    public MediaEmbed media_embed { get; set; }
    public string subreddit { get; set; }
    public string selftext_html { get; set; }
    public string selftext { get; set; }
    public object likes { get; set; }
    public SecureMedia secure_media { get; set; }
    public string link_flair_text { get; set; }
    public string id { get; set; }
    public int gilded { get; set; }
    public SecureMediaEmbed secure_media_embed { get; set; }
    public bool clicked { get; set; }
    public bool stickied { get; set; }
    public string author { get; set; }
    public Media media { get; set; }
    public int score { get; set; }
    public object approved_by { get; set; }
    public bool over_18 { get; set; }
    public bool hidden { get; set; }
    public string thumbnail { get; set; }
    public string subreddit_id { get; set; }
    public object edited { get; set; }
    public string link_flair_css_class { get; set; }
    public object author_flair_css_class { get; set; }
    public int downs { get; set; }
    public bool saved { get; set; }
    public bool is_self { get; set; }
    public string permalink { get; set; }
    public string name { get; set; }
    public double created { get; set; }
    public string url { get; set; }
    public object author_flair_text { get; set; }
    public string title { get; set; }
    public double created_utc { get; set; }
    public int ups { get; set; }
    public int num_comments { get; set; }
    public bool visited { get; set; }
    public object num_reports { get; set; }
    public object distinguished { get; set; }
}

public class Child
{
    public string kind { get; set; }
    public Data2 data { get; set; }
}

public class Data
{
    public string modhash { get; set; }
    public List<Child> children { get; set; }
    public string after { get; set; }
    public object before { get; set; }
}

public class RootObject
{
    public string kind { get; set; }
    public Data data { get; set; }
}

A: Have you tried deserialize using the following? Seems to be more robust for me.
using System.Web.Script.Serialization;
...
var x = new JavaScriptSerializer().Deserialize<Obj_type>(jsonstring);

http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer%28v=vs.110%29.aspx
as purplej0kr mentioned you will need to have a .Net model to use for Obj_type (and it will need to match the object you are parsing) or this will not work.
You will need the System.Web.Extensions.dll referenced in your project (right click add reference, dll is usually under 'Assemblies'). Otherwise:
Where can I find the assembly System.Web.Extensions dll?


text:
Q: Subtle differences in limit definitions Traditionally the limit of a sequence is defined as $\lim_{n\to\infty} x_n = L \Leftrightarrow$
$$(\forall \varepsilon > 0)(\exists N > 0)(\forall n \in \mathbf{N})(n \geq N \Rightarrow |x_n-L|<\varepsilon). \tag{1} $$
However, sometimes it seems more helpful to use the following formulation.
$$(\forall \varepsilon > 0)(\exists N > 0)(\forall n \in \mathbf{N}_{\geq N})(|x_n-L|<\varepsilon) \tag{2} $$
I'm not entirely sure that both statements are exactly equivalent, but I do have some reasons to believe so. Considering $(1)$ is immediately true $\forall n \in \mathbf{N}_{<N}$ because of the implication with a false antecedent and that for bigger $n$ the statement is true if $|x_n-a|<\varepsilon$, it seems like they are exactly equivalent.
This formulation would allow for a slightly nicer negation, but as I said, I'm not convinced enough to use $(2)$ on an exam. Could someone explain to me why there is indeed a devil in the details or why they are exactly the same?
Thanks in advance.

A: Let $P(n)$ abbreviate $|x_n-L|<\varepsilon$ . We have to show that the statements
$$\forall n \in \mathbf{N} : n \geq N \Rightarrow P(n). \tag{1} $$
and
$$\forall n \in \mathbf{N}_{\geq N} : P(n) \tag{2} $$
are equivalent.
$(1) \implies (2)$:
Let $n \in \mathbf{N}_{\geq N}$. We have to show that $$P(n)$$
is true.
Since $n \in \mathbf{N}$, we know that the implication $$n \geq N \Rightarrow P(n)$$ is true. Since the implication's premise $n \geq N$ is true for $n \in \mathbf{N}_{\geq N}$, we see that the implication's conclusion
$$P(n)$$
must be true.
$(2) \implies (1)$:
Let $n \in \mathbf{N}$. We have to show that the implication $$n \geq N \Rightarrow P(n)$$ is true.
Case 1. $n \ge N$. Then by $(2)$ the implication's conclusion
$$P(n)$$
is true. Thus the implication is true for this $n$.
Case 2. $n < N$. Then the implication's premise
$$n \ge N$$
is false. Thus the implication is true for this $n$.


text:
Q: How does GridSearchCV compute training scores? I'm having a hard time figuring out parameter return_train_score in GridSearchCV. From the docs:

return_train_score : boolean, optional
       If False, the cv_results_ attribute will not include training scores.

My question is: what are the training scores?
In the following code I'm splitting data into ten stratified folds. As a consequence grid.cv_results_ contains ten test scores, namely 'split0_test_score', 'split1_test_score' , ..., 'split9_test_score'. I'm aware that each of those is the success rate obtained by a 5-nearest neighbors classifier that uses the corresponding fold for testing and the remaining nine folds for training.
grid.cv_results_ also contains ten train scores: 'split0_train_score', 'split1_train_score' , ..., 'split9_train_score'. How are these values calculated?
from sklearn import datasets
from sklearn.model_selection import GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import StratifiedKFold

X, y = datasets.load_iris(True)

skf = StratifiedKFold(n_splits=10, random_state=0)
knn = KNeighborsClassifier()

grid = GridSearchCV(estimator=knn,
                    cv=skf,
                    param_grid={'n_neighbors': [5]},
                    return_train_score=True)
grid.fit(X, y)

print('Mean test score: {}'.format(grid.cv_results_['mean_test_score']))
print('Mean train score: {}'.format(grid.cv_results_['mean_train_score']))
#Mean test score: [ 0.96666667]
#Mean train score: [ 0.96888889]

A: It is the train score of the prediction model on all folds excluding the one you are testing on. In your case, it is the score over the 9 folds you trained the model on.

A: Maybe my other answer here will give you clear understanding of working in grid-search.
Essentially training scores are the score of model on the same data on which its trained on.
In each fold split, data will be divided into two parts: train and test. Train data will be used to fit() the internal estimator and test data will be used to check the performance of that. training score is just to check how well the model fit the training data.