text:
Q: byte-code: Symbol's value as variable is void: org-babel-tangle-lang-exts I had Emacs working pretty well and then I restarted my computer.  Now this block of code prevents me from loading my init-files:
(require 'ob-clojure)
(org-babel-do-load-languages
     'org-babel-load-languages
     '((emacs-lisp . nil)
       (R . t)
       (python . t)
       (js . t)
       (scheme . t)
       (C . t)
       (clojure . t)
       (lilypond . t)
       (octave . t)))

I don't know why this would be.  I had gotten babel to work fine with R before I restarted.  Now I get the message:

byte-code: Symbol's value as variable is void: org-babel-tangle-lang-exts

I grep'd the directory for anything mentioning org-babel and only the above expression came up.  That plus the fact that the rest of my init-files code loaded when I got rid of it makes me think that this code is the problem.  But why would org-mode be referring to a function I don't have?
Running emacs --debug-init gave:

Debugger entered--Lisp error: (void-function org-babel-do-load-languages)
    (org-babel-do-load-languages (quote org-babel-load-languages) (quote (... ... ... ... ... ... ... ...)))
    eval-buffer(#load<2>> nil "/home/kca/.emacs.d/init-org.el" nil t)  ; Reading at buffer position 3080
    load-with-code-conversion("/home/kca/.emacs.d/init-org.el" "/home/kca/.emacs.d/init-org.el" nil nil)
    load("init-org")
    eval-buffer(# nil "/home/kca/.emacs.d/init.el" nil t)  ; Reading at buffer position 1464
    load-with-code-conversion("/home/kca/.emacs.d/init.el" "/home/kca/.emacs.d/init.el" t t)
    load("/home/kca/.emacs.d/init" t t)
    #[nil "\205\264

I tried to check if the right org-mode version was loading:
M-x load-library
org
M-x org-version
=> Org-mode version 7.7

Here is the code in init.el that is loading it:
(add-to-list 'load-path (concat conf-dir "org-7.7/lisp"))
(add-to-list 'load-path (concat conf-dir "org-7.7/contrib/lisp"))

I'm using Emacs 23.2 and Org-7.7.  Thanks for your help!

A: Try rebooting again.  Then read the rest here, if that didn't help...
Use binary search of your init file to determine just what code you are loading that is the problem.
Make sure you load the source code (*.el, not *.elc) for the problematic code.
Set debug-on-error to non-nil, so you get a backtrace that tells you something about the context of the error.
If the error is completely contained in some external package, make sure all your files for that package are for the same package version.
If the only thing you changed was restarting, then perhaps the problem is in an environment variable.  One guess is that for some reason your variable load-path does not have the right value, so it isn't loading all the files you need.  Or maybe you moved some of that package's code?
HTH.  Should get you started toward finding out more about the problem.

A: Actually, the trouble was that I didn't understand the org manual instructions.  Apparently, I did need to put (require 'org-install) and (require 'ob-tangle) into my init file to get literate programming features.  I'm not sure how I got R to work in babel before, though.  Oh, well it works now!  Hat tip to edenc in the #org-mode irc channel.


text:
Q: How to solve goniometric equation where function arguments differ? I'm preparing myself for exams and I stumbled over goniometric equation:
$$\cos^2x + \cos{2x}+1=0$$
Normally, those equations are solved by pretending that $\cos{x}$ is some variable $u$ and ending up with something like (in case of quadratic equation):
$$\cos{x} = a_1\\
\cos{x} = a_2$$
But since I cannot substitute $u$ for $\cos{x}$ what should I do? I had a wild idea of removing cosinus the way you can "remove" logarithms. But I don't think this is valid:
$$\cos^2x + \cos{2x}+1=0\\
\cos^2x + \cos{2x}+\cos{0}=0\\
x^2+2x+0 = 0
$$
Even if that was actually valid, what would I do with results for $x$? Can anyone explain the correct approach to this problem?

A: $$\cos^2x+\cos2x+1=0$$
$$\cos^2x+(2\cos^2x-1)+1=0$$
$$3\cos^2x=0$$
$$\cos x=0$$
$$x=\frac{\pi}{2},\;\frac{3\pi}{2}...$$

A: An alternative way, using almost the same trigonometric relation that Lanier Freeman applied:
$$\cos^2x+\cos2x+1=0$$
$$\cos^2x+(\cos^2(x)-\sin^2(x))+(\cos^2(x)+\sin^2(x))=0$$
$$3\cos^2x=0$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: MutableLiveData doesn't work, ObservableField does - why? I have a very simple code in XML:
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword"
    android:text="@={viewModel.password}"
    android:enabled="@{viewModel.inputEnabled}">

Now when viewModel.inputEnabled is a MutableLiveData<Boolean> underneath, it simply doesn't work, edit is always enabled, regardless of value of inputEnabled. However, it takes only to change inputEnabled to an ObservableField<Boolean> (and switch setValue to set) such that it immediately starts working.
Why is that so? How can I make MutableLiveData work correctly?
Note, that this field is used in three places (to enable/disable form during processing).

A: I ran in to same issue....make sure to call following in your activity/fragment:
binding.setLifecycleOwner(this)


text:
Q: How do I convert this for loop into a while loop? I am creating an array program. I am practicing how to convert for loops to while loops, but I cannot grasp the concept.
If I have the for loop:
int [] list = new int [5];

for (int i = 0; i < 5; i++) {
    list [i] = i + 2;
}

How would I make it a while loop?
Here's my attempt
int [] list = new int [5];
int i = 0;

while (i<5) {
    list [i] = i + 2;
    i++;
}
System.out.print(list[i] + " ");

This is what I think should be done, but it comes up as an error in my computer.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Arrays2.main(Arrays2.java:21)

This is line 21
System.out.print(list[i] + " ");

A: int [] list = new int [5];

int i = 0; // initialization
while (i < 5) { // condition
    list [i] = i + 2;
    i++; // afterthought
}

The for loop posted is pretty much a shorthand for the above. The first part of a for loop is called the initialization, equivalent to the int i = 0;  in the above code. The next is called the condition, which, if true, will cause the loop to be run again; this is the i < 5 part. Finally there is the afterthought, which changes the iterator i (usually an increment of one for iterating over an array). The for loop simply condenses these three parts into one line, as such:
for (initialization; condition; afterthought) {
}

A: The general structure of a basic for statement is:
for ( ForInit ; Expression ; ForUpdate ) Statement

*

*ForInit is the initializer. It is run first to set up variables etc.

*Expression is a boolean condition to check to see if Statement should be run

*Statement is the block of code to be run if Expression is true

*ForUpdate is run after the Statement to e.g. update variables as necessary

After ForUpdate has been run, Expression is evaluated again. If it is still true, Statement is executed again, then ForUpdate; repeat this until Expression is false.
You can restructure this as a while loop as follows:
ForInit;
while (Expression) {
  Statement;
  ForUpdate;
}

In order to apply this pattern to a "real" for loop, just substitute your blocks as described above.
For your example above:

*

*ForInit => int i = 0

*Expression => i < 5

*ForUpdate => i++

*Statement => list [i] = i + 2;
Putting it together:
int i = 0;
while (i < 5) {
  list[i] = i + 2;
  i++;
}

A: Your while loop is perfetly fine, but after it ends, the value of i is 5. Since java arrays are always indexed from zero, list[5] doesn't exist and accessing it throws exception.
That's what you see when printing System.out.print(list[i] + " "); Just print any other element, list[1], list[4] or list[0] for example.


text:
Q: Series from $1,2,3,4$ that sum to $n$ $B_n$  is the number of series build from 1,2,3,4 and sum to n.
prove that :
$$ \sum_{n=0}^\infty B_n x^n =\sum_{s=0}^\infty (x+x^2+x^3+x^4)^s $$

A: HINT:
Consider a bijection, when sum of $a_1+a_2+\ldots +a_s$ corresponds to taking (and multiplying up then) $\displaystyle x^{a_k}$ from $k$th parenthesis of RHS's $s$th term $$(x+x^2+x^3+x^4)\cdot (x+x^2+x^3+x^4)\cdot\ldots\cdot(x+x^2+x^3+x^4).$$ How can you now argue that the desired equality holds?


text:
Q: Swift - Saving Int to Core Data only works once Here's how I'm saving the data
    let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let managedContext = appDelegate.managedObjectContext!
    let entity =  NSEntityDescription.entityForName("Theme", inManagedObjectContext: managedContext)
    let themeObj = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext)

    themeObj.setValue(num, forKey: "themeNumber")

    var error: NSError?
    if !managedContext.save(&error)
    {
        println("Could not save \(error), \(error?.userInfo)")
    }

And then loading it
    let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let managedContext = appDelegate.managedObjectContext!

    let fetchRequest = NSFetchRequest(entityName:"Theme")
    var resultArr = [NSManagedObject]()
    var error: NSError?

    let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]?

    if let results = fetchedResults
    {
        resultArr = results
    }
    else
    {
        println("Could not fetch \(error), \(error!.userInfo)")
    }

    theme = resultArr[0].valueForKey("themeNumber") as Int

My data model is just the entity Theme with one attribute, themeNumber which is an Integer 16. If I delete the app from the simulator, it loads the correct theme. However, if I change it and run it again... nothing. Any ideas?

A: You don't need to use setValue. Typically you would do something like this:
themeObj.themeNumber = num

So to fix your problem, you need to actually update the core data object. I just realized that you probably didn't set the themeNumber by the property because you don't have the NSManagedObject subclass setup for your entity. I'll write try to write the fix for how you have it setup.
theme = resultArr[0] as NSManagedObject
theme.setValue(num, forKey: "themeNumber")
if !managedContext.save(&error)
{
    println("Could not save \(error), \(error?.userInfo)")
}

After you save it, see if it has the new value that you are looking for.


text:
Q: Link on dropdown Selectize.js I'm trying to put a link on a selectize dropdown in order to allow the user make an operation other than select an item while still allowing that the user selects the item as main option.
Here is an example of what I want to achieve (but is not working as expected):

What I did is plainly insert links on the HTML. But it's not working, I suppose that for some kind of event propagation stop, is it possible to achieve with selectize?

Nobody did answer yet and I think there's more to say about, so, here is an example of what I did:
render: {
    option: function(item) {
        return '
'+item.label+''
            + '
'
            + 'Link'
            + '

';
    }
}

As you can see, I did change the "option" renderization, and inserted a link in plain HTML. The problem is that -as shown on image- when I do click the link, the browser does not follow the link, but executes the default action for selectize, which is selecting the clicked element.
What I want to achieve is to make it follow the link when clicked.
Here is a fiddle of what I did: http://jsfiddle.net/uetpjpa9

A: The root problem is that Selectize has mousedown and blur handlers that are dismissing the dropdown before the mouseup event that would complete the click that your link is waiting for from ever occurring.  Avoiding this without direct support from Selectize is not easy, but it is possible thanks to its plugin system and the amount of access it gives you to Selectize internals.
Here's a plugin that allows a dropdown element with the class clickable to be clicked on.  (demo)
Selectize.define('option_click', function(options) {
    var self = this;
    var setup = self.setup;
    this.setup = function() {
        setup.apply(self, arguments);

        var clicking = false;

        // Detect click on a .clickable
        self.$dropdown_content.on('mousedown click', function(e) {
            if ($(e.target).hasClass('clickable')) {
                if (e.type === 'mousedown') {
                    clicking = true;
                    self.isFocused = false; // awful hack to defuse the document mousedown listener
                } else {
                    self.isFocused = true;
                    setTimeout(function() {
                        clicking = false; // wait until blur has been preempted
                    });
                }
            } else { // cleanup in case user right-clicked or dragged off the element
                clicking = false;
                self.isFocused = true;
            }
        });

        // Intercept default handlers
        self.$dropdown.off('mousedown click', '[data-selectable]').on('mousedown click', '[data-selectable]', function() {
            if (!clicking) {
                return self.onOptionSelect.apply(self, arguments);
            }
        });
        self.$control_input.off('blur').on('blur', function() {
            if (!clicking) {
                return self.onBlur.apply(self, arguments);
            }
        });
    }
});

To use it, you need to pass the plugin option to the selectize call (.selectize({plugins:['option_click']})) and add the clickable class to links in your dropdown template.  (This is fairly specific.  If there are nested elements, make sure clickable is on the one that will first see the mousedown event.)
Note that this is a fairly hackish approach that may have edge cases and could break at any time if something about how Selectize dispatches events changes.  It would be better if Selectize itself would make this exception, but until the project catches up to its backlog and becomes more receptive to requests and PRs this may be the most practical approach.


text:
Q: Firebase GET request orderby 400 bad request For a get request, I am trying to user order by like below but always get a 400 bad request. Here, multiple users can have multiple blog posts each with a unique id like b1 in screenshot below. The long sequence of characters is the uid of a user under blogs. Each user has their own uid.

https://assignment-c3557-default-rtdb.asia-southeast1.firebasedatabase.app/blogs.json?orderBy="createdAt"

I followed the documentation here

https://firebase.google.com/docs/database/rest/retrieve-data

All I am doing is issuing a simple GET request in react js as follows:
const resp = await fetch(`https://assignment-c3557-default-rtdb.asia-southeast1.firebasedatabase.app/blogs.json?orderBy="createdAt"``)
        const data = await resp.json()
        if(!resp.ok) { ... }

Below is the database single entry for schema reference

A: As I said in my previous comment, this URL is invalid:
https://assignment-c3557-default-rtdb.asia-southeast1.firebasedatabase.app/blogs.json/orderBy="createdAt"
                                                                                ^

The query portion of a URL starts with a ? character.
https://assignment-c3557-default-rtdb.asia-southeast1.firebasedatabase.app/blogs.json?orderBy="createdAt"
                                                                                ^

A:
Firebase Realtime Database - Adding query to Axios GET request?

I followed the above similar issue resolution to solve my problem


text:
Q: Organizing a python package and its modules I currently have the following package structure
mypkg/
|-__init__.py
|-foo/
|--_init__.py
|--foo_one.py
|--foo_two.py
|--foo_three.py
|-bar/
|-__init__.py
|- ...

Inside foo_one.py, foo_two.py and foo_three.py I defined three classes, FooOne, FooTwo and FooThree.
I would like to be able to import them as

from mypkg.foo import FooOne, FooTwo

At the moment the solution I'm using is the following:

# mypkg/foo/__init__.py

from .foo_one import FooOne
from .foo_two import FooTwo
from .foo_three import FooThree

But I think that what this actually does is importing all the classes, regardless of the specific import statement I use.
I would like to avoid that since the three classes require different additional import statements.
Also I would like to keep the three classes in three different files.
What do you suggest?


text:
Q: Set question, relations, equivalence classes Let S be the set of all bit strings (a sequence of 1s and 0s) of length 3 or more.
Let R be a relation on S of all pairs (x, y) where x and y are in S if x and y have the same first two bits.
Is R is an equivalence relation? If so, how many equivalence classes are there?

A: The first two bits of every string identifies uniquely the equivalence class.

A: Hint:
Remember that equivalence relations will induce a partition. So, ask yourself: will $S$ induce a partition on the Whole set?
How many classes I will have if there are two different ways to set zeros and ones in the position you want to.

A: I think what you looking for is for [00][01][10][11]
I think!


text:
Q: Help understanding database design logic for a secondhand bookstore project in MySQL I am currently working on a small eCommerce based project that allows users to buy/sell second hand books to/from other users. I am having a hard time making design decisions on how to model the database. My requirements are as follows;
Users (should be able to both buy and sell books)
- User can sell a book.
- User can buy a book.
Temp Users
- This is for registering a user through email
Orders
- many orders can be made by one user.
Order_Details (I am yet to create it)
- stores information on each product that has been orderd
Products/Books
- many products belong to one category
Here is my first try at the design;

*

*I'm having an issue on how to incorporate buying and selling for one user.I don't want to create a second users table for selling (unless that's the only way to do it.) products only.

*Should I create a "sales" table where it holds the users_ID and information that holds the book that is meant to be sold?Would this be a temporary table like the temp_users table?
Any opinions would be helpful.
Regards

A: *

*You don't sell to users, you sell to parties (companies or individuals). Some might play the role of users.

*There are many parties involved in a sales/purchase order:

*

*the vendor (you if you sell)

*the buyer (you if you buy)

*a party selling something on consignment

*sales staff taking commission

*the party that placed the order

*the party that took the order (a clerk)

*the party that is paying for the order

*the parties to whom to ship the order items

Do yourself a favour and get a data model pattern book and don't reinvent the wheel :)
Ready-to-Use Database models example

A: Yes, you could use one table to track both sold and unsold items.  It would be like a transaction table in an OLTP, with the distinction that the transaction remains open until the sale is closed.  In theory that's a good idea, as that would be 3NF (assuming listings and sales are 1-1), but it practice it's more common to denormalize the for sale listings from the actual sale transactions.  There are several practical reasons for this, I can elaborate if you need to justify the decision.
If decide to combine them into one table, it would be a sale_transactions table with a many-to-many relationship to users.  The buyer_user_id would be null until the item was sold, and it should also include things like product_id, listing_price, listing_date, sale_date and taxes.
If you're willing to separate the tables, you would have a for_sale table and a sales_history (or just sales or similar) table.  You might want to combine the sales_history with the orders table, it depends on the way you plan to populate them.

*

*In the for_sale table is the listing_id, listing_user_id, product_id, list_price, listing_date and units_available. This represents the items for sale, and has the advantage of having only one row with multiple units for sale (whereas a combined sale_transaction table as above would only work for individual units.)  As units are sold, the available_units goes down until it reaches zero.  At that point you can either leave the row for historical records, or remove it.  (Though multiple units might not apply to this case, if sellers usually only have one copy of a book.)

*In the sales_history table is the listing_id, the buyer_user_id, the sale_date, and probably the order_id (depends how you want to associate orders to sales.)

So the buy/sell scenarios would be:

*

*User lists a book for sale.  New entry in the for_sale table with the product, seller, etc.

*User searches for books for sale.  Query the for_sale table joined to the products and categories tables to get a listing of all products for sale and their details.

*User buys a book.  New entry in the sales_history table with the listing, the buyer, etc.  Entry in the for_sale table is updated to decrement the units_available by 1.  (Or else delete the row, mark it sold with a flag, or some other way to indicate it's not available.)


text:
Q: C# 6.0 TFS Builds I'm trialing the new features of C# 6.0 within Visual Studio 2015 CTP and my project is failing to build in TFS 2013 and Visual Studio Online.
I understand that Visual Studio uses the new Roslyn compiler, which replaces the native .NET one, and the TFS build agent therefore is unable to compile.
My question is how do I install Roslyn on the build agent (and within Visual Studio Online) and tell the build agent to use this compiler over native?

A: If you create an Azure VM with Server 2012 r2 and install Visual Studio 2015 CTP and TFS 2013 Build you can connect it to VSO.
You should then be able to complete your build and it will automatically use the new compiler.
While you can just install the compilers there is more to building than just compiling. You will likely very quickly need other features of Visual Studio, like Unit Testing, to execute as part of your build. Your build agent should reflect your developer standard workstation. If your Devs need it then the agent likley needs it.
Note: Visual Studio is licensed to individuals and not by machine. There is no license needed to run it on a build agent. Indeed as long as you have a single licence registered to your or of a particular level, say Ultimate, then you can install that on every build server.

A: For the compilation step, you have a couple of options:

*

*You can reference the Microsoft.Net.Compilers NuGet package on a per-project basis to use that version of the compilers.

*You can install the Microsoft Build Tools package that is part of the VS 2015 CTP package without installing all of VS.

However, as @MrHinsh notes, these approaches may leave you missing other parts of your toolchain.

A: Used /tv:14.0 /p:GenerateBuildInfoConfigFile=false /p:VisualStudioVersion=14.0 in MSBuild arguments in Process section of BuildTemplate.


text:
Q: Splitting large table into 2 dataframes via JDBC connection in RStudio Through R I connect to a remotely held database. The issue I have is my hardware isn't so great and the dataset contains tens of millions of rows with about 10 columns per table. When I run the below code, at the df step, I get a "Not enough RAM" error from R:
library(DatabaseConnector)
conn <- connect(connectionDetails)
df <- querySql(conn,"SELECT * FROM Table1")

What I thought about doing was splitting the tables into two parts any filter/analyse/combine as needed going forward. I think because I use the conn JDBC conection I have to use SQL syntax to make it work. With SQL, I start with the below code:
df <- querySql(conn,"SELECT TOP 5000000 FROM Table1")

And then where I get stuck is how do I create a second dataframe starting with n - 5000000 rows and ending at the final row, retrieved from Table1.
I'm open to suggestions but I think there are two potential answers to this question. The first is to work within the querySql to get it working. The second is to use an R function other than querySql (no idea what this would look like). I'm limited to R due to work environment.

A: The SQL statement
SELECT TOP 5000000 * from Table1

is not doing what you think it's doing.
Relational tables are conceptually unordered.

A relation is defined as a set of n-tuples. In both mathematics and the relational database model, a set is an unordered collection of unique, non-duplicated items, although some DBMSs impose an order to their data.

Selecting from a table produces a result-set. Result-sets are also conceptually unordered unless and until you explicitly specify an order for them, which is generally done using an order by clause.
When you use a top (or limit, depending on the DBMS) clause to reduce the number of records to be returned by a query (let's call these the "returned records") below the number of records that could be returned by that query (let's call these the "selected records") and if you have not specified an order by clause, then it is conceptually unpredictable and random which of the selected records will be chosen as the returned records.
Since you have not specified an order by clause in your query, you are effectively getting 5,000,000 unpredictable and random records from your table. Every single time you run the query you might get a different set of 5,000,000 records (conceptually, at least).
Therefore, it doesn't make sense to ask about how to get a second result-set "starting with n - 5000000 and ending at the final row". There is no n, and there is no final row. The choice of returned records was not deterministic, and the DBMS does not remember such choices of past queries. The only conceivable way such information could be incorporated into a subsequent query would be to explicitly include it in the SQL, such as by using a not in condition on an id column and embedding id values from the first query as literals, or doing some kind of negative join, again, involving the embedding of id values as literals. But obviously that's unreasonable.
There are two possible solutions here.
1: order by with limit and offset
Take a look at the PostgreSQL documentation on limit and offset. First, just to reinforce the point about lack of order, take note of the following paragraphs:

When using LIMIT, it is important to use an ORDER BY clause that constrains the result rows into a unique order. Otherwise you will get an unpredictable subset of the query's rows. You might be asking for the tenth through twentieth rows, but tenth through twentieth in what ordering? The ordering is unknown, unless you specified ORDER BY.
The query optimizer takes LIMIT into account when generating query plans, so you are very likely to get different plans (yielding different row orders) depending on what you give for LIMIT and OFFSET. Thus, using different LIMIT/OFFSET values to select different subsets of a query result will give inconsistent results unless you enforce a predictable result ordering with ORDER BY. This is not a bug; it is an inherent consequence of the fact that SQL does not promise to deliver the results of a query in any particular order unless ORDER BY is used to constrain the order.

Now, this solution requires that you specify an order by clause that fully orders the result-set. An order by clause that only partially orders the result-set will not be enough, since it will still leave room for some unpredictability and randomness.
Once you have the order by clause, you can then repeat the query with the same limit value and increasing offset values.
Something like this:
select * from table1 order by id1, id2, ... limit 5000000 offset 0;
select * from table1 order by id1, id2, ... limit 5000000 offset 5000000;
select * from table1 order by id1, id2, ... limit 5000000 offset 10000000;
...

2: synthesize a numbering column and filter on it
It is possible to add a column to the select clause which will provide a full order for the result-set. By wrapping this SQL in a subquery, you can then filter on the new column and thereby achieve your own pagination of the data. In fact, this solution is potentially slightly more powerful, since you could theoretically select discontinuous subsets of records, although I've never seen anyone actually do that.
To compute the ordering column, you can use the row_number() partition function.
Importantly, you will still have to specify id columns by which to order the partition. This is unavoidable under any conceivable solution; there always must be some deterministic, predictable record order to guide stateless paging through data.
Something like this:
select * from (select *, row_number() over (id1, id2, ...) rn from table1) t1 where rn>0 and rn<=5000000;
select * from (select *, row_number() over (id1, id2, ...) rn from table1) t1 where rn>5000000 and rn<=10000000;
select * from (select *, row_number() over (id1, id2, ...) rn from table1) t1 where rn>10000000 and rn<=15000000;
...

Obviously, this solution is more complicated and verbose than the previous one. And the previous solution might allow for performance optimizations not possible under the more manual approach of partitioning and filtering. Hence I would recommend the previous solution.

My above discussion focuses on PostgreSQL, but other DBMSs should provide equivalent features. For example, for SQL Server, see Equivalent of LIMIT and OFFSET for SQL Server?, which shows an example of the synthetic numbering solution, and also indicates that (at least as of SQL Server 2012) you can use OFFSET {offset} ROWS and FETCH NEXT {limit} ROWS ONLY to achieve limit/offset functionality.


text:
Q: Can you tell me why show message "Resource not found" Microsoft Cognitive Face API in Android? I have a problem, I just download this code https://github.com/microsoft/Cognitive-Face-Android and take step all this page. But my app to show message "Resource not found" in Detection and other features.

In my azure portal ,I created Subscription , Group , Face API , I received key and Endpoint in this picture.

In my Android Studio, I put key and endpoint in this string.xml

In my gradle app.
Why this app is show message "Resource not found" ?
But I live in southeast asia.
Thank you

A: You need to have the endpoint with the method , for ex,
If you need to detect face, you need to add "/detect" in the uri
https://tana29testface1.cognitiveservices.azure.com/face/v1.0/detect


text:
Q: How to send Suricata log to Kafka? After install and config Suricata 5.0.2 according to document https://suricata.readthedocs.io/.
I try to change some configuration in suricata.yaml by adding:
- alert-json-log:
      enabled: yes
      filetype: kafka
      kafka:
        brokers: >
         xxx-kafka-online003:9092,
         xxx-kafka-online004:9092,
         xxx-kafka-online005:9092,
         xxx-kafka-online006:9092,
         xxx-kafka-online007:9092
        topic: nsm_event
        partitions: 5
      http: yes

Next I run Suricata, and receive the error
Invalid entry for alert-json-log.filetype.  Expected "regular" (default), "unix_stream", "pcie" or "unix_dgram"

I don't know to configure on Suricata to enable sending log to Kafka topics.
Please help.

A: I don't see Kafka listed as an output type, therefore "no, there is not"
Refer docs: https://suricata.readthedocs.io/en/suricata-5.0.2/output/index.html
Plus, I'm not sure I understand what you expect http: yes to do since Kafka is not an HTTP service

What you could do is set filetype: unix_stream, then I assume that is Syslog, and you can add another service like Kafka Connect or Fluentd or Logstash to route that data to Kafka.
In other words, services don't need to integrate with Kafka. Plenty of alternatives exist to read files or stdout/stderr/syslog streams


text:
Q: Database adds rows multiple times Below is my code for the start of a simple job search database.
When i try to actually populate the database using the insert statements, it adds each row multiple times.
CREATE TABLE IF NOT EXISTS Employers (
  Id INTEGER PRIMARY KEY autoincrement,
  Name VARCHAR(20) NOT NULL,
  Industry VARCHAR(20) NOT NULL,
  Description TEXT
  );

CREATE TABLE IF NOT EXISTS Jobs (
  Id INTEGER PRIMARY KEY autoincrement,
  EmpId INTEGER FOREIGN KEY REFERENCES Employers(Id),
  Title VARCHAR(20) NOT NULL,
  Description TEXT,
  Location VARCHAR(20) NOT NULL,
  Ann_sal INT NOT NULL
  );

INSERT INTO Employers(Name, Industry, Description )
VALUES
("Touchpoint Global", "IT", "We help achieve efficiency, reliability and accuracy.
 We are experts at turning complex inputs into simple outputs.");

INSERT INTO Employers(Name, Industry, Description )
VALUES
("TyTech", "IT", "Here at Tytech, we specialise is building unique business solutions from the ground up. We focus on what you want, and how you want it.");

INSERT INTO Jobs( EmpId, Title, Description, Location, Ann_sal )
SELECT emp.Id, "Project Manager", "Project manager needed to oversee all future projects.", "GoldCoast", 80000
FROM Employers emp
WHERE emp.Name="Tytech";

INSERT INTO Jobs( EmpId, Title, Description, Location, Ann_sal )
SELECT emp.Id, "Project Manager", "Project manager needed to oversee all revolutionary projects.", "Kingscliff", 95000
FROM Employers emp
WHERE emp.Name="Touchpoint Global";

INSERT INTO Jobs( EmpId, Title, Description, Location, Ann_sal )
SELECT emp.Id, "Web Designer", "Web designer needed for upcoming business solution project.", "Kingscliff", 75750
FROM Employers emp
WHERE emp.Name="Touchpoint Global";

INSERT INTO Jobs( EmpId, Title, Description, Location, Ann_sal )
SELECT emp.Id, "Data Analist", "Data analist needed to review input data during testing phases and maintanence.", "Kingscliff", 70000
FROM Employers emp
WHERE emp.Name="Touchpoint Global";

A: Creating appropriate and meaningful unique indexes will prevent unwanted duplicates from being inserted. Such as on name and industry, or title.

A: Your script is executed multiple times.
Every repeated execution will insert more records.
To ensure that the tables are empty, you could add the following statements before the INSERTs:
DELETE FROM Employers;
DELETE FROM Jobs;

However, to ensure that the tables are updated if their structure changes, you should drop the IF NOT EXISTS from the CREATE TABLE statements, and ensure they are dropped before these CREATE TABLE statements:
DROP TABLE IF EXISTS Employers;
DROP TABLE IF EXISTS Jobs;


text:
Q: ML Flow : How to access databricks dataframe(or delta table) via API I have a fairly simple use case in databricks, have a small dataframe which i need to access via api (few api calls in a minute).
exploring various ways under databricks ML flow, but not sure whats simple and easiest way to implement, so dataframe can be accessed or queried using API
df #dataframe or can be converted to delta table
Can create personal token, which can be used to for authentication.


text:
Q: triggering click event listener with custom Event I have a function which is getting triggered on some dynamic created span.
  treeFuncItom(_event:Event, catType){
    console.log('INSIDE COMPONENT', _event);
    let myEvent = {};
     if(catType == 'id'){
      myEvent['value'] = _event['item']['dataItem']['_id'];
      myEvent['module'] = 'id';
     }else {
      myEvent['module'] = 'tag';
      myEvent['value'] = _event['item']['dataItem']['name'];
     }
    this.ItemChange.emit(myEvent);
  }

I am trying to trigger this function by passing dummy event from .spec.ts in angular4.
 it('Should raise ItemChange event, and set module to \'id\'', async () => {
    let _event  = {
      item: {
        dataItem: {
          name: 'abcd'
        },
        index: 0
      },
      originalEvent: 'MouseEvent',
      index: 0
    };

    fixture.detectChanges();

    await fixture.whenStable();
    let ee = JSON.stringify(_event);

    let item = null;
    component.ItemChange.subscribe(it => {
      console.log('Int Test', it);
      item = it;
    });

    component.treeFuncItom(new Event(ee), 'id');
    expect(item).not.toBeNull();
    expect(item.module).toEqual('id');
  });

But I am getting error in console:
ERROR: 'Unhandled Promise rejection:', 'Cannot read property 'dataItem' of undefined', '; Zone:', 'ProxyZone', '; Task:', 'Promise.then', '; Value:', TypeError{}, 'TypeError: Cannot read property 'dataItem' of undefined
at SidebarComponent.webpackJsonp../src/app/service-catalog/component/sidebar/sidebar.component.ts.SidebarComponent.treeFuncItom (http://localhost:9876/_karma_webpack_/webpack:/src/app/service-catalog/component/sidebar/sidebar.component.ts:26:40)

LOG: 'INSIDE COMPONENT', Event{isTrusted: false}

why is isTrusted: false and how can I pass the proper event from spec.ts

A: *

*you don't need async and await

*You should get rid of asynchronous code in testing : don't test the observable, test that one of its methods has been called (principle of unit testing : don't rely on a dependency)

*You don't need to create a new event, you can simply pass a mock to it

*It's a function that does not involve the template, you don't need a fixture tampering

*Most important of all : keep it ismple.

Here, try this :
it('should whatever', () => {
  const mockEvent: any = {
    item: {
      dataItem: {
        _id: 'item.dataItem.id',
        name: 'item.dataItem.name'
      }
    }
  };

  const itemChange = spyOn(component.itemChange, 'emit');

  component.treeFuncItom(mockEvent, 'id');

  expect(itemChange).toHaveBeenCalledWith({
    module: 'id',
    value: mockEvent.item.dataItem._id
  });
});


text:
Q: Java: ill defined finalize method to create memory leak In java the garbage collect will invoke finalize method on an object x if there's no strong reference pointing to x and x is eligible for garbage collection.  What if the finalize method never terminates, would this cause a memory leak?

public class X{
  protected void finalize(){
     while(true){}
  }
}

A: Yes it will, easy to test
public class X {

    protected void finalize() {
        while (true) {
        }
    }

    public static void main(String[] args) throws Exception {
        while (true) {
            new X();
        }
    }
}

after some time I got
Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "main"

when I removed finalize() the test never stopped. Note that it takes a while before JVM goes OOM
BTW it's enough to run this test
public class X {
    byte[] a = new byte[100 * 1000 * 1000];

    protected void finalize() {
        System.out.println();
    }

    public static void main(String[] args) throws Exception {
        while (true) {
            new X();
        }
    }
}

to break GC
Exception in thread "main"
java.lang.OutOfMemoryError: Java heap space
    at test.X.<init>(X.java:5)
    at test.X.main(X.java:13)

comment out //System.out.println(); and it works non-stop

A: Yes.
Also inside finalize method if you give valid reference to object on which finalize method is invoked, Java will not garbage collect the object also will not invoke the finalize method again as it is invoked only once.

A: Definitely.The memory will be deallocated after finalise method returns.And if your finalise never returns, momory will not get deallocated.
Google about resurrection in garbage collection and you will get various instances where finalise method does not guarantee the gc

A: It would block the java.lang.ref.Finalizer$FinalizerThread (The Secret Life Of The Finalizer), the instance of all classes which implement finalize method would be blocked in java.lang.ref.Finalizer.ReferenceQueue. You continue creating new object with 'finalize', memory would be exhausted by those objects which are waiting to execute finalize . If take a heap dump, you would see objects are retained by java.lang.ref.Finalizer, see below example (it's a real case).


text:
Q: Angular & Firebase: Create new node I need to build same sctructure in Firebase. How can I create a new node terriangen, add {key} and set my object data?
-usernames
 -{UID}
  -mylibrary
   -{key}
  -terriangen
   -{key}
    type:mountain
    name:1.png

My code:
const newObjRef = firebase.database()
              .ref('usernames')
              .child(userId)
              .child('mylibrary/')
              .push();
            newObjRef.set({
              type: terrainType,
              name: terrainName
            });

A: You're looking for a multi-location update:
const newKey = firebase.database().ref().push.key;
const updates = { };
updates["mylibrary/"+key] = {
          type: terrainType,
          name: terrainName
        };
updates["terriangen/"+key] = {
          type: terrainType,
          name: terrainName
        };
firebase.database()
        .ref('usernames')
        .child(userId)
        .update(updates)

The biggest differences:

*

*We pre-generate the unique key, so that we can use it in both locations

*We move part of the path of the new data into the keys, so that we can perform a so-called multi-location update. This ensures none of the existing items in the library and terriangen nodes get overwritten.


text:
Q: Average cost for each customer in R I am trying to calculate the average or mean for each customerID. For the data below:
customerID <- c(1,1,1,1,2,2,2,2,3,3)

dates <- c(20130401, 20130403,  20130504,   20130508,   20130511,
       20130716,    20130719,   20130723,   20130729,   20130907)
cost <- c(12,  41,  89, 45.5,   32.89,  74, 76, 12, 15.78,  10)

data <- data.frame(customerID, dates,cost)

data$dates <- as.Date(as.character(data$dates), "%Y%m%d")

# data2 <- aggregate(cbind(average_cost=cost) + customerID, data, mean)

Data Looks like this:
customerID  dates   cost
1   20130401    12
1   20130403    41
1   20130504    89
1   20130508    45.5
2   20130511    32.89
2   20130716    74
2   20130719    76
2   20130723    12
3   20130729    15.78
3   20130907    10

How can I get an output similar to this? I can get the average for the whole data set, but not for each customer ID. Thanks!
customerID  average_cost
1           46.875
2           48.7225
3           12.89

A: dplyr solution
library(dplyr)
df %>%
  group_by(customerID) %>%
  summarise(average_cost = mean(cost))

  customerID average_cost
1          1      46.8750
2          2      48.7225
3          3      12.8900

data.table solution
library(data.table)
dt <- as.data.table(df)
dt[, .(average_cost = mean(cost)), by=customerID]

Also if you just want base R
aggregate(cost ~ customerID, data=df, mean)


text:
Q: Get all elements of the list which are less than particular number By the time I'm learning Prolog I encountered on a problem. I'm trying to make function like this
   ?- less_than([1,2,3,2,1,5],3,Y).
      Y= [1,2,2,1]

Because I was learning object-oriented programming I stacked with this and can't figure out how to solve.
This is mine code:
  less_than([],X,Y).
  less_than([H|T], X, [H1|T1]) :-
            H<X, less_than(T,X,H).

And also, I tried with findall:
  less_than([],X,Y).
  less_than([H|T],X,[H1|T1]) :-
            findall(H, (H<X, less_than(T,X,Y)), Z).

Where I'm getting this result:
Y = [_G2274|_G2275]  for ?- less_than([1,2,3,4,5],3,X)

I know that they are unknown values but how to set values in that list? I tried to change Y with and H but it wont work.
I tried to debug it but with no success, it keeps falling apart and this is only logical explanation how to solve it for me. Any1 has an idea?

A: I won't solve the whole issue for you, but I would like to show you how you can approach such issues in general.
A major advantage of Prolog is that you can debug issues declaratively. This means that you use logical properties of Prolog to locate the causes of unintended answers.
For example, in your case, you have the program:

less_than([], X, Y).
less_than([H|T], X, [H1|T1]) :-
        H < X,
        less_than(T, X, H).

and the following unintended failure of a query:

?- less_than([1,2,3,2,1,5], 3, Y).
false.

Let us use the following definition to generalize a Prolog program, like in GUPU:

:- op(950,fy, *).

*_.

For example, consider the following generalization, which we obtain by placing (*)/1 in front of all goals:

less_than([], X, Y).
less_than([H|T], X, [H1|T1]) :-
        * H < X,
        * less_than(T, X, H).

With this generalization, we have:

?- less_than([1,2,3,2,1,5],3,Y).
Y = [_G946|_G947].

So, while this is now too general, at least the query succeeds.
By refining the generalization, we can narrow down the exact cause of the problem. For example:

less_than([], X, Y).
less_than([H|T], X, [H1|T1]) :-
        * H < X,
        less_than(T, X, H).

This again yields:

?- less_than([1,2,3,2,1,5],3,Y).
false.

Observe that adding further goals can at most specialize the program, never generalize it. Therefore, the remaining fragment must be generalized if we want this query to succeed at all.
So, if you want your query to succeed at all, you must make at least the following fragment succeed for the query:

less_than([], X, Y).
less_than([H|T], X, [H1|T1]) :-
        less_than(T, X, H).

Why does this currently fail? Try the following further generalization:

less_than([], /*X*/_, /*Y*/_).
less_than([H|T], /*X*/_, [/*H1*/_|/*T1*/_]) :-
        less_than(T, /*X*/_, H).

This still fails:

?- less_than([1,2,3,2,1,5],3,Y).
false.

So, we have now reduced this to:

less_than([], _, _).
less_than([H|T], _, [_|_]) :-
        less_than(T, _, H).

And now the point: Interestingly, the following generalization succeeds:

less_than([], _, _).
less_than([H|T], _, [_|_]) :-
        less_than(T, _, /*H*/_).

Therefore, this last argument of the call of less_than/3 is a hot candidate for closer scrutiny...


text:
Q: invalid signatures EXPKEYSIG sorry if I did something dumb but I'd really appreciate some help.
this comes up whenever I try to check for updates
W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://download.opensuse.org/repositories/home:/strycore/xUbuntu_18.04  Release: The following signatures were invalid: EXPKEYSIG 2F7F0DA5FD5B64B9 home:strycore OBS Project <home:strycore@build.opensuse.org>
W: Failed to fetch http://download.opensuse.org/repositories/home:/strycore/xUbuntu_18.04/Release.gpg  The following signatures were invalid: EXPKEYSIG 2F7F0DA5FD5B64B9 home:strycore OBS Project <home:strycore@build.opensuse.org>

A:
Moderator Note: The wget link here is no longer operational as that repository no longer publishes Ubuntu 18.04 repository lists or key data.  However, the content of this post was left alone for historical reasons, and should not be flagged as 'broken link' in reviews.

You have to visit the repository page and re-add the repository signing key again:
wget -nv https://download.opensuse.org/repositories/home:strycore/xUbuntu_18.04/Release.key -O Release.key
sudo apt-key add - < Release.key
sudo apt-get update


text:
Q: receive mail with nodemailer without setting "Allow less secure apps to access" I want to ask something about nodemailer, i make code like
Var client = nodemailer.createTransport ({
Service: 'gmail',
Auth: {
User: 'example@gmail.com', // Your email address
Pass: '123' // Your password},
Tls: {rejectUnauthorized: false}
});

And this works, but after successful delivery, when I have to receive email messages that have been sent, I need to enable gmail settings like "Allow less secure apps to access". I do not want to set it.
So how do I send emails from example@gmail.com TO example1@gmail.com, without setting "Allow less secure apps to access" and message directly accept in email box !!??? Or any other plugin that should be added ??
THANX;)

A: Obtain accessToken & refreshToken from Google OAuth2.0 Playground,
clientId & clientSecret from Google developer console
const nodemailer = require('nodemailer');
const xoauth2 = require('xoauth2');
var express = require('express');
var router = express.Router();

var smtpTransport = nodemailer.createTransport('SMTP',{
  service:"Gmail",
  auth:{
    XOAuth2: {
      user:'sender@emailaddress.com',
      clientId: 'your-client-id',
      clientSecret: 'your-cliet-secret',
      accessToken:'your-access-token',
      refreshToken: 'your-refresh-token'

  }
  }
});

router.get('/emaildemo', function(req, res, next) {

  var mailOptions = {
  from: 'sender@emailaddress.com',
  to: 'xxx@email.com',
  subject: 'TEST SUBJECTT',
  text: 'TEST MAIL',
};
smtpTransport.sendMail(mailOptions, function(error, info){
  if(error){
 console.log('Error Occured', error);
  return res.send(error);
  }
  return res.send("mail send successfully");
});

});
module.exports = router;

A: You need to get the access token, you cannot give it statically.
googleapis can be user for gmail.
for example:
        const { google } = require('googleapis');
        const { OAuth2 } = google.auth;

        const {
            MAILING_SERVICE_CLIENT_ID,
            MAILING_SERVICE_CLIENT_SECRET,
            MAILING_SERVICE_REFRESH_TOKEN,
            SENDER_EMAIL_ADDRESS,
            OAUTH_PLAYGROUND //https://developers.google.com/oauthplayground
        } = process.env;

        const oauth2Client = new OAuth2(
            MAILING_SERVICE_CLIENT_ID,
            MAILING_SERVICE_CLIENT_SECRET,
            OAUTH_PLAYGROUND
        );

        oauth2Client.setCredentials({
            refresh_token: MAILING_SERVICE_REFRESH_TOKEN,
        });
        //>>> get the accessToken
        const accessToken = oauth2Client.getAccessToken();

        let transporter = nodemailer.createTransport({
            service: 'gmail',
            auth: {
                type: 'OAuth2',
                user: SENDER_EMAIL_ADDRESS,
                clientId: MAILING_SERVICE_CLIENT_ID,
                clientSecret: MAILING_SERVICE_CLIENT_SECRET,
                refreshToken: MAILING_SERVICE_REFRESH_TOKEN,
                accessToken,
            },
        });

        let mailOptions = {
            from: 'no-reply@blah.com',
            to: 'to_blah@blah.com',
            subject: 'test',
            text: 'test'
        };
        let result = await transporter.sendMail(mailOptions);


text:
Q: JWT auth with [Authorize] attribute Could someone shed a light on how default Asp.Net core attribute [Authorize] (with using Asp.Net Identity) understands how it should decode JWT token and get necessary info for granted access?
While forming JWT token I put in token RoleClaims for the user, does [Authorize] base on claims to grant them access to specific actionMethod

A: You can access your claims using the following code:
User.Claims.FirstOrDefault(el => el.Type == claim)?.Value

A: More details please follow this link
Create JWT & Authorize
    [Authorize]
    [HttpPost]
    public string Post()
    {
        var identity = HttpContext.User.Identity as ClaimsIdentity;
        IEnumerable<Claim> claim = identity.Claims;
        var UserName = claim.Where(c => c.Type == "UserName").Select(c => c.Value).SingleOrDefault();

        return "Welcome to " + UserName + "!";
    }


text:
Q: Game freezing every 10 seconds I'm not sure if this qualifies as a legit question here, but I don't know where else to ask.
I have installed the Call of Duty 2 MAC version on my iMac. My system capabilities (RAM, processor, video) are way above the recommended requirements, so I would have expected the game to run smooth.
However, in-game, doesn't matter if I am in the main menu or playing, it keeps freezing for about 2 seconds, every 10 seconds or so. I have set the quality settings to maximum and minimum, and it's the same.
Clearly it has nothing to do with in-game quality settings, as it does this even while in the main menu.
Any idea what the problem might be? I suspect my computer (1.5 years old iMac, 2.7GHz i5, 8GB@1600MHz DDR3, GeForce GT 640M 512MB) has a problem... it does boot slower than when I bought it... and overall it's not as fast.

A: My guess is that it doesn't use multi core as I have the same problem.
iMac 2011, 27″, 3.4 GHz i7, 6970M 2 GB, 12 GB RAM, 120 GB SSD.

A: Your system seems to be good enough, but you can run the system check on this site to verify (under System Requirements).
Other steps to analyze the issue

*

*make sure no other applications are running (including menulets)

*run Activity Monitor while playing the game and have an eye on the CPU usage of the various processes

*contact Aspyr Support and describe your problem


text:
Q: How to uninstall Numbers and Keynote on Mavericks? I installed Pages version 5 on Mavericks via the "App Store". But the problem is Keynote and Numbers are installed also.
I'm not interested in Keynote and definitely not in Numbers. I want to uninstall them. On Google, some people say use AppCleaner and others say don't use it because it will do harm.
So how to uninstall Numbers and Keynote (the right way)?

A: I recommend you just delete Numbers and Keynote using Finder.
The Mac App Store will detect the missing apps and allow you to reinstall them in the future if you ever need them.
Alternatively, you can use AppCleaner to delete them. This will remove all associated preference/cache files. This is usually superfluous unless you have an actual need to delete the preferences. They're not doing any harm leaving them there.


text:
Q: shall I delete smart pointer manually? This might be a dumb question but I'm just not sure about the answer. The following code read a file, and for each line of the file, a smart pointer is created by "new". If the smart pointer will be used in the future, it's stored in a list, otherwise it's not stored.
My question is that: if the smart pointer is not stored, will that cause potential memory leak? Thank you.
int main(){
    .....;
    std::list<SomeClass> aList;
    while(inFile >> ss){
         std::tr1::shared_ptr<SomeClass> aPtr(new SomeClass());
         //do something in foo(aPtr) to aPtr,
         //if aPtr will be used later, then it's stored in aList
         //otherwise, it's not stored
         foo(aPtr);
    }
    .....;
}

A: As long as you're storing it with a copy of the smart pointer, this will not leak memory. When the aPtr object falls off the stack (at the end of each while loop execution), it will be destroyed. If it is the only holder to the allocated object, it will delete it. But if you stored a copy of aPtr elsewhere, then it is not the only holder to the allocated object, and it will not delete it.

A: No memory leaks shall ensue!
why? because smart pointers are... smart, they have the automatic cleanup feature which is great, because it prevents elusive bugs like memory leaks.
Thus for smart pointers you do not need to explicitly delete the pointer.

A: No memory leak can be caused, because the shared_ptr will deallocate the allocated object when it goes out of scope.

A: When an pointer is assigned to a smart pointer, a reference counter related to the pointer is increased by one (the reference counter is 0 when the pointer has not been assigned to any smart pointer).
When a smart pointer goes out of scope and is deleted, then the reference counter for the pointer tracked by the sp is decreased by one: eventually the memory referenced by the pointer is deleted when the reference counter goes back to 0.
In your case, if the object SomeClass is assigned only to aPtr, then maybe an auto pointer will do the job with a slightly less overhead.
However, if you declare the list as std::list<std::tr1::shared_ptr<SomeClass> > then you could avoid copying SomeClass (only the reference counter to the object will be increased) and take full advantage of the smart pointer.


text:
Q: Call postgres function from ArcPy, returning set of features I'm trying to execute a postgresql function through ArcPy;
cfg = config()
sde_conn = cfg.sdeConnection()
features = sde_conn.execute(cfg.sqlSearchQuery().format(parameters[0]))

On the last line, it crashes with:
AttributeError: AttributeError(u'ArcSDESQLExecute: SreamBindOutputColumn ArcSDE Error -65 \ud490',)

cfg.sqlSearchQuery().format(parameters[0]) boils down to the simple query:

SELECT * FROM test_func('some string')

The function returns a subset of rows (features) in a table (feature class)
I have tested the function from pgAdmin query and it works.
Any ideas are appreciated!


text:
Q: Multiple temporary/local task branches in MQ/Mercurial? I've read Steve Losh's article about using MQ's qqueues command to create multiple queues.  This has the potential to get me closer to my personal take on Nirvana (namely, Git local branches), because I can keep changes related to separate features isolated from one another, I can roll the local changes into a single patch for release upstream, and I can delete the queues when I'm done with them.  Awesome.  Except I can't get it to work. I create the first queue using hg qqueue -c feature1, apply a patch to it using qrefresh, and then try to create a new queue. When I do I get an error:
~/src/mqtest$ hgl
@  55ae767d5eae  Adding feature1file  2013-04-29 15:32 -0500 Jon Blackburn default addFeature1file qbase qtip tip
|
o  58b232e9b36a  Initial commit on default.  2013-04-29 15:27 -0500 Jon Blackburn default qparent

~/src/mqtest$ hg qapplied
addFeature1file
~/src/mqtest$ hg qq
feature1 (active)
patches
~/src/mqtest$ hg qq -c feature2
abort: new queue created, but cannot make active as patches are applied
~/src/mqtest$

What am I doing wrong?
Thanks.
P.S. @Lazy Badger indicated some skepticism about whether I need to pop -a in order to change queues.  I'll say first that it's the only thing I've found that works.  Also, from mq.py:
def _setactive(name):
    if q.applied:
    raise util.Abort(_('new queue created, but cannot make active '
                           'as patches are applied'))
    _setactivenocheck(name)

If there's a more appropriate way to switch to a new queue while I've got patches applied to the one I'm on, I'd love to hear it.  With this solution the workflow would be 1) pop -a; 2) qqueue feature2; 3) optionally, push -a (if feature2 has some patches already). It's not clear to me why mq requires that no patches be applied to the queue you're leaving. I can't come up with a scenario in my head where that's useful. If my existing queue must be empty for me to leave it, then perhaps offer a flag to tell mq to pop -a my current queue (and push -a my target queue)?

A: You have one patch from feature1 applied, thus - qqueue can't switch to second queue after it's creation. From hg help qqueue

To create a new queue, use -c/--create. The queue is automatically made active, except in the case where there are applied patches from the currently active queue in the repository.

You have to:

*

*unapply patch before creating new queue

or

*

*switch to created queue by hand


text:
Q: SQL Oracle to select a column that displays the highest value in a result set I have an existing query that loads a specific dataset. Please see sample table for illustration
 Select I.Invoice_ID, I.Invoice_Date, CI.Unit_Rate
 FROM Invoice I, ChargeInvoice CI

Invoice_ID   Invoice_Date  Unit_Rate
A1           05/08/2018    100
A2           04/08/2018    200
A3           03/08/2018    300
B6           04/06/2018    150
C5           04/15/2018    2000

What I need to  add a calculated column which displays the MAX or highest value of one field in the result set, that can be named as MAX_UNIT_RATE.
The expected result set is something like this
  Invoice_ID   Invoice_Date    Unit_Rate   Max_Unit_Rate
    A1           05/08/2018    100         2000
    A2           04/08/2018    200         2000
    A3           03/08/2018    300         2000
    B6           04/06/2018    150         2000
    C5           04/15/2018    2000        2000

I tried this, but It is not getting the desired result
select IV.INVOICE_ID, IV.INVOICE_DATE , ICV.UNIT_RATE, MAX(ICV.UNIT_RATE) AS MAX_UNIT_RATE
FROM INVOICE_V IV,
    INVOICE_CHARGE_V ICV
 GROUP BY IV.INVOICE_ID,  IV.INVOICE_DATE, ICV.UNIT_RATE

A: You should be writing your query with correct join conditions.  The solution to your problem are window functions:
SELECT I.Invoice_ID, I.Invoice_Date, CI.Unit_Rate,
       MAX(CI.Unit_Rate) OVER () as MAX_Unit_Rate
FROM Invoice I JOIN
     ChargeInvoice CI
     ON I.Invoice_Id = CI.Invoice_ID -- this is a guess


text:
Q: Understanding positive lookaheads and backtracking in JavaScript I can't completely wrap my head around combining positive lookaheads and backtracking in JavaScript. I read this answer, as well as this article and did some testing with https://regex101.com/, but don't quite get the result I'm expecting.
So given the test string banana12, the following works:

*

*(?=\d{2,}) - assert that the string contains at least two digits

*(?=[a-z]{5,}) - assert that the string contains at least five lowercase characters

These two conditions work for both banana12 and 12banana.
However, when I try to combine the two (?=\d{2,})(?=[a-z]{5,}), I don't get a match. In order to get a match when using banana12, I need to add \D* to the digit-testing lookahead: (?=\D*\d{2,})(?=[a-z]{5,}).
Why doesn't (?=\d{2,})(?=[a-z]{5,}) work?
If I change the test string to 12banan, to get a match I need to use: (?=\d{2,})(?=[^a-z]*[a-z]{5,}) - so this time no backtracking for the digits, backtracking for the lowercase letters.
So in general, if I want to make sure, that my regex matches correctly both strings (12banana, banana12), I need to use: (?=\D*\d{2,})(?=[^a-z]*[a-z]{5,}).
Why? If both lookaheads work on their own, why don't they work in combination and why is it necessary to add backtracking?


text:
Q: SQL in Drupal. WHERE AND The following works...
global $user;
$items = array();
$sql = 'SELECT nid FROM {node} WHERE uid = :uid';
$result = db_query($sql, array(':uid' => $user->uid));
foreach ($result as $row) {
  $items[] = $row->nid;
}
dsm($items);

However, when I want to select the content type "venue" from the "type" column in the same database tables, I get errors using the following...
global $user;
$items = array();
$sql = 'SELECT nid FROM {node} WHERE uid = :uid AND type = venue';
$result = db_query($sql, array(':uid' => $user->uid));
foreach ($result as $row) {
  $items[] = $row->nid;
}
dsm($items);

DOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'venue' in 'where clause': SELECT nid FROM {node} WHERE uid = :uid AND
  type = venue; Array ( [:uid] => 1 )

Im ovbiously not understanding something here. The column is called "type", im not asking it to look for a column called "venue" am i?

A: When comparing a column to a string you need to wrap the string with quotes, if you dont, the optimizer will see this as a column(unless its a number) .  Try this:
$sql = "SELECT nid FROM {node} WHERE uid = :uid AND type = 'venue'"


text:
Q: how to sort list of users by score (fetching database) javascript i have db with user(name:, score:) i need to sort list by score.
code example
return (

            {loading || !data ? (

loading...

            ) : (

               <>{data["data"].map((value, index) => (

{value.name}

{value.points}

               ))}</>
            )}

    );

A: const sorting = (arr) => arr.sort(function(a, b) {
       return a - b;
    })
return (

        {loading || !data ? (

loading...

        ) : (

           <>{sorting(data["data"]).map((value, index) => (

{value.name}

{value.points}

           ))}</>
        )}

);

A: If you want to do it on the client-side, you would use the sort method of the array.
Assuming data is in this format
let data = [{name : 'jack', points: 1}, { name : 'jill', points:2}]

you can sort it as below.
For ascending order (smallest points first)
data.sort((first,second) => first.points - second.points)

Do the opposite for descending order
data.sort((first,second) => second.points - first.points)

So your code would be
return (

            {loading || !data ? (

loading...

            ) : (

               <>{data["data"].sort((first,second) => first.points - second.points).map((value, index) => (

{value.name}

{value.points}

               ))}</>
            )}

    );

For more details on how sorting works, check here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort


text:
Q: Refine on optional property in union type with flow I have a union type Entity consisting of two different types, Door and Handle. The property rotation exists in one of the sub types, but not the other. This seems to mean that I can't refine on that property, but get the error Cannot get entity.rotation because property rotation is missing inHandle[1].
I know it's missing, that's why I'm trying to check if it's there.
type Door = {
  id: number,
  rotation: number
}

type Handle = {
  id: number
}

type Entity = Handle | Door;

const foo = (entity: Entity): number => {
  if (entity.rotation) {
    return entity.rotation;
  } else {
   return 2;
  }
}

Cannot get entity.rotation because property rotation is missing in Handle 1.
Is there a way to refine where a property exists or not in the type?
Running example in the flow editor

A: By not declaring Handle as a strict type you are telling Flow that it may contains the rotation properties.
type Door = {
  id: number,
  rotation: number
}

type Handle = {|
  id: number
|}

type Entity = Handle | Door;

const foo = (entity: Entity): number => {
  if (entity.rotation) {
    return entity.rotation;
  } else {
   return 2;
  }
}

Flow editor
Flow documentation link


text:
Q: What's the proper and reliable way to store an XML string as a JSON property? I want to store a string which itself is an XML string as a property of an JSON object , what's the reliable and proper way of dong this? Should I first encode the XML data into BASE64 first prior saving it to an JSON object, due to the fact that JSON does not support binary data?
Example of data I want to store:
{
"string1" : "<xml>...moderately complex XML...</xml>"
}

A: Actually base 64 should work. But you might want to mark the property so it is clear.
{
    "Property" : {
        "Type" : "XML",
        "Encoding" : "Base64",
        "Value" : "PFhNTD48WE1MPjxYTUw+PC9YTUw+PC9YTUw+PC9YTUw+"
    }
}

A:
JSON does not support binary data?

If you mean it doesn't have a bytes datatype, well who cares? JavaScript strings can contain all possible Unicode characters, including control characters:
"string1": "\u0000\u0001\u0002..."

(Not that those are even valid in XML.)
So you can, if you really must encode bytes, just map them directly to the characters of the same ordinal number:
"xml": "<el>caf\u00C3\u00A9</el>"
// "café", encoded as a UTF-8 byte sequence read as ISO-8859-1

but really for XML you'd be better off keeping it in Unicode and just JSON-encoding it like any other string:
"xml": "<el>caf\u00E9</el>"
// or assuming your channel encoding is OK, simply
"xml": "<el>café</el>"


text:
Q: Permission Access Recently I downloaded wireshark from store but mistakely forgot to give permission for all users to use it. Is there any way to change it? I tried to reinstall but it didn't work.

A: Read man dpkg-reconfigure, and do:
sudo dpkg-reconfigure wireshark


text:
Q: Upgrade to 16.10: PAM-CGFS errors Since upgrading my Ubuntu host server installation from 15.10 to 16.04.1 yesterday these errors fill my log:
PAM-CGFS[28483]: Failed to create a cgroup for user root
Googling this turns up nothing useful.
What could cause this and how can I get rid of them?
EDIT: I put the latest output of journalctl --boot 0 here: http://paste.ubuntu.com/22553947/ . It doesn't contain the error yet, as I just rebooted. I'm hoping the boot messages may help you diagnose the problem.

A: It doesn't trigger directly on boot ,  but happens after invoking some command which uses cgroups and tries accessing non-existent cgroup . In my case , it was lxc-ls  .
See https://lists.linuxcontainers.org/pipermail/lxc-users/2016-August/012172.html
Anyhow,try modifying /etc/pam.d/common-session{,-noninteractive} , adding cpuacct to

session optional        pam_cgfs.so -c freezer,memory,name=systemd

fixed it for me .


text:
Q: What could be the meaning of variable in all capital letters? As question states, I am doing homework which have 2 variables BOOK, and MAGAZINE in all capital letters, and I can not figure out what could be the purpose of it.
Anyone have a clue?
The icon in Visio Class Diagram looks like rectangle with equal sign on it and a lock declaring it private.
This is a picture of class diagram.
Regards.

A: They are private constants.  You can tell by the icon next to their name.  Take a look at the constant TEST in this example...

EDIT:
The all caps is merely by convention, but is usually used to represent constants.

A: Variables in all capital letters in any language generally refer to constants, meaning the value should never change.
In this case, they could refer to an enumerated type, which is a special sort of constant basically is just a symbol for itself.

A: They're probably constants, defining maybe a key or index. Without a more specific question I can't give you anything but a vague answer, sorry.


text:
Q: Why is an existing field that has not changed be suddenly considered to have an invalid data type? I am modifying a legacy SSRS report (rdl file); I've added four columns to it, and am supplying those values by means of a new data source (Stored Procedure).
However, now when I try to run the report via the "Preview" tab, I get:
An error occured during local report processing.
The Group expression used in grouping 'table1_Group1' returned a data type that is not valid.
" [ a second err msg identical to the one above ] "
There is indeed a Row Group named "table1_Group1", and its properties look like this:

I don't know why NewBiz is suddenly a problem; nothing has changed about it, and there was no complaint concerning it previously.
"NewBiz" does (still) appear in the filed list in the "Dataset Properties" pane (both Field Name and Field Source are "NewBiz"); the data source (stored proc) does return it. So...?!?
NOTE: The "table1_Details_Group" beneath "table1_Group1" has no Group Expression, and thus seems to have no raison d'etre; unless I'm misunderstanding something about its role/purpose.
UPDATE
Alan Schofield raised the question over whether the dataset fields "are in the order expected."
So I examined that under a fine-toothed microscope. This is the last part of the data source/stored procedure, which returns the values:
select CY.CSDirector, CY.Category, CY.Segment, CY._Unit,
       CU.New, CU.Assumed, CU.Existing, CU.Organic,
       CY.NumUnits, CY.NumUnitsLast, CY.MonthSales, CY.MonthSalesLast,
       CY.MonthPerc, CY.YTDSales, CY.YTDSalesLast, CY.YTDPerc,
       CY.ProjSales, CY.YTDProjSales, CY.YTDBudgetPerc, CY.NewBiz
from #CombinedYears CY
left join #CategorizedUnits CU on CU.Unit = CY._Unit

And this is what I see in the Report Data pane for the data surce:

So the first possible discrepency is in that "_Unit" is seen as "ID_Unit" for some reason in the Dataset. Why would that be? Does SSRS automatically convert "" to "ID"? If this is a known gotcha, it is as yet unkown to me.
After that all Dallas breaks loose, as the order of fields diverge radically. Why? Shouldn't the Refresh have ordered them alike? How can I get them to straighten up and fly right, or manually change the order so that they match?
NOTE: I'm not sure if this should even matter - should it? Are the field values populated based on position rather than by field name? IOW, must they match up, positionally?
UPDATE 2
This woke me up to the fact that there are up/down arrows; I'll try that...
UPDATE 3
I changed the order of the fields in the list to match those returned from the stored procedure, but it made no difference - I still get the same err msg when I try to generate the report.
UPDATE 4
In the rdl file the group expression that is supposedly problematic is this:
  <TablixRowHierarchy>
      <TablixMembers>
        <TablixMember>
          <KeepWithGroup>After</KeepWithGroup>
          <RepeatOnNewPage>true</RepeatOnNewPage>
          <KeepTogether>true</KeepTogether>
        </TablixMember>
        <TablixMember>
          <Group Name="table1_Group1">
            <GroupExpressions>
              <GroupExpression>=Fields!NewBiz.Value</GroupExpression>
            </GroupExpressions>
          </Group>
          <TablixMembers>
            <TablixMember>
              <KeepWithGroup>After</KeepWithGroup>
              <KeepTogether>true</KeepTogether>
            </TablixMember>
            <TablixMember>
              <Group Name="table1_Details_Group">
                <DataElementName>Detail</DataElementName>
              </Group>
              <TablixMembers>
                <TablixMember />
              </TablixMembers>
              <DataElementName>Detail_Collection</DataElementName>
              <DataElementOutput>Output</DataElementOutput>
              <KeepTogether>true</KeepTogether>
            </TablixMember>
            <TablixMember>
              <KeepWithGroup>Before</KeepWithGroup>
              <KeepTogether>true</KeepTogether>
            </TablixMember>
          </TablixMembers>
        </TablixMember>
        <TablixMember>
          <KeepWithGroup>Before</KeepWithGroup>
          <KeepTogether>true</KeepTogether>
        </TablixMember>
      </TablixMembers>
    </TablixRowHierarchy>

...to be more specific, this:
  <Group Name="table1_Group1">
    <GroupExpressions>
      <GroupExpression>=Fields!NewBiz.Value</GroupExpression>
    </GroupExpressions>
  </Group>

Why would that be a problem? NewBiz is a value contained in the result set, and it has two values by which it could be grouped (-1, signifying "New", and 0, signifying "Existing").
So why the err msg?
That field itself is represented in the rdl file like so:
<Field Name="NewBiz">
  <DataField>NewBiz</DataField>
  <rd:TypeName>System.Int32</rd:TypeName>
</Field>

UPDATE 5
And now it's working, with now change to the code...this happens too often with this old technology, and I don't know whether to be more relieved or irritated when something that doesn't work all of a sudden starts working WITH NO CODE CHANGES. Why!?? Arghhhh!!! Gleeeep!!! (that last was a happy sound, more-or-less equating to the polar opposite of argh).

A: I had a similar problem. I had a chart being fed by a 3-column query, one of which was an aggregate (ID Code, Sum(Count), and Day - in that order). What I did to fix it was to put the field I was grouping by earlier in my query (i.e. Day, ID Code, and Sum(Count)), that seemed to do the trick. It seems kind of stupid... but there it is.


text:
Q: Convert string numpy.ndarray to float numpy.ndarray I have one problem. How can I convert:
import numpy as np

a = np.array([['0.1 0.2 0.3'], ['0.3 0.4 0.5'], ['0.5 0.6 0.7']])

To:
b = np.array([[0.1,0.2,0.3], [0.3,0.4,0.5], [0.5,0.6,0.7]])

A: Here is a possible approach:
import numpy as np
a = np.array([['0.1 0.2 0.3'], ['0.3 0.4 0.5'], ['0.5 0.6 0.7']])

# Create a placeholder list
b = []

for element in a:
  # use a list comprehension to
  #     * take the zeroeth element in each row of the 'a' array and
  #       split the string on spaces
  #     * parse through each substring thus produced
  #     * convert each of those substrings into floats
  #     * store it in the list called temp.

  temp = [float(num) for num in element[0].split()]

  # Add each temp list to the parent list 'b'
  b.append(temp)

# Convert b into an np.array
b = np.array(b)

Without the comments
This looks like this:
b = []

for element in a:
    temp = [float(num) for num in element[0].split(' ')]
    b.append(temp)
b = np.array(b)

Yields:
array([[0.1, 0.2, 0.3],
       [0.3, 0.4, 0.5],
       [0.5, 0.6, 0.7]])

An alternate approach:
I tend to like this as an approach since it uses the native casting abilities of numpy. I have not tested it, but I would not be surprised if that produces a speedup in the conversion process for large arrays.
# transform 'a' to an array of rows full of individual strings
# use the .astype() method to then cast each value as a float
a = np.array([row[0].split() for row in a])
b = a.astype(np.float)

Hattip to @ahmed_yousif

A: I'm leaving this answer for a reference to those who are looking for a vectorized NumPy approach. TL;DR: it is not fast, use np.array([row[0].split() for row in a], dtype=float) as in the accepted answer.

I was looking for a vectorized approach to this problem and came up with the following solutions.
Using np.char.split:
import numpy as np

def to_numeric1(array, sep=' ', dtype=np.float):
    """
    Converts an array of strings with delimiters in it
    to an array of specified type
    """
    split = np.char.split(array, sep=sep)
    without_lists = np.array(split.tolist())
    corrected_dimension = np.squeeze(without_lists)
    return corrected_dimension.astype(dtype)

And using pd.Series.str.split:
import pandas as pd

def by_pandas(array, sep=' ', dtype=np.float):
    df = pd.DataFrame(array)
    return df[0].str.split(pat=sep, expand=True).to_numpy(dtype=dtype)

Unfortunately, both solutions are slower than native Python loops as in E. Ducateme's answer:
a = np.array([['0.1 0.2 0.3'], ['0.3 0.4 0.5'], ['0.5 0.6 0.7']]*10000)

%%timeit
native_python_loop(a)
# 57.8 ms ± 526 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
to_numeric1(a)
# 86.6 ms ± 122 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
to_numeric2(a)
# 79.8 ms ± 1.11 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

As stated in the comment by hpaulj:

The np.char functions apply Python string methods to each element of
  the array. They are a convenience, but they do not improve speed.
  NumPy doesn't have fast compiled code that operates on the contents of
  strings. It depends on existing Python code for that. 'vectorization'
  in the common numeric sense does not exist for strings.

Ideally, the first solution could be as fast as the native Python loops and have less lines of code. The problem is with returned values of np.char.split:
>>> a = np.array([['0.1 0.2 0.3'], ['0.3 0.4 0.5'], ['0.5 0.6 0.7']])
>>> np.char.split(a)
array([[list(['0.1', '0.2', '0.3'])],
       [list(['0.3', '0.4', '0.5'])],
       [list(['0.5', '0.6', '0.7'])]], dtype=object)

It returns a NumPy array of NumPy arrays of lists of strings which should be further processed to a normal 2D NumPy array, and I assume that this processing takes lots of time. As hpaulj said: "[i.split() for i in a] and np.char.split(a) take basically the same time"
There is an issue on GitHub that proposes changes to this function, so it would return the following instead:
array([['0.1', '0.2', '0.3'],
       ['0.3', '0.4', '0.5'],
       ['0.5', '0.6', '0.7']], dtype='<U3')

A: b = []
for ai in a:
  temp=[]
  for b in ai[0].split(' '):
     temp.append(float(b))
  b.append(temp)

b = np.array(b)

You iterate through all strings, split them on a space, and typecast them to float

A: You can do it with nested lists and then reshaping them.
b = [ float(h) for j in [i[0].split(" ") for i in a  ]for h in j ]
b = np.asarray(b).reshape(3,3)

Hope this helps.
@E. Ducateme Solution is pretty compressed also.

A: first you will map every item in the array by spiting it into float strings then apply x.astype(np.float) function to convert to float
import  numpy as np

x = np.array([['0.1 0.2 0.3'], ['0.3 0.4 0.5'], ['0.5 0.6 0.7']])
x = np.array(list(map(lambda z: z[0].split(),x)))
y = x.astype(np.float)
print(y)

result:
[[0.1 0.2 0.3]
 [0.3 0.4 0.5]
 [0.5 0.6 0.7]]


text:
Q: Showing $\lor$ in terms of $\to$ and $\lnot$ I was looking at a question a user posted yesterday (link below). And one of the answers mentioned one could express $∨$ in terms of  $\to$ and $\lnot$.
In terms of $\land$ he stated it can be expressed like such:
\begin{align*}
p \land q &\equiv \neg\neg p \land \neg\neg q \\
&\equiv \neg(\neg (p) \lor (\neg q)) \\
&\equiv \neg(p \to \neg q) \\
\end{align*}
I've been thinking about how something like that could be done for a while now and its starting to bug me. Out of curiosity was that the right procedure and if so how could it be shown for $\lor$.
link: Proving that $\{\to, \lnot\}$ is logically complete

A: $p\lor q=\lnot(\lnot p\land\lnot q)=\dots$


text:
Q: Converting dynamic property to json dictionary type I have the "json" mentioned below. "changes" property is changeable
{"sort":[{"field":"recid","direction":"desc"}],"changes":[{"recid":2084,"LokasyonAdresi":"211","LokasyonAdi":"111"}],"action":"save"}

When I convert json to c# classes, the following classes are created.
public class Sort
    {
        public string field { get; set; }
        public string direction { get; set; }
    }

    public class Change
    {
        public int recid { get; set; }
        public string LokasyonAdresi { get; set; }
        public string LokasyonAdi { get; set; }
    }

    public class Root
    {
        public List<Sort> sort { get; set; }
        public List<Change> changes { get; set; }
        public string action { get; set; }
    }

I want the class I want to convert to be like this. How can I customize?
public class Root
{
    [JsonPropertyName("sort")]
    public IList<Sort> Sort { get; set; }

    [JsonPropertyName("action")]
    public string Action { get; set; }

    [JsonPropertyName("changes")]
    public IDictionary<string, object> Changes { get; set; }
}

A: try this code
var jsonParsed = JObject.Parse(json);

Dictionary<string,object> changes=((JArray)jsonParsed["changes"])
.SelectMany(x=> x.ToObject<Dictionary<string,object>>())
.ToDictionary(kvp=>kvp.Key,kvp=>kvp.Value);

List<Sort> sort= ((JArray) jsonParsed["sort"]).Select(x=> x.ToObject<Sort>()).ToList();

    var data = new Root {
      Action= (string) jsonParsed["action"],
      Sort= sort,
      Changes=changes
      };


text:
Q: ConcurrentModificationException when reading from GAE Datastore using JDO I am querying the GAE datastore to retrieve a list of entities (using a dev gae with sdk 1.8.3) :
public List<OT> getAll() {
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Query q = pm.newQuery();
    q.setClass(OT.class);
    try {
        return (List<OT>) q.execute();
    }
    finally {
        q.closeAll();
        pm.close();
    }
}

This is always throwing a ConcurrentModificationException on the pm.close() line :
java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
    at java.util.ArrayList$Itr.next(ArrayList.java:791)
    at com.google.appengine.datanucleus.DatastoreConnectionFactoryImpl$DatastoreManagedConnection.close(DatastoreConnectionFactoryImpl.java:146)
    at org.datanucleus.store.connection.ConnectionManagerImpl.closeAllConnections(ConnectionManagerImpl.java:181)
    at org.datanucleus.store.AbstractStoreManager$1.preClose(AbstractStoreManager.java:260)
    at org.datanucleus.ObjectManagerImpl.close(ObjectManagerImpl.java:1112)
    at org.datanucleus.api.jdo.JDOPersistenceManager.internalClose(JDOPersistenceManager.java:359)
    at org.datanucleus.api.jdo.JDOPersistenceManagerFactory.releasePersistenceManager(JDOPersistenceManagerFactory.java:1106)
    at org.datanucleus.api.jdo.JDOPersistenceManager.close(JDOPersistenceManager.java:343)

I am using the following dependencies:
    <dependency>
        <groupId>com.google.appengine.orm</groupId>
        <artifactId>datanucleus-appengine</artifactId>
        <version>2.0.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.datanucleus</groupId>
        <artifactId>datanucleus-core</artifactId>
        <version>3.1.3</version>
    </dependency>
    <dependency>
        <groupId>org.datanucleus</groupId>
        <artifactId>datanucleus-api-jdo</artifactId>
        <version>3.1.3</version>
    </dependency>
    <dependency>
        <groupId>javax.jdo</groupId>
        <artifactId>jdo-api</artifactId>
        <version>[3.0, 4.0)</version>
    </dependency>
    <dependency>
        <groupId>org.datanucleus</groupId>
        <artifactId>datanucleus-rdbms</artifactId>
        <version>3.1.3</version>
        <scope>runtime</scope>
    </dependency>

and the following version of the DN enhancer:
    <dependency>
        <groupId>org.datanucleus</groupId>
        <artifactId>datanucleus-enhancer</artifactId>
        <version>3.1.1</version>
    </dependency>

I am not doing any modifications to any objects from the collection, or to the collection itself. As a matter of fact, the errors occures even when the collection is empty...
Any idea what I might be doing wrong?
Additional debug details
I have entered debug mode on the pm.close() statement and found out that while iterating on the listeners, one of them is removing himself from the list of listeners:
447468239@qtp-1694835335-71@11277, prio=5, in group 'main', status: 'RUNNING'
  at org.datanucleus.store.connection.ConnectionManagerImpl$1.managedConnectionPostClose(ConnectionManagerImpl.java:247)
  at com.google.appengine.datanucleus.DatastoreConnectionFactoryImpl$DatastoreManagedConnection.close(DatastoreConnectionFactoryImpl.java:147)
  at org.datanucleus.store.connection.ConnectionManagerImpl.closeAllConnections(ConnectionManagerImpl.java:181)
  at org.datanucleus.store.AbstractStoreManager$1.preClose(AbstractStoreManager.java:260)
  at org.datanucleus.ObjectManagerImpl.close(ObjectManagerImpl.java:1112)
  at org.datanucleus.api.jdo.JDOPersistenceManager.internalClose(JDOPersistenceManager.java:359)
  at org.datanucleus.api.jdo.JDOPersistenceManagerFactory.releasePersistenceManager(JDOPersistenceManagerFactory.java:1106)
  at org.datanucleus.api.jdo.JDOPersistenceManager.close(JDOPersistenceManager.java:343)
  at net.mycrub.jacasse.persistence.dao.GenericDAO.getAll(GenericDAO.java:43)

Code at ConnectionManagerImpl.java:247
                    // Remove this listener
                    mconn.removeListener(this);

This is not a listener I have added myself. It was actually a DN listener added during the Query.closeAll() statement. Should I keep either of these 2 "close" statements, are they redundant?

A: Have you tried something like this?
public List<OT> getAll()
{
  List<OT> liResult = null;

  PersistenceManager pm = PMF.get().getPersistenceManager();
  Query q = pm.newQuery();
  try
  {
    q.setClass(OT.class);
    liResult = (List<OT>)q.execute();
  }
  finally
  {
    try
    {
      q.closeAll();
    }
    finally
    {
      pm.close();
    }
  }

  return liResult;
}

A: The DatastoreManagedConnection#close() method is simply
public void close() {
    for (ManagedConnectionResourceListener listener : listeners) {
        listener.managedConnectionPreClose();
    }
    // nothing to actually close
    for (ManagedConnectionResourceListener listener : listeners) {
        listener.managedConnectionPostClose();
    }
}

The ConcurrentModificationException cannot come from here directly as nothing in this code modifies the listeners List. Is it possible you have other code running in parallel and adding or removing from listeners, calling addListener or removeListener?


text:
Q: Can I convert image to binary and send through websocket in c I have a websocket server written in C and client also in C. I want to take a picture convert it to binary data , send it through the websocket and decode that picture so other client could see it. Is this possible to be implemented in C, because all the examples that I saw are written in C++ and C#.
Thanks in advance

A: Then fun thing is, the picture most likely already is in binary.
As for the sending, it's no difference than any other socket communication. On the server you read X bytes from the file, and send X bytes to the client. On the client you read X bytes from the server, and write X bytes to a file (or buffer if you want the data in memory only).


text:
Q: Print dictionary value into string with Python3.6 Say I have a dictionary like the following:
{'keyid': ['foo', '1', 'bar', '2', '(FancyStrininParathesis)']}

How could I extract the strings in the value of the dictionary and create and print one long string such as
 print (finalstring)  #Desired output:  'foo - 1 bar - 2 (FancyStrininParathesis)'

I've been able to output the value fine, but I can't figure out how to output the array as one long string. I'm new to python as well, I'm more familer with PHP, however I have to use a special python library for this project.
Thanks for the help!

A: From your reply to my comment, I think I understand what you want to do. With
dictionnary = {'keyid': ['foo', '1', 'bar', '2', '(FancyStrininParathesis)']}

you can iterate through the values with dictionnary.items():
for key, value in dictionnary.items():
    ...

Now because here value is a list, we can iterate through it and create our own output string:
for key, value in dictionnary.items():
    output = ""
    for item in value:
        output += item + " - "
    output = output[:-3] # Remove the last three characters
    print(output)

A more pythonic way would be to use str.join:
for key, value in dictionnary.items():
    output = str.join(" - ", value)
    print(output)

A: Try
d = {'keyid': ['foo', '1', 'bar', '2', '(FancyStrininParathesis)']}
' - '.join(d['keyid'])

A: dicttt = {'keyid': ['foo', '1', 'bar', '2', '(FancyStrininParathesis)']}

entr = dicttt["keyid"] # get the list from the dictionary

print( ' - '.join(entr)) # join each lists entry by ' - ' and print all

or if you simply want to output it you can output it by iterating the list and printing without newlines:
for n in range(len(entr)): # get an index into the list
    if (n > 0):
        print(' - ',end="") # if index > 0 print seperator, no newline

    print(entr[n] ,end="") # print list item, no newline

print() # print newline

A: Try this
dt ={'keyid': ['foo', '1', 'bar', '2', '(FancyStrininParathesis)']}
for x in dt.values():
    s =' '.join(x)

s
print(s)


text:
Q: CoreData - Not saving relationships or foreign key details on NSSet I googled and looked at most of the Core data questions before deciding to post in SO. It's kind of weird and I don't know where to go from here.
I'm building an iOS app and I'm using RestKit, Core Data and Objective Record. Before I go into the details, note that my Object Context and Object Store for Objective Record and RKObjectManager are the same. So I'm not referring objects outside the same contexts.Enough intro..
Feed_Items model is the top one in the hierarchy.
--Feed_Items
------OutFit Model (1-to-1 / Optional )
------Clothe Model (1-t0-1 / Optional )
Both Clothe and Outfit have same set of attributes and I'm interested particularly in the 'comments' attribute
--Clothe / Outfit
------Other fields
------NSSet* Comments object
When I start the app, I load all the latest feeds from the server using RestKit(json) and Object-Mapping. On the first load, I get only 1 feed item which is an outfit and that outfit has a total of 7 comments of which 5 are loaded initially. So far so good and I get the Feed_Item object and the corresponding Outfit and the 5 comments in NSSet.
Now when the user wants to load all the previous comments, I invoke another API and it returns 2 new comments which is parsed successfully as Comment objects.
[objectManager getObjectsAtPath:[NSString stringWithFormat:@"api/outfit/comments/%d",[_feed.outfit.outfit_id intValue]]
             parameters:_params
                success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                    for( Comment* _comment in [mappingResult array]){
                        [_feed.outfit addCommentsObject:_comment];
                        [_comment save];
                    }
                }
                failure:^(RKObjectRequestOperation *operation, NSError *error) {

                }];

There aren't any exceptions or errors however I suspect the foreign key for the last 2 Comment objects are not getting updated in the sqlite db. Please see the image below

To further prove my point, I tried the below on my second run
Outfit *_outfit = [[Outfit where:@"outfit_id == 3"] objectAtIndex:0];
NSLog(@"%@", [_outfit.comments allObjects]);

and there are only 5 obects
"<Comment: 0xc185ed0> (entity: Comment; id: 0xc185840 <x-coredata://2C61C98F-0B5F-4111-B681-1E43ABFB33D4/Comment/p6> ; data: <fault>)",
"<Comment: 0xc185c00> (entity: Comment; id: 0xc185820 <x-coredata://2C61C98F-0B5F-4111-B681-1E43ABFB33D4/Comment/p1> ; data: <fault>)",
"<Comment: 0xc185f10> (entity: Comment; id: 0xc185850 <x-coredata://2C61C98F-0B5F-4111-B681-1E43ABFB33D4/Comment/p8> ; data: <fault>)",
"<Comment: 0xc185f70> (entity: Comment; id: 0xc185860 <x-coredata://2C61C98F-0B5F-4111-B681-1E43ABFB33D4/Comment/p9> ; data: <fault>)",
"<Comment: 0xc185e90> (entity: Comment; id: 0xc185830 <x-coredata://2C61C98F-0B5F-4111-B681-1E43ABFB33D4/Comment/p4> ; data: <fault>)"

I don't know what happened to the last 2 objects and why it's not hooked up. It's successfully saved in the database as you can see from the image but looks like the relationship or the foreign key is not set. Any idea what's going wrong?
Cheers

A: For those who are using RestKit + Core Data + Objective Record, please ensure you modify the saveTheContext method in NSManagedObject+ActiveRecord.m like the following.
- (BOOL)saveTheContext {
    if (self.managedObjectContext == nil ||
        ![self.managedObjectContext hasChanges]) return YES;

    NSError *error = nil;
    BOOL save = [self.managedObjectContext saveToPersistentStore:&error];
    if (!save || error) {
        NSLog(@"Unresolved error in saving context for entity:\n%@!\nError: %@", self, error);
        return NO;
    }

    return YES;
}

Key to note here is the call to saveToPersistentStore which is an RKAdditions category on NSManagedObjectContext. Without this RestKit initialized object won't save any changes in the persistent store.
It took me a day to figure this out.


text:
Q: System.OutOfMemoryException как исправить? Помогите разобраться с ошибкой SystemOutOfMemoryException.
код для скриншотов
public Bitmap TakeScreenshot(By by)
{
    // 1. Make screenshot of all screen
    var screenshotDriver = Browser as ITakesScreenshot;
    Screenshot screenshot = screenshotDriver.GetScreenshot();
    var bmpScreen = new Bitmap(new MemoryStream(screenshot.AsByteArray));

    // 2. Get screenshot of specific element
    IWebElement element = Browser.FindElement(by);
    var cropArea = new Rectangle(element.Location, element.Size);
    return bmpScreen.Clone(cropArea, bmpScreen.PixelFormat);
}


text:
Q: Reading from multiple Bluetooth devices in Android? Just to make it short. I want to connect to three devices and read the data from all the three at the same time. I know how to connect to one and i can read the data from that But What i want is to connect the other two and read from them.Any suggestions , or other example i can follow.
Here is part of the code which is similar to mine but shorter . This code can connect to one device using the mac. So How to modify this to connect to three devices at the same time and display the data they are sending?
Please help i really need it cause am stuck at this part of my project. Thanks for the help.
private boolean connected = false;
private BluetoothSocket sock;
private InputStream in;
public void test() throws Exception {
    if (connected) {
        return;
    }
    BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().
        getRemoteDevice("00:14:C5:A1:02:67");
    Method m = zee.getClass().getMethod("createRfcommSocket",
        new Class[] { int.class });
    sock = (BluetoothSocket)m.invoke(zee, Integer.valueOf(1));
    devicecon.setText("Connecting......");
    sock.connect();
    devicecon.setText("Connected");
    in = sock.getInputStream();
    byte[] buffer = new byte[50];
    int read = 0;
    Log.d("ZeeTest", "++++ Listening...");
    try {
        while (true) {
            read = in.read(buffer);
            connected = true;
            StringBuilder buf = new StringBuilder();
            for (int i = 0; i < read; i++) {
                int b = buffer[i] & 0xff;
                if (b < 0x10) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(b)).append(" ");
            }
            Log.d("ZeeTest", "++++ Read "+ read +" bytes: "+ buf.toString());
        }
    } catch (IOException e) {}
    Log.d("ZeeTest", "++++ Done: test()");

A: All you need to do is create a new thread (I suggest using an instance of AsyncTask for this rather than an actual Thread) for each device and call the connection code snippet
BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().
    getRemoteDevice("00:14:C5:A1:02:67");
Method m = zee.getClass().getMethod("createRfcommSocket",
    new Class[] { int.class });
sock = (BluetoothSocket)m.invoke(zee, Integer.valueOf(1));
devicecon.setText("Connecting......");
sock.connect();

from inside that new thread.


text:
Q: Bash - Need to get records with line numbers if found duplicates based on first two column values Need to help in Bash to print duplicate records in a file with the corresponding line number.
Duplicates are to be identified based on first two column combination.
Example:
111|abc|scientist
222|ghu|developer
222|thu|doctor
222|ghu|engineer

I need output as below as duplicate is based on combination of 1st 2 columns along with its line number:
2, 222|ghu|developer
4, 222|ghu|engineer

A: Assuming your input is in file input.txt, try:
awk -F '|' '{if (t[$1$2]) {print t[$1$2]; print NR", "$0} t[$1$2] = NR", "$0}' input.txt

Improving the readability:
awk -F '|' '{
  if (t[$1$2]) {
    print t[$1$2]
    print NR", "$0
  }
  t[$1$2] = NR", "$0
}' input.txt


text:
Q: nginx reverse proxy treats request urls differently we're using nginx to provide a security layer in front of an AWS presto cluster. We registered an SSL certificate for nginx-presto-cluster.our-domain.com
Requests for presto are passed through nginx with Basic authentication.
An SQL query for presto results in multipe sequential requests to the server, to fetch query results.
We created a nginx.conf that looks like this:
location / {
  auth_basic $auth;
  auth_basic_user_file /etc/nginx/.htpasswd;
  sub_filter_types *;
  sub_filter_once off;
  sub_filter 'http://localhost:8889/' 'https://presto.nginx-presto-cluster.our-domain.com/';
  proxy_pass http://localhost:8889/;
}

Presto's responses contain a nextUri to fetch results. The sub_filter rewrites these Uri's from localhost:8889 to our secure domain, where they are passed through nginx again.
The problem:
The first response has a body that looks exactly as desired:
{
  "id":"20171123_104423_00092_u7hmr"
  , ...
  ,"nextUri":"https://presto.nginx-presto-cluster.our-domain.com/v1/statement/20171123_104423_00092_u7hmr/1"
  , ...
}

The second request, however, looks like:
{
  "id":"20171123_105250_00097_u7hmr"
  , ...
  , "nextUri":"http://localhost:8889/v1/statement/20171123_105250_00097_u7hmr/2"
  , ...
}

We would've expected the rewrite to work always the same way.
Can you help us?

A: We resolved the issue by adding
proxy_set_header Accept-Encoding "";

into the config snippet above.
The reason is that the traffic might be compressed in the process, if this is enabled.
The string replacement then would not work on the compressed content.
By not accepting any encoding we prevent this compression.