text:
Q: NSPredicate - Contains Not Functioning As Expected I am using NSPredicate on a NSMutableArray as follows, filled from an XML Sheet
//Get XML Data
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"breosla_db" ofType:@"xml"];
NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLFile:filePath];
//Place in Mutable Array
NSMutableArray *data = [xmlDoc valueForKeyPath:@"row"];
NSLog(@"Data %@", data[0]);

NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"ID contains[c] '2'"];
NSArray *filtered = [data filteredArrayUsingPredicate:bPredicate];

The data looks like this in the log:
Data {
ID =     (
    2
);
address1 =     (
    "123 Fake Street"
);
address2 =     (
    "A Sleepy Town"
);
address3 =     (
);
county =     (
);
licenseNo =     (
    12345
);
licenseType =     (
    "Trader"
);
licenseeName =     (
    "Mr. Trader"
);
nominessName =     (
);
tradingName =     (
    "Trading Shop"
);

}
The current predicate:
NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"ID contains[c] '2'"];

Only returns the data where ID == 2, it does not return 12, 22, 42 etc for example.
Secondly, I cannot filter by the e.g. All names that contain 'e':
NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"tradingName contains[c] 'e'"];

The 'data' NSMutableArray, in each position, contains data similar to that show in the log.

A: It looks like your data comprises an array of dictionaries, and the values for each of the dictionary keys are also (single element) arrays.  You can see this because your log shows
ID =     (
    2
);
etc

The ( ) denote arrays.  So, to get your predicates to work, you need to use 'ANY', as follows:
NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"ANY ID contains[c] '2'"];

or
NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"ANY tradingName contains[c] 'e'"];

But you might do better to remodel your data so that the values are not embedded in arrays.

A: It seems your predicate will work for only ID or tradingName. Assuming data[0] holds complete xml element, instead use following;
NSPredicate *idPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] '2'"];
[data filterUsingPredicate:idPredicate];
And for tradingName that contains 'e':

NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'e'"];
[data filterUsingPredicate:namePredicate];
Check this reference for more help.


text:
Q: Recover bookmarks from places.sqlite file I have a problem exporting my thousands of bookmarks in Firefox into a HTML file using the standard export function in Firefox. I get this error:
*************************
A coding exception was thrown and uncaught in a Task.

Full message: TypeError: root is undefined
Full stack: BookmarkExporter@resource://gre/modules/BookmarkHTMLUtils.jsm:980:1
BHU_exportToFile/<@resource://gre/modules/BookmarkHTMLUtils.jsm:228:22
TaskImpl_run@resource://gre/modules/Task.jsm:314:40
Handler.prototype.process@resource://gre/modules/Promise.jsm -> resource://gre/modules/Promise-backend.js:865:23
this.PromiseWalker.walkerLoop@resource://gre/modules/Promise.jsm -> resource://gre/modules/Promise-backend.js:744:7

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

see https://gist.github.com/rubo77/12ef9be4060c7935c74c
Is there a way to export my bookmarks on the console, so I can import them into a new fresh firefox profile?
UPDATE: I managed to copy and paste all bookmarks from the "manage bookmarks" menu of an instance of firefox with the old profile into another instance with the new profile opened at the same time (using the commandline option -no-remote). But unfortunately this still doesn't copy the tags that were used for my bookmarks, which would be a great loss too.

A: The bookmarks are kept under your profile directory [1] (e.g. under Linux in a place similar to ~/.mozilla/firefox/rbbfa46q.default) stored in the file places.sqlite, an SQLite 3.x database. You can manage it as each SQLite database file.
Since it is possible to have conflict in the keys, at least in principle, I suggest to export as list of html links and import after in the second firefox account.
The following is a command actually able to create this list, as reported in another answer [2].
sqlite3 places.sqlite "select '' || moz_bookmarks.title || '
' as ahref from moz_bookmarks left join moz_places on fk=moz_places.id where url<>'' and moz_bookmarks.title<>''" > t1.html

Then you can use the import method you find more cosy.

Note:

*

*Of course there are addon as "SQLite Manager" to manage it from inside Netscape...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Predict function producing fewer rows than provided I am currently trying to run the following code:
pv_model <- glm(SalePrice ~ MSSubClass + MSZoning..., data = train)
summary(pv_model)
pv_predict <- predict(pv_model)
train$PV <- pv_predict

However, when I try to assign the predictions as a column in the train data set, I get this error:
Error: Assigned data `predict(pv_model)` must be compatible with existing data.
x Existing data has 730 rows.
x Assigned data has 540 rows.
i Only vectors of size 1 are recycled.

Upon further inspection, it looks like my pv_predict variable only contains 540 rows, despite pv_model having 730. What accounts for this difference? Why does the predict function eliminate so many rows, and what can I do to fix this?
Any help is appreciated.

A: Missing data in the training set might be the issue.  Try:
predict(pv_model, newdata=train)

This will use all the rows, and give you NA where there is missing data in a predictor.


text:
Q: Optimized data structure for 2d spatial search and Javascript implementation? I'm working on a Tetris-type HTML5 game and need to beef up a space optimization algorithm.
Rectangular blocks of varying size need to be  added to the canvas in the most space efficient way.  I know how much space the block takes, I need to find the closest spot the block can be added with a fixed x coordinate- the absolute closest spot is a nice to have.
I've implemented a version that searches using pixel by pixel value checking on the canvas that pushes down until it finds enough free space for the shape and then adds it.  This works (slowly) only if the space fills left to right- the algorithm can safely assume if the first pixel column is safe then the entire block can be added.
I need to make this more robust, here's where I think this should go.
Storing a quad tree to represent the board state gives me a quicker way to identify where there's space.

4 nodes are stored for each level of depth- each node is either 0 for completely empty, or 1 for 'has some stuff somewhere'. Each progressive level of depth gives more and more information about the board.
given(boardstate, block width, block height)
-calculate the largest grid space the block must span
  // a block which is 242x38 MUST span a 16x16 free space
  // (based on 1/2 of smallest dimension)
-the block width requires n consecutive free spaces
  // (242/16) = 15
-find the first available 15x1 spaces in the board
-check the surrounding tiles at the next level of depth for collisions
  -check the surrounding tiles at the next level of depth for collisions... etc
-if there's a fit
  draw the block
  mark all affected nodes at all depths as 'filled'

What is the best javascript data structure to represent the grid?
Things I've considered so far:
A. Build a full tree object with pointers to children and values and a set of methods to navigate it.  This would be intuitive and probably space-efficient, but I suspect horribly slow.
B. Look at each grid as 4 bits and store the depths as hex arrays or objects.  If done by a person more clever than myself, this probably optimizes not just the storage but makes clever bit operations available to compare adjacent cells, turn blocks on and off, etc.  I imagine it would be incredibly fast, incredibly efficient, but it's beyond my skills to build.
C. Store each depth in an array.  Depth[0]=[1,0,0,0]; Depth[1][1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0] etc.  This is where I'm headed at the moment.  It's not very space efficient and it probably won't be incredibly fast, but I think I can get my head around it.
There's a practical limit to any structure to the number of depths (the array to store availability of 4x4 spaces in my last approach is more than 65 thousand) after which making the expensive call to check the last few pixels of image data from the canvas with a regular iterator is unavoidable.
So, A,B,C, other?
As usual, all insights appreciated.

A: You want answer b) and you want to implement a space-filling-curve or a spatial index. You don't want to store the bits in an array or object or an index but in a string-key. You want to read this string-key from the left to the right and thus you can easy query each depth with any string matching algorithm. You want to google for Nick's spatial index hilbert curve quadtree blog. But you are right with your assumption that answer b) is very expensive so I suggest you answer a) because it's not that slow and also there is already a free implementation of a javascript quadtree available from the closure library: closure-library.googlecode.com/svn/docs/class_goog_structs_QuadTree.html.


text:
Q: How to suppress Outlook's security warning in win7-32 and Outlook 2003 that uses VB6 and CDO 1.2.1 We have VB6 code that works in Win XP and Outlook 2003 using CDO 1.2.1. Now that we moved to Win7 32-bit, we have the Outlook security warning (not UAC) that an application is trying to access a particular outlook feature. I have searched for hours without success. I am looking for specific guidance rather than corrections per se to my code. If you have particular code to display the address book in said environment, that would be great! BTW, building a homegrown list of addresses rather than calling the address book (thus requiring CDO) was rejected and hence not an option.  Thank you!

A: You can use Outlook Redemption to accomplish what you desire without the security warnings.
http://www.dimastr.com/redemption/home.htm


text:
Q: Present two different dimensions in MDX as hierarchy I have two different dimensions i want to present in MDX Query with drilldown
Dim 1:
Country, CountryId

Italy,1

Mexico,2

England,3

dim 2:
Product, ProductId

Shoes,1

Shirts,2

Bags,3

Fact_Data:
Country,Product,Amount

1,2,33

3,1,50

2,3,64

1,1,100

3,1,70

2,2,44

when i join the dimensions in MDX Query:
select [Measures].[SaleAmount] on 0,
crossjoin([Country].[Country].[Country].[Italy],[Product].[Product].[Product].[Product]) on 1
from [cube]
the data presented will be:
italy   Shoes  100

        Shirts 33

        Bags   0

Mexico  Shoes  0

        Shirts 44

        Bags   64
...

And i want to present the data with drilldown option from country to product
+italy   133
+Mexico  108
+England 120

I'm using icCube

A: The complicated part is solving this in the schema, two options there

*

*Create a new dimension that is a crossjoin dim1*dim2, that defines a multiple value key for the last level + remove name unique on the last level. You could remove Dim1 and Dim2 and define them as hierarchies in Dim1Dim2 newly created dimension.

*Use categories, for now it's a bit brute you've to create one by one member (contact us directly if you want to go this way).
The easy and recommended way, use the Navigation settings to define the drilldown strategy in the reporting at chart level.


text:
Q: SQL - Conditional Window with multiple dates Table A

| Customer | Transaction_Date | Complaint_Date |
|----------|------------------|----------------|
| A        | 1                | 2              |
| A        | 1                | 3              |
| A        | 2                | 3              |
| B        | 1                | 2              |
| B        | 1                | 2              |
| B        | 2                | 3              |
| C        | 2                | 3              |

For the table above, I would like to calculate the number of complaints per customer in the last x days, taking into account when the complaint occurred.
i.e. the complaint should only be counted if it occurred before the transaction date
i.e
| Customer | Transaction_Date | Complaint_Date | Count |
|----------|------------------|----------------|-------|
| A        | 1                | 2              | 0     |
| A        | 1                | 3              | 0     |
| A        | 2                | 3              | 1     |
| B        | 1                | 2              | 0     |
| B        | 1                | 2              | 0     |
| B        | 2                | 3              | 2     |
| C        | 2                | 3              | 0     |

Currently, I am counting the number of transactions (records), with a partition of customer, transaction date and complaint date and then joining back to customer and transaction date, if the complaint date is less than the transaction date and transaction date is within the range of x days.
I then calculate a final sum over a window of x days, partition by customer, as the above results in a count for each transaction date and customer

A: I think you can do this by using a simple where condition. Assuming the date fields are stored in the date format, calculating for the last 10 days (This is in SQL server):
select Customer,count(*)
from table
where Complaint_date<transaction_date
      and Complaint_date between GETDATE()-10 and GETDATE()
Group by Customer

Hope this helps.
Edit: You can try doing a self join here:
;with tableA as
(select 'A' as customer,1 as Transaction_date,2 as Complaint_date union all
select 'A',1,3 union all
select 'A',2,3 union all
select 'B',1,2 union all
select 'B',1,2 union all
select 'B',2,3 union all
select 'C',2,3)

select a.Customer,a.transaction_date,count(b.Complaint_date) as cnt
from tableA a
left join tableA b on a.customer=b.customer
      and a.transaction_date>=b.Complaint_date
Group by a.Customer,a.transaction_date

This produces the following output:
Customer Transaction_Date Cnt
A        1                0
A        2                1
B        1                0
B        2                2
C        2                0

If you want the same output as mentioned in your answer, you can join this output back to the original table:
;with tableA as
(select 'A' as customer,1 as Transaction_date,2 as Complaint_date union all
select 'A',1,3 union all
select 'A',2,3 union all
select 'B',1,2 union all
select 'B',1,2 union all
select 'B',2,3 union all
select 'C',2,3)

select x.*,y.cnt
from tableA x
inner join
(select a.Customer,a.transaction_date,count(b.Complaint_date) as cnt
from tableA a
left join tableA b on a.customer=b.customer
      and a.transaction_date>=b.Complaint_date
Group by a.Customer,a.transaction_date) y
ON x.customer=y.customer and x.transaction_date=y.Transaction_date


text:
Q: RocketChat: How to send SMS Messages to Livechat channel from mobile I want to copy the behaviour of the Livechat-Popup - Window to send messages from mobile. How would I do that?

A: Get a Twilio # & Configure
First you need a Twilio subscription. Then purchase a phone number from within your Twilio account. This number will be used to receive SMS messages from other phone and send to LiveChat within Rocket.Chat. Within Twilio, go to your new phone number's settings...

Under 'A Message Comes In' enter this:
https://<your_rocketchat_url>:<your_port_#>/api/v1/livechat/sms-incoming/twilio

That will forward SMS incoming messages to LiveChat.
Tell Rocket.Chat to Listen for SMS's from your Twilio Account
Then, in RocketChat, go to Administration -> SMS, and enter your Twilio Account SID and Auth Token which can be found in your Twilio dashboard and be sure to enable SMS on this page...

Be sure LiveChat is enabled and that you are a LiveChat Agent.
Now, text messages from other phones will appear in LiveChat just like messages from the LiveChat embeded pop-up window. You can respond to those messages within RocketChat as well.


text:
Q: Different placement of curly braces Sometimes when I look up videos at Youtube for better explanation and usually these people places the curly braces differently.
Note that , I'm new to the coding world.
1st placement.
for(int i=1 ; i < 6 ; i++)
{

    //Statements

}

2nd placement
for(int i=1 ; i < 6 ; i++){

    //Statements

}

These 2 codes actually functions the same , it just has different placement of the curly braces.
What's the difference of these 2 placements? Why do some others use the 2nd placement instead of the first one? I actually prefer the first one, because its easier to spot errors and looks neat.

A: 1st and 2nd are the same.
The only difference is the coding style.
While you work for a company X they tend to use one coding style just for the sake of consistency. It does not matter if you use the first or second style as long as you are writing it, in the same way, all the time.
It just might confuse other developers who will have to read your code at some point.


text:
Q: Adding Localstorage item for unique IDs I want to know if its possible to use Javascript to set LocalStoarge for items to hide them.
The catch is they have unique IDs inside their ID attribute that gets generated so you have no idea what they might be but if you click the delete button it should set an item and hide it for that specific item with that specific ID:

 <button onclick="deleteChat(this)">X</button>

A: You can do it this way:

  <button onclick="deleteChat('.$contact_id.')">X</button>

window.onload = deleteChats();

function deleteChat(id){
  document.getElementById(id).style.display = "none"
  let items = JSON.parse(localStorage.getItem("deleted_items"));
  if(items){
    items.push(id);
  }
  else{
    items = [id];
  }
  localStorage.setItem("deleted_items",JSON.stringify(items));
}

function deleteChats(){
  const chats = JSON.parse(localStorage.getItem("deleted_items"));
  chats.map(chat => {
    document.getElementById(chat).display = "none";
  })
}

A: Js Fiddle Link check this out
hide all ids from localstorage
window.onload = function() {
 allStorage().map(id => {
      $("#"+id).hide();
  })
}

Get get all ids in localstorage
 function allStorage() {
    var values = [],
        keys = Object.keys(localStorage),
        i = keys.length;
    while ( i-- ) {
        values.push( localStorage.getItem(keys[i]) );
    }
    return values;
}

Get id from class, hide the div and set an item in localstorage
$('.del').on('click', function(event) {
       $("#"+this.id).hide();
       window.localStorage.setItem("id"+this.id, this.id)
})


text:
Q: Nintendo 3DS face comparison/similarity feature? If I recall correctly, on the DS Lite or DSi there was a feature where the camera would take a picture of two separate faces and display a percentage similarity between them - it may also have outputted a possible relationship for the two people, e.g. daughter, mother etc. This was not related to face recognition, it was just an added feature on the console. However, I cannot find mention of this anywhere on the Internet, which leads me to wonder if it was not in fact an inbuilt DS feature but part of an actual game.
Did this feature ever exist or is my memory incorrect and is there a way to access this feature on the 3DS, or was it not transferred?

A: The similarity feature does indeed exist in the camera app, which is part of the DSi system software.
The feature does not exist on the DS Lite, which does not have a camera in the first place, and does not seem to have carried over to the 3DS. At the very least, I have been unable to find out how to compare faces on the 3DS.


text:
Q: When does getting submatrix of an numpy array returns view but not copy? I'm trying to get a submatrix of a numpy 2D array, and modify it. Sometimes I get a copy, which modification to it does not affect the original array:
In [650]: d=np.random.rand(5,5)

In [651]: may_share_memory(d, d[[0,1],:][:,[2,3]])
Out[651]: False

In [652]: d[[0,1],:][:,[2,3]]=2

In [653]: d
Out[653]:
array([[ 0.0648922 ,  0.41408311,  0.88024646,  0.22471181,  0.81811439],
       [ 0.32154096,  0.88349028,  0.30755883,  0.55301128,  0.61138144],
       [ 0.18398833,  0.40208368,  0.69888324,  0.93197147,  0.43538379],
       [ 0.55633382,  0.80531999,  0.71486132,  0.4186339 ,  0.76487239],
       [ 0.81193408,  0.4951559 ,  0.97713937,  0.33904998,  0.27660239]])

while sometimes it seems I get a view, although may_share_memory also returns False:
In [662]: d[np.ix_([0,1],[2,3])]=1

In [663]: d
Out[663]:
array([[ 0.0648922 ,  0.41408311,  1.        ,  1.        ,  0.81811439],
       [ 0.32154096,  0.88349028,  1.        ,  1.        ,  0.61138144],
       [ 0.18398833,  0.40208368,  0.69888324,  0.93197147,  0.43538379],
       [ 0.55633382,  0.80531999,  0.71486132,  0.4186339 ,  0.76487239],
       [ 0.81193408,  0.4951559 ,  0.97713937,  0.33904998,  0.27660239]])

In [664]: may_share_memory(d, d[np.ix_([0,1],[2,3])])
Out[664]: False

What more strange is, if assign that 'view' to a variable, it becomes a 'copy' (again, modification does not affect the original array):
In [658]: d2=d[np.ix_([0,1],[2,3])]

In [659]: may_share_memory(d,d2)
Out[659]: False

In [660]: d2+=1

In [661]: d
Out[661]:
array([[ 0.0648922 ,  0.41408311,  0.88024646,  0.22471181,  0.81811439],
       [ 0.32154096,  0.88349028,  0.30755883,  0.55301128,  0.61138144],
       [ 0.18398833,  0.40208368,  0.69888324,  0.93197147,  0.43538379],
       [ 0.55633382,  0.80531999,  0.71486132,  0.4186339 ,  0.76487239],
       [ 0.81193408,  0.4951559 ,  0.97713937,  0.33904998,  0.27660239]])

A: I agree; this is strange. Yet there is a logic to it.
Note that a sliced assignment is a special overloaded method in python. A sliced assignment doesn't create the view and then write to it; it writes to the array directly. You cant create a view to an ndarray of a[[2,0,1]], because you cant express this view as a strided array, which is the fundamental interface all numpy functions demand. But you can directly consume the indices and act on them. Arguably, for consistency, such a sliced assignment should make a modification to a copy; but where is the point in that, if you don't bind the newly created array to a new name?
It is somewhat awkward in python in general that assignment and sliced assignments are completely different beasts, which do completely different things. That is also what is at the root of this. sliced assignment and slicing on the right hand side call different functions, and are conceptually somewhat distinct. may_share_memory refers to the behavior of right hand side slicing, not sliced assignments.

A: What you're seeing is the difference between "fancy" indexing and normal indexing.
Also, for clarity, d[np.ix_([0,1],[2,3])] = 1 is not a view, it's an assignment. See @EelcoHoogendoorn's answer for more explanation in that regard.  The root of your confusion seems to be with __setitem__ vs __getitem__, which Eelco addresses, but I thought I'd add a few numpy-specific clarifications.
Any time you index with a sequence of coordinates (np.ix_ returns an array of indicies), it's "fancy" indexing and will always return a copy.
Anything you can do with slicing with always return a view.
For example:
In [1]: import numpy as np

In [2]: x = np.arange(10)

In [3]: y = x[3:5]

In [4]: z = x[[3, 4]]

In [5]: z[0] = 100

In [5]: x
Out[5]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [6]: y[0] = 100

In [7]: x
Out[7]: array([  0,   1,   2, 100,   4,   5,   6,   7,   8,   9])

The reason for this is that numpy arrays have to be semi-contiguous in memory (more precisely, they have to be able to be described by an offset, strides, and shape).
Any type of slicing can be described this way (even something like x[:, 3:100:5, None]).
An arbitrary sequence of coordinates (e.g. x[[1, 4, 5, 100]]) cannot be.
Therefore, numpy always returns a view if slicing is used and a copy if "fancy indexing" (a.k.a. using a sequence of indicies or a boolean mask) is used.
Assignments (e.g. x[blah] = y), however, will always modify a numpy array in-place.


text:
Q: Save an EAV attribute in Magento2 without touching the model, repository This can be done easily in magento1 with the saveAttribute() -method of Mage_Eav_Model_Entity_Abstract . For example, if you only need to save the is_active -flag for a category, you can do:
$data = new Varien_Object();
$data->setEntityId($categoryId);
$data->setIsActive(1);

Mage::getSingleton('catalog/category')
    ->getResource()
    ->saveAttribute($data, 'is_active');

How can i do it in magento2 without using CategoryRepositoryInterface, only update one attribute?


text:
Q: How to read an online XML file for currency rates in java I'm building a simple currency converter which needs to sue online rates. I found the following API from the European Central Bank to use:
http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
My problem is im struggling to implement it. Here is what i have so far after using a bunch of different sources to try and get this code together.
        try{
                URL url = new URL("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.parse(new InputSource(url.openStream()));

                doc.getDocumentElement().normalize();

                NodeList nodeList1 = doc.getElementsByTagName("Cube");
                for(int i = 0; i < nodeList1.getLength(); i++){

                    Node node = nodeList1.item(i);

                }
            }
            catch(Exception e){

            }

So what i thought is that this code would take down all the nodes which tart with "Cube", and contain the rates.
Anyone have an easier wya to pull down the rates from the API into an array in the order they appear on the XML as that's all I'm trying to do
Thanks

A: XPath is one way to answer this, since you just want to extract information from the XML and not change the XML. The structure of the XML suggests that you're looking for nodes that are Cube nodes, that are child of Cube which is also a child of Cube -- Cube nested three times, so extract nodes with an XPath compiled using this String: "//Cube/Cube/Cube".  This looks for nodes that have Cube nested 3 times located anywhere (the //) in the Document:
XPathExpression expr = xpath.compile("//Cube/Cube/Cube");

Then check the nodes for a "currency" attribute. If they have this, then they also have a "rate" attribute, and then extract this information.
NamedNodeMap attribs = node.getAttributes();
if (attribs.getLength() > 0) {
    Node currencyAttrib = attribs.getNamedItem(CURRENCY);
    if (currencyAttrib != null) {
        String currencyTxt = currencyAttrib.getNodeValue();
        String rateTxt = attribs.getNamedItem(RATE).getNodeValue();
        // ...
    }
}

Where CURRENCY = "currency" and RATE = "rate"
For example:
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.*;
import javax.xml.xpath.*;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class TestXPath {
    private static final String CURRENCY = "currency";
    private static final String CUBE_NODE = "//Cube/Cube/Cube";
    private static final String RATE = "rate";

    public static void main(String[] args) {
        List<CurrencyRate> currRateList = new ArrayList<>();
        DocumentBuilderFactory builderFactory =
                DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
            builder = builderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        Document document = null;
        String spec = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
        try {
            URL url = new URL(spec);
            InputStream is = url.openStream();
            document = builder.parse(is);

            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            String xPathString = CUBE_NODE;
            XPathExpression expr = xpath.compile(xPathString);
            NodeList nl = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
            for (int i = 0; i < nl.getLength(); i++) {
                Node node = nl.item(i);
                NamedNodeMap attribs = node.getAttributes();
                if (attribs.getLength() > 0) {
                    Node currencyAttrib = attribs.getNamedItem(CURRENCY);
                    if (currencyAttrib != null) {
                        String currencyTxt = currencyAttrib.getNodeValue();
                        String rateTxt = attribs.getNamedItem(RATE).getNodeValue();
                        currRateList.add(new CurrencyRate(currencyTxt, rateTxt));
                    }
                }
            }
        } catch (SAXException | IOException | XPathExpressionException e) {
            e.printStackTrace();
        }

        for (CurrencyRate currencyRate : currRateList) {
            System.out.println(currencyRate);
        }
    }
}

public class CurrencyRate {
    private String currency;
    private String rate; // ?double

    public CurrencyRate(String currency, String rate) {
        super();
        this.currency = currency;
        this.rate = rate;
    }

    public String getCurrency() {
        return currency;
    }
    public String getRate() {
        return rate;
    }

    @Override
    public String toString() {
        return "CurrencyRate [currency=" + currency + ", rate=" + rate + "]";
    }

    // equals, hashCode,....
}


text:
Q: Object is possibly null inside a callback I've got the following code:
             let ctx = ref.current.getContext("2d");
             if(ctx){
                ctx.lineWidth=1; // here is ok!
                ctx.strokeStyle=props.barStroke??"darkgray";// here is ok!
                ctx.fillStyle=props.barFill??"blue"; // here is ok!
                props.data.map((v,i)=>{
                    ctx.fillRect(i*10,0,10,props.height); //here it complain about ctx is possibly null!!
                    ctx.strokeRect(1*10,0,10,props.height);
                })

             }

I've checked ctx and so ctx.lineWidth works without errors, but inside the callback, it signals that the object could be possibly null. If I use ctx?.method code works anyway, so how can be ctx, checked for null outside the callback, became null inside it?
Here a link showing the problem.

A: As per this:
This is working as intended. The type checker knows that ctx is non-null at the time the callback function is created, but it doesn't know that ctx is non-null when the callback is called (because bar is a mutable property that could be changed before or between calls to the callback function).
The suggested way to do this is to copy ctx into a const local and then use that in the callback.

A: Try this :
      let ctx = ref.current.getContext("2d");
         if(ctx) {
            ctx.lineWidth=1; // here is ok!
            ctx.strokeStyle=props.barStroke??"darkgray";// here is ok!
            ctx.fillStyle=props.barFill??"blue"; // here is ok!
            props.data.map((v,i)=>{
                ctx.fillRect(i*10,0,10, v.height); //here it complain about ctx is possibly null!!
                ctx.strokeRect(1*10,0,10, v.height);
            })

         }

Looks like props is't predicted not ctx. Because ctx is refered like local variable already.

A: See Matthieu Riegler's answer for a description of why this is happening. Another solution is to use a for loop instead of a callback, since the callback (which TS isn't smart enough to determine is occurring exactly when it's being declared in the .map callback) is what's causing the issue:
let ctx = document.querySelector<HTMLCanvasElement>('foo')!.getContext("2d");
if (ctx) {
    const props = {
        data: ['x', 'y'],
        height: 10
    }
    for (const [i, v] of props.data.entries()) {
        ctx.fillRect(i * 10, 0, 10, props.height);
        ctx.strokeRect(1 * 10, 0, 10, props.height);
    }
}


text:
Q: Finding the most common point of intersection among plotted triangles I plotted a set of triangles using the code below:
A=[1, 1; 1, 5; 3, 9; 4, 2;9,9];
plot(A(:,1),A(:,2),'oc','LineWidth',2,'MarkerSize',5);
axis([0 10 0 10]);
grid on

for ii = 1:size(A, 1) - 1
    for jj = ii + 1:size(A, 1)
        line([A(ii, 1), A(jj, 1)], [A(ii, 2), A(jj, 2)])
    end
end

The problem is, i will like the plot to indicate the region with the highest number of intersections. In this particular code, the region is the black polygon (i had to indicate this region manually).

Please can anyone help out with this problem. Thanks

A: Here is a variant with a more graphical approach.

*

*Create a grid of points

*Check the number of triangles that a point
is inside

*Plot the points with highest number of intersecting
triangles

The code
% Create the combination of all points that make the triangles
% This could be used to plot the lines as well
N = size(A,1);
comb = [];
for i = 1:N-2
    for j = i+1:N-1
        comb = [comb; repmat([i j], N-j,1) (j+1:N)']; %#ok<AGROW>
    end
end
nComb = size(comb,1);

% Create a mesh grid
dg = 0.1; % Resolution - tune this!
gridEdge = [min(A);max(A)];
[X, Y] = meshgrid(gridEdge(1,1):dg:gridEdge(2,1), gridEdge(1,2):dg:gridEdge(2,2));

% Check if a point is inside each triangle
[isInside, onEdge] = deal(zeros(numel(X),nComb));
for i = 1:nComb
   [isInside(:,i), onEdge(:,i)] = inpolygon(X(:),Y(:),A(comb(i,:),1),A(comb(i,:),2));
end
% Remove points on edge
isInside = isInside - onEdge;

% Get index of points with most intersection
inTri = sum(isInside,2);
idx = find(inTri == max(inTri));

% Plot result
hold on
plot(X(idx),Y(idx),'.')
text(mean(X(idx)),mean(Y(:)),num2str(max(inTri)),'FontSize',20)


text:
Q: What is the meaning of "on the wrong lines" in this context? This is the context:

The universe is
  telling us it is simple. It is astonishingly simple. And yet here we are with thousands of physicists worrying
  about a multiverse of infinitely complex universes, which we can't see, and so on and so forth, I think it's
  great because they're all on the wrong lines. All these very, very smart people are distracted with
  a lot of confusing ideas.
Source: The origins of the universe: why is there something rather
  than nothing?
  (in the Annals of The New York Academy Of Sciences)

I searched the phrase on the internet and found nothing useful. What is the meaning of the bold part?

A: It means that the scientists are following the wrong lines of thought. A line of thought is a common idiom referring to the logic that someone followed to conclude something.
For example, if I told you that I enjoyed eating at McDonald's, your line of thought might look like this:
McDonald's serves primarily hamburgers. -> NegativeFriction likes eating at McDonald's -> NegativeFriction likes hamburgers.
It's also possible to draw an invalid conclusion from your line of thought, despite the fact that something appeared to make sense. To continue our McDonald's example:
McDonald's serves hamburgers -> Hamburgers are made from dead cows -> NegativeFriction likes eating hamburgers -> NegativeFriction hates cows and wants to kill them all
I do not hate cows and want to kill them all, so the above is an example of following the wrong line of thought.
Returning to the snippet that you posted-- the narrator is saying that he believes scientists are following incorrect logic when they consider what the universe is telling us. In short-- the narrator feels that these are the wrong sciences to apply to determine the meaning of the universe.

A:
... I think it's great because they're all on the wrong lines.

"They" here refers to the physicists.
From Cambridge, one definition of "line" is (Approach to subject)

a way of dealing with or thinking about something or someone

It is "a way of thinking about a particular subject (often written as a line of reasoning)"

We cannot agree with their line of reasoning.

In your case, the narrator  does not agree with their line of reasoning. The narrator is saying that the physicists (thousands of them) are all distracted with a lot of confusing ideas. The narrator believes that their line of reasoning (i.e., the way they are thinking about the multiverse of infinitely complex universes),  is wrong.
Note that "line of reasoning" in this specific context can also hint to the research and work these physicists are carrying out, which according to the narrator is wrong.
It is a little strange that the narrator says he thinks it is "great" that the physicists are pursuing a wrong line of thought/reasoning.


text:
Q: post php response into div using ajax not working Hi I am currently working on a project. When a user submits a form, it loads a response into a div rather than loading a new page. I have looked at other examples of an ajax form working along with PHP online but it didn't help me solving my problem. (I am rather new to this).
When I click submit, instead of posting the response onto the same page and sending an email to the chosen email address, it takes me to the php file and echo the response there, but does not send any email.
Can anyone see where this is going wrong?
Form code:
<form name="contactform" id="contact-form" action="mailer.php">

            <input type="text" class="textbox" name="name" value="Name" required="required" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Name';}">

            <input type="text" class="textbox" name="email" value="Email" required="required" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email';}">

            <textarea name="message" value="Message:" required="required" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Message';}">Message</textarea>

           <input type="submit" value="Send Now">

</form>

Javascript code:

PHP code: (my php is stored in a seperate file called mailer.php) I am trying to get the PHP $response variable to be posted back and placed into the response div.
<?php

    // Get the form fields and remove whitespace.
    $name = $_POST["name"];
    $email = $_POST["email"];
    $message = $_POST["message"];

    $to = "your-emailaddresshere@email.com";
    $subject = "New DPS Email from $name";

    // Build the email content.
    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";

    // Build the email headers.
    $email_headers = "From: $name <$email>";

    $mailed = (mail($to, $subject, $email_content, $email_headers));

    if( isset($_POST['ajax']) )
    $response = ($mailed) ? "1" : "0";
    else
    $response = ($mailed) ? "
Thank You! Your message has been sent.
" : "
Oops! Something went wrong and we couldn't send your message.
";

    echo $response;

?>

Thanks in advance for any help!

A: correct this and report what happened,
your form ID is "contact-form" and your JQ selector have been set for "contactform".
$("#contactform")

to
$("#contact-form")

A: Here is what you can do:
The Form Code
<form name="contactform" id="contact-form">

</form>

The javascript code (Use #contact-form and not #contactform)

Your PHP Code :
<?php

// Get the form fields and remove whitespace.
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];

$to = "your-emailaddresshere@email.com";
$subject = "New DPS Email from $name";

// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";

// Build the email headers.
$email_headers = "From: $name <$email>";

$mailed = mail($to, $subject, $email_content, $email_headers);

if( $mailed )
$response = json_encode(array("status"=>true,"msg"=>"
Thank You! Your message has been sent.
"));
else
$response = json_encode(array("status"=>false,"msg"=>"
Oops! Something went wrong and we couldn't send your message.
"));

echo $response;

?>

A: It is because you're calling post function, not ajax.
try this:
$.ajax({
   url: <your_url>,
   type:'GET',
   data: {'name': name_value, 'email' : email_value, 'message': message_value},
   success: function(data){
        yourdivcontent =  eval(data)
        $( "#response" ).html(yourdivcontent);
   },
   error: function(){
        console.log("error");
   }
})

In your php function, just encode your response in json
return json_encode(response);

A: echo json_encode($response) at end of php function


text:
Q: remove google text from google maps in android I want to remove text from google maps that appear bottom left corner of the map .
is this can be done or not ?
if done then how can i do that

A: AFAIK you are not allowed to do that. You can take a look at Brand Features License section in here

In using Google Brand Features, you will not:
remove, distort, or alter any element of a Google Brand Feature
(including squeezing, stretching, inverting, or discoloring).

A: It cannot be done: http://www.google.com/permissions/geoguidelines.html

Can you give me permission to show your content without attribution,
  or put the attribution at the end of my book/movie/TV show?
Without exception, we require attribution when Content is shown.
  Please do not ask to negotiate this requirement. If you are unwilling
  to meet our attribution requirements, contact our data provider(s)
  directly to inquire about purchasing the rights to the Content
  directly. See our attribution page for more information.


text:
Q: Powershell script: pull data json data, check value (date) of a object, if older than x days, execute function {
  "items": [
    {
      "AlertID": 4369,
      "Code": 52,
      "Source": "AlphaAgentSelfMonitoring",
      "Title": "CPU-Temperatur ( (CPU Core #1), (CPU Core #2) und (CPU Package))",
      "Severity": "Critical",
      "Created": "2022-02-15T07:32:45Z",
      "SnoozedEndDate": null,
      "DeviceGuid": "*",
      "AdditionalInfo": null,
      "Archived": true,
      "AlertCategoryID": "Hardware",
      "ArchivedDate": "2022-02-15T07:55:38Z",
      "TicketID": null,
      "AlertMessage": "*",
      "DeviceName": "SERVER",
      "CustomerID": 23,
      "CustomerName": "*",
      "FolderID": null,
      "PollingCyclesCount": null
    },
    {
      "AlertID": 4368,
      "Code": 12,
      "Source": "AgentsOnlineStatusCheckLoop",
      "Title": "Machine status unknown",
      "Severity": "Critical",
      "Created": "2022-02-15T05:27:03Z",
      "SnoozedEndDate": null,
      "DeviceGuid": "*",
      "AdditionalInfo": null,
      "Archived": true,
      "AlertCategoryID": "Availability",
      "ArchivedDate": "*",
      "TicketID": null,
      "AlertMessage": "*",
      "DeviceName": "*",
      "CustomerID": 23,
      "CustomerName": "*",
      "FolderID": null,
      "PollingCyclesCount": null
    },

Hi,
I can pull this json alert data like this from Atera API. If I want to delete this alert I just need the AlertID of said alert.
I know how to pull data, however I need some kind of loop that would check the date of alert. Basically:

*

*go through json data

*check Created value

*if value > 3 days

*

*then attach value of AlertID to url and invoke-restmethod, else

*nothing

If anyone could help with this or tell me where to look for more specific instructions in powershell it would be great, thank you very much for reading.
Update:
This is the working code. It could be cleaner, but it is what it is. It throws some errors but it works as intended:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$Headers = @{
    "accept" = "application/json"
    "X-API-KEY" = "somekey"
  }
$Uri = "https://app.atera.com/api/v3/alerts?alertStatus=Open"
$alerts = Invoke-RestMethod -Uri $Uri -Method Get -Headers $Headers
$refDate = (Get-Date).AddDays(3).Date
$alerts.items | Where-Object { [datetime]$_.Created -lt $refDate } | ForEach-Object {
    $AID = $_.AlertID
    $DELETEURI = "https://app.atera.com/api/v3/alerts/" + $AID
    $senddelete = Invoke-RestMethod -Uri $DELETEURI -Method Delete -Headers $Headers

}

A: Using your example (only I have changed the Created dates in order to see the output), you can simply do this:
$json = @"
{
  "items": [
    {
      "AlertID": 4369,
      "Code": 52,
      "Source": "AlphaAgentSelfMonitoring",
      "Title": "CPU-Temperatur ( (CPU Core #1), (CPU Core #2) und (CPU Package))",
      "Severity": "Critical",
      "Created": "2022-02-11T07:32:45Z",
      "SnoozedEndDate": null,
      "DeviceGuid": "*",
      "AdditionalInfo": null,
      "Archived": true,
      "AlertCategoryID": "Hardware",
      "ArchivedDate": "2022-02-15T07:55:38Z",
      "TicketID": null,
      "AlertMessage": "*",
      "DeviceName": "SERVER",
      "CustomerID": 23,
      "CustomerName": "*",
      "FolderID": null,
      "PollingCyclesCount": null
    },
    {
      "AlertID": 4368,
      "Code": 12,
      "Source": "AgentsOnlineStatusCheckLoop",
      "Title": "Machine status unknown",
      "Severity": "Critical",
      "Created": "2022-02-10T05:27:03Z",
      "SnoozedEndDate": null,
      "DeviceGuid": "*",
      "AdditionalInfo": null,
      "Archived": true,
      "AlertCategoryID": "Availability",
      "ArchivedDate": "*",
      "TicketID": null,
      "AlertMessage": "*",
      "DeviceName": "*",
      "CustomerID": 23,
      "CustomerName": "*",
      "FolderID": null,
      "PollingCyclesCount": null
    }
    ]
}
"@ | ConvertFrom-Json

# 3 days ago, set to midnight
$refDate = (Get-Date).AddDays(-3).Date
# now filter on items where the date in the 'Created' property is older than the reference date
$json.items | Where-Object { [datetime]$_.Created -lt $refDate } | ForEach-Object {
    # here you combine the $_.AlertID with your URL and perform the Invoke-RestMethod
    # for demo, just output the ID
    $_.AlertID
}

Output for this JSON:
4369
4368


text:
Q: Adding a widget collapses form I have a script like this:
#User model
about_text = models.TextField(max_length=1000, null=True, blank=True, validators=(MaxLengthValidator(1000),))

#forms.py
class SettingsUpdateForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('about_text')
        labels = {
            'about_text': '',
        }

This works and gives a nice big field to write a text.

Problem: If I add
widgets = {
            'about_text': forms.TextInput(attrs={'placeholder': 'Describe yourself!'}),
        }

the field collapses to a singleline field.

How do I keep the field big and have a placeholder?

A: Okay, I found the error.
Apparently, a CharField translates to a TextInput and a TextField translates to a TextArea...
so changing TextInput to TextArea did the trick.


text:
Q: Will it cause any issue to perform more than one page.evaluate in puppeteer for multiple DOM manipulation? Currently, when I tried to perform two page.evaluate in puppeteer in order to execute two different kind of DOM manipulation, it just not really running the 2nd one at all.
Is there way I can run DOM manipulation in two different .evaluate or there is different way I can do it?
Thanks


text:
Q: Is it possible to use a push notification with no local app I'd have a requirement, for a cloud service (C# .NET) to send a text message (eg a calendar reminder) to a subscribed user, on their mobile device (initially for iOS devices, then Android and WP7 later).
Is there a way of doing this without a local app on their device?
Found this interesting article regarding notifications methods on mobile devices, and Apples APN docs, but it appears you need a local app.
However, with APN's, it appears that the OS displays the message for you even when the app is not running - so I thought it might be possible (although I did note to register for APN's you need a cert for your app).
Maybe there is some other technique?
Thanks
Tim

A: Even if it is possible, it is probably Apple's internal functionality, as they wouldn't want anybody to be able to spam their customers.
Local app in this case acts as an API key. Apple knows who is sending push notifications to user's devices, because they are sent through your app signed with your certificate. So they can potentially punish you, if you abuse push notification functionality.
When you work with APN, first you need to obtain device's token, which is sent to your servers when user agrees to receive push notifications from your app. Then using that token you can send this user a push notification. Without local app you have no way of obtaining this token, so you won't be able to send any user a push message.
TL;DR It is not possible

A: Probably not relevant to your use case scenario... it is possible to send an Apple Push Notification to an iOS device by installing a device settings management Enrollment configuration profile instead of an app.
This is how Apple's Mobile Device Manager (MDM) system works.


text:
Q: Redux reducers -- changing deeply-nested state I'm trying to wrap my head around how to change deeply-nested state in redux. It makes sense to me to combine reducers and change first-level properties of the state for those pieces. Where I'm not so clear is on how to change the state of a deeply-nested property.
Let's pretend that I have a shopping cart app. Below is my state:
{
    cart: {
      items: []
    },
    account: {
      amountLeft: 100,
      discounts: {
        redeemed: [],
        coupons: {
          buyOneGetOne: false
        }
      }
    }
}

When a user enters in a code, let's say they can redeem the "buyOneGetOne" coupon and that value should become true.
I have a reducer for cart and another for account. For a first-level property (like if I was clearing the cart's items), I would just do the following in my reducer:
case 'EMPTY_CART':
  return Object.assign({}, state, {items: []});

For changing buyOneGetOne, however, it seems like I would first need to do an Object.assign on coupons (because buyOneGetOne was modified), then doing an Object.assign on discounts (because I had modified coupons), and then finally emitting the action so the reducer could do Object.assign on the account (because discounts has now changed). This seems really complicated and easy to do wrong, though, which leads me to believe there must be a better way.
Am I going about this all wrong? It seems like reducers are only used to modify the root level properties of the state (like cart and account) and that I shouldn't have a reducer that touches state inside the account (like a discounts reducer), because account already has a reducer. But when I only want to change one property far down the state tree, it gets complex to merge every object from that change all the way up the object chain to the child of the root...
Can you/should you have reducers inside of reducers, like in this case have a discounts reducer?

A: you should nest combinedReducers for each level deep

A: You can definitely have reducers inside of reducers; in fact, the redux demo app does this: http://redux.js.org/docs/basics/Reducers.html.
For example, you might make a nested reducer called `discounts':
function discounts(state, action) {
    switch (action.type) {
        case ADD_DISCOUNT:
            return state.concat([action.payload]);

        // etc etc
    }
}

And then make use of this reducer in your account reducer:
function account(state, action) {
    switch (action.type) {
        case ADD_DISCOUNT:
            return {
                ...state,
                discounts: discounts(state.discounts, action)
            };

         // etc etc
    }
}

To learn more, check out the egghead.io redux series by Dan himself, specifically the reducer composition video!

A: Yes, separating those reducers is a right thing. Actually, if you are afraid that some of those actions will require change of other reducer, you can either react to other constant, or just dispatch another action.
I've created a library to address this issue -- to allow easy composition, and to avoid verbose syntax, along with merging result.
So, your example will look like that:
import { createTile, createSyncTile } from 'redux-tiles';

const cartItems = createSyncTile({
  type: ['account', 'cart'],
  fn: ({ params }) => ({ items: params.items })
});

const coupons = createSyncTile({
  type: ['account', 'coupons'],
  fn: ({ params }) => params,
});

const reedemedCoupons = createSyncTile({
  type: ['account', 'reedemedCoupons'],
  fn: ({ params }) => params.coupons
});

const account = createTile({
  type: ['account', 'info'],
  fn: ({ api }) => api.get('/client/info')
});

Using this strategy each component is atomic, and you can easily create new and dispatch others, without affecting others, it makes it easier to refactor and remove some functionality in the future, when your "tiles" are following single responsibility principle.


text:
Q: Civ 6: RnF emergency but where? In Civ 6 Rise and Fall, a religious emergency has been declared and I am game but where is the city...? I can't find it :/ is there a UI feature leading me?

A: The Emergencies should tell you the Target City within the card that appears. In the below image the Target is St Petersburg and the Members must prevent it from following the specified Religion for 16 turns.
There are essentially two scenarios that could need to be played out:

*

*The city is currently following a different religion then the goal of the Emergency. Since this emergency will last for only 30 turns you need to change the religion within the city in at least 14 turns. Also if waiting for the last minute like that you must ensure that the religion does not swap back during the rest of the Emergency. Generally in this scenario the city has been flipped and you must flip it back.

*The city is currently following the religion that is the goal of the Emergency. The strategy here is the opposite from above, the only goal is to keep the city following that religion for the first 16 turns, then the Emergency will have to end. Generally in this scenario a city has been flipped and you must prevent it from flipping back.

Note: I found this image during a Google search and I do not take credit for its creation.


text:
Q: JsonIgnore for Scala method with default parameters does not work as expected I would like to mark the default method generated by scala compiler to be ignored from being serialized.
@JsonIgnore def getSum(a: Int, b: Int = 2): Int = a + b
compiler creates two methods:
def getSum(a: Int, b: Int): Int = a.+(b);
<synthetic> def getSum$default$2(): Int = 2; (default value at position 2)
The first method getSum does not get serialized as the JsonIgnore is applied on it, but the new default parm method generated is serialized by jackson, how to tell Jackson to not serialize it?
Example:
  import com.fasterxml.jackson.annotation.JsonIgnore
  import com.fasterxml.jackson.databind.ObjectMapper;

  case class A(id: Int) {
    @JsonIgnore def getSum(a: Int, b: Int = 2): Int = a + b
  }

  @Test
  def test(): Unit = {
    val a = A(5)
    val mapper = new ObjectMapper()
    println(mapper.writeValueAsString(a))
  }

output: {"id":5,"sum$default$2":2}

A: I believe this is a bug, but there are workarounds:
Explicitly ignore the generated property
The @JsonIgnoreProperties annotation can be used at the class level.
@JsonIgnoreProperties(Array("sum$default$2"))
case class A(id: Int) {
  def getSum(a: Int, b: Int = 2): Int = a + b
}

Rename the method
It's detected as a property because it matches the JavaBeans getter convention. If the method name can be changed to remove the get prefix, it won't be treated as a property by Jackson:
case class A(id: Int) {
  def calculateSum(a: Int, b: Int = 2): Int = a + b
}

Avoid default arguments
Of course, another option is to avoid the use of default arguments entirely in favour of method overloading:
case class A(id: Int) {
  def getSum(a: Int, b: Int): Int = a + b
  def getSum(a: Int): Int = getSum(a, 2)
}

These examples are all demonstrated in this Scastie: https://scastie.scala-lang.org/TimMoore/werEmJF9S7ip4QP5sT73CQ/39
All of these options produce this JSON:
{"id":5}


text:
Q: Hibernate: update table query is not working I have a query
     public void saveReportId(BigDecimal reportId) {
               entityManager.createQuery("UPDATE ReportEntity r set r.report_id = reportId WHERE s.phase = :phase")
                       .setParameter("reportId", reportId)
                       .setParameter("phase", ReportStatus.NEW.getValue())
                       .executeUpdate();
      }

But instead of populating the table with value of the reportId that I pass in the argument I've got an error :
Problem compiling - The state field cannot be resolved.

A: Missing :reportId and also replace s.phase to r.phase . Just update it :
entityManager.createQuery("update ReportEntity r set r.report_id = :reportId where r.phase = :phase")
                           .setParameter("reportId", reportId)
                           .setParameter("phase", ReportStatus.NEW.getValue())
                           .executeUpdate();

Hope this helps :)

A: In your named parameter query, you may be missed to follow the rule i.e ... condition= :paramName.
So, in your case, just take care of your reportId parameter. Just change your second like this:
entityManager.createQuery("UPDATE ReportEntity r set r.report_id = :reportId WHERE s.phase = :phase")


text:
Q: What is the relative frequency of English graphemes and/or phonemes in printed UK English texts/spoken English? Having reviewed freely accessible research I found references to The Grapheme-Phoneme Problem in Reading and other spelling studies and have sought other frequency tables that describe the relative frequency of the letters (graphemes) used to represent the sounds (phonemes).
There are available online resources for frequency tables of words in spoken language and printed texts, but not as readily available are comparable tables for the graphemes and/or phonemes used in UK English.
As a primary school teacher, I am curious as to whether it would be worthwhile focussing on teaching children those graphemes that occur more frequently, as is done with high frequency sight words.  This question may be of use to those professionals that support children with decoding when reading and using phonics knowledge when spelling.
I've done my own diagnostics for spelling errors but I'm no statistician and so am seeking help from those that may have access to relevant publications and studies.

A: I found two resources focused on British spelling that deal with frequency.
The Dictionary of the British English Spelling System (2015) is available through the publisher in PDF for free. It directly tackles the grapheme/phoneme problem and diagrams the possible grapheme combinations for each phoneme. While there isn't a simple list of graphemes in order of frequency, chapter 3 gives frequencies of graphemes for each phoneme in consonants, and chapter 5 does the same for vowels. Meanwhile, chapter 8 gives comprehensive lists of graphemes/phonemes, and Appendix B ("Pedagogically selected lists of phoneme-grapheme and grapheme-phoneme correspondences") is both more accessible and groups phonemes and graphemes according to its "basic" (read: most common) form and its "other" variants.
Then there's this article: Gontijo, P.F.D. et. al., "Grapheme-phoneme probabilities in British English." Behavior Research Methods, Instruments, and Computers 35.1 (2003): 136-157. The article is pretty technical, but its appendix is worth a sit-down over tea: for each grapheme they generated the probability that it would represent a given phoneme. If you just look at the word that it uses as an example, it'll give you a good idea of how each grapheme is used. For instance, "f" is used to represent /f/ about 2/3rds of the time. (The other third of the time it represents /v/, as in "of.")
I hope those help.

A: From various sources I could find and doing my own calculations, 41% of the letters in British English texts are vowel letters (counting Y in words like "bay" but not in "yard"). The large number of silent vowel letters means that counting phonemes reveal that only 39% of them are vowels. That number appears to be closer to 37% in American English, due to the abundance or rhotics.


text:
Q: Fancybox multiple image gallery within 1 link click I'm trying to make a simple 2 image gallery using JQuery Fancybox.
Upon clicking the small thumbnail image, it loads up a different, larger image, after a short while, i'd like to know how to fade/switch to another DIFFERENT image, and then possibly loop back to the original image after x amount of time. Also, how would I link to these 2 images, that would supposedly be in an array?

Is how the image is linked at the moment in html.

<link rel="stylesheet" type="text/css" href="fancybox/jquery.fancybox-1.3.4.css" media="screen">

Is the current script for fancybox definitions. (Bare in mind I have a video displayed through fancybox, which is why the features are swf based.)

A: Here is an example and working fiddle http://jsfiddle.net/AwRk2/1/  Ver 1.3.4
HTML code for 3 photos that will cycle through. Just use 2 instead of 3 photos.

Then this is the fancybox code used to do it.
$("a[rel=example_group]").fancybox({
        'transitionIn'      : 'none',
        'transitionOut'     : 'none',
        'titlePosition'     : 'over',
        'cyclic'            : true,
        'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
            return 'Image ' +  (currentIndex + 1) + ' / ' + currentArray.length + ' ' + title + '';
        }
    });


text:
Q: Sum of all powers of imaginary unit $\pmb i$ So I have a home assignment and one of the questions is one that I know the solution of, but can't quite properly prove it using math terms.
The question goes as follows :
Let $\pmb S$ = $\{$ $\pmb i$ $+$ $\pmb i^2$ $+$ $\pmb i^3$ $+$ $\dots$ $+$ $\pmb i^n$ $\}$ where $n$ $\in$ $\mathbb N$.
Prove that $\pmb S$ $^4$ $\in$ $\mathbb R$.
Now I know that :
$\pmb i^{4n}$ $\pmb =$ $\pmb 1$
$\pmb i^{4n+1}$ $\pmb =$ $\pmb i$
$\pmb i^{4n+2}$ $\pmb =$ $\pmb -$ $\pmb 1$
$\pmb i^{4n+3}$ $\pmb =$ $\pmb -$ $\pmb i$
And that no matter what $n$ $\in$ $\mathbb N$ is chosen, I can always divide $\pmb i^{n}$ by the closest $\pmb i^{4n}$ and then be left with worst case scenario $\bigl(i^{3})^4$, but as pointed above any $\pmb i^{4n}$ will be equal to $\pmb 1$ $\in$ $\mathbb R$. It proves what I want to say, but it's kind of a mess since I believe there's a way to start from the right side and get to the left or vice versa.
If anyone could give me any pointers it would be greatly appreciated.
Thanks!

A: If $S_n=i+i^2+\cdots+i^n$, then, since $1+i+i^2+i^3=0$,$$S_n=\begin{cases}0&\text{ if $n$ is of the form }4k\\i^n&\text{ if $n$ is of the form }4k+1\\i^n(1+i)&\text{ if $n$ is of the form }4k+2\\i^{n+1}&\text{ if $n$ is of the form $4k+3$}\end{cases}$$and each of the numbers $0$, $i^n$, $i^n(1+i)$, and $i^{n+1}$ is such that its fourth power is real.


text:
Q: How do I make a grouping that includes only values from the list? I have a table presented below.
+------+-------+--------------+------------------------------+------+
| good | store | date_id      | map_dates                    | sale |
+------+-------+--------------+------------------------------+------+
| 1    | 2     | '2019-01-01' | ['2018-07-08']               | 10   |
+------+-------+--------------+------------------------------+------+
| 1    | 2     | '2019-05-06' | ['2019-01-01', '2018-07-08'] | 5    |
+------+-------+--------------+------------------------------+------+
| 5    | 4     | '2019-10-12' | ['2018-12-01']               | 24   |
+------+-------+--------------+------------------------------+------+
| 1    | 2     | '2018-07-08' | []                           | 3    |
+------+-------+--------------+------------------------------+------+
| 5    | 4     | '2018-12-01' | []                           | 15   |
+------+-------+--------------+------------------------------+------+

I want to group by columns good, store, and include only the dates specified in the map_dates column in the result. For example:
+------+-------+--------------+----------+
| good | store | date_id      | sum_sale |
+------+-------+--------------+----------+
| 1    | 2     | '2019-01-01' | 3        |
+------+-------+--------------+----------+
| 1    | 2     | '2019-05-06' | 13       |
+------+-------+--------------+----------+
| 5    | 4     | '2019-10-12' | 15       |
+------+-------+--------------+----------+

How can I do this without using a loop?

A: First we explode, then we match our values by an inner merge on good, store, map_dates and date_id. Finally we GroupBy.sum:
dfn = df.explode('map_dates')
dfn = dfn.merge(dfn,
                left_on=['good', 'store', 'map_dates'],
                right_on=['good', 'store', 'date_id'],
                suffixes=['', '_sum'])

dfn = dfn.groupby(['good', 'store', 'date_id'])['sale_sum'].sum().reset_index(

   good  store     date_id  sale_sum
0     1      2  2019-01-01         3
1     1      2  2019-05-06        13
2     5      4  2019-10-12        15


text:
Q: "Rule 30" in the infinite setting This question tries to get right what went wrong in an earlier question.
Let $\{0,1\}^\mathbb{Z}$ denote the set of all functions $x:\mathbb{Z}\to \{0,1\}$. Let $+$ denote addition modulo $2$ on $\{0,1\}$ (corresponding to ${\sf XOR}$ in computer science).
Define a function $f:\{0,1\}^\mathbb{Z} \to \{0,1\}^\mathbb{Z}$ by $x \mapsto f(x)$ where $f(x):\mathbb{Z}\to\{0,1\}$ is defined by $$f(x)(i) = x(i-1) \; + \;\max\{x(i), x(i+1)\}\ \text{ for all }i\in \mathbb{Z}.$$ Inductively define $f^{(0)}(x) = x$, and $f^{(n+1)}(x) = f(f^{(n)}(x))$ for all integers $n\geq 0$.
Question. For what integers $n>1$ is there $x\in \{0,1\}^\mathbb{Z}$ such that $f^{(n)}(x) = x$ but $f^{(k)}(x) \neq x$ for all integers $k\geq 1$ with $k<n$?

A: A partial answer: Table A.1 of https://core.ac.uk/download/pdf/236376428.pdf lists the number of preperiodic points with minimal preperiod $q$ and minimal period $p$ with small $q$ and $p$ for various elementary cellular automata. For example, for Rule 30 and for $q=0$, $p=1,2,3,4,5,6$ these cardinalities are $3,0,12,28,45,84$ and in particular there does not exist a configuration with minimal period $2$.


text:
Q: Autocomplete in windows application How can i select value in textbox character by character Like HDPOS Autocomplete textbox
I tried
In Page Load
private void loadproductName()
{
    DataTable dt = _poshelper.getproductName("Bill_Select_ProductName");
    if (dt.Rows.Count != 0)
    {
        string[] postSource = dt
                .AsEnumerable()
                .Select<System.Data.DataRow, String>(x => x.Field<String>("UniqueName"))
                .ToArray();

        var source = new AutoCompleteStringCollection();
        source.AddRange(postSource);
        txtItemName.AutoCompleteCustomSource = source;
    }
}

In Leave
private void txtItemName_Leave(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(txtItemName.Text))
    {
        DataSet ds1 = _poshelper.getproductNameExistWhileLeave(txtItemName.Text);
        if (ds1.Tables[0].Rows.Count == 0)
        {
            txtItemName.Text = "";
            txtItemName.Focus();
        }
        else
        {
            loadLeave(ds1);
            txtItemName.Focus();
        }
    }
}

I need to
If i delete a character using backspace it delete permanently

I need like 2 nd image if i delete mean i need that containt remain in textbox

Update
more clarification, from comments

The String in the textbox it should not be deleted if i press back space Key. Instead it should select each character.Every time i press backspace

A: Here I'm suggesting changes to make your textbox carry following behavior.
When you don't want "appended suggestion" text (as shown in first image) to be gone when you type backspace in text box,
you can do it these steps

*

*Get Current Textbox text (removed last character as we have back spaced lastly)

*Clear Text's Text

*Send Text taken text back to textbox

do following change in your code
private void loadproductName()
{
  DataTable dt = _poshelper.getproductName("Bill_Select_ProductName");
  if (dt.Rows.Count != 0)
  {
    string[] postSource = dt
            .AsEnumerable()
            .Select<System.Data.DataRow, String>(x => x.Field<String>("UniqueName"))
            .ToArray();

    var source = new AutoCompleteStringCollection();
    source.AddRange(postSource);
    txtItemName.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
    txtItemName.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
    txtItemName.AutoCompleteCustomSource = source;
  }
}

I'm not sure what you are doing in Leave Event. But you can add textBox's KeyUp event, and add code like below in that event.
private void txtItemName_KeyUp(object sender, KeyEventArgs e)
{
    // track for backspace
    if (e.KeyCode == Keys.Back)
    {
        if (txtItemName.Text != "")
        {
            string text = txtItemName.Text.Substring(0, txtItemName.Text.Count() - 1);
            txtItemName.Text = "";
            txtItemName.Focus();
            SendKeys.Send(text);
        }
    }
}


text:
Q: Deleted public_html without reason I had a problem today in the morning which I am still trying to figure it out, so it does not happen again.
Somehow a lot of files from public_html got deleted, except one folder. I did not delete anything. Basically the whole website went missing.
How can I check logs on what happened to these files?
All I did today was yum update and then upgrade cyberpanel to the newest version, I hope this was not the problem.
Thank you


text:
Q: Multiple routers in ember.js? In my app I have a requirement for a functional area to open in an overlay such that it sits on top of the current route which could be almost any other route in the app.
This functional area will have it's own routes as it contains at least a master-detail view.
What is the current best practice for dealing with this situation?
Is it possible to have top-level routes that don't tear down the current route/views when entering them? If not and it's necessary to have the ApplicationController (or similar) handle the globally accessible overlay, what's the best way to achieve router-like functionality for that area?

A: I think you got confused by open in overlay requirement and you are trying to solve non-existing problem.
Opening messaging functionality in another page in your app or opening it as overlay on top of the app is just a design thing that should be handled by CSS and existing app router. Just create messaging route, controller, etc.
You didn't say that, but in case you want to boot separate application there, the best approach is to open it in the iframe. New app, new lifecycle, etc. Again, how you display it inside another app is just matter of CSS.


text:
Q: SSL handshake error in a JavaRMI application I'm having some trouble with the very beginning of SSL handshake in a JavaRMI application.
My application works well with the standard RMI sockets but it doesn't complete the handshake if I change the default sockets to SSL sockets following this guide: https://blogs.oracle.com/lmalventosa/entry/using_the_ssl_tls_based
So, I changed the constructor of my Activatable Server from
public MyActivatableServer(ActivationID id, MarshalledObject<MyType> obj)
        throws RemoteException
{
    // Some code ...
    // int port = ...
    // Other code ...

    Activatable.exportObject(this, id, port);
}

to
public MyActivatableServer(ActivationID id, MarshalledObject<MyType> obj)
        throws RemoteException
{
    // Some code ...
    // int port = ...
    // Other code ...

    Activatable.exportObject(this, id, port, new SslRMIClientSocketFactory(),
        new SslRMIServerSocketFactory());
}

Then I created a Keystore and a Truststore following this guide: http://docs.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#CreateKeystore
At this point on the server-side I have these files:

*

*keystore ( with password: "password" );

*truststore ( with password: "trustword" );

*user.cer ( the self-signed certificate ).

And I copied trustore and user.cer on client-side.
Finally I added these properties to the JVM which launch the Activatable Server:

*

*-Djavax.net.ssl.keyStore=keystore

*-Djavax.net.ssl.keyStorePassword=password

and on the Client JVM I added:

*

*-Djavax.net.ssl.trustStore=truststore

*-Djavax.net.ssl.trustStorePassword=trustword

*-Djavax.net.debug=ssl

This is the complet output of the ssl debug: http://pastebin.com/sxbLhTnF
I can't understand why the client receives an Alert after the "ClientHello":
*** ClientHello, TLSv1
RandomCookie:  GMT: 1410959810 bytes = { 20, 172, 181, 158, 246, 172, 183, 30, 232, 42, 80, 36, 77, 5, 67, 56, 30, 191, 170, 142, 14, 2, 113, 241, 183, 154, 213, 24 }
Session ID:  {}
Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
Compression Methods:  { 0 }
Extension elliptic_curves, curve names: {secp256r1, sect163k1, sect163r2, secp192r1, secp224r1, sect233k1, sect233r1, sect283k1, sect283r1, secp384r1, sect409k1, sect409r1, secp521r1, sect571k1, sect571r1, secp160k1, secp160r1, secp160r2, sect163r1, secp192k1, sect193r1, sect193r2, secp224k1, sect239k1, secp256k1}
Extension ec_point_formats, formats: [uncompressed]
***
main, WRITE: TLSv1 Handshake, length = 149
main, READ: TLSv1 Alert, length = 2
main, RECV TLSv1 ALERT:  fatal, handshake_failure
main, called closeSocket()
main, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

A:
Finally I added these properties to the JVM which launch the Activatable Server:

-Djavax.net.ssl.keyStore=keystore
-Djavax.net.ssl.keyStorePassword=password

You need to define those properties in the ActivationGroupDesc in your setup program.


text:
Q: How to add some extra fields to the page in django-cms? (in django admin panel) I would like to add some extra fields to pages in django-cms (in django admin panel). How do this in the simplest way?

A: There is an official way to extend the page & title models, I highly recommend this official documentation:

*

*Extending the page & title models from docs.django-cms.org

I also highly recommend using a placeholder if you can, since writing this answer, I now prefer creating a placeholder for the use case of cover images. (You can even get just the image URL in your template if you want to).
Summary of the link:

*

*Create a subclass of PageExtension in your models.py file and register it:
class IconExtension(PageExtension):
    image = models.ImageField(upload_to='icons')

extension_pool.register(IconExtension)

*Create also a subclass of PageExtensionAdmin in your admin.py file and register it:
class IconExtensionAdmin(PageExtensionAdmin):
    pass

admin.site.register(IconExtension, IconExtensionAdmin)

*Finally, to make it accessible from the toolbar, create a subclass of ExtensionToolbar in cms_toolbars.py and register it:
@toolbar_pool.register
class IconExtensionToolbar(ExtensionToolbar):
    model = IconExtension

    def populate(self):
        current_page_menu = self._setup_extension_toolbar()
        if current_page_menu:
            page_extension, url = self.get_page_extension_admin()
            if url:
                current_page_menu.add_modal_item(_('Page Icon'), url=url,
                    disabled=not self.toolbar.edit_mode)

The official documentation goes into more detail and explanation.
There is an open GitHub issue on adding support for adding elements to the normal and advanced "page settings" dialogues.

A: There's also a way to do this without using an inline, and having the fields anywhere on the Page form.  For example, I have a custom setting for "color scheme" that I wanted to be under the "Basic Settings" fieldset. This can be done by overriding the ModelForm and the ModelAdmin's fieldsets. Also, I opted for a OneToOne field instead of a ForeignKey, for simplicity's sake.
models.py:

from django.db import models
from cms.models.pagemodel import Page
from django.conf import settings

class PageCustomSettings(models.Model):
    page = models.OneToOneField(Page, editable=False,
                                related_name='custom_settings')
    color_scheme = models.CharField(blank=True, choices=settings.COLOR_SCHEMES,
                                    max_length=20)

admin.py:

from django import forms
from django.conf import settings
from django.contrib import admin
from cms.admin.pageadmin import PageAdmin, PageForm
from cms.models.pagemodel import Page
from web.models import PageCustomSettings

color_scheme_choices = (('', '---------'),) + settings.COLOR_SCHEMES

class CustomPageForm(PageForm):
    color_scheme = forms.ChoiceField(choices=color_scheme_choices,
                                     required=False)

    def __init__(self, *args, **kwargs):
        # make sure that when we're changing a current instance, to set the
        # initial values for our custom fields
        obj = kwargs.get('instance')
        if obj:
            try:
                opts = obj.custom_settings
                kwargs['initial'] = {
                    'color_scheme': opts.color_scheme
                }
            except PageCustomSettings.DoesNotExist:
                pass
        super(CustomPageForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        # set the custom field values when saving the form
        obj = super(CustomPageForm, self).save(commit)
        try:
            opts = PageCustomSettings.objects.get(page=obj)
        except PageCustomSettings.DoesNotExist:
            opts = PageCustomSettings(page=obj)
        opts.color_scheme = self.cleaned_data['color_scheme']
        opts.save()
        return obj

PageAdmin.form = CustomPageForm
PageAdmin.fieldsets[1][1]['fields'] += ['color_scheme']

admin.site.unregister(Page)
admin.site.register(Page, PageAdmin)

A: I've got here via Google and the answers got me on the right track for Django CMS 3 Beta. To extend the page model and hook your extension into the toolbar, you can follow along the official documentation:
http://django-cms.readthedocs.org/en/latest/how_to/extending_page_title.html
Access value in template
{{ request.current_page.<your_model_class_name_in_lowercase>.<field_name> }}

For example, I extended the page model with this model:
from django.db import models

from cms.extensions import PageExtension
from cms.extensions.extension_pool import extension_pool

class ShowDefaultHeaderExtension(PageExtension):
    show_header = models.BooleanField(default=True)

extension_pool.register(ShowDefaultHeaderExtension)

To access its values in the template:
{{ request.current_page.showdefaultheaderextension.show_header }}

A: Since I dont have enough reputation I cannot comment on Timmy O'Mahony's Post directly. However I want to note that the proposed solution of adding a StackedInline Object to the PageAdmin.inlines list does not work any more as supposed.
I'm working with Djangocms 3.3 and somewhere between Timmy O'Mahony's version any mine the authors changed the semantic of the inline List. It's content is now shown in the Permissions Menu for that specific page (including possibly added futher StackedInline or TabularInline items).

A: Create a new app (called extended_cms or something) and in models.py create the following:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.models.pagemodel import Page

class ExtendedPage(models.Model):
    page = models.ForeignKey(Page, unique=True, verbose_name=_("Page"), editable=False, related_name='extended_fields')
    my_extra_field = models.CharField(...)

then create an admin.py:
from models import ExtendedPage
from cms.admin.pageadmin import PageAdmin
from cms.models.pagemodel import Page
from django.contrib import admin

class ExtendedPageAdmin(admin.StackedInline):
    model = ExtendedPage
    can_delete = False

PageAdmin.inlines.append(ExtendedPageAdmin)
try:
    admin.site.unregister(Page)
except:
    pass
admin.site.register(Page, PageAdmin)

which will add your extended model to as an inline to any page you create. The easiest way to access the extended model setttings, is to create a context processor:
from django.core.cache import cache
from django.contrib.sites.models import Site

from models import ExtendedPage

def extended_page_options(request):
    cls = ExtendedPage
    extended_page_options = None
    try:
        extended_page_options = request.current_page.extended_fields.all()[0]
    except:
        pass
    return {
        'extended_page_options' : extended_page_options,
    }

and now you have access to your extra options for the current page using {{ extended_page_options.my_extra_field }} in your templates
Essentially what you are doing is creating a separate model with extra settings that is used as an inline for every CMS Page. I got this from a blog post previously so if I can find that I'll post it.
EDIT
Here is the blog post: http://ilian.i-n-i.org/extending-django-cms-page-model/


text:
Q: Quicksort Running Time I am trying to refresh my knowledge (and hopefully learn more) about Algorithm Analysis. I took a course on this two years ago but I am trying to catch up on what I had learned back then.
The way I am going about it is by doing exercises from the classic text Introduction to Algorithms, 2nd Edition - CLRS.
The problem that I am trying to solve is this:

Exercise 7.2-2
What is the running time of QUICKSORT when all elements of array A have the same value?
My Solution
The running time of QUICKSORT when all elements of array A have the same value will be equivalent to the worst case running of QUICKSORT since no matter what pivot is picked, QUICKSORT will have to go through all the values in A. And since all values are the same, each recursive call will lead to unbalanced partitioning.
Thus the recurrence will be:
$$T(n) = T(n-1) + \Theta(n)$$
The above recurrence has the solution (I will prove this later):
$$T(n) = \Theta(n^2)$$
Hence the running time of QUICKSORT in this case is $$\Theta(n^2)$$

Please verify if I have answered the question appropriately :)
Please let me know if this question should be posted elsewhere in the SE network.
Thanks!
Jake Clawson

A: Your solution looks fully right.

A: The answer depends on how you are selecting the pivot.  If you follow the algorithm present in the CLSR which always selects the last element as the pivot then it would result in the equation $T(N)=T(N-1)+N$ and hence $T(N)=O(N^2)$ else if you select the middle element as the pivot every time the equation will become $T(N)=2T(N/2)+N$ which would result in $T(N)=\Theta(N\log N)$.

A: No, the partitionings will lead to perfectly balanced subarrays. Indeed, the algorithm will search for the first element $\ge$ pivot on the left and $\le$ pivot on the right and swap them. As all elements are equal (and equal to the pivot), the leftmost and righmost element will be immediately swapped. This will continue until the two indexes meet, which occurs exactly in the middle.


text:
Q: Dragon NaturallySpeaking writes "{Gauche 13}{Maj+Droite}{Maj+Gauche}..." when I select a word This 15-second video http://www.youtube.com/watch?v=pTdWTsFmzQE shows the issue. I say "we are going to eat", then I want to select "going" and Dragon writes the following:

we are going to eat.{Gauche 13}{Maj+Droite}{Maj+Gauche}{Maj+Droite
  6}{Maj+Gauche 6}{Maj+Droite}{Maj+Gauche}{Maj+Droite 5}

The issue disappears when I restart Dragon. But why does this issue appear sometime?
Note that Gauche and Droite are French words for Left and Right. Although I used Dragon in English in the video, my "core" version of Dragon is French, and for whatever reason Dragon outputs those French words even when using my English profile.

A:
The issue disappears when I restart Dragon. But why does this issue
  appear sometimes?

Can't tell why this happens exactly, but Dragon outputs the keypresses required to select the given word as text. It appears that Dragon is not correctly processing your command. Instead of parsing it as a command, it is being parsed as text. A classical bug. The underlying reason is probably only known to the programmers of Dragon. All you can do is isolate the contexts in which the error appears and try to avoid them.
As for possible solutions:

*

*Try creating a new profile.

*Try using Dragon on a different computer.

*Verify that you are using an application with Full Text Control (FTC, check is green). Standard applications that offer Full Text Control are Word, Outlook and Internet Explorer.

*If you are working in Gmail in Chrome or Firefox, you need to make sure that the Rich Internet Application plugin is activated. You can do this in your Chrome extensions. (Dragon installs it automatically. I keep it deactivated because it makes Chrome crash quite frequently.)

*Try using the Dication Box.

*Dictate into DragonPad or Notepad and see if the issue appears there. These are the two applications best supported by Dragon, especially DragonPad which was literally made to work with Dragon. If it does not, use these applications to create your text and the create a command to transfer the text to you desired application.

If the issue appears in Full Text Control apps:
You can submit a ticket to Nuance and hope that they will fix it in a new version or in a patch. Alternately, create a new profile and see if it happens there. If it doesn't happen there, you can just export your vocabulary and commands to the new profile.
Some background on what is being displayed: When you issue a command in some applications, Dragon will attempt to calculate the distance between the word and where you are now in the text. It will cross that distance and select the word by simulating keypresses like Shift-Right or Shift-Left, just as you would with your keyboard. (Dragon does this with some additional jiggling that I don't quite follow, but I suspect it is to avoid issues with spaces before or after words. It probably even does more than this command, but this it was you see anyway. This is all in the background, hidden in the source code.)
I think this behaviour occurs only in applications that do not offer FTC because Dragon cannot "see" the text and needs to calculate the distance differently.
If you do scripting for Dragon as I've done, you will recognize the expressions like {Maj+Droite 5} as commands to send keystrokes (there are several varieties).

for whatever reason Dragon outputs those French words even when using my English profile

As for the French: This is tied to the language of your operating system. And indeed the French versions will display the keys in French (in German versions it is in German).


text:
Q: time function in Python for add an interval to a datetime object I want to do some queries on PostgreSQL database.
I wonder what package or built-in function  can do these.
origin_time = 2014-02-21 00:00:00
origin_time + '1 week' #  2014-02-28 00:00:00
origin_time + '3 hours' # 2014-02-21 00:06:00

A: Use datetime.datetime.strptime to convert the string to datetime.datetime object. (DB API module do this for you.) And use datetime.timedelta to time addition.
>>> import datetime
>>>
>>> origin_time = '2014-02-21 00:00:00'
>>> d = datetime.datetime.strptime(origin_time, '%Y-%m-%d %H:%M:%S')
>>> d + datetime.timedelta(weeks=1)  # + 1 week
datetime.datetime(2014, 2, 28, 0, 0)
>>> d + datetime.timedelta(hours=3)  # + 3 hours
datetime.datetime(2014, 2, 21, 3, 0)

Use datetime.datetime.strftime, str.format or format to get back string:
>>> (d + datetime.timedelta(hours=3)).strftime('%Y-%m-%d %H:%M:%S')
'2014-02-21 03:00:00'

>>> '{:%Y-%m-%d %H:%M:%S}'.format(d + datetime.timedelta(hours=3))
'2014-02-21 03:00:00'


text:
Q: Maven deploy without  tag Project structure:
src
- pom.xml (parent POM)
- core (lot of folders, sub-folders, source files)
- deploy
    - DTO
    - pom.xml

The DTO folder:

*

*uses shade plugin to collect a few classes from core and create a new jar

*this new jar has simple POJOs and does not need any dependencies

*hence the deployed POM for this jar should not have any parent or dependencies as this jar is used by many other clients (android is one)

*however, since the POM in DTO folder is inherited from the parent pom, this parent inheritence is an issue

Question: how can we deploy this jar with a simplified custom POM without any parent?
Possible solution: DTO POM can be without parent. However, we lose many inheritences, such as version, properties, repository etc., which need to be redefined in the DTO POM if it does not have any parent.
Is there a better way of doing this?


text:
Q: vimrc command to add uid in insert mode In my .vimrc I have the following, which in Vim Visual mode inserts an unique alphanumeric string.
vnoremap <leader>u :!pwgen -A 8 1<CR>

For convenience, I want to do the same thing in Vim Insert mode: something like this (not working: .vimrc):
iabbrev uuid `pwgen -A 8 1`

where the abbreviation uuid (or :uid: or similar) triggers the BASH pwgen command (e.g replacing uuid with moh6sei5).

Edit
Per the comment immediately following mentioning Defining linux command inside vim abbreviations
the issue is that strtime (there) is a native Vim function (:h strftime), whereas pwgen is a BASH function. In .vimrc:

*

*works:
iabbrev xxx <C-r>=strftime('%c')<CR>
" Sun 02 Oct 2022 11:03:58 AM PDT

*does not work:
iabbrev uidd <C-r>=pwgen -A 8 1<CR>
iabbrev uidd <C-r>=!pwgen -A 8 1<CR>
iabbrev uidd <C-r>=`pwgen -A 8 1`<CR>
...

A: inoreabbrev <expr> uuid system('pwgen -A 8 1')->trim()

Breakdown:

*

*<expr> tells Vim that the right hand side of the abbreviation is to be evaluated as a Vim expression.

*Since pwgen is an external command, you need :help system() to capture its output.

*External commands often end with a newline character so you need to :help trim() it.

A: This works, .vimrc:
inoremap <F3> <c-r>=trim(system('pwgen -A 8 1'))<cr>

Test: Insert mode, typing apple <F3> banana gives apple ipav7lier banana, where <F3> is that key. Each <F3> keypress inserts a UID.

*

*system(): Vim system() command (:h system in Vim)

*pwgen: BASH alphanumeric password generator command (man pwgen in BASH terminal)

*pwgen -A 8 1: lowercase only (-A), 8 characters, 1 password

*<F3> : keyboard function 3 key

*See also: https://www.grailbox.com/2021/07/insert-uuids-in-vim-neovim/ ... links to (explanation) https://old.reddit.com/r/vim/comments/bnh7su/inserting_the_output_of_an_external_program_inline/