text:
Q: How do I move a legend label within its own legend in matplotlib? I have a graph with, say, three lines.  The red and blue lines have short labels, and the black dotted line has a longer more detailed label.  Currently I have some code to produce the figure below.
import numpy as np
import matplotlib.pyplot as plt

a = np.linspace(0,50,20)
b = np.exp(-0.1*a)*70+np.random.random(20)*10
c = np.exp(-0.1*a)*70+np.random.random(20)*10

plt.plot(a,b,'b.-',lw=3,ms=10,label='short label')
plt.plot(a,c,'r.-',lw=3,ms=10,label='short label')
plt.plot([a[3],a[3]],[-1,100],'k--',lw=2,label='much longer label, I want to span two columns')

plt.ylim([0,80])
plt.xlim([0,50])
plt.legend(loc='best')

plt.show()

I would like to move the label for the red line so that it fills the space next to the label for the blue line (see figure below).  Is this possible?  Note I don't want the label for the black line to shrink and have a line-break.

A: it can be done something like this
import numpy as np
import matplotlib.pyplot as plt

a = np.linspace(0,50,20)
b = np.exp(-0.1*a)*70+np.random.random(20)*10
c = np.exp(-0.1*a)*70+np.random.random(20)*10

plt.plot(a,b,'b.-',lw=3,ms=10,label='short label')
plt.plot([a[3],a[3]],[-1,100],'k--',lw=2,label='much longer label, I want to span two columns')
plt.plot(a,c,'r.-',lw=3,ms=10,label='short label')

plt.ylim([0,80])
plt.xlim([0,50])
plt.legend(loc='best', ncol=2,columnspacing=-8)

plt.show()

You can reduce the size between the columns more by reducing the value of columnspacing, but the frame of legend will also reduce. Your third label will go outside the frame as its length is larger.

A: One option is to add the argument column to the function legend:
import numpy as np
import matplotlib.pyplot as plt

a = np.linspace(0,50,20)
b = np.exp(-0.1*a)*70+np.random.random(20)*10
c = np.exp(-0.1*a)*70+np.random.random(20)*10

plt.plot(a,b,'b.-',lw=3,ms=10,label='short label')
plt.plot([a[3],a[3]],[-1,100],'k--',lw=2,label='much longer label, I want to span two columns')
plt.plot(a,c,'r.-',lw=3,ms=10,label='short label')

plt.ylim([0,80])
plt.xlim([0,50])
plt.legend(loc='best', ncol = 2)

plt.show()


text:
Q: Spread Array of Objects in JavaScript I have a react-redux application, and I have a reducer named dataReducer that has a default state like this:
const defaultState = {
  isLoading: false,
  data: [{
    id: 1,
    label: 'abc',
    elements: [{ color: 'red', id: 1}],
  }],
};

One of the reducers adds elements to data in the defaultState. I need to test this reducer by passing the payload and then validating the new state. I want to use the spread operator to build the new state from the old defaultState, but I am having some trouble achieving it. I tried the following, but it's not working:
const newElement = {
  colour: 'blue',
  id: 1
};

const newState = [
  {
    ...defaultState.data[0],
    elements: [{
      ...defaultState.data[0].elements,
      ...newElement,
    }]
  }
];

expect(dataReducer(defaultState, action)).toEqual(newState); // returns false

It would be great if I could somehow avoid using array index (defaultState.data[0]) as there might be multiple objects in the defaultState array in the real application, though for the purpose of testing, I am keeping just one object to keep things simple.

A: If you're adding to the end, you spread out the other aspects of state in the new state object, then override data with the current contents of it followed by the new entry:
const newState = {               // New state is an object, not an aray
  ...defaultState,               // Get everything from defaultState
  data: [                        // Replace `data` array with a new array
    {
      ...defaultState.data[0],   // with the first item's contents
      elements: [                // updating its `elements` array
        ...defaultState.data[0].elements,
        newElement
      ]
    },
    ...defaultState.data.slice(1) // include any after the first (none in your example)
  ]
};

Live Example:

const defaultState = {
  isLoading: false,
  data: [{
    id: 1,
    label: 'abc',
    elements: [{ color: 'red', id: 1}],
  }],
};

const newElement = {
  colour: 'blue',
  id: 1
};

const newState = {               // New state is an object, not an aray
  ...defaultState,               // Get everything from defaultState
  data: [                        // Replace `data` array with a new array
    {
      ...defaultState.data[0],   // with the first item's contents
      elements: [                // updating its `elements` array
        ...defaultState.data[0].elements,
        newElement
      ]
    },
    ...defaultState.data.slice(1) // include any after the first (none in your example)
  ]
};

console.log(newState);
.as-console-wrapper {
    max-height: 100% !important;
}

There's no getting around specifying the entry in data that you want (e.g., data[0]).

In a comment you've asked how to handle this:

Let's say data (present inside defaultState) has multiple objects entries in it. First object has id of 1, second one has id of 2. Now the newElement to be added has an id of 2. So the newElement should get added to the second object. Where in second object? Inside the elements property of the second object. The addition should not over-write existing entries in the elements array.

You'll need to find the index of the entry in data:
const index = defaultState.data.findIndex(({id}) => id === newElement.id);

I'm going to assume you know that will always find something (so it won't return -1). To then apply that index to the code above, you'd do this:
const newState = {                        // New state is an object, not an aray
  ...defaultState,                        // Get everything from defaultState
  data: [                                 // Replace `data` array with a new array
    ...defaultState.data.slice(0, index), // Include all entries prior to the one we're modifying
    {
      ...defaultState.data[index],        // Include the entry we're modifying...
      elements: [                         // ...updating its `elements` array
        ...defaultState.data[index].elements,
        newElement
      ]
    },
    ...defaultState.data.slice(index + 1) // include any after the one we're updating
  ]
};

The only real change there is adding the ...defaultState.data.slice(0, index) at the beginning of the new data, and using index instead of 0.
Live Example:

const defaultState = {
  isLoading: false,
  data: [
      {
        id: 1,
        label: 'abc',
        elements: [{ color: 'red', id: 1}],
      },
      {
        id: 2,
        label: 'def',
        elements: [{ color: 'green', id: 2}],
      },
      {
        id: 3,
        label: 'ghi',
        elements: [{ color: 'yellow', id: 3}],
      }
  ],
};

const newElement = {
  colour: 'blue',
  id: 2
};

const index = defaultState.data.findIndex(({id}) => id === newElement.id);

const newState = {                        // New state is an object, not an aray
  ...defaultState,                        // Get everything from defaultState
  data: [                                 // Replace `data` array with a new array
    ...defaultState.data.slice(0, index), // Include all entries prior to the one we're modifying
    {
      ...defaultState.data[index],        // Include the entry we're modifying...
      elements: [                         // ...updating its `elements` array
        ...defaultState.data[index].elements,
        newElement
      ]
    },
    ...defaultState.data.slice(index + 1) // include any after the one we're updating
  ]
};

console.log(newState);
.as-console-wrapper {
    max-height: 100% !important;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can i replace "<" with "<", ">" with ">" before doc.save in xmldocument c#? Let say i have this code:
XmlDocument doc = new XmlDocument();
XmlNode school = doc.CreateElement("School");
school.Innertext = "<p>" + Welcome to the school "</p>";
doc.AppendChild(school);
doc.Save(filepath);

It will return this xml file:
<School>
<p%gt;Welcome to the school</p%gt;
</School>

How do i replace &lt ; with "<", &gt ; with ">" before doc.save in xmldocument?


text:
Q: is it possible not to show app part titles? I've made a site that shows one list with links twice, but with different views.
The titles above the two web parts now say "Links (1)" and "Links (2)". In the text above the web parts I already explain what the purpose of the lists is, so i do not need these titles, especially not since they have this funny (1) and (2). Is it possible not to show these titles?
Or does someone have another solution?

A: When you edit the webpart you have to option to change or deactivate the titles.

Change it to "None" and the title will be gone.
Your titles have (1) and (2) because they are the same. Once they are different (1) and (2) will be gone.


text:
Q: Removing hyphen from JSON I am using this JSON code with OWEBIA Shipping 2.0 to create an shipping method on my magento store:
 {  "demo": {       "label": "3 dias úteis",        "conditions":
 "({cart.price+tax+discount} > 59.89) && ({shipto.postcode} > 88000000)
 && ({shipto.postcode} < 88124999)",        "fees": 10,         "customer_groups":
 "3"    } }

It works fine, but the Brazilian Zip Code uses a hyphen!
It would be like this xxxxx-xxx
How do I remove the "-" from the string that the user inserts on the field?
Thanks a lot!

A: As long as i remember Magento is PHP based so you 1st need to do this:
$response = json_decode($json_response); // this will convert the json object into php array;

Then in order to avoid removing all hypens (if you need them anywhere else) search for the property with the postcode and do this:
$postcode_without_hyphens = str_replace('-','', $response->post_code); //example

Regards! Please tell me if you need any further help or explanation! :)

A: It's too late?
I had the same problem. But inspecting the Owebia code i found the solution.
The solution is add a validator to allow only numbers in postcode:
File: app/code/community/Owebia/Shipping2/Model/ConfigParser.php Line 152
Change this function:
protected function _extract($data, $attributes)
{
    $extract = array();
    foreach ($attributes as $to => $from) {
        $extract[$to] = isset($data[$from]) ? $data[$from] : null;
    }
    return $extract;
}

To this:
protected function _extract($data, $attributes)
{
    $extract = array();
    foreach ($attributes as $to => $from) {
        // Here we validate the info, check if the current attribute is the postcode
        if($from == "dest_postcode"){
            //So we use preg_replace to allow only digits
            $data[$from] = preg_replace('/\D/', '', $data[$from]);
        }
        $extract[$to] = isset($data[$from]) ? $data[$from] : null;
    }
    return $extract;
}


text:
Q: Running owncloud in docker as other user not possible When I'm trying to run owncloud with docker everything is fine. But when I then try to run it as other user I'm always getting the following error:

docker run --user 1005:1005 owncloud/server:latest
/etc/entrypoint.d/05-nsswrapper.sh: line 8: /home/owncloud/passwd: Permission denied

Without the --user 1005:1005 options the container starts properly.
The initial thing I wanted to do is to run owncloud with docker compose and running it as other user so I can have a volume with the data on another disk as the default disk with the operating system on it does not have enough space. I already changed the ownership to a user called owncloud with uid=gid=1005
I also had a look to the docs of the docker image and also to https://hub.docker.com/_/php/ section Running as an arbitrary user. But this doesn't work for me. When having a look inside the docker image there is a folder called /home/owncloud with ownership root. I'm already running other services with dedicated users and having no such problems.


text:
Q: Why can't I call del [:] on a dict? What's going on here?
>>> a = {1: "a", 2: "b"}
>>> del a[1]
>>> a
{2: 'b'}
>>> a = {1: "a", 2: "b"}
>>> del a[:]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type
>>> a.clear()
>>> a
{}

Why must I call dict.clear?

A: a[:] is a quick way to make a shallow copy of a list (and tuple). See towards the bottom of the docs for clarification on different types of copying.
Thus, it would reason to say that del a[:] on a dictionary doesn't really make much sense.
If you want to delete the entire dictionary, you can simply do del a
>>> a = {1: "a", 2: "b"}
>>> del a
>>> a

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    a
NameError: name 'a' is not defined
>>>

A: The reason is rather simple: It isn't defined. There's no reason why it couldn't work, if someone put the effort into catching the empty slice and delegating to the appropriate method.
On the other hand, this would violate a symmetry principle with assigning and getting the same slice, so probably would not gain acceptance.

A: a[:] is a special case of a slicing operation, which is defined only for sequences. It is a short form of a[0:len(a)]. A dict is not a sequence.

A: If this functionality is crucial to your system, you could subclass the dict builtin to add this function.
import sys
class newdict(dict):

    def __delslice__(self,i,j):
        if i==0 and j==sys.maxint:
            self.clear()
        else:
            dict.__delslice__(self,i,j)

A: When you're doing del a[1] you're not deleting the first element in dictionary, you're deleting the element with key 1. Dictionary does not have any ordering and thus slicing algorigthm (in this case at least).
That's why with the dict a = {1 : 'one', 5 : 'five'} you can do del a[1] and cannot do del a[2] or del a[0]


text:
Q: Mongodb ID integer to Binary UUID format The ID values of my objects are int format. I want to turn it into binary uuid format.
For example, my old IDs:
 "id": 18,
I want to new ID format like below:
"id": {
    "$binary": {
      "base64": "0M8jsEQ2Sqii/MGhZ7lFFw==",
      "subType": "03"
    }
  },

And if possible, the new IDs should form automatically. I don't write one by one.
Actually this question subject is Django. Because I used Mongodb in my django project.


text:
Q: reveal negation in the Text I have a program that analyzes user comments (reviews) in the data frame. The idea is that everything that meets the word cheap increases the variable x.
import pandas as pd
import nltk

def get_review_words(review):
    review_words = nltk.word_tokenize(review)
    for i in range (0, len(review_words)):
        review_words[i] = review_words[i].lower()
    return review_words

df = pd.read_csv("lastFile3.csv", sep=',' )

wordList= ['cheap']
x = 0
review_words =  get_review_words(str(df['review_text'].loc[i]))
if any(item in wordList for item in review_words):
    x += 1

My question is, how can I take into account cases of negation, so that, for example, if the text not cheap is mentioned, it is not taken into account.
Likewise for all cases  (not cheap,never,not be, ...)
Can someone help me, thanks in advance

A: A very basic, rule-based approach would be:

*

*Define a list of negation indication words (never, not, no, don't/dont/doesn't/doesnt, can't/..., won't/..., ...), you can probably find ressources for this online

*Iterate through the tokens in a review, when a negation word is used, assume any usage of "cheap" means the opposite in the scope of that negation word

*The scope of the negation can be assumed e.g. as being limited by the next punctuation character (., ,, !, ?, ...), check out for example https://analyticsindiamag.com/when-to-use-negation-handling-in-sentiment-analysis/

*Think about what to do when you found such probably negated words (e.g. exclude these cases from the analysis, use them in the opposite direction analysis, ...)

Note that this is a probability-based approach and can fail in a lot of cases, so you will have to try out if applying this actually improves your results or the analysis works better without it.


text:
Q: How do I store private app data on Google Drive with my iOS app? I have an iOS app that has a local database. I'd like to back that up for users who choose to sign in with Google. The web (https://developers.google.com/drive/web/appdata) and android (https://developers.google.com/drive/android/appfolder) have guides on how to do this, but I can't find a similar one for iOS. Does it exist?

A: If you already have code to upload a file to the user's Drive account, it is very easy to switch to uploading into the private app folder instead.  When making the Files.insert call, the file will be added to all of the folders listed in the parents[] array.  (If this array is empty, by default the file is added to the root folder.)  To upload the file into the private app data folder, simply set the parents[] array to appfolder.  You have to do this at the same time as uploading the file, because once it has been uploaded the file can't be moved between the user's drive and your app's private data folder.
(Note:  you may need to use the regular REST API to do this, because Google's Drive API for iOS docs do not show any methods for actually uploading a new file to Drive.)

A: Check this how this is working for me in swift 4.2 and above:
let googleDrive: GTLRDrive_File = GTLRDrive_File()
    googleDrive.name = "name.json"
    googleDrive.parents = ["appDataFolder"]
    let uploadParam: GTLRUploadParameters = GTLRUploadParameters(data: data, mimeType: "application/json")
    uploadParameters.shouldUploadWithSingleRequest = true;
    let queryDrive: GTLRDriveQuery_FilesCreate = GTLRDriveQuery_FilesCreate.query(withObject: metadata, uploadParameters: uploadParam)
    queryDrive.fields = "id"
    self.service.executeQuery(queryDrive) { (result, response, error) in
        if let file = response as? GTLRDrive_File {
            if (error == nil) {
                print(file.identifier)
               /// your code here
            } else {
                // handle error part
            }
        }
        else {
           //handle exception part
        }
    }

"data" the json data  you get this like below
let param = [["key": "value"], ["key": "value"], ["key": "value"]]
let data = try JSONSerialization.data(withJSONObject: param, options: .prettyPrinted)


text:
Q: Which Shell object is the correct one constructing a JFace dialog I'm new in JFace and I'm testing some of its components.
Now I'm a little bit confusing about the different methods to show a modal window.
For example I have an application with a button and want to open a dialog by clicking this button:
public class TestApp extends ApplicationWindow {
  protected Control createContents(Composite parent) {
    Button button1 = new Button(parent, SWT.PUSH);
    button1.setText("Open");
    button1.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        MyDialog myDialog = new MyDialog(...);
        myDialog.open();
      }
    });
  }
}

And now it's the question which Shell object I have to assign to the Dialog constructor.
For that I found the following alternatives:
new MyDialog(getShell());
new MyDialog(parent.getShell());
new MyDialog(new Shell());

But which one is the correct or the most common? And where are the differences?

A: You should use the shell of the current dialog / window so:
new MyDialog(getShell());

is what you normally use.
This makes the new dialog a child of the current window. So if you close the window the dialog will close as well.


text:
Q: Recoloring a set of PNG icons I have a set of icons in a .png format. The customer wants them in a different colour. I know they are from either glyphicons or fontawesome icon fonts, but I do not know how they were generated. I tried this command to recolour them, but bits of red are always left behind and increasing fuzz value has negative effects on other parts of image:
mogrify -fuzz 41% -fill "#5DBFAD" -opaque "#ea5648" *icon.png *arrow.png *rtl.png

Image before:

Image after:

Note: Look closely if you have a dark theme on, there is a second dark-grey icon over the coloured one.
I need either a way to get rid of these red artefacts or a way to generate these icons on my own with the colour of my choice (a full replacement in css is also an option, using the icon font, colouring it and animating). Also for an unknown reason some icons have the coloured one on top like this:

Extra info: When hovered-over these icons transition a few pixels up/down to show the other icon. This is a part of a free nopCommerce theme: http://themes.nopaccelerate.com/themes/nopaccelerate-simplex-theme-3/?utm_source=nop&utm_medium=extension&utm_campaign=extension-directory

A: You can use ImageMagick to re-color just the bottom half of your input image with a command like this...
magick input.png -crop 1x2@ ^
   ( +clone -fill "#5DBFAD" -colorize 100 ) -delete 1 -append result.png

That isolates just the bottom half inside the parentheses, and uses "-colorize" to re-color the image without leaving the artifacts. Then it re-assembles the halves to complete the icon.
Unfortunately "-clone" is not an available option to "mogrify", so for a command like this you'd need to use just "magick" and a "for" loop in your command shell to process multiple images.
The command is in Windows syntax. For a *nix system change the continued-line caret "^" to a backslash "\" and escape the parentheses with backslashes "\(...\)".
Regarding the icons with the colored part on top instead of the bottom, ImageMagick can probably determine which end is colored, but it could get complicated. Maybe easier to sort them manually and process them in two groups. To color just the top half, add "-rotate 180" just after reading in the image and "-rotate 180" again before writing the result.

A: Hi Best way is ask support team for this
As you using nopAccelerate's theme you can direct reach them at support(at)nopaccelerate.com or go to here and create support ticket with them.

A: I ended up writing a simple program to do this, so I am posting the source here, but the @GeeMack's answer seems like a more elegant solution so I am accepting it.
My source code:
Program.cs
using System;
using System.Drawing;
using System.IO;

namespace ColorReplacer
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($"Supplied path: {args[0]}, from color: {args[1]} to color: {args[2]}");

            FileStream fs = new FileStream(args[0], FileMode.Open);
            var image = new Bitmap(fs);
            fs.Close();

            for (var i = 0; i < image.Width; i++)
            {
                for (var j = 0; j < image.Height; j++)
                {
                    var pixel = image.GetPixel(i, j);
                    if (pixel.R == ColorConverter.RfromHex(args[1]) && pixel.G == ColorConverter.GfromHex(args[1]) && pixel.B == ColorConverter.BfromHex(args[1]))
                    {
                        image.SetPixel(i, j, Color.FromArgb(pixel.A, ColorConverter.RfromHex(args[2]), ColorConverter.GfromHex(args[2]), ColorConverter.BfromHex(args[2])));
                    }
                }
            }

            image.Save(args[0]);
        }
    }
}

ColorConverter.cs
using System.Globalization;

namespace ColorReplacer
{
    public static class ColorConverter
    {
        public static int RfromHex(string color)
        {
            if (color.IndexOf('#') != -1)
                color = color.Replace("#", "");

            return int.Parse(color.Substring(0, 2), NumberStyles.AllowHexSpecifier);
        }

        public static int GfromHex(string color)
        {
            if (color.IndexOf('#') != -1)
                color = color.Replace("#", "");

            return int.Parse(color.Substring(2, 2), NumberStyles.AllowHexSpecifier);
        }

        public static int BfromHex(string color)
        {
            if (color.IndexOf('#') != -1)
                color = color.Replace("#", "");

            return int.Parse(color.Substring(4, 2), NumberStyles.AllowHexSpecifier);
        }
    }
}


text:
Q: Setting Up Apache Solr in Cloud Mode I have to do the following:

*

*I have to deploy Solr on 2 servers/nodes.

*Deploy Zookeeper on another server.

*Upload a custom config to Zookeeper

*Create a custom collection with 2 shards and 2 replicas

Version of Solr 7.4.0 & Zookeeper: 3.4.12
I have done the following:
Set Up Zookeeper:

*

*Created a Zookeeper data folder & made a zoo.conf & put the dataDir there.

*Started zookeeper using ./zkServer.sh start
Set up Solr:

*

*Started Solr using:
./solr start -cloud -s /home/demo/LocalFolder/Downloads/SolrHome -p 8987 -z localhost:2181

*Trying to upload config in Zookeeper using:
./solr create -c mycollection -d /media/sf_VM/Dump/conf
It is giving me an exception:
Caused by: javax.servlet.UnavailableException: Error processing the request. CoreContainer is either not initialized or shutting down.
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:341)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:323)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1634)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:533)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:146)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:257)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1595)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:255)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1253)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:203)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:473)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1564)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:201)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1155)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:144)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:219)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:126)
    ... 17 more
</pre>

I have searched many pages & seen Solr tutorials but there they have used the default examples. I just dont have any step by step idea to

*

*How to Upload a config in Zookeeper?

*Then what I need to do to create a collection pointing to that config. I want that collection to have 2 shards & 2 replicas.

*Where will be the solr.xml. If it should be in Zookeeper how do I upload it there

*How do I see in Zookeeper that the config has been uploaded?

I know this question might be a duplicate. I have read several of posts but not able to come up a solution. Please help.

A: Well I figured out how to setup. Please note that I have read these steps from different site & gathered here step by step:
1. Set Up ZooKeeper:
This is used to keep the collection specific configuration files to store in a central space & map it with a name. Later we can use this name to create collection which would point to this config. This config is the same as you find in the below folder:
solr-7.4.0\server\solr\configsets\sample_techproducts_configs\conf
1.1 Download latest Zookeeper. I have used 3.4.12
1.2 Unpack downloaded archive and copy conf/zoo_sample.cfg to conf/zoo.cfg
1.3 Modify zoo.cfg:
1.3.1 Change dataDir to directory where you want to hold all cluster configuration data.
dataDir=/var/zookeeper/data
1.3.2 Add information about all Zookeeper servers: I have used only 1 ZooKeeper server so this is not required. If you want to add more servers then please go through the below links:
DZone Tutorial
Apache Tutorial
1.3.3 Start ZooKeeper using (after going to zookeeper-3.4.12/):
./bin/zkServer.sh start-foreground conf/zoo.cfg
OR
./bin/zkServer.sh start conf/zoo.cfg
Note: You can stop the ZooKeeper using the below command:
bin/zkServer.sh stop
1.3.4 ZooKeeper Status:
Hit the below:
bin/zkServer.sh status
Or do telnet localhost 2181 and hit stats when connected.
2. Set Up Solr
2.1 Download the Solr
2.2 Extract install_solr_service.sh from the .tar file. Solr includes a service installation script (bin/install_solr_service.sh) to help you install Solr as a service on Linux. For more info click here.
tar -xzf solr-7.4.0.tgz solr-7.4.0/bin/install_solr_service.sh --strip-components=2
2.3 Install Solr as a service using the above script:
sudo bash ./install_solr_service.sh solr-7.4.0.tgz
This will also extracting solr-7.4.0.tgz to /opt/solr
2.4 Go to /opt/solr and do the following:
mkdir solr/server/solr2
mkdir solr/server/solr3
mkdir solr/server/solr4
cp solr/server/solr/solr.xml solr/server/solr2
 cp solr/server/solr/solr.xml solr/server/solr3
 cp solr/server/solr/solr.xml solr/server/solr4
2.5 Change the jetty port in solr.xml. Do this for all the 3 solr.xml mentioned in the above step:
vi solr/server/solr2/solr.xml
Search for the port 8983 & change it 8984 (for solr2), change it 8985 (for solr3), change it 8986 (for solr4)
2.6 Stop the Solr running at 8983
root@dev-base:/opt/solr/bin# ./solr stop  -p  8983
2.7 Start all the solr instances:
root@dev-base:/opt/solr# bin/solr start -c -s  server/solr -p 8983 -z  localhost:2181 -noprompt -force
root@dev-base:/opt/solr# bin/solr start -c -s  server/solr2 -p 8984 -z  localhost:2181 -noprompt -force
root@dev-base:/opt/solr# bin/solr start -c -s  server/solr3 -p 8985 -z  localhost:2181 -noprompt -force
root@dev-base:/opt/solr# bin/solr start -c -s  server/solr4 -p 8986 -z  localhost:2181 -noprompt -force
Note: Running solr as a root is not recommended for security reason.
2.8 See Solr Status:
root@dev-base:/opt/solr# bin/solr status
3 Make a Custom Config
3.1 Copy the conf directory from solr-7.4.0\server\solr\configsets\sample_techproducts_configs\conf to another location (In my case it is /media/sf_VM/Dump/new/conf ).
3.2 Change the managed-schema file inside conf to specify the fields you are using.
4 Upload the config to ZooKeeper:
root@dev-base:/opt/solr# bin/solr zk -z localhost:2181 upconfig -d /media/sf_VM/Dump/new/conf -n myConf6
The name of the config I have uploaded is myConf6
5 Create a Solr Collection using this custom config
root@dev-base:/opt/solr# bin/solr create -c myNewCollection -n myConf6 -shards 2 -replicationFactor 2 -force
Hit Solr Admin URL
6 Index Data Using POST API using Json
URL: http://localhost:8983/solr/myNewCollection/update
Method: POST
Body:
[{
    "_id": "99999999999999999999",
    "author": [
        "New Inserted 9000"
    ],
    "authorLastName": [
        "New Inserted 9000"
    ],
    "impn": "New Inserted 9000",
    "isbn10": "9999999999",
    "isbn13": "9999999999999",
    "title": "New Inserted 9000",
    "publisher": "New Inserted 9000",
    "sales_a": 5.0,
    "sales_t": 5.0,
    "haveImage": 1,
    "pages": "76",
    "image": "http://ip.ip.com/is/image/",
    "format": "Paper",
    "mtc_id": "99999999999",
    "subjects" : [
        "9000"
    ]
    "rating": 0,
    "description_long": "Snahashis call me in your marriage."
}

Delete a configuration in Zookeeper:
If you want to delete an old/wrong configuration already uploaded to ZooKeeper run the below command:
./server/scripts/cloud-scripts/zkcli.sh -cmd clear -z "<ZK_HOST>:<ZK_PORT>" /configs/AAA
The path of the configuration is /configs/< name of the configset >
To delete a specific file:
zkcli.sh --zkhost <ZK_HOST>:<ZK_PORT> -cmd clear /configs/<MY_COLLECTION>/solrconfig.xml
Upload an updated file:
zkcli.sh --zkhost <ZK_HOST>:<ZK_PORT> -cmd putfile /configs/<MY_COLLECTION>/solrconfig.xml  /<MY_UPDATED_FILE_LOCAL_FOLDER>/solrconfig.xml
Then we need to restart the solr nodes.
To Delete a Collection Via API:

*

*First delete alias created on this collection (if any)

http://localhost:8983/solr/admin/collections?action=DELETEALIAS&name=aliasName

*Delete Collection:

http://localhost:8983/solr/admin/collections?action=DELETE&name=collectionName


text:
Q: Confusion regarding tense Is the following sentence grammatically correct?
I had forgotten that John is in New York now.
(I'm confused because the first part is in the past perfect tense and the second in simple present tense. Is it grammatically acceptable to construct a sentence like this?)
I could rephrase it as follows:
I had forgotten that John was in New York.
(But this does not clearly convey the idea that John is still in New York!)
Please explain.
Thank you.

A: "John is in New York now." is the subject, it what was forgotten.
It's not mixed tense, just seems that way. You can shuffle it around all you like, but it still means the same.

A: This differs from dialect to dialect.  The tense of "is/was" in the embedded clause agrees either with the tense of the main clause verb "had forgotten", or else it agrees with the time that the sentence is uttered, in the event that the speaker of the sentence agrees with the truth of the embedded clause.  Personally, I'd say "was", whether or not I agree.  Other (I think, younger) speakers would always say "is" if they agree.


text:
Q: (Un)Inferred Subclass Rules Protégé vs OWL API I am a bit confused about the subclass handling in Protégé as compared to when using the OWL API directly.
I have built a simple ontology where I logically define what a "Man" or a "Woman" is, namely male or female humans.
The classes are
Human
Woman
Man
Gender
    Female
    Male

Properties:
hasSex (Human -> Gender)

So a Woman is
    Human and hasGender some Female
My issue: When I display this ontology in Protégé, it automatically organizes Man and Woman as subclasses of Human, WITHOUT using a reasoner.
However, when I iterate over all classes in the OWL API and print their subclasses, only the asserted subclasses are found:
Subclasses of <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Female>
Subclasses of <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Woman>
Subclasses of <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Male>
Subclasses of <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Human>
Subclasses of <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Gender>
    <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Female>
    <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Male>
Subclasses of <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Man>

I need to use a reasoner to get the expected result, that Protégé shows without using one:
Subclasses of <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Female>
    Node( owl:Nothing )
Subclasses of <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Woman>
    Node( owl:Nothing )
Subclasses of <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Male>
    Node( owl:Nothing )
Subclasses of <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Human>
    Node( <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Man> )
    Node( <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Woman> )
Subclasses of <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Gender>
    Node( <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Female> )
    Node( <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Male> )
Subclasses of <http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Man>
    Node( owl:Nothing )

What am I doing wrong here? Has Protégé some built-in rules for "clear" cases of subclasses? Where can I find them?
For reference, the example ontology and the OWL API code follow:

<!--
///////////////////////////////////////////////////////////////////////////////////////
//
// Object Properties
//
///////////////////////////////////////////////////////////////////////////////////////
 -->

<!-- http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#hasAge -->

<owl:ObjectProperty rdf:about="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#hasAge">
    <rdfs:domain rdf:resource="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Human"/>
</owl:ObjectProperty>

<!-- http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#hasSex -->

<owl:ObjectProperty rdf:about="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#hasSex">
    <rdfs:domain rdf:resource="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Human"/>
    <rdfs:range rdf:resource="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Gender"/>
</owl:ObjectProperty>

<!--
///////////////////////////////////////////////////////////////////////////////////////
//
// Classes
//
///////////////////////////////////////////////////////////////////////////////////////
 -->

<!-- http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Female -->

<owl:Class rdf:about="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Female">
    <rdfs:subClassOf rdf:resource="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Gender"/>
</owl:Class>

<!-- http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Gender -->

<owl:Class rdf:about="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Gender"/>

<!-- http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Human -->

<owl:Class rdf:about="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Human"/>

<!-- http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Male -->

<owl:Class rdf:about="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Male">
    <rdfs:subClassOf rdf:resource="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Gender"/>
</owl:Class>

<!-- http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Man -->

<owl:Class rdf:about="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Man">
    <owl:equivalentClass>
        <owl:Class>
            <owl:intersectionOf rdf:parseType="Collection">
                <rdf:Description rdf:about="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Human"/>
                <owl:Restriction>
                    <owl:onProperty rdf:resource="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#hasSex"/>
                    <owl:someValuesFrom rdf:resource="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Male"/>
                </owl:Restriction>
            </owl:intersectionOf>
        </owl:Class>
    </owl:equivalentClass>
</owl:Class>

<!-- http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Woman -->

<owl:Class rdf:about="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Woman">
    <owl:equivalentClass>
        <owl:Class>
            <owl:intersectionOf rdf:parseType="Collection">
                <rdf:Description rdf:about="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Human"/>
                <owl:Restriction>
                    <owl:onProperty rdf:resource="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#hasSex"/>
                    <owl:someValuesFrom rdf:resource="http://www.semanticweb.org/user/ontologies/2017/4/untitled-ontology-222#Female"/>
                </owl:Restriction>
            </owl:intersectionOf>
        </owl:Class>
    </owl:equivalentClass>
</owl:Class>

public static void main(String[] args) throws OWLOntologyCreationException {
    OWLOntologyManager m = OWLManager.createOWLOntologyManager();
    OWLOntology o = m.loadOntologyFromOntologyDocument(new File("testonto/Untitled.owl"));
    OWLReasonerFactory reasonerFactory = new JFactFactory();
    OWLReasoner reasoner = reasonerFactory.createReasoner(o);
    o.classesInSignature().forEach(c -> {
        System.out.println("Subclasses of " + c);
        reasoner.getSubClasses(c, true).forEach(sc -> System.out.println("    " + sc));
//          EntitySearcher.getSubClasses(c, o).forEach(sc -> System.out.println("    " + sc));
    });
}

A: Short answer is yes, Protégé has some minimal reasoning to organise the asserted hierarchy.


text:
Q: Help, SQL 2008 table locked after large update! I had a large update statement run over the weekend that took approximately 6.5 hours to complete.  That was 2 days ago (friday evening, today is monday morning).
The table has 77million records in it, and about 10 fields were updated.
Monday morning I logged in to check my update results and the table is locked.
I have a COMMIT TRANSACTION at the end of the stored procedure, so I don't know what is goig on with the table?
I don't want to kill the SPID either, because it might roll back whatever it is doing.
Help!  What can I do to get
Thanks in advance.

A: If it's still running, you have two options: let it finish and commit the work, or kill the process and thus roll back the transaction.
If it's finished, and it just didn't commit the open transaction for whatever reason, find the system that connection is from so you can manually commit the transaction rather than killing it and rolling back.


text:
Q: How to stop ProGuard from stripping the Serializable interface from a class Is there an explicit way to stop ProGuard from changing a class from implementing an interface?
I have a class that implements java.io.Serializable, let's call it com.my.package.name.Foo. I've found that after running through ProGuard, it no longer implements Serializable. I get null after I cast from Serializable to Foo and false if I check an instance with instanceof Serializable. I've made sure to set ProGuard to ignore this class:
-keep class com.my.package.name.Foo

I've also tried:
-keep class com.my.package.name.Foo { *; }

and I've also tried the whole package by doing this:
-keep class com.my.package.name.** { *; }

or:
-keep class com.my.package.** { *; }

and also just to keep all Serializable classes:
-keep class * implements java.io.Serializable { *; }

but to no avail. I have another class in a sibling package (roughly: com.my.package.name2.Bar) that also implements Serializable and is used similarly but has no issues.
I'm not sure it's relevant, but I'm packing this in a jar for use with Android. The code that uses these classes include putting them in Bundles which is why I need Serializable. I considered that perhaps somehow ProGuard thinks that Foo is never used as a Serializable but that seems unlikely given that I pass it as a parameter to Bundle.putSerializable(String, Serializable) and also I do an implicit cast: Serializable serializable = foo;. In fact, when I debug, I can see the Foo get put into the Bundle and I can examine the Bundle and see the instance of Foo there, but when retrieving it the cast fails.

A: ProGuard doesn't ever strip interfaces that are defined in libraries (like Serializable) from classes in code that is processed (like Foo). Library code may be casting to those interfaces, so they can't be removed.

I get null after I cast from Serializable to Foo

This means that the instance must be null to start with. Your analysis would be correct if you'd get  a ClassCastException. You can check that Foo still implements Serializable with javap. The problem probably lies elsewhere. For tips on serialization, you can look at the ProGuard manual > Examples > Processing serializable classes.
Update:
In this case, it turns out to be a configuration problem. ProGuard can only process class files if it knows everything about their hierarchy (just like a compiler). You really have to specify the runtime classes:
-libraryjars <java.home>/lib/rt.jar

or for Android:
-libraryjars /usr/local/android-sdk/platforms/android-17/android.jar

The Android Ant/Eclipse builds automatically specify all necessary -injars/-outjars/-libraryjars options for you, but in a custom build process, you have to specify them yourself. Cfr. ProGuard manual > Examples > A complete Android application.
Note that the option -dontwarn makes the warnings go away, but not the problems. Only use it if really necessary.

A: I had the same issue fixed using below config.
-keepnames class * implements java.io.Serializable
-keepclassmembers class * implements java.io.Serializable {
    static final long serialVersionUID;
    private static final java.io.ObjectStreamField[] serialPersistentFields;
    !static !transient <fields>;
    private void writeObject(java.io.ObjectOutputStream);
    private void readObject(java.io.ObjectInputStream);
    java.lang.Object writeReplace();
    java.lang.Object readResolve();
}

Official Documentation
http://proguard.sourceforge.net/manual/examples.html#serializable


text:
Q: Cumulative distribution function derivation
Can someone please explain me why in the first example limits of integration are from - infinity to s and then from 1 to s but in the second c.d.f the limits of the integration are from - a to a and -1 to s/a ?
Thank you!

A: The definition of the cumulative distribution function (corresponding to a density function $f$) is always $F(s) = \int_{-\infty}^s f(x)\,dx$, with lower limit $-\infty$ and upper limit $s$. This choice will always be correct.
If a function $f(x)$ is identically zero for all $x<c$ for some constant $c$, then $\int_{-\infty}^s f(x)\,dx = \int_c^s f(x)\,dx$ (just from how integrals are defined). That's why in the first example we can replace $\int_{-\infty}^s f_1(x)\,dx$ with $\int_1^s f_1(x)\,dx$, and why in the second example we can replace $\int_{-\infty}^s f_2(x)\,dx$ with $\int_{-a}^s f_2(x)\,dx$.
Finally, the fact that $\int_{-a}^s \frac2{\pi a^2}\sqrt{a^2-x^2}\,dx = \int_{-1}^{s/a} \frac2{\pi}\sqrt{1-y^2}\,dy$ is a fact from calculus, due to the change of variables $y=x/a$; it doesn't have anything to do with the definition of the cumulative density function, but just provides one person's way of evaluating this particular cumulative density function.


text:
Q: ImportError: No module named Quandl No module named Quandl in my Python version 2.7 please help.
How do i fix this issue even I can see this in my pip list Quandl is there.

A: Try using import quandl, per the Quandl python docs.


text:
Q: Tkinter - Maximizing and minimizing the window before using any widgets, hides the widgets when I use them This is the code that I have written. As you can see, it has a button which when clicked opens up a Text where one can enter something. It works, the window resizes if you click the button.
But I have noticed that, if I maximize and minimize the window just after starting the program (i.e. the first thing I do is to maximize and minimize the window), then the window doesn't resize to fit the whole frame (on clicking the button) and my widgets get hidden.
from tkinter import *

def Home():
    global homeP
    homeP = Tk()
    homeP.title('Grades')

    enterButton = Button(homeP, text='Enter Grades', bg='blue', fg='white', command=enterG)
    enterButton.grid(row=1, column=0, padx=(5,5), pady=(5,2), sticky="e")

    homeP.mainloop()

curFrame = ''

def enterG():
    global homeP
    global eGrade
    global curFrame

    if curFrame == 'e':
        return
    if 'eGrade' not in globals(): #Prevent frames from stacking up on one another
        eGrade = Frame(homeP)
        enterGrades = Text(eGrade, width=64, height=10)
        enterGrades.grid(row=0, column=0)

        eGrade.grid(row=2, column=0, columnspan=2, padx=(10,10), pady=(1,5))
    else:
        eGrade.grid(row=2, column=0, columnspan=2, padx=(10,10), pady=(1,5))
    curFrame = 'e'

    # for name, value in globals().copy().items():
    #   print(name, value)
Home()

Any help as to why this is happening and how I can prevent this?

A: You will have exactly the same problem if you manually resize the window before clicking the button. The issue isn't tied to maximize/minimize per se, it's tied to the fact that the user has said "I want the window to be this size" and tkinter is trying to honor that by not resizing the window against the user's wishes.
The solution is to reset the size of the window before adding or removing widgets. Add the following line of code after your global statements in enterG:
homeP.geometry("")


text:
Q: Reduction of torsion points on Neron Model Let $K/\mathbb{Q}_p$ be a finite extension with ring of integers $R$ and residue field $k$. Let $A/K$ be an abelian variety with Neron model $\mathcal{A}/R$. We denote by $\tilde{\mathcal{A}}/k$ the special fiber and by $\mathcal{A}^0$ - the connected component of $\mathcal{A}$.

*

*Is it true that $\mathcal{A}^0(R)[n] \hookrightarrow \tilde{\mathcal{A}^0}(k)$ for $p \nmid n$? What is the right reference for this fact?

This is discussed here in case that $A$ has good reduction. Liu's answer in that topic addresses the general case:

(...) when A is not an abelian scheme (for example, when it is the Néron model of an abelian variety over $\mathbb{Q}_p$ with not necessary good reduction), then for any n prime to p, the kernel $A[n]$ is still étale over $\mathbb{Z}_p$ (because the tangent map at 0 of the multiplication by n is just multiplication by n for any commutative algebraic group), but not necessarily finite. There is a biggest closed subscheme H of $A[n]$ which is étale and finite over $\mathbb{Z}_p$. The reduction map on H is injective (see Pete's proof). The generic fiber of H corresponds to the points of the generic fiber of $A[n]$ having specialization mod p. (...)

I don't really understand the last sentence - what does it mean for a point to have a specialization mod $p$? Isn't it true that every point in $A(K)$ corresponds to a point in $\mathcal{A}(R)$ and every point in $\mathcal{A}(R)$ can be reduced to $\mathcal{A}(k)$?

*Is it possible to prove the "$(1) \Rightarrow (2)$" implication of Neron-Ogg-Shafarevich criterion for abelian varieties in the language of Silverman's Arithmetic of Elliptic Curves? This would be my attempt:

Theorem If $A/K$ has good reduction, then inertia $I_K$ acts trivially on $A[n]$ for $p \nmid n$.
Proof: Let $L = K(A[n])$ and let $R', k'$ be the ring of integers and residue field of $L$. Let $\mathcal{A}/R'$ be the Neron model of $A_L$. Then any point $P \in A[n]$ corresponds to a point $\mathcal{P} \in \mathcal{A}(R')[n]$. Let $\sigma \in I_K$. Then $\mathcal{P}^{\sigma} - \mathcal{P} \in \mathcal{A}(R')[n]$ and
$$
\widetilde{\mathcal{P}^{\sigma} - \mathcal{P}} = \mathcal{O}
$$
  in $\tilde{\mathcal{A}}(k')$. Thus (since prime-to-p torsion injects into $\tilde{\mathcal{A}}(k')$ - by [1]) $\mathcal{P}^{\sigma} = \mathcal{P}$ and $P^{\sigma} = P$.

Edit:

*

*Seems to be true by a formal group argument, just like in the case of good reduction (cf. Proposition 7 in Clark, BOUNDS FOR TORSION ON ABELIAN VARIETIES WITH INTEGRAL MODULI and the preceeding discussion.

*I think it is not true in general that reduction commutes with Galois action. Is it true at least on identity component, ie.
$$
\widetilde{P^{\sigma}} = (\widetilde{P})^{\sigma}
$$
for $P \in \mathcal{A}^0(R_{\overline{K}})$, $\sigma \in Gal(\overline{K}/K)$?
Edit 2:

*Ok, I know what is wrong. The Galois group $Gal(L/K)$ doesn't act on $\mathcal{A}$, since it is defined over $R'$ and not $R$. In the case of elliptic curves with good reduction we know that the minimal equation stays the same after base change (since we have a discriminant of valuation 0) and thus the Neron model is basically defined over $R$. In the case of abelian varieties we have no discriminant, that's why it is harder.

I guess we can close this topic.


text:
Q: Extends base template not appearing in Flask Python I've got a base.html page that has both a header and a footer block.
When I use {% extends "base.html" %} in my home.html page, I get nothing from the base.html page.
If I use {% include "base.html" %}, all my content in the home.html page is at the bottom, with the header and footer at the top. Does anyone know how I can fix this?
I'd like the header block at the top, the content from home.html in the middle, and the footer block rendered on the bottom of the home page.
I'd be grateful for any help. Thanks.
Here is my code. myapp.py
from flask import Flask, render_template, url_for
app = Flask(__name__)

@app.route("/")
@app.route("/home")
def home():

    return render_template("home.html", title="Home",
                          menu = menu)

@app.route("/base")
def base():

    return render_template("base.html", title="Base")

if __name__ == "__main__":
    app.run(debug=True)

base.html
<!DOCTYPE html>

        <title>{{title}} - Restaurant</title>

    {% block header %}

Home

    {% endblock header %}

    {% block footer %}

This is a footer

    {% endblock footer %}

home.html
{% extends "base.html" %}
{% block header %}

Home Page

{% endblock header %}

{% block footer %}

New stuff in home page

{% endblock footer %}

A: Defining a block in a child template automatically overrides the version from the parent template completely. If you want to also output the parent version, you need to call super() - see the Jinja2 docs.
So your home.html should be:
{% extends "base.html" %}
{% block header %}
{{ super() }}

Home Page

{% endblock header %}

{% block footer %}
{{ super() }}

New stuff in home page

{% endblock footer %}

A: Try this?
base.html
<!DOCTYPE html>

        <title>{% block title %}{% endblock %} - Restaurant</title>

    {% block header %}

Home

    {% endblock header %}

    {% block content %}{% endblock %}

This is a footer

home.html
{% extends "base.html" %}
{% block content %}

{% block header %}

Home Page

{% endblock header %}

{% block footer %}

New stuff in home page

{% endblock footer %}

{% endblock %}

https://flask.palletsprojects.com/en/1.1.x/tutorial/templates/


text:
Q: How to implement a virtual function equal() I want to implement a function to compare derived class. But I found that I have to cast the base class object to derived class object.
Is there a way to avoid using cast here or another better design to implement the compare function ?
class A {
    public :
        virtual bool equal(const A & obj) const = 0;
};

class AA : public A{
    public:
        AA (int i) : m_i(i) {}
        virtual bool equal(const A & obj) const
        {
            return m_i == dynamic_cast<const AA&>(obj).m_i;
        }

    private:
        int m_i;
};

int main () {
    AA aa1(10), aa2(9);
    A &a1 = aa1, &a2 = aa2;

    a1.equal(a2);

    return 0;
}

A: I've been bitten by this request many times in my own code.  I'll present a simplified example:
struct Fruit
{
  virtual bool is_equal(Fruit const & f) const = 0; // Compare two fruits
  // Some dangerous actions:
  bool operator==Fruit const & f)
  {
    return is_equal(f); // Dispatch!
  }
};

struct Strawberry : public Fruit
{
  bool is_equal(Fruit const & f)
  {
     bool equal = false;
     // The f could be any fruit, such as tomatoes or pineapples or bananas.
     // Need to perform a dynamic_cast to verify that the f is a strawberry.
     Strawberry const & s = dynamic_cast<Strawberry const &>(f);
     // perform strawberry comparison;
     return equal;
  };
}

struct Banana : public Fruit
{
  bool is_equal(Fruit const & f)
  {
     bool equal = false;
     // The f could be any fruit, such as tomatoes or pineapples or strawberries.
     // Need to perform a dynamic_cast to verify that the f is a banana.
     Banana const & b = dynamic_cast<Banana const &>(f);
     // perform banana comparison;
     return equal;
  };
}

bool Compare_Fruits(Fruit const * pf1, Fruit const * pf2)
{
  if (*pf1 == *pf2)
  {
    cout << "Fruits are equal\n";
    return true;
  }
  cout << "Fruits are different\n";
  return false;
}

int main(void)
{
  // Fun with fruit.
  Fruit * p_fruit_1 = new Strawberry;
  Fruit * p_fruit_2 = new Banana;
  Fruit * p_fruit_3 = new Strawberry;

  // Is this valid, comparing two different fruits, when
  // we just want to compare two strawberries?
  if (Compare_Fruits(p_fruit_1, p_fruit_3)) // OK, both are strawberries
  {
     // ...
  }
  if (Compare_Fruits(p_fruit_1, p_fruit_2)) // Not OK, two different fruits.
  {
     // ...
  }
  return 0;
}

The point here is that if you are implementing the equal operation in the base class so that descendents can compare instances, you have made a poor decision.  Be aware that I can pass a pointer to an instance of one descendent (Strawberry) to the comparison method of another descendent (Banana), because the equality function is based on pointers to the base class.  Unfortunately, there is no way to tell how many or all of the descendents that are derived from the base class.
For programming safety, I highly recommend against placing virtual comparison operators in the base class.  The base class should have comparison operators, declared protected, that only compare the base data members.  This method would be called by the descendents.


text:
Q: If I have 1000 different Infopath forms do I need to create 1000 Form Library in SharePoint2010? If I have 1000 different Infopath forms do I need to create 1000 Form Library in SharePoint2010 to collect the data and trigger workflows?
I don't want to save the user submitted data into a list and is there a way to group all the Form Libraries? Or I am doing it completely wrong???
Thanks :)

A: You can do it via single Form Library itself. Deploy the forms as content type or as Administrator Approved form template.
You can then add the Infopath form content type specific to your forms to the single form library.
http://www.lcbridge.nl/vision/infopath.htm


text:
Q: DSE cassandra and spark map collections type: how to perform get operation For example I have the following table named "example":
  name      |       age       |       address

  'abc'     |       12        | {'street':'1', 'city':'kl', 'country':'malaysia'}
  'cab'     |       15        | {'street':'5', 'city':'jakarta', 'country':'indonesia'}

In Spark I can do this:
scala> val test = sc.cassandraTable ("test","example")
and this:
scala> test.first.getString
and this:
scala> test.first.getMapString, String
which gives me all the fields of the address in the form of a map
Question 1: But how do I use the "get" to access "city" information?
Question 2: Is there a way to falatten the entire table?
Question 3: how do I go about counting number of rows where "city" = "kl"?
Thanks

A: Question 3 : How do we count the number of rows where city == something
I'll answer 3 first because this may provide you an easier way to work with the data. Something like
sc.cassandraTable[(String,Map[String,String],Int)]("test","example")
 .filter( _._2.getOrElse("city","NoCity") == "kl" )
 .count

First, I use the type parameter [(String,Map[String,String],Int)] on my cassandraTable call to transform the rows into tuples. This gives me easy access to the Map without any casting. (The order is just how it appears when I made the table in my test environment you may have to change the ordering)
Second I say I would like to filter based on the _._2 which is shorthand for the second element of the incoming tuple. getOrElse returns the value for the key "city" if the key exists and "NoCity" otherwise. The final equivalency checks what city it is.
Finally, I call count to find out the number of entries in the city.
1 How do we access the map?
So the answer to 2 is that once you have a Map, you can call get("key") or getOrElse("key") or any of the standard Scala operations to get a value out of the map.
2 How to flatten the entire table.
Depending on what you mean by "flatten" this can be a variety of things. For example if you want to return the entire table as an array to the driver (Not recommended since your RDD should be very big in production.) You can call collect
If you want to flatten the elements of your map into a tuple you can always do something like calling toSeq and you will end up with a list of (key,value) tuples.  Feel free to ask another question if I haven't answered what you want with "flattening."


text:
Q: Find deleted element in Array I need to find the first available deleted slot in the Array
This works:
var A = [1,2]
A[0] = undefined
console.log(A.indexOf(undefined))

But how about this?:
var A = [1,2]
delete A[0]
console.log(A)
console.log(A.indexOf(null)) ???

A: Loop through the array looking for keys not present.
function find_first_empty_slot(arr) {
    for (var i = 0; i < arr.length; i++) {
        if (!(i in arr)) { return i; }
    }
    return -1;
 }

You cannot find these using indexOf, because it does not look at missing elements. You can also not use Array#forEach etc. because they skip over the missing elements.


text:
Q: NSSplitView screen artefacts I'm buildng an app for macOS with an NSSplitView. In the top frame of the splitview, there is another NSSplitView, this time vertical, to make a three-pane window. (Two frames across the top, one frame across the bottom, a bit like FCP etc.)
It looks like this at launch:

However if I resize the app window, or move any of the dividers, then the original divider positions stay drawn on screen.
Like this:

How can I remove these screen artefacts?

A: FIXED.
I simply sub-classed NSSPlitView, and set the class-type in the inspector to my new sub-class. This got rid of the screen artefacts. I have no idea why this works.


text:
Q: PHP - Upload utf-8 filename I'm Vietnamese and i want to upload a utf-8 filename like
Tên Tệp Tiếng Việt.JPG
Here is my code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>utf-8</title>
</head>

<body>
<?php
    if(isset($_POST["submit"])) {
       if($_FILES["upload"]["error"] > 0 ) echo "FILE ERROR!";
       else
         {
           $base_dir = "D:/";
           $fn = $_FILES["upload"]["name"];

           $fn2 = $base_dir.$fn;

           move_uploaded_file($_FILES["upload"]["tmp_name"],$fn2);
         }
     }
?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
  <input type="file" name="upload" id="upload" />
  <input type="submit" name="submit" id="submit" value="Send" />
</form>
</body>
</html>

but when i upload that i see on my computer D:\ has a file like
Tên Tệp Tiếng Việt.JPG
How to fix that thanks

A: This meta has no effect:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
because the web server has already sent Content-Type header, and thus decided what the encoding will be. Web browsers send forms in the same encoding. The meta is useful when user is off-line.
So you have to sned http header Content-Type by yourself:
<?php header("Content-Type: text/html; charset=utf-8"); ?>

ensure that you put this before any html, content or whatever is sent.

Alternatively, accept-charset tag on form should work as weel:
 <form accept-charset="utf-8">

A: I am Persian and I have same problem with utf-8 character in my language.
I could solve my problem with this code:
$fn = $_FILES["upload"]["name"]; // name of file have some utf-8 characters
$name=iconv('utf-8','windows-1256', str_replace('ی', 'ي', $fn));
move_uploaded_file($_FILES["upload"]["tmp_name"],$name );

I am not sure about vientam language but maybe you can use the same code as above with a few changes:
$fn = $_FILES["upload"]["name"]; // name of file have some utf-8 characters
$name=iconv('utf-8','cp936', $fn);
move_uploaded_file($_FILES["upload"]["tmp_name"],$name );

A: I'm on Windows 8 chinese version, and I deal with similar problem with this:
$filename = iconv("utf-8", "cp936", $filename);

cp stands for Code page and cp936 stands for Code page 936, which is the default code page of simplified chinese version of Windows.

So  I think maybe your problem could be solved in a similar way:
$fn2 = iconv("UTF-8","cp1258", $base_dir.$fn);

I'm not quite sure whether the default code page of your OS is 1258 or not, you should check it yourself by opening command prompt and type in command chcp. Then change 1258 to whatever the command give you.

UPDATE
It seems that PHP filesystem functions can only handle characters that are in system codepage, according to this answer. So you have 2 choices here:

*

*Limit the characters in the filename to system codepage - in your case, it's 437. But I'm pretty sure that code page 437 does not include all the vietnamese characters.

*Change your system codepage to the vietnamese one: 1258 and convert the filename to cp1258. Then the filesystem functions should work.
Both choices are deficient:
Choice 1: You can't use vietnamese characters anymore, which is not what you want.
Choice 2: You have to change system code page, and filename characters are limited to code page 1258.
UPDATE
How to change system code page:
Go to Control Panel > Region > Administrative > Change system locale and select Vietnamese(Vietnam) in the drop down menu.

A: The only solution  I have found so far.. (2014 year):
1) I dont store files on my FTP in UTF-8 string. Instead, i use this function, to rename the uploaded files:
<?php
// use your custom function.. for example, utf8_encode
$newname  = utf8_encode($_FILES["uploadFile"]["name"]);
move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $newname);
?>

2) Now  you can rename (or etc) $newname;

A: For a start get detecting filename encoding (before uploading).
print_r($_FILES["upload"]);

Insert filename to decoder and check encoding.

A: Sorry! your question is about file name.
You must save your file name with iconv but read without this.
for saving:
<?php
$name = $_FILES['photo']['name'];
$unicode = iconv('windows-1256', 'utf-8', $name);
move_uploaded_file($_FILES['photo']['tmp_name'], 'photos/' . $name);
mysql_query("INSERT INTO `photos` (`filename`) VALUES ('{$unicode}')");
?>

for reading:
<?php
$images = mysql_query('SELECT * FROM `photos`');
if($images && mysql_num_rows($images) > 0) {
    while($image = mysql_fetch_assoc($images)) {
        $name = iconv('utf-8', 'windows-1256', $image['filename']);
        echo '<img src="photos/' . $name . '"/>';
    }
    mysql_free_result($images);
}?>

A: You can use this
$fn2 = basename($_FILES['upload']['name']);

A: try this
$imgname     = $_FILES['img'] ['name'] ;
$imgsize     = $_FILES['img'] ['size'] ;
$imgtmpname  = $_FILES['img'] ['tmp_name'] ;
$imgtype     = $_FILES['img'] ['type'] ;
$size     = 1024;
$imgtypes    = array('image/jpeg','image/gif','image/png');
$folder = "up";

if(empty($imgname)){
  echo "Shose ur photo";
}else if(!in_array($imgtype,$imgtypes)){
  echo "this photo type is not avalable";
}else if($imgsize > $size){
  echo "this photo is dig than 6 MB";
}else if($imgwidth > 5000){
echo "the file is to big";
}
else{
 move_uploaded_file($imgtmpname, $folder, $filename);
}

A: function convToUtf8($str)
{
if( mb_detect_encoding($str,"UTF-8, ISO-8859-1, GBK")!="UTF-8" )
{

return  iconv("gbk","utf-8",$str);

}
else
{
return $str;
}

}

$filename= convToUtf8($filename) ;


text:
Q: Where to set breakpoint on multi-line statement? Considering the following source code:
1    f(
2      foo(),
3      bar(),
4      spam(a,
5           b,
6      ),
7     )

Where should I set a breakpoint if I want the code to break immediately before calling f, but after calling foo(), bar(), and spam(a, b)?  If I set it at line 1 the breakpoint will occur too early.  But I tried setting it at line 7, and pdb never broke into code in the first place.  Where do I set the breakpoint and why?

A: You can put break point inside the function definition of f then it will break at your desired location. And the reason is f will be called after the execution of foo(),bar() and spam(a,b)
Or
Write a wrapper function
def wrapper(fun,a,b):
    temp = fun(a,b)
    return temp

f(
      foo(),
      bar(),
      wrapper(spam,a,b),
     )

And put beak point at return statement


text:
Q: Promises on non-supported browsers My web page is potentially loaded by some old browsers (specifically, in an Android app with WebView, which may still be used by some pretty old devices)... not that many so I don't want to go to too much trouble to support them fully, but I at least want the page to load.  So, I'd rather not resort to transpilers etc to back everything fully backward compatible.
So how do I make my code "safe" to use on the older browsers?  Those parts of my code that use promises are "optional" in the sense that if they are not accessible then the page will still be of use.  So I'd like some way of including promises in my code without it breaking things for older browsers.
Is it enough to put these parts inside a check for promise support, like if (window.Promise) { myPromise = getMeAPromise(); mPromise.then(...).catch(...); } so that these parts would never be reached by the interpreter?  Or is there a compilation process that would still cause this to fail on a non-supported browser?

A: So long as you test for support in a way that won't fail if it's not there, you don't need to worry. Your if (window.Promise) fits that definition, but if it were me, I'd use if (typeof Promise !== "function"). So perhaps:
var hasPromiseSupport = typeof Promise === "function";

...and then if (hasPromiseSupport) around the optional bits.
All of that said: There are complete Promise polyfills available, so you could conditionally include one:
if (typeof Promise !== "function") {
    document.write('<script src="some-promise-polyfill.js"><\/script>');
}

...and then you'd have promises. (Yes, to my mind this is the one remaining valid use case for document.write.)


text:
Q: I want to add generic type numbers I have a simple class called Employee.
public class Employee<T extends Number> {
    private final String id;
    private final String name;
    private final T salary; //generic type salary

    public Employee(String id,String name,T salary){
        this.id = id;
        this.name = name;
        this.salary = salary;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public T getSalary() {
        return salary;
    }

}

Here using reduction, i am able to add Double type. But i need generic type addition. The values in the salary can be either Double or Integer. So is there any way to use provide any flexibility so that i can add any Sub type of Number.
  public static void main(String[] args) {
        //creates employee list and three employees in it
        List < Employee > employees = new LinkedList < > ();
        employees.add(new Employee("E001", "John", 30000.00));
        employees.add(new Employee("E002", "Mark", 45000.00));
        employees.add(new Employee("E003", "Tony", 55000.00));
        employees.stream().map(Employee::getSalary).reduce(0, (a, b) -> {
        //only able to add double type values, but i need any sub type of number
                return a.doubleValue() + b.doubleValue();
            });
    }

Please help me.

A: I would suggest you to first add the correct generic type arguments in your variable declarations:
List<Employee<Double>> employees = new LinkedList<>(); // you need to add "<>"s here
employees.add(new Employee<>("E001", "John", 30000.00));
employees.add(new Employee<>("E002", "Mark", 45000.00));
employees.add(new Employee<>("E003", "Tony", 55000.00));

Then, this will return a double which is convertible to Number, and Number can be converted to int, float, short etc:
Number num = employees.stream().map(Employee::getSalary).reduce(0.0, (a, b) -> {
        return a + b;
});

Alternatively, just get rid of the generics. Instead of using T, just use Number as the type of salary.
class Employee {
    private final String id;
    private final String name;
    private final Number salary; //generic type salary

    public Employee(String id,String name,Number salary){
        this.id = id;
        this.name = name;
        this.salary = salary;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Number getSalary() {
        return salary;
    }

}

A: There's no easy out of this... As the compiler can't do addition via + on two Numbers. You could of course use a cast here. The deeper problems might arise when an Employee has salary of type Double, but another of type Long for example, in which case casts are going to get pretty nasty.
One approach if you are ok with returning a BigDecimal is this:
  BigDecimal r = employees.stream().map(Employee::getSalary)
            .map(n -> new BigDecimal(n.toString()))
            .reduce(BigDecimal.ZERO, (left, right) -> {
                return new BigDecimal(left.toString()).add(new BigDecimal(right.toString()));
            });


text:
Q: Dynamically create the version number within the Ambari's metainfo.xml file using maven build processes I don't want to hardcode my service version into metainfo.xml, Can I do it?
    <service>
      <name>DUMMY_APP</name>
      <displayName>My Dummy APP</displayName>
      <comment>This is a distributed app.</comment>
      <version>0.1</version> --------------This I don't want to hardcode, Can I doit?
     <components>
     ...
    </components>
  </service>

I am using maven as my build tool.

A: This can be done by using maven's resource filtering. Three steps are required:

*

*Define a maven property that will hold the version number

*Add that maven property in between filter tags in the metainfo.xml file

*Notate in the pom that the metainfo.xml file needs to be filtered.

For example lets assume you want to use the same version as the projects maven version identifier, ${project.version}, as your version in the metainfo.xml file. You would replace <version>0.1</version> with <version>${project.version}</version>. Then in your pom file you would need to list that metainfo.xml file as needing to be filtered. The procedure for this step will vary depending on how you are bundling the custom Ambari service (rpm, assembly, etc.). In general whichever plugin you are using when you list the sources (content to include in the bundle) you will need to specify the path to the metainfo.xml file and make sure filtering is set to true.
Now lets assume you want to create an rpm that will install your artifact. It would look something like this:
Your project structure should be as follows:
--src
  --main
    --resources
      --configuration
      --scripts
      metainfo.xml

Your pom file would look like this:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<version>0.0.1-SNAPSHOT</version>
<artifactId>com.example.project</artifactId>
<packaging>pom</packaging>

<properties>
    <hdp.name>HDP</hdp.name>
    <hdp.version>2.3</hdp.version>
    <stack.dir.prefix>/var/lib/ambari-server/resources/stacks</stack.dir.prefix>
</properties>
<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>rpm-maven-plugin</artifactId>
            <version>2.1.2</version>
            <extensions>true</extensions>
            <executions>
                <execution>
                    <id>generate-hdp-rpm</id>
                    <phase>package</phase>
                    <goals>
                        <goal>attached-rpm</goal>
                    </goals>
                    <configuration>
                        <classifier>hdp</classifier>
                        <needarch>true</needarch>
                        <sourceEncoding>UTF-8</sourceEncoding>
                        <distribution>blah</distribution>
                        <group>something/Services</group>
                        <packager>company</packager>
                        <vendor>company</vendor>
                        <name>SERVICENAME-ambari-hdp</name>
                        <defineStatements>
                            <!-- I use the below line to prevent compiled python scripts from failing the build -->
                            <defineStatement>_unpackaged_files_terminate_build 0</defineStatement>
                            <defineStatement>platform_stack_directory ${stack.dir.prefix}/${hdp.name}/${hdp.version}</defineStatement>
                        </defineStatements>
                        <requires>
                            <require>ambari-server</require>
                        </requires>
                        <mappings>
                            <mapping>
                                <directory>${stack.dir.prefix}/${hdp.name}/${hdp.version}/services/SERVICENAME</directory>
                                <filemode>755</filemode>
                                <username>root</username>
                                <groupname>root</groupname>
                            </mapping>
                            <mapping>
                                <directory>${stack.dir.prefix}/${hdp.name}/${hdp.version}/services/SERVICENAME</directory>
                                <directoryIncluded>false</directoryIncluded>
                                <filemode>755</filemode>
                                <username>root</username>
                                <groupname>root</groupname>
                                <sources>
                                    <source>
                                        <location>src/main/resources/metainfo.xml</location>
                                        <filter>true</filter>
                                    </source>
                                </sources>
                            </mapping>
                            <mapping>
                                <directory>${stack.dir.prefix}/${hdp.name}/${hdp.version}/services/SERVICENAME/configuration</directory>
                                <filemode>755</filemode>
                                <username>root</username>
                                <groupname>root</groupname>
                            </mapping>
                            <mapping>
                                <directory>${stack.dir.prefix}/${hdp.name}/${hdp.version}/services/SERVICENAME/configuration</directory>
                                <directoryIncluded>false</directoryIncluded>
                                <filemode>755</filemode>
                                <username>root</username>
                                <groupname>root</groupname>
                                <sources>
                                    <source>
                                        <location>src/main/resources/configuration</location>
                                    </source>
                                </sources>
                            </mapping>
                            <mapping>
                                <directory>${stack.dir.prefix}/${hdp.name}/${hdp.version}/services/SERVICENAME/package</directory>
                                <filemode>755</filemode>
                                <username>root</username>
                                <groupname>root</groupname>
                            </mapping>
                            <mapping>
                                <directory>${stack.dir.prefix}/${hdp.name}/${hdp.version}/services/SERVICENAME/package/scripts</directory>
                                <filemode>755</filemode>
                                <username>root</username>
                                <groupname>root</groupname>
                            </mapping>
                            <mapping>
                                <directory>${stack.dir.prefix}/${hdp.name}/${hdp.version}/services/SERVICENAME/package/scripts</directory>
                                <directoryIncluded>false</directoryIncluded>
                                <filemode>755</filemode>
                                <username>root</username>
                                <groupname>root</groupname>
                                <sources>
                                    <source>
                                        <location>src/main/resources/scripts</location>
                                    </source>
                                </sources>
                            </mapping>
                        </mappings>
                    </configuration>
                </execution>
                <!-- You may have multiple executions if you want to create rpms for stacks other then HDP -->
            </executions>
        </plugin>
    </plugins>
</build>
<dependencies>
    <!-- List any dependencies you need -->
</dependencies>

This will create an rpm that when installed will add your service to the HDP 2.3 stack. After installing the rpm you would have to restart ambari-server to make sure the new service definition is picked up.
Update:
To create additional RPMs for other stacks, you will need to:

*

*Duplicate the execution block in the rpm-maven-plugin section of the pom.

*Change the id element of the new execution to be unique.

*Modify the mappings to reflect the directory/file structure you want for the other stack.


text:
Q: Finding what gone wrong by checking GDB When I open the core file which has been created by my software I see:
 0x0000000800d2afc7 in g_slice_set_config () from /usr/local/lib/libglib-2.0.so.0
 0x0000000800d2b21b in g_slice_set_config () from /usr/local/lib/libglib-2.0.so.0
 0x0000000800d2b703 in g_slice_free1 () from /usr/local/lib/libglib-2.0.so.0
 0x00000000004a027d in user_free (user=0x859945bc0) at user/user.c:178
 0x00000000004a016c in user_exit () at user/user.c:349
 0x000000000049e865 in dpi_exit () at dpi.c:465
 0x00000000004156ae in worker_run () at itapworker.cpp:818
 0x00000000004168fc in worker_main (wptr=0x8006a7124) at itapworker.cpp:957
 0x0000000000416ddb in spawn_newworker (wptr=0x8006a7124) at itapworker.cpp:265
 0x0000000000416ee6 in spawn_workers () at itapworker.cpp:162
 0x0000000000414569 in main (argc=5, argv=0x7fffffffebc0) at itap.cpp:463

The code I am familiar with in my project is user_free. Inside of user_free:
 static inline void
 user_free(dpi_user_t *user)
 {
    if (user->policy)
        policy_rem_ref(user->policy);
    user_remove(user);
    g_slice_free(dpi_user_t, user);
 }

When I print suspicious pointers:
 (gdb) print user
 $5 = (dpi_user_t *) 0x859945bc0
 (gdb) print user->policy
 $6 = (rbpe_policy_t *) 0x80b1acc20

Because the core happens in the one free function, only thing comes to my mind is null pointer access. But when I check pointers they are not null at all.
Do you guys have any idea what might be the cause?


text:
Q: UDP protocol not supported in mono? I do not understand because it gives me error code:
Socket socket = new Socket(
    AddressFamily.InterNetwork,
    SocketType.Stream,
    ProtocolType.Udp
);

Return an error:
me@machine:~/Demo/bin/Debug$ mono Demo.exe
Marshaling clicked signal
Exception in Gtk# callback delegate
  Note: Applications can use GLib.ExceptionManager.UnhandledException to handle the exception.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Net.Sockets.SocketException: Protocol not supported
  at System.Net.Sockets.Socket..ctor (AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) [0x00000] in <filename unknown>:0
  ...
   at Gtk.Application.gtk_main()
   at Gtk.Application.Run()
   at Demo.MainClass.Main(System.String[] args)

But my system support UDP connections:
me@machine:~$ nc -u -v host.com 53
Connection to host.com 53 port [udp/domain] succeeded!

That I have done wrong?

A: Using a SocketType.Stream for UDP doesn't work, as UDP is not a stream protocol (TCP is). You almost certainly want to use SocketType.Dgram (datagram) for UDP. UDP stands for "User Datagram Protocol" as it is functionally built on datagrams.


text:
Q: CrateDB as timeseries database for Django I am trying to use CrateDB as timeseries database for Django. I am deploying both services on docker for development.
I started by deploying the following versions:

*

*Django: 4.1.3

*CrateDB: 5.1.0

However, I was getting compatibility error: django.db.utils.NotSupportedError: PostgreSQL 11 or later is required (found 10.5).
I have downgraded the Django version to 3.0 where I don't get that error, however now I get this one:
System check identified no issues (0 silenced).
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute
    return self.cursor.execute(sql)
psycopg2.errors.InternalError_: Unknown function: pg_catalog.pg_table_is_visible(c.oid)
CONTEXT:  io.crate.exceptions.SQLExceptions.esToCrateException(SQLExceptions.java:164)
io.crate.exceptions.SQLExceptions.prepareForClientTransmission(SQLExceptions.java:151)
io.crate.protocols.postgres.Messages.sendErrorResponse(Messages.java:190)
io.crate.protocols.postgres.PostgresWireProtocol.handleSingleQuery(PostgresWireProtocol.java:795)
io.crate.protocols.postgres.PostgresWireProtocol.lambda$handleSimpleQuery$3(PostgresWireProtocol.java:748)
java.base/java.util.concurrent.CompletableFuture.uniComposeStage(CompletableFuture.java:1187)
java.base/java.util.concurrent.CompletableFuture.thenCompose(CompletableFuture.java:2309)
io.crate.protocols.postgres.PostgresWireProtocol.handleSimpleQuery(PostgresWireProtocol.java:748)
io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.dispatchMessage(PostgresWireProtocol.java:335)
io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.dispatchState(PostgresWireProtocol.java:325)
io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.channelRead0(PostgresWireProtocol.java:293)
io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.channelRead0(PostgresWireProtocol.java:277)
io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:99)
io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:336)
io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:308)
io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/threading.py", line 980, in _bootstrap_inner
    self.run()
  File "/usr/local/lib/python3.9/threading.py", line 917, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run
    self.check_migrations()
  File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 486, in check_migrations
    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
  File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__
    self.build_graph()
  File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 220, in build_graph
    self.applied_migrations = recorder.applied_migrations()
  File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations
    if self.has_table():
  File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 56, in has_table
    tables = self.connection.introspection.table_names(cursor)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/introspection.py", line 52, in table_names
    return get_names(cursor)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/introspection.py", line 47, in get_names
    return sorted(ti.name for ti in self.get_table_list(cursor)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/introspection.py", line 49, in get_table_list
    cursor.execute("""
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute
    return super().execute(sql, params)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute
    return self.cursor.execute(sql)
django.db.utils.InternalError: Unknown function: pg_catalog.pg_table_is_visible(c.oid)
CONTEXT:  io.crate.exceptions.SQLExceptions.esToCrateException(SQLExceptions.java:164)
io.crate.exceptions.SQLExceptions.prepareForClientTransmission(SQLExceptions.java:151)
io.crate.protocols.postgres.Messages.sendErrorResponse(Messages.java:190)
io.crate.protocols.postgres.PostgresWireProtocol.handleSingleQuery(PostgresWireProtocol.java:795)
io.crate.protocols.postgres.PostgresWireProtocol.lambda$handleSimpleQuery$3(PostgresWireProtocol.java:748)
java.base/java.util.concurrent.CompletableFuture.uniComposeStage(CompletableFuture.java:1187)
java.base/java.util.concurrent.CompletableFuture.thenCompose(CompletableFuture.java:2309)
io.crate.protocols.postgres.PostgresWireProtocol.handleSimpleQuery(PostgresWireProtocol.java:748)
io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.dispatchMessage(PostgresWireProtocol.java:335)
io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.dispatchState(PostgresWireProtocol.java:325)
io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.channelRead0(PostgresWireProtocol.java:293)
io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.channelRead0(PostgresWireProtocol.java:277)
io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:99)
io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:336)
io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:308)
io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)

Any suggestion?

A: A change has just been made in CrateDB ( https://github.com/crate/crate/pull/13223 ) which will allow returning a different PostgreSQL version number, and this would get us past the first issue.
But even with the latest version of Django we would still see this issue with the call to pg_table_is_visible, this is a function that is not currently implemented in CrateDB, this is tracked under https://github.com/crate/crate/issues/7988 . This particular problem can be bypassed by editing /usr/lib/python3/dist-packages/django/db/backends/postgresql/introspection.py and editing the SQL statements there removing the checks on this function, this should be ok if you are using a single schema and a user with sufficient permissions.
I hope that helps, but depending on what you are trying to do another issue you are likely to encounter is with auto-increment columns, by default Django uses data types such as serial (e.g. in django_migrations) and bigserial (for auto fields), CrateDB is a distributed system and it currently does not have a concept of sequences like that. UUIDs could be used instead (see https://code.djangoproject.com/ticket/32577 ).


text:
Q: prefersStatusBarHidden not updating after calling setNeedsStatusBarAppearanceUpdate() Different vcs inside my app show the status bar visible and others are hidden. This is set to YES in the info.pList
 "View controller-based status bar appearance": YES

 // also tried togging this between yes and no
 "Status bar is initially hidden": YES

The app has 2 windows, the main window and a second window. The second window gets presented it front of the main window on a button push. The vc in the second window has the status bar hidden.
The problem is if I'm on a vc (mainVC) inside the main window that shows the status bar, I press the button to show the second window, mainVC's status bar disappears. The second window gets presented and after I dismiss it I send a notification to mainVC to call setNeedsStatusBarAppearanceUpdate() but prefersStatusBarHidden isn't triggered so the status bar stays hidden even though it shouldn't be. I even subclassed a Navigation Controller and added the code there with mainVC as it's root.
Why isn't prefersStatusBarHidden getting called?
I added prefersStatusBarHidden inside the mainVC by itself, the nav to the mainVC by itself, and then in both the mainVC and it's nav at the same time. It's still not getting called after setNeedsStatusBarAppearanceUpdate() gets called in either places.
Subclassed nav:
class MainVCNavController: UINavigationController {

    override init(rootViewController: UIViewController) {
        super.init(rootViewController: rootViewController)

        NotificationCenter.default.addObserver(self, selector: #selector(updateStatusBar), name: NSNotification.Name(rawValue: "updateStatusBar"), object: nil)
    }

    let statusBarHidden: Bool = false

    @objc func updateStatusBar() {
        self.setNeedsStatusBarAppearanceUpdate() // this gets called when the notification is triggered
    }

    override var prefersStatusBarHidden: Bool {
        return statusBarHidden // this doesn't get called after setNeedsStatusBarAppearanceUpdate() is called
    }

    // I added this just to see if it would make a difference but it didn't
    override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
        return .slide
    }

    override open var childViewControllerForStatusBarStyle: UIViewController? {
        return self.topViewController
    }

    override open var childViewControllerForStatusBarHidden: UIViewController? {
        return self.topViewController
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
}

MainVC is the rootVC of the above nav
class MainVCController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(updateStatusBar), name: NSNotification.Name(rawValue: "updateStatusBar"), object: nil)
    }

    let statusBarHidden: Bool = false

    @objc func updateStatusBar() {
        self.setNeedsStatusBarAppearanceUpdate() // this gets called when the notification is called
    }

    override var prefersStatusBarHidden: Bool {
        return statusBarHidden // this doesn't get called after setNeedsStatusBarAppearanceUpdate() is triggered
    }

    // I added this just to see if it would make a difference but it didn't
    override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
        return .slide
    }
}

SecondVC inside the second window has it's status bar hidden. It sends the notification when it's dismissed to the above mainVC:
class SecondController: UIViewController {

    override var prefersStatusBarHidden: Bool {
        return true
    }

    if dismissed {
       NotificationCenter.default.post(name: Notification.Name(rawValue: "updateStatusBar"), object: nil)
    }
}

I also read that I need to call the below to trigger the prefersStatusBarHidden but even when I added these to the updateStatusBar() it didn't make a difference.
navigationController?.setNavigationBarHidden(false, animated: false)
// or
navigationController?.navigationBar.isHidden = false

A: Updating the status bar needs to be on the main thread.
There are two ways to ensure that:
Add notification observer on the main thread: (you don't need to expose the func to objc c):
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "updateStatusBar"), object: nil, queue: .main, using: updateStatusBar)

func updateStatusBar(_ notification: Notification) {
    setNeedsStatusBarAppearanceUpdate()
}

Or update the status bar on the main thread:
NotificationCenter.default.addObserver(self, selector: #selector(updateStatusBar(_:)), name: NSNotification.Name(rawValue: "updateStatusBar"), object: nil)

@objc func updateStatusBar(_ notification: Notification) {

    DispatchQueue.main.sync {
        self.setNeedsStatusBarAppearanceUpdate()
    }
}

A: @zombie's answer about the updating on the main thread 100% worked. On another note he also suggested I use symbolic breakpoints to diagnose the problem. He provided a great link to help:
Symbolic Breakpoints