text:
Q: weighted RDF predicate (owl:ObjectProperty) in RDF a statement is represented with S,P and O; In OWL the owl:ObjectProperty represents the predicate logic.
 (S) (P) (O)
  I like dog

<owl:Class rdf:about="Person" />
<owl:NamedIndividual rdf:about="I">
    <rdf:type rdf:resource="Person"/>
    <like rdf:resource="Dog"/>
</owl:NamedIndividual>

<owl:Class rdf:about="Pet" />
<owl:NamedIndividual rdf:about="Dog">
    <rdf:type rdf:resource="Pet"/>
</owl:NamedIndividual>

<owl:ObjectProperty rdf:about="like">
    <rdfs:domain>
        <owl:Restriction>
            <owl:onProperty rdf:resource="like"/>
            <owl:someValuesFrom rdf:resource="Person"/>
        </owl:Restriction>
    </rdfs:domain>
    <rdfs:range>
        <owl:Restriction>
            <owl:onProperty rdf:resource="like"/>
            <owl:someValuesFrom rdf:resource="Pet"/>
        </owl:Restriction>
    </rdfs:range>
</owl:ObjectProperty>

But how about to describe "the degree" I like dogs?
How can I give a property or value to a predicate?
One solution I got is to extend one (S,P,O) statement to 3 statements.
For example,
(S)             (P)        (O)
 Person       isSrcOf    LikeRelation
 Pet          isTargetOf LikeRelation
 LikeRelation hasValue   [0~100]

It should work but obviously it will let ontology 3 times bigger :(
I appreciate any suggestion!

A: I wouldn't use RDF reification, not in this case and almost not in any case. RDF reification just makes the things always more complicated. As you commented it will inflate your ontology, but not just that, it'll also make your ontology very difficult for applying OWL reasoning.
I've dealt with the same scenario that you've presented and most of times I've ended up with the following design.
(S) (P) [    (P)         (O)         (P)                (O)]
 I like [ 'what I like'  Dog  , 'how much I like it'   'a lot']
Class: LikeLevel //it represents class of things a person likes with a degree factor.

ObjectProperty: likeObject
    Domain: LikeLevel
    Range: Pet //(or Thing)

ObjectProperty: likeScale
    Domain: LikeLevel
    Range: xsd:int //(or an enumeration class i.e: 'nothing', 'a bit', 'very much',...)

ObjectProperty: like
    Domain: Person
    Range: LikeLevel

If you want to represent some instance data with this model (in RDF/Turtle syntax):
:I :like [ a :LikeLevel;
   :likeObject :dogs;
   :likeScale 5.7] .

In this case I'm creating a blank node for the object LikeLevel but you could create a ground object as well, sometimes you might want/need to avoid bNodes. In that case:
:I :like :a0001 .
:a0001 a :LikeLevel;
   :likeObject :dogs;
   :likeScale 5.7.

This design can be consider a light case of reification, the main difference with RDF reification is that keeps the ontology design in the user's model.

A: Your suggestion is a valid one; it is called reification and is the standard way of representing properties inherent to a relationship between two items in an ontology or RDF graph, where statements are made in a pairwise manner between items - it is a limitation of the data model itself that makes reification necessary sometimes.
If you're worried that reification will inflate your ontology, you could try the following instead, but are generally less desirable and come with their own problems:

*

*Create specific properties, such as somewhatLikes, doesntLike, loves; this may be suitable if you have a limited set of alternatives, and don't mind creating the extra properties. This becomes tedious and cumbersome (and I'd go so far as to suggest incorrect) if you intend to encode the 'degree of likeness' with an integer (or any wide range of alternatives) - following this approach, you'd have properties like likes0,  likes1, ..., likes99, likes100. This method would also preclude querying, for example, all dogs that a person likes within a range of degree values, which is possible in SPARQL with the reification approach you've specified, but not with this approach.

*Attach the likesDogs property to the Person instance, if the assertion can be made against the person onto all types/instances of Dog, and not individual instances. This will, of course, be dependent of what you're trying to capture here; if it's the latter, then this also won't be appropriate.

Good luck!

A: I think @msalvadores gets it wrong.
Let's forget about the dogs and likes. What we are really doing here is:
a x b
axb y c
axb z d

where axb is the identifier of the a x b statement, a, b, c, d are subjects or objects and x, y, z are predicates. What we need is binding the a, x, b resources to the axb statement somehow.
This is how reification does it:
axb subject a
axb predicate x
axb object b

which I think is very easy to understand.
Let's check what msalvadores does:
:I :like [ a :LikeLevel;
   :likeObject :dogs;
   :likeScale 5.7] .

we can easily translate this to axb terms
a x w
w type AxbSpecificObjectWrapper
w object b
w y c

which is just mimicking reification with low quality tools and more effort (you need a wrapper class and define an object property). The a x w statement does not makes sense to me; I like a like level, which objects are dogs???

But how about to describe "the degree" I like dogs?

There are 2 ways to do this as far as I can tell with my very limited RDF knowledge.
1.) use reification
stmt_1
    a LikeStatement
    subject I
    predicate like
    object dogs
    how_much "very much"

2.) instantiate a predicate class
I like_1 dogs
like_1
    a Like
    how_much "very much"

It depends on your taste and your actual vocab which one you choose.

How can I give a property or value to a predicate?

I don't think you understand the difference between a predicate and a statement. A great example about it is available here: Simple example of reification in RDF
Tolkien wrote Lord of the rings
Wikipedia said that

The statement here:
that: [Tolkien, wrote, LotR]

If we are making statements about the statement, we write something like this:
[Wikipedia, said, that]

If we are making statements about the predicate then we write something like this:
[Wikipedia, said, wrote]

I think there is a big difference. Reification is about making statements about statements not about predicates...

A: A sentence from Jena's document just catch my eye.
...OWL Full allows ... state the following .... construction:

<owl:Class rdf:ID="DigitalCamera">
  <rdf:type owl:ObjectProperty />
</owl:Class>
..

does OWL Full really allow an ObjectProperty be a Class as well?
If an ObjectProperty could be a Class, and could have individuals then I could describe a statement with
S_individual P_individual O_individual

and I could have further properties on P_individual. Is it right?
or am I missing some points?
since the following RDF is valid, a corresponding OWL should be achievable.
<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:j.0="http://somewhere/" >

  <rdf:Description rdf:about="http://somewhere/Dog_my_dog">
    <j.0:name>Lucky</j.0:name>
  </rdf:Description>
  <rdf:Description rdf:about="http://somewhere/like_dog">
    <j.0:degree>80</j.0:degree>
  </rdf:Description>

  <rdf:Description rdf:about="http://somewhere/Cat_my_cat">
    <j.0:name>Catty</j.0:name>
  </rdf:Description>
  <rdf:Description rdf:about="http://somewhere/like_cat">
    <j.0:degree>86</j.0:degree>
  </rdf:Description>

  <rdf:Description rdf:about="http://somewhere/Person_I">
    <j.0:name>Bob</j.0:name>
    <j.0:like_dog rdf:resource="http://somewhere/Dog_my_dog"/>
    <j.0:like_cat rdf:resource="http://somewhere/Cat_my_cat"/>
  </rdf:Description>

</rdf:RDF>


text:
Q: Is there a way I can determine the source port number? I am working on a couple of network troubleshooting scenarios and I wanted to check if there is a way I can find out what source port my PC is using to connect to a website? I am using Windows 10.
I tried using netstat -a, but this shows a lot of active connections and if my understanding is correct, the port numbers shown here are destination ports, correct?
nestat capture

A: The port numbers are clearly shown in your netstat output, i.e. TCP 10.0.0.166:2424 13.107.5.88:https  means that it connected from the local IP 10.0.0.166 source port 2424 to the remote system 13.107.5.88 on port 443 (https). Note that due to NAT the source IP  on the remote system will be different (i.e. your external IP address) and the source port can be different too, but the value can not be detected on the local system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reference imported class from within imported class For a chess board, imagine there's a Board class, with a squares attribute, which is an array of Square instances. The file structure is that there is main.py, board.py, square.py, and an empty __init__.py (I have to say I don't fully understand the purpose of the latter... but apparently that's the way to do things). These are all in the same directory. (I've not done anything in Python involving multiple files before.)
In main.py I want to instantiate a Board object. Here's the contents of main.py:
from board import Board
from square import Square

board = Board()

here's square.py:
class Square:
    def __init__(self):
        pass
        #this class doesn't do anything yet

and here's board.py:
class Board:
    row_count = 8
    column_count = 8

    def __init__(self):
        self.squares = self.generate_squares()

    def generate_squares(self):
        squares = {}
        for i in range(0, self.row_count * self.column_count):
            squares[i] = Square()
        return squares

However, when I run main.py I get told that there's an error on the squares[i] = Square() line; namely that NameError: global name 'Square' is not defined.
I've tried changing it to squares[i] = square.Square() but that yields the same error.
If I remove the import statements and just copy the class definitions into main.py then the instantiation works fine, so that pinpoints the issue down to being related to the import statements themselves.

A: In main.py you import both classes, however, Board has no way to see Square, and vice versa. Add "import Square" to your Board class, and remove it from main.py.


text:
Q: Is there a terminal command to keep apps from quitting? In macOS Terminal.app how can I issue a command similar to caffeinate that keeps all running applications from quitting?
In my System Preferences I have Energy Saver to: computer sleep-never and Display sleep-never, I even have caffeinate issued in the terminal.
After a while of no keyboard or mouse activity the screen will go to login mode. All apps like Excel and Mail have quit except those that required a save.
Even Terminal is asking if I really want to quit. I want all to be as if I were touching my keyboard every few minutes so not even the login screen shows and Excel never quits.

A: You can use the screen terminal window manager and its detach feature. This command is installed by default on OS X.
Example scenario.

*

*Open a terminal

*Run screen

*Run a program of your choice e.g. htop.

*Suspend this program (Ctrl+z) and run it in background bg

*Detach your current session (Ctrl+a d)

*Exit your session and exit the terminal

*Open the terminal again

*List running session with screen -ls

*Go back to your session with screen -r <session id>

*Use your program again with fg


text:
Q: Keep number picker value when changing tab (fragments) I've got 3 tabs (I'm working with fragments) and each fragment has differents number pickers... I have a problem, I' am on tab 1 and I set numberpicker's value to 25. Ok, when I go for example to tab 2 and afeter I come back to tab 1, the numberpicker's value changes to its default value, I mean, it doesn't keep the value a introduced before... I've solved this with an static class where I save all values, but I have to check that class each time I go from a tab to another one. Is there a different way to keep this values withouth using this static class??
I would appreciate any help. Thanxs a lot.


text:
Q: Displaying tabular data in Android Coming from years of .NET Framework programming experience, I wonder if there is anything in Android out of the box that resembles the .NET WPF component DataGrid: it should be something like an Android AdapterView, where you set the Adapter (ItemsSource in .NET) and it will show up with a table whose rows are populated with data coming from the adapter (I tried using a ListView but it doesn't show like a table).
Thank you in advance


text:
Q: MVC EditorFor model binding for multiple edit forms on one page I have a class called CategoryModel, one of the properties of which is a list of objects of the same type.  So CategoryModel.Categories is of type List<CategoryModel>.
On the category index page, I display an editor for each category so that the user can change any of the category names without having to go to a dedicated page to do so.  Like so:

    @Html.EditorFor(model => model.Categories)

And the editor template for CategoryModel looks like this:

    @using (Html.BeginForm("Edit", "Category", new { id = Model.Key }, FormMethod.Post, new { @class = "ajaxoff"})) {
        @Html.ValidationSummary(true)
        @Html.HiddenFor(model => model.Key)
        @Html.HiddenFor(model => model.ParentKey)
        @Html.HiddenFor(model => model.Sequence)
        @Html.HiddenFor(model => model.IncludeDeleted)

        @Html.TextBoxFor(model => model.Name, null, new { @class = "catName" })
        @Html.ValidationMessageFor(model => model.Name)

        <input type="submit" value="Save" class="icon save" />
    }

The problem I have is that submitting the form does not bind correctly to the Edit action of the CategoryController:
[HttpPost]
public ActionResult Edit(CategoryModel category)
{
    // At this point all properties in category are null
}

If I check the names on the hidden fields and textboxes, they are labelled based on their position in the current category (e.g. Categories[0].Name).  If I create a dedicated edit view, however, they are simply named according to the field name (e.g. Name).
I have tried changing the controller to accept a list of Categories:
[HttpPost]
public ActionResult Edit(List<CategoryModel> categories)
{
    var category = categories.First();
}

This works if I submit the very first category, but none of the others (in those cases Categories is null).
I have also tried changing how I display my EditorFor, by doing this:

    @foreach (var cat in Model.Categories)
    {
        @Html.EditorFor(model => cat);
    }

Which changes the field names to be the same for each category (e.g. all category names are called cat.Name), which I believe is a step in the right direction.
So how do I bind correctly to my controller?  I realise that I could submit the whole parent category and then save each subcategory, but this seems like a very inefficient way to submit a single change.

A: I discovered how to do this.  There is an overload for Html.EditorFor that allows you to specify the htmlFieldName property (the third parameter in the example below):
@foreach (var cat in Model.Categories)
{
    @Html.EditorFor(model => cat, null, "");
}

This renders all of the field names without any prefix and allows me to submit any single category successfully.

A: Your Edit action accept CategoryModel category so you need to reset model prefix for right binding. For this you need to create your own extension method for HtmlHelper like this:
public class BeginHtmlScope : IDisposable
    {
        private readonly TemplateInfo templateInfo;
        private readonly string previousHtmlFieldPrefix;

        public BeginHtmlScope(TemplateInfo templateInfo, string htmlFieldPrefix)
        {
            this.templateInfo = templateInfo;

            previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
            templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
        }

        public void Dispose()
        {
            templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix;

        }
    }
    public static class MyHtmlExtensions
    {
        public static IDisposable BeginHtmlScope(this HtmlHelper html, string htmlFieldPrefix)
        {
            return new BeginHtmlScope(html.ViewData.TemplateInfo, htmlFieldPrefix);
        }
    }

And then use it inside your editor template:
@using (Html.BeginHtmlScope(""))
{

    @using (Html.BeginForm("Edit", "Category", new { id = Model.Key }, FormMethod.Post, new { @class = "ajaxoff"})) {
        @Html.ValidationSummary(true)
        @Html.HiddenFor(model => model.Key)
        @Html.HiddenFor(model => model.ParentKey)
        @Html.HiddenFor(model => model.Sequence)
        @Html.HiddenFor(model => model.IncludeDeleted)

        @Html.TextBoxFor(model => model.Name, null, new { @class = "catName" })
        @Html.ValidationMessageFor(model => model.Name)

        <input type="submit" value="Save" class="icon save" />
    }

}


text:
Q: gcc detecting "subindex out of bound" error Surprisingly I found gcc can find this error when it compiles C. I simplified the code which still triggers the warning. I post the question for making clear the details of the techniques it uses. Below is my code of file a.c
int main(){
  int a[1]={0};
  return(a[1]);
}

My gcc version is gcc (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3. When using gcc a.c -Wall, there is no warning; when using gcc -O1 a.c -Wall, there is a warning:
warning: 'a[1]' is used uninitialized in this function [-Wuninitialized]

and when using gcc -O2 a.c -Wall (or -O3), there is another warning:
warning: array subscript is above array bounds [-Warray-bounds]

The most surprising thing is that, when I give a[1] a value, then none of the above compiling options gives any warning. There is no warning even when I change the index to a huge number (of course the compiled file offends the operating system and will be kicked out),
int main(){
  int a[1]={0};
  a[2147483648]=0;
  return(a[2147483648]);
}

I think the above phenomenon is more of a function than a bug. I hope someone help me figure out what happens, and/or why the compiler is designed so. Many thanks!

A: Accessing memory past the end of the array results in undefined behaviour.
gcc is nice enough to go out of its way to detect, and warn you about, some of these errors. However, it is under no obligation to do so, and certainly cannot be expected to catch all such errors.

A: The compiler is not required to provide diagnostic for this kind of error, but gcc is often able to help; notice that these warnings often arise in part as a byproduct of the static analysis passes done for optimization purposes, which means that, as you noticed, such warnings often depend from the specified optimization level.


text:
Q: Excel file saved with wrap text is opened without wraping in Libreoffice and soffice I have set wrap text for the cell and auto height in Microsoft office 2007 with the new format xlsx (it works the same for the old xls).
When I save the file and when I open it with Libreoffice the wrap text doesn't work (it shows the cell on one row, while the text inside may be is wrapped - but I cannot see it). Then I go to the menu File -> Text -> and I see here Wrap text selected. I deselect it and then the column height automatically changes to height that is the height of the cell with wrapped text, but the text is on one line. Then I go to File -> Text -> Wrap text again and I select it and finally then everything looks normal.
The problem is that I need to have the column height of wrapped text recognized by Libreoffice somehow in order to have everything working right after open the xlsx file, without doing any changes on it.
So is there way to set this row height from Microsoft office in a way that is recognized by Libreoffice. For creating the Microsoft excel file I use template + openpyxl. I have set the wrap text in python over the xlsx template (using openpyxl) and in the template before.
But I think that is not openpyxl specific because using just Microsoft office, saving the xlsx file, and opening with Libreoffice is showing the cell the wrong way.
Using the whole procedure 1.Microsoft xlsx 2.python openpyxl 3. saving the file leads to having normal Microsoft file with row height working , and having one line cell inside Libreoffice for wrapped text.
So I don't know how to solve this. There might be solution using openpyxl or using just microsoft office, but I have to have the file to open in libre office with this wrapped text (row height) working, because afterwards I send the file programmatically to soffice to export it as pdf
subprocess.call(['soffice', '--headless', '--convert-to', 'pdf', path_xlsx, '--outdir', directory_xlsx])

and thus I don't have the option to open the file and change this manually.
Chanigng the pdf export solution is not an option
==============
Before editing the wrap option from Libreoffice the row looks this way in the sheet (this code is extracted from the xlsx archive from the sheet file xl/worksheets/sheet1.xml):
<row r="4" spans="1:13">

after edit it looks like this:
<row r="4" customFormat="false" ht="41.95" hidden="false" customHeight="false" outlineLevel="0" collapsed="false">

So may be if there is a way to add collapsed="false", customHeight="false" and customFormat="false" via openpyxl this could solve the problem.
Edit 1:
I found them in the openpyxl.worksheet.dimensions module. But they cannot be set.

A: The solution for me was to set height on every row depending on the content that it has using openpyxl. This can be done if we use mono font and we calculate the possible width and height depending on the biggest cell in the row. This is not perfect solution, because there can be extra space, and it can break in some cases, so I don't accept this as answer. I have increased the constant giving more space for any case (making the height bigger), and thus this cannot be accepted answer, but still is solution.


text:
Q: Development build + Express.js Разрабатывал фронтенд-часть через vue-cli-service serve, теперь стал делать бэкенд на том же NodeJS + Express.js. Столкнулся с той проблемой, что, используя connect-history-api-fallback, в качестве статических файлов нужно указывать готовую сборку приложения. Соответственно, при внесении любых изменений во фронтенд-часть приложения, приходится заново билдить проект, что не очень удобно.
Есть какие-то способы "подружить" фронтенд и бэкенд часть так, чтобы при внесении изменений в процессе разработки, происходила автоматическая сборка так же, как при разработке с помощью vue-cli-service serve? Например, чтобы development build собирался в отдельной папке и мгновенно пересобирался при изменениях в проекте?

A: vue-cli-service build имеет возможный флаг --watch, который позволяет пересобирать проект при изменениях. Один раз вызываем vue-cli-service build --watch и development сборка будет собираться при каждом изменении.


text:
Q: for loop questions python matching excel I am trying to go through an entire row of cells and compare it to the row of cells on another excel sheet. i have figured it out so that it reads from the sheet, but there must be something wrong with my for loops and if statements. what i am doing is assigning the first cell and then comparing it to the first cell in the other sheet. if they are equal i want it to write a ' ' in a different sheet, at the point of that row in the first sheet. if they aren't the same, i want to see if the first 6 digits are the same, and if they are... i want to write "CHECK" on that cell on the first sheet. i want to keep going down the cells in the second sheet, and until that is all checked, move on to the next cell in the first sheet and start over.
what is wrong with my code here? it is outputting the wrong outputs into the excel sheet.
thank you.
for row in range(sheet.nrows):
     cell = str(sheet.cell_value(row, 0))

         for row in range(windc_sheet.nrows):

             windcell = str(windc_sheet.cell_value(row, 0));

             if cell == windcell:
                outputsheet.write(row, 1, ' ')
             else:
                sixdig = cell[0:6]
                sixdigwind = windcell[0:6]
                if sixdig == sixdigwind:
                    outputsheet.write(row, 1, 'Check')
         else:
             continue;

 else:
     continue

error output onto excel:        wanted output:

check                            check
check
check
check                            check
check

two sheets being compared:
 123456-01            123455-01
 124445               123336-55
 123454-99            123456-02
 123455-03            133377-66
 1277                 199227-22

A: Second iteration is the one that is making the error. Just try this:
for row in range(sheet.nrows):
    cell = str(sheet.cell_value(row, 0))
    windcell = str(windc_sheet.cell_value(row, 0))
    if cell == windcell:
       outputsheet.write(row, 1, ' ')
    else:
       sixdig = cell[0:6]
       sixdigwind = windcell[0:6]
       if sixdig == sixdigwind:
           outputsheet.write(row, 1, 'Check')


text:
Q: Fetching data with axios in react I'm new in react so I'm trying to make a get request with axios in react with a service to get a track and the respective races from it, but I got track like a empty object. I need to know how to make the get request efficiently.
trackUtils.js
import AppDispatcher from '../dispatcher/AppDispatcher';
import ActionTypes from '../constants/AppConstants';
import config from '../../config';
import axios from 'axios';

class trackUtil {

    constructor() {
        this.serverConfig = config.ServiceConfig;
        this.baseURL = this.serverConfig.url + ':' + this.serverConfig.port + '/';
        this.appConfig = config.AppConfig;
    }

    trackRequest(data) {
        const url = this.baseURL + 'BusRace/GetRacesTrack';

        axios.get(url)
            .then((response ) =>  {
                AppDispatcher.dispatch({
                    type: ActionTypes.GET_TRACK,
                    data: { ...response.data.tracks }
                });
                console.log(data);
            })
            .catch((error) => {
                console.log(error);
            });
    };

}

export default new trackUtil();

ConfigStore.js
import { ReduceStore } from 'flux/utils';
import ActionTypes from '../constants/AppConstants';
import AppDispatcher from '../dispatcher/AppDispatcher';
import config from '../../config';

class ConfigStore extends ReduceStore {

    getInitialState() {
        return {
            language: config.SiteConfig.defaultLanguage,
            languageLabels: {},
            tracks : {}

        };
    }

    reduce(state, action) {

        switch (action.type) {
            case ActionTypes.GET_TRACK:
                var newState = Object.assign({}, state);
                newState.tracks = action.data;
                return newState;
            default:
                return state;
        }
    }
}

export default new ConfigStore(AppDispatcher);

EDIT
Adding from my component Body.js
static getStores() {
    return [ConfigStore];
};

static calculateState() {
    let configData = ConfigStore.getState();
    return {
        configInfo: configData,
        local: {"lineTypesDropTitle": ""}
    };
};

componentDidMount() {

    const params = {...this.state, ...{actionType: ActionTypes.GET_TRACK}};
    ActionCreators.actionTrigger(params);
}

Hope someone can help me.

A: Quick thing I noticed was "BusRace/GetRacesTrack" is that correct? not maybe "BusRace/GetRaceTracks", you do refer to tracks as plural in your question.

A: If you are not using Redux or other state management usually a good place to fetch data is componentDidMount(), so you define your component with it's initial state, once the component is mounted the axios call is made and once the data is resolved you update the state. Something like this.
class MyAwesomeComponent extends Component{
    //Defining initial state
    state ={
        data : null
    }

    //Making the API call and once resolved updating the state
    componentDidMount(){
        axios.get('myendpoint').then( res => this.setState({data : res})
    }
}

A: In addition to @Dupocas answer you can also use a functional component for this:
const MyAwesomeComponent = () => {
    //Defining initial state
    const [data, setData] = useState(null)

    //Making the API call and once resolved updating the state
    useEffect(() => axios.get('myendpoint').then( res => setData(res)), [])
}


text:
Q: Instance variables and Inheritance Currently I am trying to calculate the distance between the Image1 and Player classes, in my main(). My variables of interest are Bx,By,Px, and Py seen below. Currently I can get the images in the Pygame window to update and print out their respective coordinates in real time. However I would like to have access to the individual variables so I can implement a distance variable.

class Image1(pygame.sprite.Sprite):
    def __init__(self, img, all_active_sprites):
        super().__init__()

        #scale player image
        self.image = pygame.transform.scale(ImageOne, (100, 100))
        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()

        #set spawn location for image
        self.rect.x = random.randrange(25, WINDOWWIDTH - 25)
        self.rect.y = random.randrange(25, WINDOWHEIGHT - 25)

        #set speed/direction
        self.speed_x = random.choice([-1,1])
        self.speed_y = random.choice([-1,1])

    def update(self):
        ''' update Image1 class '''
        self.rect.y += self.speed_y
        self.rect.x += self.speed_x

        #simulate zigzag movement

        "Omitted for Space - Movement Rules"

        #calculate coordinates
        Bx = self.rect.x
        By = self.rect.y
        coordinates_Image1 = (Bx,By)
        print("Image1 Position:",coordinates_Image1)

class Player(pygame.sprite.Sprite):
    def __init__(self, player_img,all_active_sprites):
        super().__init__()
        #scale player image
        self.image = pygame.transform.scale(player_img, (25, 25))
        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()

        #player starting location
        self.rect.x = WINDOWWIDTH / 2
        self.rect.y = WINDOWHEIGHT/ 2

        #player speed
        self.speed_x = 0
        self.speed_y = 0

    def update(self):
        '''update the Player class'''
        #arrow controls
        "Omitted for Space - Key Commands"

        #update movement, stop at boundaries
        self.rect.x += self.speed_x
        self.rect.y += self.speed_y

        "Omitted for Space - Movement Rules"

        #calculate coordinates
        Px = self.rect.x
        Py = self.rect.y
        coordinates_player = Px,Py
        print("Player Position:",coordinates_player)

My thinking was that I needed to find a way to access these instance variables outside of the locale, so what I tried as a solution was as follows. I separated the coordinates into their own functions inside each class, away from the movement calculations. Then in my main() I created an instance for each class, p = Player(args) for example. I then called the coordinate functions from my main(), and the paired coordinates, (x,y), would print as before but I still could not access/print the individual variables desired. Not sure what I'm doing wrong. Thank you and be well!

A: The variables Px and Py are only in scope in the update() function. They are called "local variables". On the other hand, you have a variable named p which represents an entire player. It has a field p.rect that is its bounding rectangle. And from there you can access p.rect.x and p.rect.y.


text:
Q: Conformal Mapping Question Relating Solution of Laplace Equation on Different Domains
Above is my question. The issue that I'm having is that I find that the given mapping, call it $f$, maps $C_1$ to itself, and $C_2$ maps to a circle of radius $5$ and centre $-2$. As much as this in itself isn't a problem, it doesn't really help me with my question!
We have $f(1) = -1,$ $f(-1) = 1$ and $C_1$ perpendicular to $\Bbb R$ at $1$, so this gives $f(C_1) = C_1$; similarly for $C_2$. Also, $f$ is self-inverse.
How can I use the mapping to solve the equation?
Thanks in advance!

A:
$C_2$ maps to a circle of radius $5$ and centre $−2$.

Wrong. $f(C_2)$ is the circle of radius $2$ centered at $0$. Justification below.

Observe that $C_2$ is symmetric about the real axis. It crosses the axes at $0$ and $4/5$. The map $f$ preserves the real axis. Also, $f(0)=2$ and $f(4/5)=-2$. Hence, $[-2,2]$ is a diameter of $f(C_2)$.
Now that you have concentric circles, it remains to fit a function of the form $a\log|z|+b$ to the boundary values, and then return to original domain.


text:
Q: Powershell - Set -server flag globally (AD cmdlets) I'm trying to set the -server flag globally for a whole script using the Active Directory cmdlets.
My issue is that I am running a script from a different domain, and have a few domains I need to execute these commands on, from a single management domain.
Example:
Get-ADUser 'john' -server domain1.acme.com

However I'd like to just run:
Get-ADUser 'john'

from domain2, without having to specify a -server flag every time I use an AD cmdlet.
Currently, I am simply declaring a $server variable and inserting it into every command, e.g. Get-ADUser 'john' -server $server
But this is rather messy and I feel like there must be a better way. My research has yielded nothing.

A: You can use $PSDefaultParameterValues for this,The below example for adding server parameter default value for get-aduser:
$PSDefaultParameterValues.Add('Get-ADUser:server', 'domain1.acme.com')

after psdefaultparametervalue addition you can use the commandlet like this :
Get-ADUser 'john'

PSDefaultParameterValues supports wildcard as well
$PSDefaultParameterValues.Add('Get-AD*:server', 'localhost')
For reference:
https://blogs.technet.microsoft.com/heyscriptingguy/2012/12/03/use-powershell-default-parameter-values-to-simplify-scripts/
PS: This feature will work only from PowerShell V3 onwards


text:
Q: Magento catalog_eav_attribute foreign key fails phpmyadmin I am trying to do a simple copy of my database using phpmyadmin and I am getting an error seen at this link http://screencast.com/t/WB9WGs6mW
I have tried to dump the database with the disable foreign key option but I still get the same error after importing the database and trying to copy.
I am running magento 1.8.1.0 community just did an update recently from magento 1.8.0.0

A: If you are creating the dump with phpMyAdmin, I suggest you to select "Custom" as export method and tick the "Add drop table" statement in the Object creation options.
Otherwise, If you have access to the shell, you can create a dump with the --opt parameter.
mysqldump -uuser -p --opt dbname > dumpfile.sql

A: Be sure you follow this instructions in phpmyadmin export:

*

*Export Method: custom

*Format specific options: tick Disable foreign keys check

*in Object creation options: tick Add DROP TABLE / VIEW / PROCEDURE / FUNCTION / EVENT statement

*in Data creation options: tick Truncate table before insert

Let me know if it works.


text:
Q: Real Analysis Limit of a Sequence Question I'm working on this question (from an introductory Real Analysis textbook):

Define a sequence $(a_n)^{\infty}_{n=1}$ such that $\lim_{n \to \infty} a_{n^2}$ exists but $\lim_{n \to \infty} a_n$ does not exist.

I've come up with a sequence for which this holds.
Define
$$
a_n =
\left\{\begin{matrix}
0 \; \; \;  \text{if} \; \;  \sqrt{n} \in \mathbb{I}\\
1 \; \; \;  \text{if} \; \;  \sqrt{n} \notin \mathbb{I}
\end{matrix}\right.
$$
where $n \geq 1$ and $n \in \mathbb{I}$. This sequence does not converge, as $(a_n)$ flips between $0$ and $1$, depending on whether or not $\sqrt{n}$ is an integer. However, for $(a_{n^2})$, we have,
$$
a_{n^2} =
\left\{\begin{matrix}
0 \; \; \;  \text{if} \; \;  \sqrt{n^2} \in \mathbb{I}\\
1 \; \; \;  \text{if} \; \;  \sqrt{n^2} \notin \mathbb{I}
\end{matrix}\right.
$$
$$
 =
\left\{\begin{matrix}
0 \; \; \;  \text{if} \; \;  n \in \mathbb{I}\\
1 \; \; \;  \text{if} \; \;  n \notin \mathbb{I}
\end{matrix}\right.
$$
which of course is simply a sequence of zeros and as such "converges" to zero. Have I taken the right approach? Or should I be using the limit definition to define a more general sequence for which the given conditions hold. Thanks for any input.

A: Yeah it works but you could express it simplier with
$$a_n = \left\{ \begin{array}{rl}
1 & \exists k \in \mathbb{N} : k^2=n \\
0 & \text{else} \end{array}\right.$$

A: Your answer is correct and convincing: you needed only to "find" such a sequence, and indeed you did.  I'd simply add that to make the argument fully convincing (or, perhaps more rigorous, as it seems pretty convincing to me), it might be a good idea to demonstrate that it is, indeed, an example of such a sequence (i.e., explicitly prove that indeed, $\;\large a_{n^2}\;$ converges to 0).


text:
Q: bulk delete from a many-to-many relation table based on a WHERE condition that checks ids in two lists Assume that there is an employee table and a project table.
A relationship table emp_proj contains following column: (id, emp_id, proj_id)
I would like to delete rows from emp_proj that contain following pairs of (emp_id, proj_id) : (1,101) , (1,102), (2,202), (3,303)
Note that the table may contain other rows with emp_ids 1, 2 and 3.
How would I use WHERE clause that would compare these pairs ?
I thought of using nesting of ORs but that would complicate the query.
Also I would like to do a bulk delete operation that in one-go, would delete all rows that contain the concerned pairs.

A: On Postgres, your suggested approach might be the only option:
DELETE
FROM emp_proj
WHERE
    emp_id = 1 AND proj_id = 101 OR
    emp_id = 1 AND proj_id = 102 OR
    emp_id = 2 AND proj_id = 202 OR
    emp_id = 3 AND proj_id = 303;

Note that on certain other databases, such as MySQL, you could have used a tuple syntax which is a bit more terse:
DELETE
FROM emp_proj
WHERE
    (emp_id, proj_id) IN ((1, 101), (1, 102), (2, 202), (3, 303));


text:
Q: remove words starting with "@" in a column from a dataframe I have a dataframe called tweetscrypto and I am trying to remove all the words from the column "text" starting with the character "@" and gather the result in a new column "clean_text". The rest of the words should stay exactly the same:

tweetscrypto['clean_text'] = tweetscrypto['text'].apply(filter(lambda x:x[0]!='@', x.split()))

it does not seem to work. Can somebody help?
Thanks in advance

A: Please str.replace string starting with @
Sample Data
                                       text
0  News via @livemint: @RBI bars banks from links
1      Newsfeed from @oayments_source: How Africa
2                   is that bitcoin? not my thing

 tweetscrypto['clean_text']=tweetscrypto['text'].str.replace('(\@\w+.*?)',"")

Still, can capture @ without escaping as noted by @baxx
tweetscrypto['clean_text']=tweetscrypto['text'].str.replace('(@\w+.*?)',"")

                    clean_text
0  News via :  bars banks from links
1         Newsfeed from : How Africa
2      is that bitcoin? not my thing

A: In this case it might be better to define a method rather than using a lambda for mainly readability purposes.
def clean_text(X):
    X = X.split()
    X_new = [x for x in X if not x.startswith("@")
    return ' '.join(X_new)

tweetscrypto['clean_text'] = tweetscrypto['text'].apply(clean_text)


text:
Q: How to calculate custom fiscal year in pandas? I have a dataframe like as shown below
app_date
20/3/2017
28/8/2017
18/10/2017
15/2/2017
2/5/2017
11/9/2016

df = pd.read_clipboard()

Our company fiscal year is from October of current year to September of next year
Q1 - Oct to Dec
Q2 - Jan to Mar
Q3 - Apr to Jun
Q4 - July - Sep

I was trying something like below
tf['app_date'] = pd.to_datetime(tf['app_date'])
tf['act_month'] = pd.DatetimeIndex(tf['app_date']).month
tf['act_year'] = pd.DatetimeIndex(tf['app_date']).year
tf['act_qtr'] = tf['app_date'].dt.to_period('Q').dt.strftime('Q%q')
tf['comp_fis_year'] = np.where(tf['act_month'] >= 9,tf['act_year']+1,tf['act_year'])
tf['comp_fis_qtr'] = tf['app_date'].dt.to_period('Q').add(1).dt.strftime('Q%q') #thanks to jezrael for this trick to get quarter

Is there any elegant and efficient way to do the above? Mainly for calculating the fiscal year based on our financial year (Oct to Sep)?
I expect my output to be like as shown below

A: IIUC, use to_period with a custom frequency:
pd.to_datetime(df['app_date'], dayfirst=True).dt.to_period('Q-SEP')

output:
0    2017Q2
1    2017Q4
2    2018Q1
3    2017Q2
4    2017Q3
5    2016Q4
Name: app_date, dtype: period[Q-SEP]

for separate columns:
s = pd.to_datetime(df['app_date'], dayfirst=True).dt.to_period('Q-SEP')
s.astype(str).str.extract('(?P<year>\d+)(?P<quarter>Q\d+)')

output:
   year quarter
0  2017      Q2
1  2017      Q4
2  2018      Q1
3  2017      Q2
4  2017      Q3
5  2016      Q4

Q start/end:
df['Q'] = pd.to_datetime(df['app_date'], dayfirst=True).dt.to_period('Q-SEP')
df['Qstart'] = df['Q'].dt.asfreq('D', 's')
df['Qend'] = df['Q'].dt.asfreq('D', 'e')

output:
     app_date       Q      Qstart        Qend
0   20/3/2017  2017Q2  2017-01-01  2017-03-31
1   28/8/2017  2017Q4  2017-07-01  2017-09-30
2  18/10/2017  2018Q1  2017-10-01  2017-12-31
3   15/2/2017  2017Q2  2017-01-01  2017-03-31
4    2/5/2017  2017Q3  2017-04-01  2017-06-30
5   11/9/2016  2016Q4  2016-07-01  2016-09-30

A: You can use:
# Create 2 DatetimeIndex instead of a Series (avoid using .dt accessor)
start = pd.to_datetime(df['app_date'].values, dayfirst=False)
end = start + pd.DateOffset(months=3)

cols = ['act_month', 'act_year', 'act_qtr', 'comp_fis_year', 'comp_fis_qtr']
df = df.join(pd.DataFrame([start.month, start.year, 'Q' + start.quarter.astype(str),
                           end.year, 'Q' + end.quarter.astype(str)],
                           index=cols).T)

Output:
>>> df
     app_date act_month act_year act_qtr comp_fis_year comp_fis_qtr
0   3/20/2017         3     2017      Q1          2017           Q2
1   8/28/2017         8     2017      Q3          2017           Q4
2  10/18/2017        10     2017      Q4          2018           Q1
3   2/15/2017         2     2017      Q1          2017           Q2
4    2/5/2017         2     2017      Q1          2017           Q2
5   11/9/2016        11     2016      Q4          2017           Q1

Setup:
app_date
3/20/2017
8/28/2017
10/18/2017
2/15/2017
2/5/2017
11/9/2016

df = pd.read_clipboard()


text:
Q: In shinydashboard how to maintain on the same tabItem panel after click on refresh button This is my shinydashboard code:
library(shiny)
library(shinydashboard)

ui <- dashboardPage(dashboardHeader(title = p("Title")),

                    dashboardSidebar(skin = 'light',
                                     collapsed = TRUE,
                                     tags$head(tags$style(HTML('.content-wrapper { height: 1500px !important;}'))),
                                     sidebarMenu( id = "sidebarMenu",
                                                  menuItem(text = p(style = 'sidebar_menu_li',"Screen 1", style = "font-size: 1.25em;"), tabName = "panel_1"),
                                                  menuItem(text = p(style = 'sidebar_menu_li',"Screen 2", style = "font-size: 1.25em;"), tabName = "panel_2"),
                                                  menuItem(text = p(style = 'sidebar_menu_li',"Screen 3", style = "font-size: 1.25em;"), tabName = "panel_3"),
                                                  menuItem(text = p(style = 'sidebar_menu_li',"Screen 4", style = "font-size: 1.25em;"), tabName = "panel_4"))
                    ),

                    dashboardBody(
                      tabItems(
                        tabItem(tabName = "panel_1" ,h1("Title 1")),
                        tabItem(tabName = 'panel_2',h1("Title 2")),
                        tabItem(tabName = 'panel_3',h1("Title 3")),
                        tabItem(tabName = "panel_4",h1("Title 4"),
                                actionButton("submit1" ,"Submit", icon("refresh"),
                                             class = "btn btn-primary")))

                    )
)

server <- function(input, output, session) {
  observeEvent(input$submit1, {
    session$reload()})

}

shinyApp(ui, server)

Once I click on Submit button on Screen/TabItem 4 I would like to saty on this Screen (Screen) 4, instead once I click on refresh button I come back to the Screen 1.
Any help?

A: Okay, since it sounds like shinyjs::reset() can work for you, I used your code to show an example of how it would work, refreshing several inputs in one page. You can individually reset inputs, or if you wrap a whole page in a div, you can reset multiple items at once. To test it, just put some random text in the textInput() found on panel 4, then press the submit button, and they should all return to their default empty value. Hopefully this helps you proceed, good luck!
library(shiny)
library(shinydashboard)
library(shinyjs)

ui <- dashboardPage(dashboardHeader(title = p("Title")),

                    dashboardSidebar(skin = 'light',
                                     collapsed = TRUE,
                                     tags$head(tags$style(HTML('.content-wrapper { height: 1500px !important;}'))),
                                     sidebarMenu( id = "sidebarMenu",
                                                  menuItem(text = p(style = 'sidebar_menu_li',"Screen 1", style = "font-size: 1.25em;"), tabName = "panel_1"),
                                                  menuItem(text = p(style = 'sidebar_menu_li',"Screen 2", style = "font-size: 1.25em;"), tabName = "panel_2"),
                                                  menuItem(text = p(style = 'sidebar_menu_li',"Screen 3", style = "font-size: 1.25em;"), tabName = "panel_3"),
                                                  menuItem(text = p(style = 'sidebar_menu_li',"Screen 4", style = "font-size: 1.25em;"), tabName = "panel_4"))
                    ),

                    dashboardBody(
                      useShinyjs(), #Need this for shinyjs to work
                      tabItems(
                        tabItem(tabName = "panel_1" ,h1("Title 1")),
                        tabItem(tabName = 'panel_2',h1("Title 2")),
                        tabItem(tabName = 'panel_3',h1("Title 3")),
                        tabItem(tabName = "panel_4",h1("Title 4"),
                                div(id = "text_reset", #Wrapping the text inputs in a div, to reset all of them at once
                                textInput("text_1", "Text_1"), #Added some text inputs to demonstrate shinyjs reset
                                textInput("text_2", "Text_2"),
                                textInput("text_3", "Text_3"),
                                textInput("text_4", "Text_4")
                                ),
                                actionButton("submit1" ,"Submit", icon("refresh"),
                                             class = "btn btn-primary")))

                    )
)

server <- function(input, output, session) {
  observeEvent(input$submit1, {
    shinyjs::reset("text_reset") #Using reset instead of session$reload
    # session$reload()
    })

}

shinyApp(ui, server)


text:
Q: Access StoryBoard defined in GridView DataTemplate for specific instance of GridViewItem Ok so I have a GridView with a DataTemplate and the ItemSource set to Binding. The GridView is populated perfectly and I have no issues there.
My problem is as follows

*

*User taps on an image inside the DataTemplate

*A Flyout is displayed showing a simple ListView of the GridView items (works)

*User taps on a ListView item inside the flyout

*The GridView item matching the ListView item is then updated (works fine)

*A StoryBoard should be started (doesn't work)

The idea is that one player has attacked another player and I would like an animation to be started on the attacked player, but I can only access the attacking player using (sender).
The storyboard is defined within the GridViewItem DataTemplate, I can access this if that GridViewItem was tapped by using the sender and .Find() However I cannot use this I want to start a storyboard on a GridViewItem that hasn't been tapped.
I had a thought that maybe the Storyboard could be written inside the class used for the GridViewItem Bindings? How then would this be done?
Or maybe use a DataTrigger, but can this be used when the value I want to check against is and int being reduced?

A: Use .Resources["MyStoryboard"] as Storyboard to get the Storyboard which is defined inside the DataTemplate. Also, use the ContainerFromIndex to get the item from the index.
Here is a code sample
In XAML
<DataTemplate>
    <Grid Name="MyGrid">
        <Grid.Resources>
            <Storyboard x:Name="MyStoryboard"/>
        </Grid.Resources>
        ....
    </Grid>
</DataTemplate>

In Code Behind
private void StartStoryboard(int index)
{
    var MyGridViewItem = MyGridView.ContainerFromIndex(index);
    Storyboard MyStoryboard = MyGridViewItem.Resources["MyStoryboard"] as Storyboard;
    MyStoryboard.Begin();
}

Now you can use StartStoryboard(index) to start the Storyboard when ever you want.

A: How do I access a control inside a XAML DataTemplate?
the link above talks about a similar issue, using the FindControl function worked a charm


text:
Q: Exclude a class in gradle I am trying to exclude a particular class from build but apparently it doesn`t work. This is how my gradle looks. Any solutions?
   android {
    sourceSets {
            main {
                java {
                    filter.excludes = [
                        'path/MyClass.java',
                      ]
                }
    }
    }
}


text:
Q: How to call useSelector inside callback This is a follow up question to this question:
How to call useDispatch in a callback
I got a React component which needs to receive information from redux in its props. The information is taken using a custom hook.
This is the custom hook:
  export function useGetData(selectorFunc)
  {
    return type =>
    {
      if(!type)
      {
        throw new Error("got a wrong type");
      }
      let myData = selectorFunc(state =>
      {
        let res = JSON.parse(sessionStorage.getItem(type));
        if(!res )
        {
          res = state.myReducer.myMap.get(type);
        }
        return res;
      });
      return myData;
    }
  }

Based on the answer for the linked question, I tried doing something like this:
function Compo(props)
{
   const getDataFunc = useGetData(useSelector);
   return <MyComponent dataNeeded = { getDataFunc(NeededType).dataNeeded } />
}

but I get an error because an hook can not be called inside a callback.
How can I fix this issue?

A: Don't pass the selector, just use it.
Also, according to your logic, you should parse the storage key outside the selector.
export function useDataFunc() {
  const myData = useSelector(state => myReducer.myMap);

  const getDataFunc = type => {
    const resByData = myData.get(type);
    try {
      // JSON.parse can throw an error!
      const res = JSON.parse(sessionStorage.getItem(type));
    } catch (e) {
      return resByData;
    }
    return res ? res : resByData;
  };
  return getDataFunc;
}

function Compo(props) {
  const getDataFunc = useDataFunc();
  return <MyComponent dataNeeded={getDataFunc(NeededType).dataNeeded} />;
}

A: I think it should be like,
const myData = useSelector(state => state.myReducer.myMap);


text:
Q: SMTP config and java error in ReportServer. No password supplied for PKCS#12 KeyStore I am trying to config smtp for scheduled reports in ReportServer.
So my smtp congif:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
   <smtp>
      <host>smtp.gmail.com</host>
      <port>587</port>
      <username>xxx@gmail.com</username>
      <password>xxx</password>

      <ssl>false</ssl>
      <tls>
         <enable>true</enable>
         <require>false</require>
      </tls>
   </smtp>
   <mail>
      <sender>xxx@gmail.com</sender>
      <forceSender>false</forceSender>
      <encryptionPolicy>allow_mixed</encryptionPolicy>
   </mail>
</configuration>

I tried different configurations using ssl true, port 465.
https://forum.reportserver.net/viewtopic.php?pid=2291#p2291
I also used this configuration on Knowage BI and it worked but it did not have scheduler on free version so I tried ReportServer.
Now I can't figure this error out:
java.lang.RuntimeException: javax.mail.MessagingException: Could not convert socket to TLS;
  nested exception is:
    java.net.SocketException: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext)
    at net.datenwerke.rs.scheduler.service.scheduler.mail.MailReportAction$1.handleException(MailReportAction.java:149)
    at net.datenwerke.rs.core.service.mail.MailServiceImpl.sendMailSync(MailServiceImpl.java:243)
    at net.datenwerke.rs.scheduler.service.scheduler.mail.MailReportAction.doExecute(MailReportAction.java:140)
    at net.datenwerke.scheduler.service.scheduler.entities.AbstractAction.execute(AbstractAction.java:59)
    at net.datenwerke.scheduler.service.scheduler.tasks.SchedulerTask.executeAction(SchedulerTask.java:495)
    at net.datenwerke.scheduler.service.scheduler.tasks.SchedulerTask.executeActions(SchedulerTask.java:385)
    at net.datenwerke.scheduler.service.scheduler.tasks.SchedulerTask.safeCall(SchedulerTask.java:209)
    at net.datenwerke.scheduler.service.scheduler.tasks.SchedulerTask.call(SchedulerTask.java:101)
    at net.datenwerke.scheduler.service.scheduler.tasks.SchedulerTask.call(SchedulerTask.java:1)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: javax.mail.MessagingException: Could not convert socket to TLS;
  nested exception is:
    java.net.SocketException: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext)
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1918)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:652)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at net.datenwerke.rs.core.service.mail.MailServiceImpl.sendMailSync(MailServiceImpl.java:233)
    ... 11 more
Caused by: java.net.SocketException: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext)
    at java.base/javax.net.ssl.DefaultSSLSocketFactory.throwException(SSLSocketFactory.java:263)
    at java.base/javax.net.ssl.DefaultSSLSocketFactory.createSocket(SSLSocketFactory.java:285)
    at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:484)
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1913)
    ... 18 more
Caused by: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext)
    at java.base/java.security.Provider$Service.newInstance(Provider.java:1831)
    at java.base/sun.security.jca.GetInstance.getInstance(GetInstance.java:236)
    at java.base/sun.security.jca.GetInstance.getInstance(GetInstance.java:164)
    at java.base/javax.net.ssl.SSLContext.getInstance(SSLContext.java:168)
    at java.base/javax.net.ssl.SSLContext.getDefault(SSLContext.java:99)
    at java.base/javax.net.ssl.SSLSocketFactory.getDefault(SSLSocketFactory.java:123)
    at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:479)
    ... 19 more
Caused by: java.lang.NullPointerException: No password supplied for PKCS#12 KeyStore.
    at org.bouncycastle.jce.provider.JDKPKCS12KeyStore.engineLoad(Unknown Source)
    at java.base/java.security.KeyStore.load(KeyStore.java:1479)
    at java.base/sun.security.ssl.TrustStoreManager$TrustAnchorManager.loadKeyStore(TrustStoreManager.java:365)
    at java.base/sun.security.ssl.TrustStoreManager$TrustAnchorManager.getTrustedCerts(TrustStoreManager.java:313)
    at java.base/sun.security.ssl.TrustStoreManager.getTrustedCerts(TrustStoreManager.java:55)
    at java.base/sun.security.ssl.TrustManagerFactoryImpl.engineInit(TrustManagerFactoryImpl.java:49)
    at java.base/javax.net.ssl.TrustManagerFactory.init(TrustManagerFactory.java:278)
    at java.base/sun.security.ssl.SSLContextImpl$DefaultManagersHolder.getTrustManagers(SSLContextImpl.java:1052)
    at java.base/sun.security.ssl.SSLContextImpl$DefaultManagersHolder.<clinit>(SSLContextImpl.java:1022)
    at java.base/sun.security.ssl.SSLContextImpl$DefaultSSLContext.<init>(SSLContextImpl.java:1197)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at java.base/java.security.Provider.newInstanceUtil(Provider.java:153)
    at java.base/java.security.Provider$Service.newInstance(Provider.java:1824)
    at java.base/sun.security.jca.GetInstance.getInstance(GetInstance.java:236)
    at java.base/sun.security.jca.GetInstance.getInstance(GetInstance.java:164)
    at java.base/javax.net.ssl.SSLContext.getInstance(SSLContext.java:168)
    at java.base/javax.net.ssl.SSLContext.getDefault(SSLContext.java:99)
    at java.base/javax.net.ssl.SSLSocketFactory.getDefault(SSLSocketFactory.java:123)
    at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:479)
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1913)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:652)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at net.datenwerke.rs.core.service.mail.MailServiceImpl.sendMailSync(MailServiceImpl.java:233)
    at net.datenwerke.rs.core.service.mail.MailServiceImpl$1.run(MailServiceImpl.java:266)
    ... 3 more

So I read a few topics, maybe I am missing certificate, I am not sure. Kind of fresh here.
Additional information:
Java jdk_1.8.0_202
Windows 7
Thanks for the help.

A: I solved this issue myself.
I checked log files and found a warning message: "server certificate does NOT include an ID which matches the server name".
After some digging opened openssl.exe. It gave an error it cannot find ssi.conf file, wrong path.
Fixed it.
Scheduler and mailing works fine now. :)


text:
Q: Draw new sphere in front of the camera in 3D animation With the use of Python and OpenGL, I created an optic flow animation, where a camera moves towards spheres (the circles displayed in the GIF).

I tried to create two conditions within the loop that updates the camera position frame by frame, and plays the animation :
near_z = -0.05;
far_z = -50.0;
nSpheres = 40;

for nframes in range(200):
   camera_z -= .7  # the camera moves with a speed of .7 on the z-axis.

1 - The first condition says that when the camera reaches the far clip plane (far_z), get the camera back to the near clip plane again (near_z). As you can see in the GIF, it is working.
camera_z = np.where(camera_z <= far_z, near_z, camera_z)

2- The second condition says that when a camera passes a sphere, redraw a new sphere in front of the camera, that way I would maintain the same number of spheres in the animation. So Every time a sphere disappears from the frame, redraw one. For some reason, it is not working. I tried to figure out why, but I am obviously failing.
if sphere.position.z >= camera_z: # if the sphere is behind the camera, so the sphere is not visible

           sphere.position.z = np.random.uniform(camera_z,far_z) # define a new position for the sphere in front of the camera.

Thanks in advance for your help!!

A: near_z respectively far_z are no absolute coordinates. This are relative distances to the current z coordinate of the camera.
So it has to be:
sphere.position.z = np.random.uniform(camera_z+near_z, camera_z+far_z)

But be aware, if the camera is "reset", by

camera_z = np.where(camera_z <= far_z, near_z, camera_z)

then suddenly all the spheres are out of the viewing frustum and clipped by the far plane.
In this case you've to translate all the spheres by the distance from the near plane to the far plane.
In this context near_z and far_z are "absoulte" coordinates (for a moment).
e.g. (instead of camera_z = np.where(camera_z <= far_z, near_z, camera_z):
if camera_z > far_z:
    offset_z = far_z - near_z
    camera_z -= offset_z
    for sphere in spheres:
        sphere.position.z -= offset_z


text:
Q: Битовый сдвиг для набора байт Есть byte[]
Требуется выполнить для него битовый сдвиг влево или вправо с минимальными затратами.
В поиске решений я наткнулся на BitArray. Один из его конструкторов принимает массив байт. Класс позволяет выполнять различные битовые операции (AND NOT OR XOR), но не позволяет делать сдвиги.

A: #region сдвиг на 1 бит

byte[] myBytes;
BitArray gamma_value = new BitArray(myBytes);

int len = gamma_value.Length; //длина массива бит
c = gamma_value[0]; //младший бит

//создание массива типа bool
//такой же длины как gamma_value типа BitArray
bool[] gamma_new = new bool[len];

//копируем массив типа BitArray в массив типа bool
gamma_value.CopyTo(gamma_new, 0);

//копируем массив bool со сдвигом на 1ну позицию в другой массив bool
Array.Copy(gamma_new, 1, gamma_new, 0, len - 1);

//преобразование массива типа bool в массив типа BitArray
gamma_value = new BitArray(gamma_new);

gamma_value.CopyTo(myBytes, 0); //переводим массив бит в массив байт

#endregion

A: Идея состоит в ручном копировании битов. То есть если делаем сдвиг влево на 4 бита, то копируем в 0-й бит 4-й бит, в 1-й - 5-й и т.д. Соответственно, в, например, 15-й бит (2-й байт) копируется 19-й бит (3-й байт).
Для сдвига вправо - аналогично.
private static readonly byte[] bits = new byte[] { 0x80, 0x40, 0x20, 0x10, 8, 4, 2, 1 };

public static byte[] ShiftLeft(byte[] array, int shift)
{
    var result = new byte[array.Length];
    var totalLength = array.Length * 8;
    for (var toIndex = 0; toIndex < totalLength - shift; toIndex++)
    {
        var fromIndex = toIndex + shift;
        SetBit(fromIndex, toIndex, array, result);
    }
    return result;
}

public static byte[] ShiftRight(byte[] array, int shift)
{
    var result = new byte[array.Length];
    var totalLength = array.Length * 8;
    for (var toIndex = totalLength - 1; toIndex >= shift; toIndex--)
    {
        var fromIndex = toIndex - shift;
        SetBit(fromIndex, toIndex, array, result);
    }
    return result;
}

private static void SetBit(int fromIndex, int toIndex, byte[] fromArray, byte[] toArray)
{
    var fromByte = fromArray[fromIndex / 8];
    var fromBit = bits[fromIndex % 8];
    if ((fromByte & fromBit) != 0)
    {
        toArray[toIndex / 8] |= bits[toIndex % 8];
    }
}

A: Можно было бы попробовать
return ((new System.Numerics.BigInteger(b)) << k).ToByteArray()

хотя потенциальные 3 копирования массива несколько настораживают.
Впрочем, можно заглянуть в его исходники и как-то использовать соответствующий код:
public static BigInteger operator <<(BigInteger value, int shift) {

    if (shift == 0) return value;
    else if (shift == Int32.MinValue) return ((value >> Int32.MaxValue) >> 1);
    else if (shift < 0) return value >> -shift;

    int digitShift = shift / kcbitUint;
    int smallShift = shift - (digitShift * kcbitUint);

    uint[] xd; int xl; bool negx;
    negx = GetPartsForBitManipulation(ref value, out xd, out xl);

    int zl = xl + digitShift + 1;
    uint[] zd = new uint[zl];

    if (smallShift == 0) {
        for (int i = 0; i < xl; i++) {
            zd[i + digitShift] = xd[i];
        }
    } else {
        int carryShift = kcbitUint - smallShift;
        uint carry = 0;
        int i;
        for (i = 0; i < xl; i++) {
            uint rot = xd[i];
            zd[i + digitShift] = rot << smallShift | carry;
            carry = rot >> carryShift;
        }
        zd[i + digitShift] = carry;
    }
    return new BigInteger(zd, negx);
}

A: Сдвиг придётся реализовывать алгоритимчески: требуется на основе величины сдвига в цикле определить в какой байт попадут данные из текущего байта. Данные байта делятся на две части: смещённая и смещаемая часть.
Задание решить несложно, но это требует времени. Советую разбить задачу на несколько частей, например:
превратить любое отрицательное смещение в положительное;
сделать переход по всем байтам в цикле;
разбить байт на две части - та что выпала после смещения и вторая;
в локальные переменные записать значения новых индексов и смещения в их байтах для данных текущего байта;
записать в другой массив такой же длинны по смещённым индексам

A: /// <summary>
/// Rotates the bits in an array of bytes to the left.
/// </summary>
/// <param name="bytes">The byte array to rotate.</param>
public static void RotateLeft(byte[] bytes)
{
    bool carryFlag = ShiftLeft(bytes);

    if (carryFlag == true)
    {
        bytes[bytes.Length - 1] = (byte)(bytes[bytes.Length - 1] | 0x01);
    }
}

/// <summary>
/// Rotates the bits in an array of bytes to the right.
/// </summary>
/// <param name="bytes">The byte array to rotate.</param>
public static void RotateRight(byte[] bytes)
{
    bool carryFlag = ShiftRight(bytes);

    if (carryFlag == true)
    {
        bytes[0] = (byte)(bytes[0] | 0x80);
    }
}

/// <summary>
/// Shifts the bits in an array of bytes to the left.
/// </summary>
/// <param name="bytes">The byte array to shift.</param>
public static bool ShiftLeft(byte[] bytes)
{
    bool leftMostCarryFlag = false;

    // Iterate through the elements of the array from left to right.
    for (int index = 0; index < bytes.Length; index++)
    {
        // If the leftmost bit of the current byte is 1 then we have a carry.
        bool carryFlag = (bytes[index] & 0x80) > 0;

        if (index > 0)
        {
            if (carryFlag == true)
            {
                // Apply the carry to the rightmost bit of the current bytes neighbor to the left.
                bytes[index - 1] = (byte)(bytes[index - 1] | 0x01);
            }
        }
        else
        {
            leftMostCarryFlag = carryFlag;
        }

        bytes[index] = (byte)(bytes[index] << 1);
    }

    return leftMostCarryFlag;
}

/// <summary>
/// Shifts the bits in an array of bytes to the right.
/// </summary>
/// <param name="bytes">The byte array to shift.</param>
public static bool ShiftRight(byte[] bytes)
{
    bool rightMostCarryFlag = false;
    int rightEnd = bytes.Length - 1;

    // Iterate through the elements of the array right to left.
    for (int index = rightEnd; index >= 0; index--)
    {
        // If the rightmost bit of the current byte is 1 then we have a carry.
        bool carryFlag = (bytes[index] & 0x01) > 0;

        if (index < rightEnd)
        {
            if (carryFlag == true)
            {
                // Apply the carry to the leftmost bit of the current bytes neighbor to the right.
                bytes[index + 1] = (byte)(bytes[index + 1] | 0x80);
            }
        }
        else
        {
            rightMostCarryFlag = carryFlag;
        }

        bytes[index] = (byte)(bytes[index] >> 1);
    }

    return rightMostCarryFlag;
}

A: В результате у меня получились 2 функции:
Сдвиг влево
public static byte[] ShiftLeft(byte[] src, int val)
{
    var res = new byte[src.Length];
    var byteShift = val >> 3;
    if (byteShift >= src.Length)
        return res;
    val ^= byteShift << 3;

    for (var i = 1; i < src.Length - byteShift; i++)
        res[i + byteShift] = (byte)((src[i] << val) | src[i - 1] >> 8 - val);

    res[byteShift] = (byte)(src[0] << val);
    return res;
}

И сдвиг вправо
public static byte[] ShiftRight(byte[] src, int val)
{
    var res = new byte[src.Length];
    var byteShift = val >> 3;
    if (byteShift >= src.Length)
        return res;
    val ^= byteShift << 3;

    for (var i = byteShift; i < src.Length - 1; i++)
        res[i - byteShift] = (byte)((src[i] >> val) | src[i + 1] << 8 - val);

    res[src.Length - byteShift - 1] = (byte)(src[src.Length - 1] >> val);
    return res;
}

Функции "как есть" предполагают правильное использование. Для меня очень важна скорость, поэтому я не стал делать проверку на отрицательные значения. В идеале отрицательный сдвиг влево - это сдвиг вправо на то же число по модулю.
Так же можно было добавить проверки на нулевой сдвиг, на сдвиг кратный 8 и тд. Возможно, это ускорит общий процесс, но, как показала практика, такие случаи бывают реже, чем в каждом восьмом сдвиге, а каждое условие и операция добавляют дополнительное время выполнения.
И да, Regent говорил что-то про порядок байтов. Я не стал в этом разбираться, потому что тот вариант, который есть сейчас меня полностью устраивает. Если вы получите набор байт из числа типа long и выполните сдвиг моей функцией, то вы получите тот же результат, как если вы сначала выполните такой же сдвиг для числа, а затем получите из результата набор байтов. Набор байтов из числа я получаю функцией BitConverter.GetBytes(theLong)
На данный момент на моем компе мои функции выполняют 10млн сдвигов за 700-900 мс при величине сдвига 0-7 и время обратно пропорционально величине сдвига деленной на 8. То есть то же самое количество сдвигов на 8-15 выполнится быстрее, чем на 0-7, а на 16-23 еще быстрее и тд...
UPD
Указанное время на выполнение указано для Debug. В релизе все работает в 3-4 раза быстрее.


text:
Q: Knockout Template Binding ViewModel data as argument I am reposting this as my older post was not very clear.
I have a KO View Model liek this with a complex object like this (with lists and child lists, etc.) - much simplified than what I actually have:
$(function () {

function MyViewModel() {
  this.collection = {
    List: [{ name: 'amar', progress: 20 },
           { name: 'vijay', progress: 50}]
  }
}

ko.applyBindings(new MyViewModel());

Then at some point I am passing an object (that is deep inside the KO View Model) to a function like this where I want to create a div for that item:
var createDivs = function (item) {
// "task-template" is defined in my html
var itemDiv = $("

");
itemDiv.appendTo("#ParentDiv");
}

But, as you can see in the above code, I am not sure how to refer the item object (or specify that as the data source) while defining the itemDiv template? Can someone help?
The requuirement is that I want to bind the style of this div to some property in the item (that's in the KO view model).
Thanks

A: Check out the $parent, $parents, and $root objects http://knockoutjs.com/documentation/foreach-binding.html


text:
Q: Form within Iframe not submitted in IE11 using Jquery From below code, the alert function should be executed after the form submit.But it executes at first time, after that it won't.It executes fine in all browsers except IE11.
Code:

<form id="profile">
<input type="file" id="UPLOADED_FILE" name="UPLOADED_FILE" value="" >
<input type="submit" name="save_photo" value="Save" onclick="pressUpload();">
</form>

function pressUpload() {
    var iframe_document = document.getElementById('iframeID').contentWindow.document;
    var form_profile = $(iframe_document).find('#profile');
    var file_input_field = $(form_profile).find('input[name=UPLOADED_FILE]');

    $(file_input_field).bind('change', function () {
        var value = $(this).val();

        if (value) {

            $(form_profile).submit();

            if (navigator.userAgent.indexOf("MSIE") > -1 && !window.opera) {
                iframe.onreadystatechange = function () {
                    if (iframe.readyState == "complete") {

                        alert("HI");
                    }
                };
            }
        }
    })
}

A: That is invalid way to write markup. but you should not use any element between iframe's opening/closing tags like you have done in your case.
Actually that only gets executed when this element is not supported in any browser. @MDN you can see the example1

Your browser does not support iframes.


text:
Q: Parameters of GetListItems() method while calling SharePoint webservice? I'm calling SharePoint web service in asp.net. Following is my code. In that EmpPortal is name of service reference.
  EmpPortal.Lists L = new EmpPortal.Lists();
  L.Credentials = System.Net.CredentialCache.DefaultCredentials;

  XmlDocument xmlDoc = new System.Xml.XmlDocument();

  XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
  XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
  XmlNode ndQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");

  ndQueryOptions.InnerXml =
         "<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>" +
         "<DateInUtc>TRUE</DateInUtc>";

  ndViewFields.InnerXml = "<FieldRef Name='ows_Calendar Type' />" +
                          "<FieldRef Name='ows_Title'/>" +
                          "<FieldRef Name='ows_Holiday Type'/>" +
                          "<FieldRef Name='ows_Day'/>" +
                          "<FieldRef Name='ows_Holiday Date'/>";

  ndQuery.InnerXml = "<Where><Gt><FieldRef Name='ows_Holiday Date'/>" +
                "<Value Type= 'DateTime'>2014-01-01T00:00:00</Value></Gt></Where>";
XmlNode n = L.GetListItems("Holidays", null, ndQuery,ndViewFields ,null,ndQueryOptions, null);

I m facing problem with what Name I should give in FieldRef tag.
because with this code I'm getting exception :
 'Microsoft.SharePoint.SoapServer.SoapServerException'
So please give me more clarity about parameters of Lists.GetListItems()?
and how I should use them for my code.

A: happy to say friends I got answer to my question
            ndViewFields.InnerXml = "<FieldRef Name= 'Calendar Type' />" +
                     "<FieldRef Name='Title'/>" +
                     "<FieldRef Name='Holiday Type' />" +//HERE SPACE IS THERE IN BETWEEN WORDS
                     "<FieldRef Name='Day'/>" +
                     "<FieldRef Name='Holiday Date'/>";  //HERE SPACE IS THERE IN BETWEEN WORDS

                ndQuery.InnerXml = String.Format("<Where><Gt><FieldRef Name='Holiday_x0020_Date'></FieldRef><Value Type='DateTime'>2014-01-01T00:00:00</Value></Gt></Where>");

main change required was to replace SPACE with x0020 with prefix and postfix with underscore character as shown in above code.


text:
Q: Learning to use Git. Local repository / project file directory I am trying to learn to use Github. I have been uploading using the site directly and all that was fine until I ended up with problems with too many files, too large of a file size etc. So I started to use something called Git Portable. I have set up a new repository, which is on my computer. So I guess a local repository?
So I have this local repository, and in another location the project files. I copied from this project file location to the local repository, so I could then push it to Github.
But I am wondering, do I work from that repository. I mean is that now where I edit the code etc from, so the changes can then be pushed? Or do I still use the original location where the project files are? And, if I don't use the new repository to update the code, how do I then update the code in the repository, do I just copy it over like I did before?
I am really new to all this.

A: I think from hereon out you want to be making changes to your local repository. Once you have changes you want to move to your GitHub, you have to do just two things. What kind of IDE or text editor do you use to edit and add files in your git repository? It might have a UI that will allow you to do this, if not, you can use git from the command line.

*

*You need to commit your changes. A "commit" is essentially a set of a changes. You can associate a commit with a message and this can be really if you are working on a team with multiple developers. Read more about committing here: https://git-scm.com/docs/git-commit

*You need to push your commits. To push is to update your remote repository (GitHub in your case) with your local commits. Read more about pushing here: https://git-scm.com/docs/git-push


text:
Q: How do I write xPath for the XML file How do I write a xPath for below XML to fetch the data from field "fname"
-- where field 'Department' contains data "IT"
-- and ID and ImgID are same.
-- Below is sample XML ----
[Sample XML][1]
<?xml version="1.0" encoding="UTF-8"?>
<dbdump>
<database name="testDatabase" schemaVer="1.0.0">
    <table name="testTable">
        <row>
            <field name="ID">1</field>
            <field name="lname">Smith</field>
            <field name="fname">Tom</field>
            <field name="department">HR</field>
            <field name="ImgID">0</field>
        </row>
        <row>
            <field name="ID">2</field>
            <field name="lname">K</field>
            <field name="fname">John</field>
            <field name="department">IT</field>
            <field name="ImgID">2</field>
        </row>
        <row>
            <field name="ID">3</field>
            <field name="lname">D</field>
            <field name="fname">Sam</field>
            <field name="department">IT</field>
            <field name="ImgID">3</field>
        </row>
        <row>
            <field name="ID">4</field>
            <field name="lname">J</field>
            <field name="fname">Tina</field>
            <field name="department">IT</field>
            <field name="ImgID">0</field>
        </row>
    </table>
</database>
</dbdump>

A: Slightly more precise and efficient XPath:
/dbdump/database/table/row[field[@name="department"] = "IT"][field[@name="ID"] = field[@name="ImgID"]]/field[@name="fname"]/text()


text:
Q: NuxtJs login works but unauthorized 401 I am using NuxtJs auth module to handle my authorization in the state. For the auth I wrote an express api which works.
I have following configuration in my nuxt.config.js:
  axios: {
    baseURL: 'http://localhost:4000/api'
  },

  auth: {
    strategies: {
      local: {
        endpoints: {
          login: { url: '/users/login', method: 'post', propertyName: 'data.token' },
          user: { url: '/users/me', method: 'get', propertyName: 'data' },
        },
      }
    }
  },

And in my login component I call the login route like this:
const { data } = await this.$auth.loginWith('local', {
  data: this.login
})

This call the /api/users/login route successfully (200) and after that calls the /api/users/me with an error saying

xhr.js:178 GET http://localhost:4000/api/users/me 401 (Unauthorized)

In postman I am calling the api route which returns the user like this*
> Get - localhost:4000/api/users/me
>
> Authorization:
>
> Type: Bearer Token Token: xxxx

Which returns the users data.
I read that nuxt auth module default the type to 'Bearer' but in my case it does not work.
The user login work but the second route which returns the user data does not work due to authorization. The Api is not inside the nuxtjs it is a different project written in Express.

A: You can try this:
axios: {
baseURL: 'http://localhost:4000/api' },
auth: {
strategies: {
  local: {
    endpoints: {
      login: { url: '/users/login', method: 'post', propertyName: 'data.token' },
      user: { url: '/users/me', method: 'get', propertyName: 'data' },
    },
    tokenType: ''
  }
}

},
Setting tokenType to an empty string overrides the default "Bearer". Some server configurations may throw a 401.


text:
Q: c++ overloading stream operator, parameters by reference and anonymous instances If I have a POD with an overloaded stream operator:
struct Value{
...
    friend ostream& operator<< (ostream &out, Value &val);
...
};

I can't use the stream operator with anonymous instances.
for example I can't do:
cout<<Value();

This gives me:
error: ambiguous overload for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'Value')

On the other hand, I can pass the POD by value, but I would like to avoid the copy. Is there a way to both?
Value v1;
cout<<v1<<" "<<Value()<<endl;

A: Since the operator should not modify the right operand, it should take it by const reference:
friend ostream& operator<< (ostream &out, const Value &val);

const references can bind to temporaries, so it will work (and that's how the standard library does it as well).


text:
Q: is it possible to install/run several instance of openfire server on hosting with operation linux? I want to install several openfire server XMPP on one hosting with operation linux.
1.Is it possible?
2.is there any guide for this issue?

A: Yes, it is possible, but you have to be sure to configure the ports on at least one of them to something other than the defaults.  You can't share resources (including the db, if you are not using the embedded one).


text:
Q: Flood fill GLUT code not working I wrote the following piece of code for flood-fill as part of a paint program I'm developing:
void setPixel(int x, int y)
{
     glColor4f(red, green, blue, alpha);
     glBegin(GL_POINTS);
     glVertex2f(x, y);
     glEnd();
     glFlush();
}
void floodFill(int x, int y)
{
     unsigned char pick_col[3];
     float R, G, B;
     glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, pick_col);
     R = (float) pick_col[0]/255.0;
     G = (float) pick_col[1]/255.0;
     B = (float) pick_col[2]/255.0;

     //std::cout<<R<<" "<<G<<" "<<B<<"\n";

     if(R!=0.0 || G!=0.0 || B!=0.0) //true for any non-black colour (BTW, my canvas is black)
     return;

     setPixel(x,y);

     floodFill(x+1,y);
     floodFill(x,y+1);
     floodFill(x,y-1);
     floodFill(x-1,y);
}

Unfortunately, this code is not working. For example, I first drew a rectangle and tried to fill the rectangle. What actually happened was that from the point where I clicked to fill, pixels to its right started getting filled in a line and eventually the pixels near the right-most edge started getting drawn. But that's all that happened. I don't understand why.

A: First of all: don't do this. Doing it completely on the CPU will be orders of magnitude faster than doing 2 roundtrips to the GPU per pixel.
Having said that, I can still see the problem with your implementation: you are never checking the borders. glReadPixels will just return undefined results if you try to read back pixels which lie outside of the framebuffer, and that might very well be all zeros.


text:
Q: Does a webapplication run faster when Maximum Worker Processes is more than one? for IIS7
Does a webapplication run faster when Maximum Worker Processes is more than one?

A: By increasing the Maximum Worker Processes over 1 you're creating a Web Garden. So the short answer is: likely no... unless:
To quote Chris Adams an ex IIS PM's article I have flowers... should I get a Web Garden?:

Web gardens was designed for one single reason – Offering applications that are not CPU-bound but execute long running requests the ability to scale and not use up all threads available in the worker process.
  The examples might be things like -
  Applications that make long running database requests (e.g. high computational database transaction)
  Applications that have threads occupied by long-running synchronous and network intensive transactions
  The question that you must ask yourself -
  What is the current CPU usage of the server?
  What is the application's threads executing and what type of requests are they?
  Based on the criteria above, you should understand better when to use Web Gardens. Web Gardens, in the metabase, equals the MaxProcesses metabase property if you are not using the User Interface to configure this feature.
  cscript adsutil.vbs set w3svc/apppools/defaultapppool/maxprocesses 4
  I hope that I get some mileage out of having this blog and more importantly I hope it helps you understand this better…

You may want to look at "What is Web Garden?" from Deploying ASP.NET Websites on IIS 7.0 [codeproject.com] which says:

By default each Application Pool runs with a Single Worker Process (W3Wp.exe). We can assign multiple Worker Processes With a Single Application Pool. An Application Pool with multiple Worker process is called "Web Gardens". Many worker processes with the same Application Pool can sometimes provide better throughput performance and application response time. And each worker process should have their own Thread and Own Memory space.

A: WebGarden is faster than single worker process in case if application contains locks that prevent its parallelization. For example, GDI+ based image processing.
See this and this questions for more info.


text:
Q: Unpersist after checkpoint I have written a few custom-built graph algorithms using Apache Spark Graphx. I have three queries regarding caching and checkpoint methods. As I am new to spark and graphx, I will highly appreciate a detailed explanation.
Query 1:
I am working on a large graph with 200m vertices and 350m edges. As the graph size is large, I call the checkpoint method at regular intervals on the interim graph created in the long-running graphx algorithms. The majority of the time, the checkpoint works fine. However, I have observed the following warnings in the driver logs a few times.
22/08/04 03:25:48 [WARN] o.a.s.r.ReliableCheckpointRDD - Error writing partitioner org.apache.spark.HashPartitioner@e10 to file:/mnts/nfsvol/AML/tmp/checkpoint/a153fc7b-1be7-460d-a41b-f17c820c3bf1/rdd-496

22/08/04 03:29:35 [WARN] o.a.s.r.ReliableCheckpointRDD - Error writing partitioner org.apache.spark.HashPartitioner@e10 to file:/mnts/nfsvol/AML/tmp/checkpoint/a153fc7b-1be7-460d-a41b-f17c820c3bf1/rdd-482

How to fix such warnings?
Query 2:
It is recommended to cache/persist the object (in my case, the graph object) before checkpointing so that the DAG is not recomputed during the checkpoint. However, is it safe to unpersist the object immediately after the checkpoint is over and release the memory?
FYI, I have compared both the approaches of calling and not calling the unpersist and have not found any difference in the performance. Also, in the Spark UI, I have observed that in both the approaches, the stage starts with the ReliableCheckpointRDD.
Query 3:
If the answer to query # 2 is yes, then is it risky to get the warning mentioned in Query # 1? Would it fail the job altogether?
During one of the executions of the algorithm, I received the following error that failed the job. I wonder what is the cause of this error if the answer to query # 2 is no.
22/08/04 03:55:46 [INFO] i.c.s.a.a.AMLGraphMain$ - Execution of AML Graph application failed or stopped with exception: Error while executing AML Graph Application: Error while executing AML Graph Application: Error occurred during execution of graph algorithms: Job aborted due to stage failure: Task creation failed: java.io.FileNotFoundException: File file:/mnts/nfsvol/AML/tmp/checkpoint/a153fc7b-1be7-460d-a41b-f17c820c3bf1/rdd-482/part-00000 does not exist
java.io.FileNotFoundException: File file:/mnts/nfsvol/AML/tmp/checkpoint/a153fc7b-1be7-460d-a41b-f17c820c3bf1/rdd-482/part-00000 does not exist
      at org.apache.hadoop.fs.RawLocalFileSystem.deprecatedGetFileStatus(RawLocalFileSystem.java:611)
      at org.apache.hadoop.fs.RawLocalFileSystem.getFileLinkStatusInternal(RawLocalFileSystem.java:824)
      at org.apache.hadoop.fs.RawLocalFileSystem.getFileStatus(RawLocalFileSystem.java:601)
      at org.apache.hadoop.fs.FilterFileSystem.getFileStatus(FilterFileSystem.java:428)
      at org.apache.spark.rdd.ReliableCheckpointRDD.org$apache$spark$rdd$ReliableCheckpointRDD$$getPartitionBlockLocations(ReliableCheckpointRDD.scala:102)
      at org.apache.spark.rdd.ReliableCheckpointRDD.getPreferredLocations(ReliableCheckpointRDD.scala:117)
      at org.apache.spark.rdd.RDD.$anonfun$preferredLocations$1(RDD.scala:299)
      at org.apache.spark.rdd.RDD$$Lambda$1728/00000000B4035EF0.apply(Unknown Source)
      at scala.Option.map(Option.scala:230)
      at org.apache.spark.rdd.RDD.preferredLocations(RDD.scala:299)
      at org.apache.spark.scheduler.DAGScheduler.getPreferredLocsInternal(DAGScheduler.scala:2134)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$3(DAGScheduler.scala:2145)
      at org.apache.spark.scheduler.DAGScheduler$$Lambda$1734/00000000B4037B50.apply$mcVI$sp(Unknown Source)
      at scala.runtime.java8.JFunction1$mcVI$sp.apply(JFunction1$mcVI$sp.java:23)
      at scala.collection.immutable.List.foreach(List.scala:392)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$2(DAGScheduler.scala:2144)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$2$adapted(DAGScheduler.scala:2142)
      at org.apache.spark.scheduler.DAGScheduler$$Lambda$1733/00000000B4036AD0.apply(Unknown Source)
      at scala.collection.immutable.List.foreach(List.scala:392)
      at org.apache.spark.scheduler.DAGScheduler.getPreferredLocsInternal(DAGScheduler.scala:2142)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$3(DAGScheduler.scala:2145)
      at org.apache.spark.scheduler.DAGScheduler$$Lambda$1734/00000000B4037B50.apply$mcVI$sp(Unknown Source)
      at scala.runtime.java8.JFunction1$mcVI$sp.apply(JFunction1$mcVI$sp.java:23)
      at scala.collection.immutable.List.foreach(List.scala:392)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$2(DAGScheduler.scala:2144)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$2$adapted(DAGScheduler.scala:2142)
      at org.apache.spark.scheduler.DAGScheduler$$Lambda$1733/00000000B4036AD0.apply(Unknown Source)
      at scala.collection.immutable.List.foreach(List.scala:392)
      at org.apache.spark.scheduler.DAGScheduler.getPreferredLocsInternal(DAGScheduler.scala:2142)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$3(DAGScheduler.scala:2145)
      at org.apache.spark.scheduler.DAGScheduler$$Lambda$1734/00000000B4037B50.apply$mcVI$sp(Unknown Source)
      at scala.runtime.java8.JFunction1$mcVI$sp.apply(JFunction1$mcVI$sp.java:23)
      at scala.collection.immutable.List.foreach(List.scala:392)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$2(DAGScheduler.scala:2144)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$2$adapted(DAGScheduler.scala:2142)
      at org.apache.spark.scheduler.DAGScheduler$$Lambda$1733/00000000B4036AD0.apply(Unknown Source)
      at scala.collection.immutable.List.foreach(List.scala:392)
      at org.apache.spark.scheduler.DAGScheduler.getPreferredLocsInternal(DAGScheduler.scala:2142)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$3(DAGScheduler.scala:2145)
      at org.apache.spark.scheduler.DAGScheduler$$Lambda$1734/00000000B4037B50.apply$mcVI$sp(Unknown Source)
      at scala.runtime.java8.JFunction1$mcVI$sp.apply(JFunction1$mcVI$sp.java:23)
      at scala.collection.immutable.List.foreach(List.scala:392)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$2(DAGScheduler.scala:2144)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$2$adapted(DAGScheduler.scala:2142)
      at org.apache.spark.scheduler.DAGScheduler$$Lambda$1733/00000000B4036AD0.apply(Unknown Source)
      at scala.collection.immutable.List.foreach(List.scala:392)
      at org.apache.spark.scheduler.DAGScheduler.getPreferredLocsInternal(DAGScheduler.scala:2142)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$3(DAGScheduler.scala:2145)
      at org.apache.spark.scheduler.DAGScheduler$$Lambda$1734/00000000B4037B50.apply$mcVI$sp(Unknown Source)
      at scala.runtime.java8.JFunction1$mcVI$sp.apply(JFunction1$mcVI$sp.java:23)
      at scala.collection.immutable.List.foreach(List.scala:392)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$2(DAGScheduler.scala:2144)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$2$adapted(DAGScheduler.scala:2142)
      at org.apache.spark.scheduler.DAGScheduler$$Lambda$1733/00000000B4036AD0.apply(Unknown Source)
      at scala.collection.immutable.List.foreach(List.scala:392)
      at org.apache.spark.scheduler.DAGScheduler.getPreferredLocsInternal(DAGScheduler.scala:2142)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$3(DAGScheduler.scala:2145)
      at org.apache.spark.scheduler.DAGScheduler$$Lambda$1734/00000000B4037B50.apply$mcVI$sp(Unknown Source)
      at scala.runtime.java8.JFunction1$mcVI$sp.apply(JFunction1$mcVI$sp.java:23)
      at scala.collection.immutable.List.foreach(List.scala:392)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$2(DAGScheduler.scala:2144)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$getPreferredLocsInternal$2$adapted(DAGScheduler.scala:2142)
      at org.apache.spark.scheduler.DAGScheduler$$Lambda$1733/00000000B4036AD0.apply(Unknown Source)
      at scala.collection.immutable.List.foreach(List.scala:392)
      at org.apache.spark.scheduler.DAGScheduler.getPreferredLocsInternal(DAGScheduler.scala:2142)
      at org.apache.spark.scheduler.DAGScheduler.getPreferredLocs(DAGScheduler.scala:2108)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$submitMissingTasks$2(DAGScheduler.scala:1166)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$submitMissingTasks$2$adapted(DAGScheduler.scala:1166)
      at org.apache.spark.scheduler.DAGScheduler$$Lambda$2427/00000000B43AEE30.apply(Unknown Source)
      at scala.collection.TraversableLike.$anonfun$map$1(TraversableLike.scala:238)
      at scala.collection.TraversableLike$$Lambda$26/00000000A52C4560.apply(Unknown Source)
      at scala.collection.Iterator.foreach(Iterator.scala:941)
      at scala.collection.Iterator.foreach$(Iterator.scala:941)
      at scala.collection.AbstractIterator.foreach(Iterator.scala:1429)
      at scala.collection.IterableLike.foreach(IterableLike.scala:74)
      at scala.collection.IterableLike.foreach$(IterableLike.scala:73)
      at scala.collection.AbstractIterable.foreach(Iterable.scala:56)
      at scala.collection.TraversableLike.map(TraversableLike.scala:238)
      at scala.collection.TraversableLike.map$(TraversableLike.scala:231)
      at scala.collection.AbstractTraversable.map(Traversable.scala:108)
      at org.apache.spark.scheduler.DAGScheduler.submitMissingTasks(DAGScheduler.scala:1166)
      at org.apache.spark.scheduler.DAGScheduler.submitStage(DAGScheduler.scala:1118)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$submitStage$5(DAGScheduler.scala:1121)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$submitStage$5$adapted(DAGScheduler.scala:1120)
      at org.apache.spark.scheduler.DAGScheduler$$Lambda$2420/00000000B43ABF50.apply(Unknown Source)
      at scala.collection.immutable.List.foreach(List.scala:392)
      at org.apache.spark.scheduler.DAGScheduler.submitStage(DAGScheduler.scala:1120)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$submitStage$5(DAGScheduler.scala:1121)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$submitStage$5$adapted(DAGScheduler.scala:1120)
      at org.apache.spark.scheduler.DAGScheduler$$Lambda$2420/00000000B43ABF50.apply(Unknown Source)
      at scala.collection.immutable.List.foreach(List.scala:392)
      at org.apache.spark.scheduler.DAGScheduler.submitStage(DAGScheduler.scala:1120)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$submitStage$5(DAGScheduler.scala:1121)
      at org.apache.spark.scheduler.DAGScheduler.$anonfun$submitStage$5$adapted(DAGScheduler.scala:1120)
      at org.apache.spark.scheduler.DAGScheduler$$Lambda$2420/00000000B43ABF50.apply(Unknown Source)
      at scala.collection.immutable.List.foreach(List.scala:392)
      at org.apache.spark.scheduler.DAGScheduler.submitStage(DAGScheduler.scala:1120)
      at org.apache.spark.scheduler.DAGScheduler.handleJobSubmitted(DAGScheduler.scala:1061)
      at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:2196)
      at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2188)
      at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2177)
      at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:49)
 : Array(in.co.sbi.analytics.aml.AMLGraphMain$.executeGraphApp$1(aml_graphx_main.scala:622), in.co.sbi.analytics.aml.AMLGraphMain$.main(aml_graphx_main.scala:642), in.co.sbi.analytics.aml.AMLGraphMain.main(aml_graphx_main.scala), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method), sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62), sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43), java.lang.reflect.Method.invoke(Method.java:498), org.apache.spark.deploy.JavaMainApplication.start(SparkApplication.scala:52), org.apache.spark.deploy.SparkSubmit.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:928), org.apache.spark.deploy.SparkSubmit.doRunMain$1(SparkSubmit.scala:180), org.apache.spark.deploy.SparkSubmit.submit(SparkSubmit.scala:203), org.apache.spark.deploy.SparkSubmit.doSubmit(SparkSubmit.scala:90), org.apache.spark.deploy.SparkSubmit$$anon$2.doSubmit(SparkSubmit.scala:1007), org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:1016), org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala))

Here are the cluster details: 32 executors with 4 CPU and 24GB memory each.
Kindly let me know if any more details are required. Thanks!


text:
Q: c++:Is it possible to define overloaded operators ind drived class that will work objs base class type Is it possible to define overloaded operators in drived class that will work objs  from base class type?
for example:lets say i have a class Point and i want to do all the operator overloading in a class named Operators that will inherit Point class
is it possible?if not, is there any other way to do that?

A: No, it's not possible. Besides, your approach is wrong. Inheritance is a is-a relationship, and Operators is clearly not a Point. You seriously need to rethink your design.

A: The whole point of deriving classes is to make the derived classes more specific. I'm not sure that you would want a class called Operators that is derived from Point.
You might just want to make a definition outside of a class for operator+, or whatever that takes Point objects as parameters.