text:
Q: Json layout grails respond Currently i'm using a custom marshaller to render json:
        JSON.registerObjectMarshaller( PlannedEvent) { PlannedEvent pe ->
        return [
                id : pe.id,
                event : [
                    eventId  : pe.baseEvent.id,
                    subject  : pe.baseEvent.subject
                ],

                //rooms: pe.rooms

                rooms: [
                    id : pe.rooms
                ]

        ]
    }

This gives the following output:
{"id":1,"event":{"eventId":626,"subject":"Baggeren hc (Kv2)"},"rooms":{"id":[8]}}

I would like to know how to set up my map so the value for rooms is a list with each index representing a separate room. Instead of keys, like "id", being set up as a list. The solution in comment gives to much information about the room, so I can't use that.
Wanted result :
"rooms":[{"id":8},{"id":9}]}

A: If i am correct for your domain modelling you have a hasMany relationship between PlannedEvent & Room .So if you want to get only the list of ROOMS as IDs from the PlannedEvent domian you need to register custom marshallar for Rooms also like :
 JSON.registerObjectMarshaller( Room) { Room room ->
// Map of IDs is returned from here
def returnMap = [:]
returnMap["id"] = room.id
return returnMap
}

And in PlannedEvent:
JSON.registerObjectMarshaller( PlannedEvent) { PlannedEvent pe ->
// This is also a map but the value of key rooms will contain the list of IDs of each room
def roomList = [:]
roomList["rooms"] = pe.rooms
return roomList
}

And for next time please clarify your domians & also what do you want clearly.


text:
Q: html php meta charset UTF-8 not working?
Possible Duplicate:
Browser displays � instead of ´

i'm kind of stuck on a php file with almost only html in it. I use PHP only to send information from a contact form to my mail adres.
When developing the website on localhost everything was all fine. After uploading to my server it messes up the special characters.
My meta tag looks like this:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

If someone could please help me it would be highly appreciated.

A: Add this to the header in your php file and let me know if it solves or not -
header('Content-Type: text/html; charset=UTF-8');

A: If your browser is specifically styled to have the character set as ISO-8859-1 or another charset, it will still display in that charset. I think that's the only problem I can detect.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Помогите правильно указать путь к файлу Положил изображение в папку "res", но не получается его подгрузить. При сборке jar файла изображение не отображается. Пытался по всякому указывать путь - не получается. Как правильно?

A: Положить файл в папку resources и через код можно будет обратиться
import java.net.URI;

public class Resource {
    public static void main(String[] args) throws Exception {
        String fileName = "noise.jpg";
//        URI uri = Thread.currentThread().getContextClassLoader().getResource(fileName).toURI();
        URI uri = Resource.class.getResource(fileName).toURI();

    }
}

A: Создать в src пакет res например и положить в него картинку и получить путь примерно так Image noiseImage = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/res/noise.jpg"));

A: Используйте или абсолютный путь, или относительный, начиная с папки src: src/res/noise.jpg


text:
Q: How to reparametrize a curve by arclength using Mathematica? There are some formulas in Differential Geometry that require a curve to be parametrized by arc length. Suppose we have a curve $\alpha(t)$, given by
alpha[t_] := {f1[t], f2[t], f3[t]}.

Now, my question is: if I wanted to reparametrize by arc length the procedure would be:

*

*Compute $\alpha'(t)$ and integrate $s(t) = \int_0^t |\alpha'(\tau)|^2 \mathrm{\tau}$

*Invert $s(t)$ to obtain $t = t(s)$.

*Define a new curve $\beta(s) = \alpha(t(s))$.

How could I do this with mathematica? There are procedures there like inverting which I'm unsure how would be used.
On the other hand since this is a quite common use case I believe there might be some easier way to do with Mathematica.
How could I do this? How can I get a curve and reparametrize by arc length with Mathematica?

A: I post this to illustrate some functions, e.g. ArcLengthand Interpolation that may be helpful. In the following a "three-petalled rose" is used to show 2 parametrizations (polar:green, arclength: red). The arc length parametrization is approximated by interpolation
r[t_] := RotationMatrix[Pi/4, {1, 0, 0}].{Cos[t] Sin[3 t],
   Sin[t] Sin[3 t], 0}
arc[t_] := ArcLength[r[u], {u, 0, t}];
if[n_, step_] :=
 Interpolation[Table[{arc[j], r[j][[n]]}, {j, 0, 2 Pi, step}]]
{xs, ys, zs} = if[#, 0.1] & /@ Range[3];
ra[u_] := {xs[u], ys[u], zs[u]};
anim = Table[Show[ParametricPlot3D[r[t], {t, 0, 2 Pi}],
    Graphics3D[{Red, PointSize[0.04], Point[ra[p]]}]],
   {p, 0, 0.95 arc[2 Pi], 0.05}];
anim2 = Table[Show[ParametricPlot3D[r[t], {t, 0, 2 Pi}],
    Graphics3D[{Green, PointSize[0.04], Point[r[p]]}]],
   {p, 0, 2 Pi, 0.05}];

Polar parametrization:

Arclength parametrization:

It is not perfect. Comparing 'speeds' along curve:
Plot[Evaluate[Sqrt[D[r[t], t].D[r[t], t]]], {t, 0, 2 Pi}]
Plot[Evaluate[Sqrt[D[ra[t], t].D[ra[t], t]]], {t, 0, 0.95 arc[2 Pi]},
 PlotRange -> {0, 1.5}]


text:
Q: Integration by parts, What I should do next I'm integrating a function by parts but I get stuck in a part.

Since here, What should I do next?

A: Hint: $${x^2 \over x+1} = {(x+1)^2 \over x+1} - {2x + 1 \over x+1} = {(x+1)^2 \over x+1} - {2(x + 1) \over x+1} + {1\over x+1}$$

A: Note that $\frac{x^2}{x+1}=x+\frac{1}{x+1}-1$, then the integral shouldn't be hard at all.

A: Notice that $$\frac{x^2}{x+1} =\frac{(x  + 1   -1)^2}{x  +1} = \frac{(x+1)^2 - 2(x+1) + 1}{x+1}$$

A: alright so u got the integral $\int \:x\ln \left(x+1\right)dx$ ?
let
$u=x+1\quad \quad du=1dx,\:\quad \:dx=1du$
sub dx for du, and x+1 for u
$=\int \:x\ln \left(u\right)du$
$u=x+1\quad \Rightarrow \quad \:x=u-1$
$=\int \left(u-1\right)\ln \left(u\right)du$
integration by parts:
$u=\ln \left(u\right),\:\:u'=\frac{1}{u},\:\:v'=\left(u-1\right),\:\:v=\frac{\left(u-2\right)u}{2}$
$=\ln \left(u\right)\frac{\left(u-2\right)u}{2}-\int \frac{1}{u}\frac{\left(u-2\right)u}{2}du =\frac{\left(u-2\right)u\ln \left(u\right)}{2}-\int \frac{u-2}{2}du =\frac{\left(u-2\right)u\ln \left(u\right)}{2}-\frac{\frac{u^2}{2}-2u}{2}$
sub back u=x+1 and add the integration constant and ur done.


text:
Q: SwiftUI LazyVGrid missing some content I have been experimenting with LazyVGrid to produce a table with grid lines. I'm using XCode 13.4 & iOS15. Everything seemed to be going well until I parameterized all the column sizes, line widths, etc. The content consists of an array of row data with 5 pieces of text in each row. Here is the code:
struct StatisticsView: View {

    private let columnMinWidths: [CGFloat] = [120, 50, 50, 50, 50]
    private let rowHeight: CGFloat = 40
    private let thinGridlineSize: CGFloat = 0.5
    private let thickGridlineSize: CGFloat = 2
    private let lineColour = Color.accentColor

    private let columns: [GridItem]

    private let rowContents = [
        ["Player's name", "Graham", "John", "Archie", ""],
        ["Round 1", "2", "3", "1", ""],
        ["Round 2", "3", "-", "2", ""],
        ["Round 3", "1", "2", "4", ""],
        ["Round 4", "2", "1", "1", ""]
    ]

    init() {
        self.columns = [
            GridItem(.fixed(thickGridlineSize), spacing: 0),
            GridItem(.flexible(minimum: columnMinWidths[0]), spacing: 0),
            GridItem(.fixed(thickGridlineSize), spacing: 0),
            GridItem(.flexible(minimum: columnMinWidths[1]), spacing: 0),
            GridItem(.fixed(thinGridlineSize), spacing: 0),
            GridItem(.flexible(minimum: columnMinWidths[2]), spacing: 0),
            GridItem(.fixed(thinGridlineSize), spacing: 0),
            GridItem(.flexible(minimum: columnMinWidths[3]), spacing: 0),
            GridItem(.fixed(thinGridlineSize), spacing: 0),
            GridItem(.flexible(minimum: columnMinWidths[4]), spacing: 0),
            GridItem(.fixed(thickGridlineSize), spacing: 0),
        ]
    }

    var body: some View {
        VStack(spacing: 0) {
            // top horizontal gridline
            lineColour.frame(height: thickGridlineSize)
            LazyVGrid(columns: columns, alignment: .leading, spacing: 0) {
                ForEach(0..<rowContents.count, id: \.self) { row in
                    lineColour.frame(height: rowHeight)
                    ForEach(0..<rowContents.first!.count, id: \.self) { col in
                        // cell contents with bottom gridline
                        VStack(spacing: 0) {
                            Text(rowContents[row][col])
                                .font(.caption2)
                                .frame(height: rowHeight - thinGridlineSize)
                            // tried using a colour fill but same result
                            // Color.green
                            //    .frame(height: rowHeight - thinGridlineSize)
                            lineColour.frame(height: thinGridlineSize)
                        }
                        // vertical gridline between cells
                        lineColour.frame(height: rowHeight)
                    }
                }
            }
            // bottom horizontal gridline
            lineColour.frame(height: thickGridlineSize)
        }
        .padding(.horizontal, 8)
    }
}

and here is what is being displayed on the simulator screen:

Can anyone see where I'm going wrong here? Any help would be much appreciated. Thanks.

A: You have to remove id: \.self from both loops. View Id become duplicated so it's not drawing more than one line.


text:
Q: Programmatically find and navigate to record on subreport in MS Access using VBA? In Access, I can navigate to a record in a subform by using code similar to:
Dim rs As Recordset
Set rs = Me.Form.RecordsetClone
rs.FindFirst "CodeID = " & MyID
Me.Form.Bookmark = rs.Bookmark

Is there any way to do something similar with subreports, or any other way to navigate to a record within a subreport without using filters to only show one record? I'm looking to still be able to see the other records in the report, having the focus jump to the relevant record.

A: I figured out a way to do it. Assuming the report is embedded as a subreport:
Me.rptTest.SetFocus
DoCmd.SearchForRecord , "", acFirst, "[IDField] = " & RelevantID


text:
Q: insertion sort using the data from operation file I need to make a sorting program specifically insertion sort where the data came from the operation file that I already made before, but the data from the operation file can't be passed to the sorting program which is affected the output too. I really appreciate you guys who were willing to help me, thank you.

#include <stdio.h>
#include <string.h>

int main

 ()
{
    FILE *af = fopen("modul.txt", "r");
    int i, n, j, key;
    char id[6], eko[5], geo[5], sos[5], sej[5], pil;
    printf("DATA NILAI UTBK SOSHUM 2019\n");
    i=1;
    do{
        printf("\t\t  | id | eko | geo | sos | sej |\n");
        do{
            fscanf(af, "%s %s %s %s %s", id, eko, geo, sos, sej);
            printf("Data input ke-%d : |%s|-|%s|-|%s|-|%s|-|%s|\n", i, id, eko, geo, sos, sej);
            i++;
        }
        while(!feof(af));

        //mengurutkan data dengan metode INSERTION SHORT
        printf("\nMengurutkan nilai TKA Soshum UTBK 2019\n");
        printf("1. Nilai Ekonomi\n"); printf("2. Nilai Geografi\n"); printf("3. Nilai Sosiologi\n"); printf("4. Nilai Sejarah\n");
        printf("Masukkan Pilihan : "); fflush(stdin); scanf("%c", &pil);

        if (pil == '1')
        {
            printf("Nilai Ekonomi\n");
            FILE *af = fopen("modul.txt", "r");
            fscanf(af, "%s", eko[i]);
            for (i=1; 1<=eko[i]; i++)
            {
                key = eko[i];
                j = i-1;
                while (j>=0 && eko[j]>key)
                {
                    eko[j+1] = eko[j];
                    j = j-1;
                }
                    eko[j+1] = key;
            }

            for (i=0; i<n; i++)
            {
                fscanf(af, "%s", eko[i]);
                printf("%s", eko[i]);
            }
            printf("\n");
        }

        else if (pil == '2')
        {
            printf("2. Nilai Geografi\n");
            for (i=1; 1<=n; i++)
            {
                key = geo[i];
                j = i-1;
                while (j>=0 && geo[j]>key)
                {
                    geo[j+1] = geo[j];
                    j = j-1;
                }
                geo[j+1] = key;
            }

            for (i=0; i<n; i++)
            {
                printf("%d", geo[i]);
            }
            printf("\n");
        }

        else if (pil == '3')
        {
            printf("3. Nilai Sosiologi\n");
            for (i=1; 1<=n; i++)
            {
                key = sos[i];
                j = i-1;
                while (j>=0 && sos[j]>key)
                {
                    sos[j+1] = sos[j];
                    j = j-1;
                }
                sos[j+1] = key;
            }

            for (i=0; i<n; i++)
            {
                printf("%d", sos[i]);
            }
            printf("\n");
        }

        else if (pil == '4')
        {
            printf("4. Nilai Sejarah\n");
            for (i=1; 1<=n; i++)
            {
                key = sej[i];
                j = i-1;
                while (j>=0 && sej[j]>key)
                {
                    sej[j+1] = sej[j];
                    j = j-1;
                }
                sej[j+1] = key;
            }

            for (i=0; i<n; i++)
            {
                printf("%d", sej[i]);
            }
            printf("\n");
        }

        else
        {
            printf("Salah Masukkan Pilihan\nUlangi Lagi!");
        }
    }
    while(!feof(af));
    fclose(af);

}

all I need was how I can pass the data from the operation file to the sorting program


text:
Q: ARIA - How to indicate the maximum amount checkboxes the user may check In my web application I present the user with a set of options, of which they are allowed to select a variable number.  What is an accessible way to prevent the user from selecting too many items?
My markup looks like this:

Option Name

Select up to 3 items

 ...

  ...

Initially I wanted to use aria-invalid="true" on the checkbox divs if the user tries to select an additional option beyond the maximum, but the spec indicates that aria-invalid is for a value that has been entered, whereas checking or unchecking options may not be considered entering a value.
I also considered using the aria-valuemax set of attributes on the parent group div, but like with aria-invalid the spec defines this in terms of values that are entered into the element, rather than state which is toggled by the actions of the user.
Currently, my thinking is to apply aria-disabled="true" to all non-selected checkbox divs if the user has selected the maximum, but I'm not sure if there's a way to indicate the reason for the aria-disabled attribute in the same way as you would for an aria-invalid element with an aria-errormessage.
I appreciate any feedback, thank you all for your time.

A: Notes:

*

*explicitly associate both the group label and the instruction with
the grouping element. (you can use multiple sources to make up the
accessible name for the group).

*aria-labelledby is used as aria-describedby on role=group without an acc name will not be announced.

*once the maximum number of checkboxes have been checked set aria-disabled=true on remaining.

suggested code:

Option Name

Select up to 3 items

 ...

  ...

A: When 3 items have been checked, I suggest using aria-readonly(this property shows that an element is operable but cannot be edited). When one or more items of the selection have been unchecked, then all the checkboxes should become editable allowing users to edit or reselect items. I suggest that you also add a javascript alert when maximum selection has been attained so users know the reason behind making the options noneditable.


text:
Q: Pinterest OAuth API - connect: connection refused - Error Code '12' Getting below response in Pinterest OAuth Connect API response :
{"status": "failure", "code": 12, "data": "path: /oauth/\nparams:<dict_itemiterator object at 0x7efb64c41710>\nAuthError(code=500, message='dial tcp 127.0.0.1:22000: connect: connection refused')", "message": "Something went wrong on our end. Sorry about that.", "endpoint_name": "oauth_connect"}

The documentation we are following is here:
https://developers.pinterest.com/docs/api/overview
Is there any change in this flow or any one else with same type of issue ?

A: The auth flow is working fine now. Looks like they have fixed the issue.

A: I'm seeing the same thing using the Postman application to generate a token while logged into my pinterest account.
My Error Code:
{"status": "failure", "code": 12, "data": "path: /oauth/\nparams:<dict_itemiterator object at 0x7f2cec58f950>\nAuthError(code=500, message='dial tcp 127.0.0.1:22000: connect: connection refused')", "message": "Something went wrong on our end. Sorry about that.", "endpoint_name": "oauth_connect"}

A:
Pinterest is depracting the developer API.


text:
Q: Nutch hadoop map reduce java heap space outOfMemory I am running a Nutch 1.16, Hadoop 2.83, Solr 8.5.1 crawler setup that is running fine up to a few million indexed pages. Then I am running into Java Heap Space issues during the MapReduce job and I just cannot seem to find the correct way to up that heap space. I have tried:

*

*Passing -D mapreduce.map.memory.mb=24608 -D mapreduce.map.java.opts=-Xmx24096m when starting nutch crawl.

*Editing NUTCH_HOME/bin/crawl commonOptions mapred.child.java.opts to -Xmx16000m

*Setting HADOOP_HOME/etc/hadoop/mapred-site.xml mapred.child.java.opts to -Xmx160000m -XX:+UseConcMarkSweepGC

*Copying said mapred-site.xml into my nutch/conf folder

None of that seems to change anything. I run into the same Heap Space error at the same point in the crawling process. I have tried reducing the fetcher threads back to 12 from 25 and switching off parsing while fetching. Nothing changed and I am out of ideas. I have 64GB RAM so thats really not an issue. Please help ;)
EDIT: fixed filename to mapred-site.xml

A:

*

*Passing -D ...

The heap space needs to be set also for the reduce task using "mapreduce.reduce.memory.mb" and "mapreduce.reduce.java.opts". Note that the script bin/crawl was recently improved in this regard, see NUTCH-2501 and the recent bin/crawl script.

3./4. Setting/copying hadoop-site.xml

Shouldn't this be set in "mapred-site.xml"?


text:
Q: Batch File Replace Extracted File I have a .bat file that unzips a kml from a kmz. If I run the batch file again it prompts me if I want to replace the file. Is there away I can have it always replace the file without prompting the user or displaying a cmd window?
    @echo off
    md tempKml
    cd tempKml
    ..\unzip ..\%1 >nul
    cd ..
    dir tempKml\*.kml /s/b

A: Use the -o option?
..\unzip -o ..\%1 >nul


text:
Q: Training and Testing deep CNN with same piece of data I have created a deep CNN from a research paper (using tensorflow) and am now curious if I have done everything correctly. Eventually I want to train and test the CNN on many images, but at the moment I only have one image on hand. If I was to use this one image as training and testing data, should the CNN always have 100% accuracy

A: Yes, with only one image to match, you will have a trivial case of perfect accuracy (1-for-1).  However, this is only a "breath of life" test for your model.  All you'll know is that you are functionally capable of running one image through that model; this will tell you nothing (or very little) about your topology's effectiveness with that type of image.


text:
Q: Building data access layer in PHP application and ORM I'm having some trouble figuring out how to access data from my database tables. I know there are many frameworks out there that facilitate with this, such as Yii for example, but I'm trying to avoid that route due to its learning curve with others in my team and time restriction.
Suppose I have a table called File which houses a list of files with their names, upload dates, upload user etc. I also have another table called Versions which essentially holds each file's version: when user uploads the same file, it considers it as a revision.
Files
fid | name  | uploadDate
1   | test  | 2017-01-01
2   | test2 | 2017-01-01

Versions
vid | fid   | user
1   | 1     | a
2   | 1     | b

My initial thought was to create a class for each table where I would throw in a fid in the Files constructor and retrieve that single row and do the same for the Versions, where an vid would be put in the constructor and retrieve a specific version.
However, this means that I would have two separate queries, one for each class. So I was thinking of perhaps combining them into one. This would mean that I would retrieve the file information AND the versions information under one query  (with the use of LEFT JOIN) within the Files class then use Versions class to handle the data rather than querying the db and also handling the data.
For some reason I feel like this comes with a better performance since I'm using JOINS to help me out here, but on the other hand, if I only need information for a specific Version of a file, I need to create an instance of File, which means using a fid THEN retrieving the Version I want from within. (<-- poorly worded).
Perhaps someone can give me a little insight on this manner and what to do when no access to a framework.

A: ORM will not solve all your problems
In many cases it is convenient to use Models to access DB but not always. Probably it will be better for you to keep your ORM models free of tasks where you need complex queries and high performance.
Use ORM pattern properly
ORM is just one of many coding patterns which you can use in your code.
Read this topic to learn more about it What is an ORM and where can I learn more about it?
You should not consider ORM as application layer which isolates access to database. It is just a technique to manipulate data in object oriented manner.
In every popular framework you'll see that ORM is an option, not a mandatory layer.
Consider the case when you want to get all versions for specific file. Create something like FileVersionManager singleton with method getAllVersions which will perform JOIN query by fid. Here can be also something like checkoutToVersion or getPreviousVersion. This methods can return one or set of your Version ORM models. And what is important -- this way will be more semantically meaningful and therefore more simple to read and to understand by other programmers.
Or if you need to produce version on each file change you can delegate this logic to something like Versionable behavior or something.
I prefer to think about ORM as about some kind of application domain definition layer.
So, answering your question
If you want your own ORM implementation, then do not make it too complex. Create separate ORM models for each table with CRUD methods and schema definition. And use other patterns to perform complex queries.
Example (Query.selectWhere should be implemented to make example working):
<?php

/**
 * @property $name
 **/
class File extends ORMModel
{
    public function tableName()
    {
        return 'files';
    }

    public function properties()
    {
        return array_merge(parent::properties(), ['name']);
    }
}

/**
 * @property $number
 * @property $file_id
 **/
class Version extends ORMModel
{
    public function tableName()
    {
        return 'versions';
    }

    public function properties()
    {
        return array_merge(parent::properties(), ['file_id', 'number']);
    }

    public function getFile()
    {
        return new File($this->file_id);
    }
}

class FileVersionManager
{
    public static function getLatestVersion($file)
    {
        $query = new Query();
        $rows = $query->selectWhere((new Version())->tableName(), ['file_id' => $file->id]);

        $max = 0;
        $maxId = null;
        foreach ($rows as $row) {
            if ($row['number'] > $max) {
                $maxId = $row['id'];
                $max = $row['number'];
            }
        }

        return new Version($maxId);
    }

    public static function createNewVersion($file)
    {
        $latestVersion = static::getLatestVersion($file);
        $newVersion = new Version();
        $newVersion->file_id = $file->id;
        $newVersion->number = $latestVersion->number + 1;
        $newVersion->insert();

        return $newVersion;
    }
}

class Query
{

    private static $datasource = [
        'files' => [
            1 => [
                'name' => 'file1',
            ],
            2 => [
                'name' => 'file1',
            ]
        ],
        'versions' => [
            1 => [
                'file_id' => 1,
                'number' => 1
            ],
            2 => [
                'file_id' => 1,
                'number' => 2
            ],
            3 => [
                'file_id' => 2,
                'number' => 1
            ],
            4 => [
                'file_id' => 2,
                'number' => 2
            ],
        ]
    ];

    public function select($tablename) {
        return static::$datasource[$tablename];
    }

    public function selectOne($tablename, $id) {
        return @static::$datasource[$tablename][$id];
    }

    public function selectWhere($tableName, $condition) {
        //@todo: implement selection assuming that condition is ['propertyName1' => 'propertyValue1', 'propertyName2' => 'propertyValue2',  ]
        //should retun array of properties including id for above example
        return [];
    }

    public function update($tableName, $id, $values) {
        if (empty(static::$datasource[$tableName][$id])) return false;
        static::$datasource[$tableName][$id] = $values;
        return true;
    }

    public function insert($tableName,  $values) {
        $id = max(array_keys(static::$datasource[$tableName])) + 1;
        static::$datasource[$tableName][$id] = $values;
        return $id;
    }

    public function delete($tableName, $id)
    {
        unset(static::$datasource[$tableName][$id]);
        return true;
    }

}

/**
 * @property $id
 **/
abstract class ORMModel
{
    private $properties;

    public abstract function tableName();
    public function properties() {
        return ['id'];
    }

    public function __get($name) {
        $propertyNames = $this->properties();

        if (in_array($name, $propertyNames)) {
            return @$this->properties[$name];
        }
    }

    public function __set($name, $value) {
        $propertyNames = $this->properties();

        if (in_array($name, $propertyNames)) {
            $this->properties[$name] = $value;
        }
    }

    public function __construct($id = null)
    {
        if (!empty($id)) {
            $query = new Query();
            if ($this->properties = $query->selectOne($this->tableName(), $id)) {
                $this->properties['id'] = $id;
            }
        }
    }

    public function insert()
    {
        $query = new Query();
        $id = $query->insert($this->tableName(), $this->properties);
        $this->properties['id'] = $id;
        return $this;
    }

    public function update()
    {
        if (empty($this->properties['id'])) return false;

        $query = new Query();
        return $query->update($this->tableName(), $this->id, array_diff($this->properties, ['id']));
    }

    public function delete()
    {
        if (empty($this->properties['id'])) return false;

        $query = new Query();
        return $query->delete($this->tableName(), $this->id);
    }
}

$version = new Version(1);
$file = $version->getFile();
var_dump($file->name);

$file = new File(2);
$version = FileVersionManager::getLatestVersion($file);
var_dump($version->number);

FileVersionManager::createNewVersion($file);
$version = FileVersionManager::getLatestVersion($file);
var_dump($version->number);

P.S. Here you can define own Query implementation and this should work fine with your (any) data source
P.P.S. And I still would recommend you to learn some popular framework (Yii2, Laravel, Symfony or any other) just because it is a good way to learn best practices in building application architecture


text:
Q: Отключение каскадного удаления в Entity Framework Core Я хочу создать 2 таблицы: Team, Match, где в таблице Match существует 2 ссылки на таблицу Team. Когда пытаюсь сгенерировать БД, появляется ошибка связанная с каскадным удалением. Можете подсказать, как решить проблему?
public class Team {
  public int Id { get; set; }
  public string Name { get; set; }
}

public class Match {
  public int Id { get; set; }
  public int? HomeId { get; set; }
  public int? GuestId { get; set; }

  public Team Home { get; set; }
  public Team Guest { get; set; }
}

A: Во-первых, вам нужно до конца расставить навигационные свойства:
public class Team
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual IEnumerable<Match> HomeMatches { get; set; }
    public virtual IEnumerable<Match> GuestMatches { get; set; }
}

public class Match
{
    public int Id { get; set; }
    public int HomeId { get; set; }
    public int GuestId { get; set; }
    public Team Home { get; set; }
    public Team Guest { get; set; }
}

Во-вторых, в ApplicationDbContext добавьте:
protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.Entity<Match>()
           .HasOne(m => m.Home)
           .WithMany(t => t.HomeMatches)
           .OnDelete(DeleteBehavior.Restrict);

    builder.Entity<Match>()
           .HasOne(m => m.Guest)
           .WithMany(t => t.GuestMatches)
           .OnDelete(DeleteBehavior.Restrict);
}

(Формально хватило бы и один каскад отключить)
На метаинте есть подробности: https://metanit.com/sharp/entityframeworkcore/3.2.php


text:
Q: Create an instance of a class inside the same class and use the same class as parameter I have the following class:
class state(list):
    def __init__(self,parent = None, path = None, *args):
        list.__init__(self, *args)
        self.n = len(self)
        self.parent = parent
        self.path = path

    def neighbors(self):
        lista = []
        if self.__hasUp():
            lista.append(state(Self,'Up',self.__swap(self.index(0),self.index(0) - 3))))
        if self.__hasDown():
            lista.append(state(Self,'Down',self.__swap(self.index(0),self.index(0) + 3))))
        if self.__hasLeft():
            lista.append(state(Self,'Left',self.__swap(self.index(0),self.index(0) - 1))))
        if self.__hasRight():
            lista.append(state(Self,'Right',self.__swap(self.index(0),self.index(0) + 1))))

        return lista

I normally create an instance of the class as follow:
inicial = state(None,None,[1,2,5,3,4,0,6,7,8])

I need to do the followin (I think if I put the whole context of what I am doing, it will be missleading):
anotherList = []
for neighbor in inicial.neighbors():
    anotherList.append(neighbor)

I just want to have a list with few extra attributes and methods. The problem is I need this class to create istances of itself with the object that is creating them as a parameter in the neighbors method. I have testet all methods referenced in the code and they work as expected, but I just think they are not need for this question and they will make it a really long question.
I have also checked this Declaring a class with an instance of it inside in Python, Create static instances of a class inside said class in Python and this Class constructor able to init with an instance of the same class object. However, I do not understand it yet :(
I am quite an amateur,so if you have any suggestions, they are all welcome ;)

A: I am sorry..I tried and it turns out it is very straightforward. It was simply a mistake from the beggining. I leave the answer here in case someone needs it, but if you suggest I delete it (is it possible?) I'will do it.
class test(list):
    def __init__(self,pa, name, *args):
        list.__init__(self, *args)
        self.name = name
        self.par = pa

    def create(self):
        lista = []
        lista.append(test(self,'a',[0,1]))
        lista.append(test(self,'b',[0,2]))
        return lista

Best regards,


text:
Q: jQuery: Make strings with varying capitalization Title case Pretty simple question, but I can't quite seem to find the answer.
I have several HTML pages from differing sources that have strings in their
 elements with dumb capitalizations. Such as:

Are there OTHER USES for this medicine?

I'm looking to make these regular sentence case, i.e.,

Are there other uses for this medicine?

I began by making them all lower case with CSS:
h2 {
  text-transform: lowercase;
}

because I was hoping to then manipulate them with jQuery by making a function that just capitalizes the first letter.
So the question is: How would I write a jQuery function to capitalize just the first letter of each h2 element on a page?
After reading this thread, tried this:
function capitaliseFirstLetter(string){
  return string.charAt(0).toUpperCase() + string.slice(1);
}

$('h2').each(function(){
  capitaliseFirstLetter($(this).text());
});

But it didn't work, and the console didn't give me any errors, so I don't know what's wrong.
EDIT
I made one large oversight in this question. Using
text-transform: lowercase
made the word I lowercase, so

What should I do in case of OVERDOSE?

became

What should i do in case of overdose?

when I used @marcelo-biffara's solution. (Or the :first-letter CSS syntax.)
Now, do I need to use a complicated regexp to just capitalize the string " i "?
EDIT 2
If there are two occurrences of " i " (such as in "What should i do if i take too many doses?"), do I need a loop to replace them with " I "?

A: capitaliseFirstLetter($(this).text()); returns you a string.  That's it.  You're not doing anything with that string.  You need to put the returned string somewhere.
$('h2').each(function(){
    var str = capitaliseFirstLetter($(this).text());
    $(this).text(str);  // Set the text of the element
});

A: you can make this function
function capitalizeMe(val){
    return val.charAt(0).toUpperCase()+val.substr(1).toLowerCase();
}

oh, and maybe you need to remove you css h2 rule
you can apply it to your h2 like this
$('h2').each(function(){
    var str = capitalizeMe($(this).html());
    $(this).html(str);
});

function replaceAll( text, v1, v2 ){
  while (text.toString().indexOf(v1) != -1)
      text = text.toString().replace(v1,v2);
  return text;
}

if you want to capitalize each instance of  "i" you could do something like this
$('h2').each(function(){
    var str = replaceAll(capitalizeMe($(this).html())," i "," I ");
    $(this).html(str);
});

A: Couldn't you just use CSS
h2 {
    text-transform: lowercase;
}
h2:first-letter {
    text-transform: capitalize;
}

http://jsfiddle.net/mowglisanu/CbDHH/

A: You need to save the new value of the h2 content:
$('h2').each(function(){
  $(this).text(capitaliseFirstLetter($(this).text()));
});

A: you cant do anything you just add following css
 h2{
       text-transform: lowercase;
    }

h2 {
    text-transform: lowercase;
}

My Name is xYz


text:
Q: Why is ping time much higher using wifi than Ethernet connection? I have struggled with API of https://api.materialsproject.org recently. Because it is so slow and unstable when fetching data. I thought it was just the problem of this site. However, I found it is not true today.
I always work on my laptop which is connected to a wifi router. I just happened to try another computer with an ethernet connection, and I found it fetches data fast!
So I made a ping test on my laptop.
Disable wifi and insert the network cable, I got
PING api.materialsproject.org (104.18.41.120) 56(84) bytes of data.
64 bytes from 104.18.41.120 (104.18.41.120): icmp_seq=1 ttl=54 time=136 ms
64 bytes from 104.18.41.120 (104.18.41.120): icmp_seq=2 ttl=54 time=134 ms
64 bytes from 104.18.41.120 (104.18.41.120): icmp_seq=3 ttl=54 time=137 ms

remove cable, and insert the same cable into wifi router, and connect laptop to this wifi router, I got
PING api.materialsproject.org (104.18.41.120) 56(84) bytes of data.
64 bytes from 104.18.41.120 (104.18.41.120): icmp_seq=4 ttl=44 time=303 ms
64 bytes from 104.18.41.120 (104.18.41.120): icmp_seq=6 ttl=44 time=301 ms
64 bytes from 104.18.41.120 (104.18.41.120): icmp_seq=9 ttl=44 time=301 ms

Wow, this is really impressive, an immediate 200ms delay. To rule out the possibility that I may have a bad wifi, I tried another wifi router, still 300ms!
This really perplexed me, because my wifi is actually very fast tested by https://www.speedtest.net, which gives

An even weirder thing is that my work place has an AP network. If I connect to this AP network, I got a fast ping
PING api.materialsproject.org (104.18.41.120) 56(84) bytes of data.
64 bytes from 104.18.41.120 (104.18.41.120): icmp_seq=1 ttl=54 time=134 ms
64 bytes from 104.18.41.120 (104.18.41.120): icmp_seq=2 ttl=54 time=135 ms
64 bytes from 104.18.41.120 (104.18.41.120): icmp_seq=3 ttl=54 time=135 ms

However, according to speedtest, this AP network is much slower!

Can somebody explain what is going on? Is there a way to decrease my ping time to api.materialsproject.org via wifi connection?

PS:
As suggested by Martin, I ping the gateway, and I got
Pinging 192.168.31.1 with 32 bytes of data:
Reply from 192.168.31.1: bytes=32 time=1ms TTL=64
Reply from 192.168.31.1: bytes=32 time=2ms TTL=64
Reply from 192.168.31.1: bytes=32 time=2ms TTL=64
Reply from 192.168.31.1: bytes=32 time=3ms TTL=64

Ping statistics for 192.168.31.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 1ms, Maximum = 3ms, Average = 2ms

As suggested by petitradisgris, I run tracert api.materialsproject.org when connected to wifi and got
Tracing route to api.materialsproject.org [104.18.41.120]
over a maximum of 30 hops:

  1     3 ms     2 ms     1 ms  XiaoQiang [192.168.31.1]
  2     3 ms     3 ms     3 ms  172.16.24.1
  3     6 ms     6 ms     3 ms  120.199.21.1
  4     5 ms     5 ms     5 ms  221.131.254.53
  5     *        *        *     Request timed out.
  6     *        7 ms     6 ms  111.24.10.169
  7    28 ms    28 ms    29 ms  221.183.118.37
  8    32 ms    28 ms    28 ms  111.24.17.161
  9    32 ms    35 ms    34 ms  221.176.21.190
 10    33 ms    37 ms    34 ms  221.183.25.202
 11    33 ms    54 ms    32 ms  221.183.55.109
 12   203 ms   204 ms   204 ms  223.120.12.213
 13   218 ms   217 ms   217 ms  223.120.6.218
 14   362 ms   368 ms   364 ms  223.119.64.110
 15   307 ms   316 ms   306 ms  172.70.212.2
 16     *      309 ms     *     104.18.41.120
 17   301 ms     *      301 ms  104.18.41.120

Trace complete.

Then I run tracert api.materialsproject.org with only cable connected
Tracing route to api.materialsproject.org [104.18.41.120]
over a maximum of 30 hops:

  1     2 ms     2 ms    <1 ms  172.16.24.1
  2    27 ms     7 ms     6 ms  61.153.0.129
  3     *        *        *     Request timed out.
  4     *        *        2 ms  115.233.18.21
  5     *        *        4 ms  202.97.101.189
  6     7 ms     7 ms     7 ms  202.97.64.182
  7     *        7 ms     7 ms  202.97.50.193
  8   142 ms   146 ms   143 ms  202.97.71.198
  9   209 ms   267 ms   220 ms  218.30.53.214
 10   168 ms   157 ms   158 ms  172.68.188.22
 11   135 ms   135 ms   134 ms  104.18.41.120

Trace complete.

PS
Now I came back home. I can test yet on another wifi router, and this one is expensive :)
Surprisingly, the ping also takes 300ms. Trace are below
Tracing route to api.materialsproject.org [104.18.41.120]
over a maximum of 30 hops:

  1     1 ms    10 ms    <1 ms  RT-AX86U-0158 [192.168.50.1]
  2     2 ms     1 ms     1 ms  SMBSHARE [192.168.1.1]
  3     6 ms     4 ms     4 ms  10.109.128.1
  4     5 ms     4 ms     6 ms  221.131.254.41
  5     *        *        *     Request timed out.
  6     6 ms     6 ms     7 ms  111.24.10.169
  7    28 ms    28 ms    28 ms  221.183.118.33
  8    31 ms    52 ms    30 ms  111.24.2.250
  9    29 ms    28 ms    28 ms  221.176.21.190
 10    28 ms    28 ms    27 ms  221.183.52.1
 11    36 ms    38 ms    41 ms  221.183.55.109
 12   206 ms   208 ms   212 ms  223.120.12.213
 13   202 ms   207 ms   209 ms  223.120.6.218
 14   445 ms   459 ms   450 ms  223.119.64.110
 15   317 ms   318 ms     *     141.101.72.32
 16   323 ms     *        *     104.18.41.120
 17     *        *        *     Request timed out.
 18     *        *        *     Request timed out.
 19   312 ms   305 ms   313 ms  104.18.41.120

Trace complete.

Still takes a complicated route. So I came up another question. Since we already know there is a shortcut to the server, is it possible to force wifi to take the best route?

A: If you drive straight to work and back it'll take one amount of time, if you go via Starbucks and McD's on the way there and back it'll take longer right?
A wifi connection does extra things that a plain ethernet link doesn't - that's the delay, there's nothing to be done, laws of physics and all that.
The best you can do is be close to a very good wifi base-station that's attached to the primary network with the best latency.
Now I want a quarter-cheese...

A: It may be related to the Way your Operating System (Windows 10) trust or not your network leading to possible VPN features.I'm talking about network profiles in Windows (private, public).
1. First suggestion:
Open your VPN settings (System > Network and Internet > VPN) and disable the advanced settings:

*

*Allow VPN over metered networks

*Allow VPN while roaming
Try to traceroute again in both situation to see any changes.
2. Second Suggestion:
Try to change the network profile (in both situation), and check for impacts on your traceroute.
Below is a CMD command to do it quickly (on all interfaces). Do it as ADMINISTRATOR rights.
Set all connections to 'private' profile :
powershell -c "Get-NetConnectionProfile |Set-NetConnectionProfile -NetworkCategory private"

Set all connections to 'public' profile :
powershell -c "Get-NetConnectionProfile |Set-NetConnectionProfile -NetworkCategory public"

Try to traceroute again in both situation to see any changes.
3. Third Suggestion:
It appears that your ISP provider router (in the other side of your ethernet wire) seems to redirect differently your network traffic depending on the connected device.
Try to configure your Wifi Router WAN interface (the ethernet wired interface) by changing it's MAC address to something more 'Workstation related', for example something very similar to your Windows 10 workstation ethernet MAC interface.
Then try to traceroute again to see if it has effect on the latency and routes.

A: I partly solved my problem.
Since my cable network acquires IP dynamically. I found I can just let wifi router run in AP mode so that it just expand the cable network instead of build a new one. Now the trace route is short and fast.

A: In general, Wi-Fi connections will always be slower than ethernet because wireless signals will always weaken the further you get from the router. By contrast, wired connections do not degrade over distance and deliver much more consistent bandwidth and stable speeds
The maximum speeds of many Wi-Fi protocols are slower than speeds offered by common ethernet connections. Even if higher, Wi-Fi speeds are significantly more affected by interference, distance, and signal strength, resulting in slower transfer speeds. If possible, wired connections should be used where speed is critical.
Your WiFi equipment is old and needs replacement to obtain higher speeds
Protocol    Maximum Bitrate
802.11b      11 Mbps
802.11a      54 Mbps
802.11g      54 Mbps
802.11n     600 Mbps


text:
Q: Scroll Google Maps in iframe I've embedded Google Maps via an iframe in my website. I can't use the API at this point which is why I'm using the iframe.
Is there a way to scroll the iframe so that the upper part of the Google Maps page (search bar, etc.) are no longer visible to the user?

A: If the page was hosted in the same domain, you could use the scrollTop and scrollLeft dhtml properties on the iframe.document.body. However this is unlikely if you are hosting google maps from a remote server. You will be unable to modify the child frame contents via script.
Even if you could, this would always be a fragile solution. If the structure of the Google Maps changed at all, you would have to update your scrollTop/Left mechansim. Users will still be able to click in the frame and drag up to get the frame to scroll up, or even use the arrow keys.
Trying to fix the scroll position, then blocking the user from scrolling will likely be more trouble than it is worth.
ScrollTop Doc:
http://msdn.microsoft.com/en-us/library/ms534618(v=VS.85).aspx
You should probably try to eliminate whatever hurdles exist to using the API.


text:
Q: How far does this restricted definition on $\mathcal{O}$ goes? $\mathcal{O}$ notation describes an onto function $f:\mathcal{O} \rightarrow \omega_{CK}$. In calculating all values $n \in \mathbb{N}$ such that $f(n)=\alpha$, when $\alpha$ is a limit, all indexes $e$ of ordinary programs are considered such that $\phi_e(i)=n_i$ (with $i \in \mathbb{N}$). The values $n_i$ must satisfy the condition that $f(n_i)=\alpha_i$ with the $\alpha_i$'s forming a (fundamental) sequence for $\alpha$.
I am just interested in the variation where we don't consider indexes of normal programs but instead consider indexes of primitive recursive functions/programs (given a suitable indexing for them).
(Q1) How far would such a variation go? That is, what is the smallest ordinal it can't represent.
(Q2) Consider the notation system (described by a 1-1 function $g:\beta \rightarrow \mathbb{N}$) assigning a unique number to each ordinal in which on limit values $\alpha<\beta$ we seek the p.r. function with smallest index $e$ satisfying $\phi_e(i)=g(\alpha_i)$ where the $\alpha_i$'s must form a (fundamental) sequence for $\alpha$.
At what value $\beta$ would such a system stop?
I don't have proficiency with the underlying theory so if the question seems posed in a strange manner then that might be the reason.

A: For Q2, the answer is $\omega^2$, for both recursive and primitive recursive notations.  It's not hard to see that every ordinal below $\omega^2$ can be reached.
To show that $\omega^2$ cannot be reached, the argument is the same for both primitive recursive and full recursive.  For each $a$, we construct a $b$ ensuring that $a$ is not a notation of this sort for $\omega^2$.  We will construct $b$ knowing its own index.  For recursive notations, this is an application of the recursion theorem.  For p.r. notations, even though we don't have the recursion theorem, this is still possible so long as we're willing to specify an a priori p.r. bound on the runtime.  Since we intend to kill time by enumerating successors, an exponential bound will be fine.
Our first goal is to arrange that $b$ codes $\gamma+\omega$, where $\gamma$ is greatest such that some $c < b$ with $c <_\mathcal{O} a$ codes $\gamma$.  So we unwrap the notation $a$ while enumerating successors.  As soon as we see some $c < b$ with $c <_{\mathcal O} a$ and $|c|$ larger than any of the others yet seen, a c.e. event, we include $c$ in the sequence we're enumerating.
As soon as we see $b <_\mathcal{O} a$, we do something to ensure that $b$ is not a valid notation, e.g. break the monotonicity of our sequence.
If $a$ is a notation for $\omega^2$ with $b \not <_\mathcal{O} a$, then $\gamma+\omega < |a|$, and $b$ is the least notation for $\gamma+\omega$ (for any smaller notation would be included in the definition of $\gamma$, contradicting our choice of $\gamma$).  So if $a$ is a notation of the desired sort for $\omega^2$, then $b <_\mathcal{O} a$.  But then $b$ is not a notation, by construction, so $a$ is not a notation.


text:
Q: safe convert uint8_t into wchar_t This is my very first native extension between AIR and C++, and in C++ programming as well, so I am not sure where to look for help with type conversions.
From AIR side I receive a string in uint8_t (FRE... function call). I need to use this string for writing to registry, where wchar_t is expected.
I am not sure if I can simply make a type casting, or make new wchar[] array of the same size and copy characters or do I need to use someting like MultiByteToWideChar() to convert UTF-8 characters to wchar_t. Im not sure about the correct size of output array in this case.

...
FREObject retObj = NULL;
uint32_t strLength = 0;
const uint8_t *path8 = NULL;

// this is what I get from actionscript call
FREResult status = FREGetObjectAsUTF8(argv[ARG_PATH], &strLength,     &path8);
if ((status != FRE_OK) || (strLength <= 0) || (path8 == NULL)) return retObj;

LONG hStatus;
HKEY hKey;
wchar_t *path;

// ??? how to copy uint_t into wchar_t

hStatus = RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_ALL_ACCESS, &hKey);
...

A: std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> cv;
std::wstring dst = cv.from_bytes(src);


text:
Q: Changing all the heading tags at once using jQuery So I'm using jQuery to concatenate a string to all the heading tags i.e. h1, h2,...., h6 and display it on the screen. I just want help in the replacing part and if you have a solution in plain javascript, it will be useful too.
This my code which I'm certain is wrong:
        jQuery.noConflict();
        jQuery(document).ready(function(){

            var heading_text = '$heading_text';
            var page_heading = jQuery('h1','h2','h3','h4','h5','h6').text();

            //concatenating the two variables
            page_heading.html(page_heading+' '+heading_text);
        });

here, $heading_text is the input received.
for eg: if  $heading_text is xyz and text between h1 tag is  oh then after calling out this function, the text between h1 tag should be oh xyz

A:

elems = $('h1, h2, h3, h4, h5, h6');
heading_text = ' some text';
elems.each(function(){
  text = $(this).text();
  $(this).text(text + heading_text);
})

h1

h2

h3

h4

h5

h6

A: You can use the .text(function) overload to append text, however this will replace any html within the header. The alternative is to .append() new content to each header.
As jQuery works on collections, there's no need for any loops:

var heading_text = '$heading_text';

$('h1,h2,h3,h4,h5,h6').append(" " + heading_text);

H1 italic

H3

Same, but using .text()

var heading_text = '$heading_text';

$('h1,h2,h3,h4,h5,h6').text((i, txt) => txt + " " + heading_text);

H1 italic

H3


text:
Q: Get list of loaded libraries in C++ on Linux (at runtime) How can you obtain the list of all loaded shared libraries and their memory addresses (start, end) from a running C++ program?
I'm writing a small crash reporting utility that outputs what libraries were loaded at what address ranges at the time of a crash along with other information. Here is what I'm using for Windows:
void GetLoadedModules(std::vector<Module> &modules) {
  HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0);
  if (snapshot != INVALID_HANDLE_VALUE) {
    MODULEENTRY32 module_entry;
    module_entry.dwSize = sizeof(module_entry);
    if (Module32First(snapshot, &module_entry)) {
      do {
        Module module(module_entry.szModule,
                      (uint32_t)module_entry.modBaseAddr,
                      module_entry.modBaseSize);
        modules.push_back(module);
        module_entry.dwSize = sizeof(module_entry);
      } while (Module32Next(snapshot, &module_entry));
    }
    CloseHandle(snapshot);
  }
}

Can you do something equivalent on Linux? Or is it best to read from something like /proc/$pid/maps?
Update:
Here is what I ended up with. As suggested by @n.m. in his/her comment I used dl_iterate_phdr to achieve this:
extern const char *__progname;

int VisitModule(struct dl_phdr_info *info, size_t size, void *data) {
  std::vector<Module> *modules = reinterpret_cast<std::vector<Module> *>(data);

  const char *name = info->dlpi_name;
  if (modules->size() == 0) {
    // First visited entry is the main program.
    name = __progname;
  }

  uint32_t base_address = info->dlpi_addr;
  uint32_t total_size = 0;
  for (int i = 0; i < info->dlpi_phnum; i++) {
    total_size += info->dlpi_phdr[i].p_memsz;
  }

  Module module(name, base_address, total_size);
  modules->push_back(module);
  return 0;
}

void GetLoadedModules(std::vector<Module> &modules) {
  modules.clear();
  dl_iterate_phdr(VisitModule, reinterpret_cast<void *>(&modules));
}


text:
Q: Why does characteristic of F matter in Maschke's Theorem? I am reading Dummit and Foote chapter 18 recently. I have a confusion about Maschke's Theorem.
Maschke's Theorem: Let $G$ be a finite group and let $F$ be a field whose characteristic does not divide $|G|$. If $V$ is any $FG$-module and $U$ is any submodule of $V$, then $V$ has a submodule $W$ such that $V=U\oplus W$.
The theorem makes sense but I am wondering why we must have the characteristic of $F$ not divide $|G|$? What if it does divide $|G|$?


text:
Q: R - ggplot2 - limit bar chart output for categorical data I am trying to create a bar chart in ggplot2 that limits output on the x-axis to the top-10% most frequent categorical variables.
My dataframe is a dataset that contains statistics on personal loans. I am examining the relationship between two categories, Loan Status and Occupation.
First, I want to limit Loan Status to loans that have been "charged off." Next, I want to plot how many loans have been charged off across various occupations using a bar chart. There are 67 unique values for Occupation - I want to limit the plot to only the most frequent occupations (by integer or percentage, i.e. "7" or "10%" works).
In the code below, I am using the forcats function fct_infreq to order the bar chart by frequency in descending order. However, I cannot find a function to limit the number of x-axis categories. I have experimented with quantile, scale_x_discrete, etc. but those don't seem to work for categorical data.
Thanks for your help!
df %>% filter(LoanStatus %in% c("Chargedoff")) %>%
ggplot() +
  geom_bar(aes(fct_infreq(Occupation)), stat = 'count') +
  scale_x_discrete(limits = c(quantile(df$Occupation, 0.9), quantile(df$Occupation, 1)))

Resulting error:

Error in (1 - h) * qs[i] : non-numeric argument to binary operator

UPDATE:
Using Yifu's answer below, I was able to get the desired output like this:
pd_occupation <- pd %>%
  dplyr::filter(LoanStatus == "Chargedoff") %>%
  group_by(Occupation) %>%
  mutate(group_num = n())

table(pd_occupation$group_num)#to view the distribution

ggplot(subset(pd_occupation, group_num >= 361)) +
  geom_bar(aes(fct_infreq(Occupation)), stat = 'count') +
  ggtitle('Loan Charge-Offs by Occupation')

A: You can do it in dplyr instead:
#only use cars whose carb appears more than 7 times to create a plot
mtcars %>%
    group_by(carb) %>%
    mutate(group_num = n()) %>%
    # you can substitute the number with 10% percentitle or whatever you want
    dplyr::filter(group_num >= 7) #%>%
    #ggplot()
    #create your plot

The idea is to filter the observations and pass it to ggplot rather than filter data in ggplot.


text:
Q: XWindow + OpenGL, cant compile files I want to compile my OpenGL + Xwindow C++ program, but I am getting errors:
g++: fatal error: no input files
compliation terminated.
./source/Linux_OpenGL.c: line 10: //: is catalogue
...typedef: command not found
...Bool command not found
...XSetWindowAttributes command not found
...Syntax error near '}'.

and so on...
This is my compile script:
$(g++ -Wall -pedantic -ansi) ./source/Linux_OpenGL.cpp ./source/render.cpp -o Linux_OpenGL -lX11 -lGL -lGLU -lXxf86vm

How can I successfully compile my program?

A: Well I'd start by not doing this: $(g++ -Wall -pedantic -ansi)
This is telling the shell:

"interpret the output of g++ -Wall -pedantic -ansi as script and execute it".

This is definitely not what you want.
Use just
g++ -Wall -pedantic -ansi ./source/Linux_OpenGL.cpp ./source/render.cpp -o Linux_OpenGL -lX11 -lGL -lGLU -lXxf86vm


text:
Q: Total number of authors with more than one post <?php
$users = $wpdb->get_var("SELECT COUNT(ID) FROM $wpdb->users");
echo '(', count( get_users( array( 'role' => 'author' ) ) ); echo ')'
?>

code by Jan Beck
I need to know what is my best option for displaying the total number of authors who have at least posted and/or published something on my blog.
Currently the code is counting all the authors even if they haven't posted anything. Please let me know if there is a simple solution to this. I have looked throughout the wordpress codex and have not found a solution to this yet.

A: I believe that wp_list_authors will do what you want, sort of. You could run the function with the echo parameter false and count the results.
$authors = wp_list_authors(
  array(
    'echo'=>false,
    'html'=>false
  )
);
echo var_dump($authors);
echo count (explode(',',$authors));

Or, alternately, and perhaps less profligately, steal that function's SQL.
$authors = $wpdb->get_results(
  "SELECT DISTINCT post_author, COUNT(ID) AS count
  FROM $wpdb->posts
  WHERE post_type = 'post'
  AND " . get_private_posts_cap_sql( 'post' ) . "
  GROUP BY post_author"
);
var_dump($authors);
echo count($authors);

Those are slightly different in that the first ignores the admin user by default, but there is a parameter to change that.


text:
Q: Can I run multiple copies of Terraria if I bought it on Steam? I play Terraria a bit with my brother and friends and I am always the one with the server, but sometimes while I am playing it gets a bit boring and I want to play on my own world and character (I do know about that whole duplicating cheat and am not a fan) at the same time. I was able to do this for a while and now I can't. Is there a setting that I accidentally turned on or just an annoying patch?

A: A good way to do this is to run a Terraria dedicated server. This is a separate executable that runs the server in the background, leaving you free to launch Terraria and connect to the server, or play single player while the server continues running for everyone else. To run the dedicated server, browse the Terraria folder in your Steam folder, and run TerrariaServer.exe. For further information, and to set up port forwarding if required, visit the Dedicated Server page on the Terraria wiki.

A: If you're on a local network you can start Terraria client on one computer, yank the internet for just that computer, login to Steam on the second and start the client again there, and yank the internet again for that computer. Restart Steam in offline mode and reconnect the internet on both computers.
It would probably pay to buy a second copy of the game itself on a separate Steam account, but this could function if you're in a pinch.
Insofar as running the server, I recommend TShock. It's a bit more beefed up than the regular server software (commands, user groups, login passwords, all that good stuff) but accomplishes the same.

A: The easiest way is to open the steam in the folder location by right clicking the steam application. Then, open the steamapps, then the common folder, then the terraria folder and find the terraria application (should have the terraria picture). Finally just double click as many times as you want and you will have as many terraria windows open as you want.


text:
Q: Facing challenge in SSIS Integration service auto Refresh Between Sql Server 2012 and Oracle 11g ) I have created an integration service, well with the help of colleague. We are getting data from an Oracle table and bulk insert to SQL server using SSIS. It's working fine when we execute run/debug in Visual Studio. Now, one issue we have is how we can automate the process so that one of us does not have to do it manually?
Thanks.

A: You can create a SQL Server job directly, my preference is to create a maintenance plan.

*

*Open SSMS and goto Management => Maintenance plans

*Right click and select "New Maintenance Plan"

*Name it and click 'OK'

*Drag "Execute T-SQL Statement Task" from tool box to design area

*Configure

*I highly recommend adding a Notify Operator Task for when it fails.

*Click on Calendar Icon at top to schedule

*Save and step back, your task is now scheduled


text:
Q: Java custom annotation - calling methods with annotation I have two annotation (@Translation, @Translate).
@Retention(RUNTIME)
@Target({FIELD})
public @interface Translation {
}

@Retention(RUNTIME)
@Target({PARAMETER})
public @interface Translate {
}

With @Translation I want to mark some fields like below
class User {
   @Translation
   String name;
}

And I have Injector class that implementing @Translation.
>   public class Injector {
    public void inject(Object instance) {
        Class clazz = instance.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Translation.class)) {
                Translation set = field.getAnnotation(Translation.class);
                // set value to fields
            }
        }
    }
}

I want to execute method inject with @Translate like
class UserDto{

String name;

void UserDto(@Translate User user){
    name = user.name;
}

If I asked something wrong, please correct me. Thank you for your advice.

A: As far as I know, you need to use aspect-oriented programming (SpringAOP) to take some action before the method invocation and validating parameter annotated with @Translate.
On the other hand, you could implement the method, that validates @Translate annotation as you did with @Translation and invoke it in the constructor.

A: First off Spring AOP(proxy based) works with intercepting method invocations only.
The following Aspect is triggered whenever the annotation is incountered on a method (in your case you can use setters). Particularly @Around executes on entry and exist of a particular method.
It should be more or less similar to the following. Note I have used List of String to capture the method arguments.
@Aspect
@Component
public class TranslateAspect {

    Logger logger = LoggerFactory.getLogger(TranslateAspect.class);

    //The argument ProceedingJoinPoint will be an executing **method** which has been annotated with @Translation.
    @Around("@annotation(your.package.Translation)")
    public Object translationInterceptor(ProceedingJoinPoint jointPoint) throws Throwable {
        List<String> arguments = new ArrayList<>(); //may be add a map
        String declaringMethod = TranslateAspect.class.getSimpleName();
        Object proceed = null;
        try{
            MethodSignature methodSignature = (MethodSignature) jointPoint.getSignature();
            Method method = methodSignature.getMethod();
            declaringMethod = methodSignature.getDeclaringType().getSimpleName() + "." + method.getName() + "()"; //like clazz.methodName()

            //argument name and value
            String[] argumentNames = methodSignature.getParameterNames();
            Object[] methodArguments = jointPoint.getArgs();

            //add name and value of each parameter
            for(int i=0; i < methodArguments.length; i++){
                arguments.add(argumentNames[i] + " = " + methodArguments[i]);
            }

            proceed = jointPoint.proceed();
        }catch (Exception e) {
            throw e; //should not swallow the thrown exception
        }finally {
            // add logging?
        }
        return proceed;
    }
}


text:
Q: When i want to solve the leetcode.225 in pure c, there's something wrong '''
With the help of the answer, I modified the code, such as the return type and function parameter settings. Thank you all here, but I still don't understand why my code still reports such an error. I checked a lot of information and felt that there was nothing wrong with the code in the enqueue function. What is going wrong? thank you very much !
'''
typedef struct {
    int val;
    struct QNode* next;
}QNode;

typedef struct {
    struct QNode *rear;
    struct QNode *front;
}Queue;

typedef struct {
    struct Queue *q1;
    struct Queue *q2;
}MyStack;

Queue* qcreate(void){
    Queue* q = malloc(sizeof(Queue));

    q->front = NULL;
    q->rear = NULL;
    return q;
}

bool qisempty(Queue* q){
    return (q->rear == NULL);
}

void enqueue(Queue *q, int x){
    QNode *qn = malloc(sizeof(QNode));
    qn->val = x;
    qn->next = NULL;

    if(q->front==NULL){
        q->front = q->rear = qn; // line 35
    }
    else{
        q->rear->next = qn; // line 38
        q->rear = qn;
    }
}

int dequeue(Queue* q){
    QNode *pt;
    int n = q->front->val;
    pt = q->front;

    q->front = q->front->next;

    free(pt);
    return(n);
}

void freeq(Queue* q){
    while(!qisempty(q)){
        dequeue(q);
    }
    q->front = q->rear = NULL
    free(q);
}

/** Initialize your data structure here. */

MyStack* myStackCreate() {
    MyStack* st = (MyStack*)malloc(sizeof(MyStack));

    st->q1 = qcreate();
    st->q2 = qcreate();
    return st;
}

/** Push element x onto stack. */
void myStackPush(MyStack* obj, int x) {
    int m;
    while(!qisempty(obj->q1)){
        m = dequeue(obj->q1);
        enqueue(obj->q2, m);
    }
    enqueue(obj->q1, x);
    while(!qisempty(obj->q2)){
        m = dequeue(obj->q2);
        enqueue(obj->q1, m);
    }
}

/** Removes the element on top of the stack and returns that element. */
int myStackPop(MyStack* obj) {
    int m;
    m = dequeue(obj->q1);
    return m;
}

/** Get the top element. */
int myStackTop(MyStack* obj) {
    return obj->q1->front->val;
}

/** Returns whether the stack is empty. */
bool myStackEmpty(MyStack* obj) {
    return qisempty(obj->q1);
}

void myStackFree(MyStack* obj) {
    freeq(obj->q1);
    freeq(obj->q2);
}

/**
 * Your MyStack struct will be instantiated and called as such:
 * MyStack* obj = myStackCreate();
 * myStackPush(obj, x);

 * int param_2 = myStackPop(obj);

 * int param_3 = myStackTop(obj);

 * bool param_4 = myStackEmpty(obj);

 * myStackFree(obj);
*/`enter code here`

solution.c: In function 'enqueue'
Line 35: Char 28: warning: assignment to 'struct QNode *' from incompatible pointer type 'QNode *' {aka 'struct  *'} [-Wincompatible-pointer-types]
q->front = q->rear = qn;
^
Line 38: Char 16: error: dereferencing pointer to incomplete type 'struct QNode'
q->rear->next = qn;
^~

A: Your error is here:
void qinit(){

and you call it like:
qinit(st->q1);
qinit(st->q2);

Apparently, you expect the function to initialize st->q1 and st->q2 but it doesn't. You probably wanted:
void qinit(){
    ....
    return MALLOCED_AND_INITIALIZED_QUEUE_POINTER;
}

st->q1 = qinit();
st->q2 = qinit();

So why didn't you get a compiler warning/error ?
Well, void qinit() means a function that takes an unspecified number of parameters so you don't get a warning for qinit(st->q1);.
Had you used: void qinit(void) the compiler would have screamed at you.
Lesson: Never use an empty parameter list in a function. Use void if it takes no parameter.
Besides that:
Here is a bug that needs to be fixed too.
Here:
void freeq(struct Queue* q){
    while(!qisempty(q)){
        dequeue(q);
    }
    free(q->front);   // q-> front is NULL due to the while above
                      // so this does nothing

    free(q->rear);    // q->rear is pointing to an already free'ed object
                      // so this is an error
}

In other words - both free should be deleted.
And here:
int dequeue(struct Queue* q){
    struct QNode *pt;
    int n = q->front->val;
    pt = q->front;

    q->front = q->front->next;
    q->count--;
    free(pt);
    return(n);
}

you are missing an update of q->rear. Like:
    if (q->front == NULL) q->rear = NULL;
    return(n);

And a comment regarding the design:
Why do you push at the end of the queue and pop from the front?
That is how a FIFO works.
For a stack you would normally do both push and pop in the same way. That will really simplify your code. Further, it will perform a lot better.
If you always push and pop from the front you can

*

*Delete q2 in MyStack

*Delete rear in struct Queue
and consequently delete all code that operates on those.


text:
Q: How I can update my objects in template dynamically? I have comments on a product on the page. and there is a button to add a comment, which puts a new comment into the database. How can I automatically display a new comment on a page?
mytemplate.html
<div id="comments">
{% include 'comments.html' %}
</div>

comments.html
{% for comment in comments %}
        <!-- some code for display comments -->
{% endfor %}

script.js
$("#addComment").on("click", function(e){
        e.preventDefault()
        if ($("#addCommentArea").val() != ""){
            data = {
                commentText: $("#addCommentArea").val(),
                product_id: "{{ product.id }}"
            }
            $.ajax({
                type: "GET",
                url: "{% url 'newcomment' %}",
                datatype: 'json',
                data: data,
                success: function(data){
                    $("#addCommentArea").val("")
                }
            })
        }
    })

views.py
class CommentView(View):
    def get(self, request):
        commentText = request.GET.get("commentText")
        if (len(commentText) > 0):
            newComment = Comment()
            newComment.Author = request.user
            product_id = request.GET.get("product_id")
            product = Product.objects.get(id=product_id)
            newComment.Product = product
            newComment.Comment = commentText
            newComment.save()
        return JsonResponse({'ok': 'ok'})

A: Currently, you just render the template once and fetch the comments, further you are using Ajax to submit, which means your template doesn't get updated. To update the comments without a page refresh you can either make a javascript polling or use for example web sockets


text:
Q: How to pass a member function to a class constructor? I want to pass my class Worker a pointer to a funtion, but something is wrong when im calling the constructor...
Worker.h
class Worker : public QObject
{
Q_OBJECT

public:
Worker(void (*process)());

public slots:
void work();

signals:
void error(QString error);
void paused();

private:
void (*_task)();
};

Worker.cpp:
Worker::Worker(void (*task)())
{
_task = task;
}

void Worker::work()
{
_task();
paused();
}

This is what i want to do...
Worker should perform a function call of any function.
(Update is a void without attributes, not static or const etc.)
Main.cpp:
_worker = new Worker(someClass->Update());

A: First, when a function is a non static member function of a class, its first argument is the object from which its called.
In your example, the real code for your function Update() from the object someClass is "void Update(&someClass)"
Secondly, when you do Update(), you call the function and so, takes its return in your Worker constructor.
To use member function pointers, the syntax is : &ClassType::FunctionName
To use 'normal' function pointers, the syntax is : &FunctionName
In your exemple, you can for exemple turn Update function to static and change your constructor like this :
_worker = new Worker(&someClassType::Update);

Like someone said in the comments, if you want to improve your code, learn about std::function from C++11

A: Just a variant of Félicie's answer.
If you want to be able to pass methods operating on arbitrary objects, the C++11 way will be to use std::function and std::bind.
If for any reason you must use a pre C++11 system, you will have to revert to the C-ish style of passing arbitrary arguments, the good old void * type:
void someClassUpdateWrapper(void *obj) {
    SomeClassType someClass = static_cast<SomeClassType *>(obj);
    someClass->Update();
}

You will have to slightly change your declarations:
class Worker : public QObject
{
Q_OBJECT

public:
Worker(void (*process)(), void *obj);

...

private:
void (*_task)();
void *_obj;
};

then:
Worker::Worker(void (*task)(), void *obj;)
{
_task = task;
_obj = obj;
}

void Worker::work()
{
_task(_obj);
paused();
}

and finaly:
_worker = new Worker(someClassUpdateWrapper, static_cast<void *>(someClass));

But this looses all the possible type controls allowed by the C++11 way - the reason why std::function and std::bind were invented...


text:
Q: SQL - How can I select a particular element in a row? I want to get/select a particular element in a row. How can i do that for Oracle 11g, sql server and mysql ?
eg. id - name - address
    1  - abc  - def
    2  - adl  - eio
    3  - yuc  - pwr

Select/display adl, ie 2nd row name column.

A: with a particular element do you mean a field ?
in all of them, is the same way: Standard ANSI SQL. For example:
select TheFieldYouWant from YourTable where RowIdYouWant = 1

This will get from the table the row with Id = 1
and then, show you the field you want. You could put more fields, if you want to show more, or * to show all of them


text:
Q: FlatFileFooterCallback Exception not coming in Skip Listener Issue :- Error throwing from FlatFileFooterCallback is not skippable and Job is getting stopped
What we tried
Job Configuration below
    @Bean
public Step mmsSlaveStep() throws Exception {
    return stepBuilderFactory.get("mmsSlaveStep").<BaseDTO, BaseDTO>chunk(chunkSize).reader(mmsReader(null))
            .processor(mmsProcessor()).writer(mmsItemWriter(null)).faultTolerant().skipLimit(skipErrorCount)
            .skip(Exception.class).listener(itemSkipListener()).build();
}

ItemWriter that have Footer Call Back
@Bean
@StepScope
public FlatFileItemWriter<BaseDTO> mmsItemWriter(@Value("#{stepExecutionContext['fileName']}") String filePath)
        throws Exception {
    BeanWrapperFieldExtractor<BaseDTO> fieldExtractor = new BeanWrapperFieldExtractor<>();
    fieldExtractor.setNames(mmsWriterFields);
    fieldExtractor.afterPropertiesSet();
    FormatterLineAggregator<BaseDTO> lineAggregator = new FormatterLineAggregator<>();
    lineAggregator.setFormat(mmsWriterFieldsFormat);
    lineAggregator.setFieldExtractor(fieldExtractor);
    String fileName = FilenameUtils.getName(filePath);
    Resource outputResource = new FileSystemResource(new File(sucessPath + fileName + inputDataSource));
    return new FlatFileItemWriterBuilder<BaseDTO>().name("mmsWriter").resource(outputResource)
            .lineAggregator(lineAggregator).shouldDeleteIfEmpty(true).footerCallback(mmsSummaryItemWriter()).build();
}

FooterCall Back Writer that have writeFooter that aggregates data to a DB table. This exception is not coming to SkipListener
public class MMSSummaryWriter implements FlatFileFooterCallback {
@Autowired
private MMSMasterService mmsMasterService;
@Value("#{stepExecution}")
private StepExecution stepExecution;

@Autowired
@Qualifier("jdbcTemplate")
private JdbcTemplate jdbcTemplate;

@Override
    public void writeFooter(Writer writer) throws IOException{
        ExecutionContext  executionContext =stepExecution.getExecutionContext();
    HashMap<String,MMSDto> summaryMap = (HashMap<String, MMSDto>) executionContext.get("Summary");

    List<MMSDto> summaryValues = new ArrayList<>(summaryMap.values());

    int[] updateCounts =  jdbcTemplate.batchUpdate(InterConnectUtils.SUMMARY_EVENT_INSERT, new BatchPreparedStatementSetter() {
              @Override
              public void setValues(PreparedStatement ps, int i) throws SQLException   {
                  int counter =0;
                  MMSDto mmsDto = summaryValues.get(i);
                  ps.setString(1,mmsDto.getBatchNumber());
                  ps.setString(2,mmsDto.getEntityCode());
                  ps.setString(3,mmsDto.getInputFileType());
                  ps.setInt(4, mmsDto.getTotalType());
                  ps.setString(5,mmsDto.getServiceType());
                  ps.setString(6, mmsDto.getCallInd());
                  ps.setString(7,mmsDto.getCallDateTime());
                  ps.setString(8,mmsDto.getEventDirection());
                  ps.setString(9,mmsDto.getProductID());
                  ps.setInt(10,mmsDto.getTargetInd());
                  ps.setInt(11,mmsDto.getNoRecords());
                  ps.setLong(26,mmsDto.getTotalDuration());
                System.out.println("InsertValues : "+mmsDto.getBatchNumber()+"#"+mmsDto.getTotalType()+"#"+mmsDto.getCallInd()+"#"+mmsDto.getServiceType()+"#"+
                        mmsDto.getProductID()+"#"+mmsDto.getCallDateTime()+"#"+mmsDto.getTotalType());
              }
              @Override
              public int getBatchSize() {
                  System.out.println("summaryMap.size()"+summaryMap.size());
                return summaryMap.size();
              }

            });

}

}
SkipListner Class that handles errors and log to table and allow the job to continue
public class PreProcSkipListener implements SkipListener<BaseDTO, BaseDTO> {

private static final Logger logger = LoggerFactory.getLogger(PreProcSkipListener.class);

@Autowired
@Qualifier("jdbcTemplate")
private JdbcTemplate jdbcTemplate;
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void onSkipInWrite(BaseDTO item, Throwable t) {
    Exception ex = new Exception(t);
    jdbcTemplate.update(InterConnectUtils.BATCH_ERROR_INSERT, new PreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps) throws SQLException {
            MMSDto mmsDto = (MMSDto) item;
            StringWriter sw = new StringWriter();
            ex.printStackTrace(new PrintWriter(sw));
            String exceptionAsString = sw.toString();
            ps.setDate(1, new java.sql.Date(new Date().getTime()));
            ps.setString(2, mmsDto.getBatchNumber());
            ps.setString(3, "WRITER");
            Reader reader = new StringReader(exceptionAsString + "--" + ex.getMessage());
            ps.setClob(4, reader);
        }

    });

    }
   }}

There is an open issue mentioned in github to consider. Let us know any workaround
github defect


text:
Q: Magnetic force and relative frame The magnetic field for to a moving charge depend on its velocity (Biot Savart's law). My question is that is it then not frame dependent? If it is, it means if a man is walking and other is standing magnetic field at same point to both will be different. But magnetic field at that point can have only on "constant value". Can you please explain this.
PS I know nothing about special theory of relativity. But I read on Google it has got something to do with "Lorentz force"

A: I'm afraid your statement that magnetic field at a point can have only on(e) "constant value" is not true, and you will have to learn a bit about special relativity to understand why.
There is a classic thought experiment, which is to imagine the electromagnetic fields due to a charged particle at rest in what we'll call the stationary frame. Clearly, the electric field is radial and diminishes as $r^{-2}$ as we move away from the particle. There is NO magnetic field.
But now consider what this looks like from the point of view of an observer moving past the charge at high speed. They will "see" a moving charge - or a current. This moving charge will generate an electric field (but one that is different at any point in space from that measured in the stationary frame), but more importantly, they would be able to detect a magnetic field due to the current.
So, electric field and magnetic field are not invariant when measured in different reference frames - there are a set of transformations that allow you to work out how they change.
http://en.wikipedia.org/wiki/Classical_electromagnetism_and_special_relativity#The_E_and_B_fields

A:
But magnetic field at that point can have only on "CONSTANT VALUE".

Not true. If a particle is acted on by some combination of electrical and magnetic forces in one frame of reference, then in another frame of reference, it will be a different combination of electrical and magnetic forces. It's possible to have a force that's purely electrical in one frame and purely magnetic in another.


text:
Q: d3.js / JSFiddle - loading .tsv data I created a JSfiddle to collaborate on a project but I can't get it to run properly:

*

*It's loading correctly the html/css elements

*It's apparently running the .js code as the dimensions  (960*500 px )of the result look correct to me

*

*However it does not seem to load the dataEL.tsv file I attached as an external resource, and that I use in my code to load data via:
window.onload = function draw(data) {
    d3.tsv("dataEL.tsv", type, function(error, data) {
 (...)

=> Here is the link to the JSfiddle
Can you please help me load correctly the data in order to display the result?
It displays correctly on my personal server

A: I don't think jsFiddle.net lets you upload external resources other than referencing JS files.
If you open the Javascript console, or Developer Tools of your browser (F12 assuming you are on Windows and using IE/Chrome/FF) you see that you are getting a 404 not found error for the file dataEl.tsv:

Failed to load resource: the server responded with a status of 404
  (NOT FOUND) http://fiddle.jshell.net/46yxnukv/2/show/dataEL.tsv

You could try a different site, or upload the file dataEL.tsv to an internet-accessible web server and then request it using the full URL instead of an URL on jsFiddle.net.


text:
Q: Any idea of how to list gcp service account keys using python I need a list of all service account keys in all gcp projects within an organization. What i am looking for is a list of user managed service account keys that are active...Below is the code i am using

Not sure what is missing, i don't see user managed service account keys, i only see system managed. How can i get a list of user managed service account keys??

A: You're calling the projects.serviceAccounts.keys.list method with an (optional?) KeyType
of SYSTEM_MANAGED but you want USER_MANAGED
I encourage you to jettison all the subprocess stuff. It's entirely redundant, makes your code unnecessary complex and problematic.
Example
import google.auth

from googleapiclient import discovery

credentials, project = google.auth.default()

crm = discovery.build(
    "cloudresourcemanager",
    "v1",
    credentials=credentials
)
iam = discovery.build(
    "iam",
    "v1",
    credentials=credentials
)

projects_list_rqst = crm.projects().list()

while projects_list_rqst is not None:
    projects_list_resp = projects_list_rqst.execute()
    projects = projects_list_resp.get("projects",[])

    for project in projects:
        project_id = project["projectId"]
        print(f"Project: {project_id}")
        name="projects/{project_id}".format(project_id=project_id)
        sa_list_rqst = iam.projects().serviceAccounts().list(
            name=name
        )

        while sa_list_rqst is not None:
            sa_list_resp = sa_list_rqst.execute()
            accounts = sa_list_resp.get("accounts",[])

            for account in accounts:
                name=account["name"]
                print(f"\tAccount: {name}")
                keys_list_rqst = iam.projects().serviceAccounts().keys().list(
                    name=name,
                    keyTypes="USER_MANAGED"
                )
                keys_list_resp = keys_list_rqst.execute()
                keys = keys_list_resp.get("keys",[])

                for key in keys:
                    name=key["name"]
                    print(f"\t\tKey: {name}")

            sa_list_rqst = iam.projects().serviceAccounts().list_next(
                previous_request=sa_list_rqst,
                previous_response=sa_list_resp
            )

    projects_list_rqst = crm.projects().list_next(
        previous_request=projects_list_rqst,
        previous_response=projects_list_resp)


text:
Q: When did Jo Grant see the Doctor recover from the cold after a temperature rise? In Planet of the Daleks, Jo mentions that this isn't the first time she's seen the Doctor enter a coma due to being cold. She claims that a sudden rise in temperature allowed him to recover the last time.
When was this? I assume this was a known adventure (be it on-screen or in another medium), since the TARDIS Wikia says, "The Doctor once again goes into a catatonic state in extreme cold, but reawakens after an extreme rise in temperature". I was disappointed that this comment contained no hyperlink to a relevant previous story, even though such comments often do. I also got nowhere googling it, short of this story.

A: Season 8, The Daemons, part 2
http://www.bbc.co.uk/programmes/p01bb3lq/p01bb3fz
He's even a bit sweaty...
EDIT to add TARDIS.WIKIA quote and link...
"Garvin holds both of them at gunpoint and moves them outside, just as the ground starts to shake. Garvin fires up at something gigantic, but is engulfed in a fireball. The heat wave extends even into the village, knocking Jo and Yates down, just as the Doctor awakens with a start."
http://tardis.wikia.com/wiki/The_D%C3%A6mons_%28TV_story%29


text:
Q: Возврат из fragment в activity При нажатии на одну из кнопок в activity, поверх нее появляется fragment. Вопрос: как вернуться обратно в activity при помощи кнопки Back?

A: Переопределите метод onBackPressed
@Override
public void onBackPressed() {
    if (mFragmentManager.getBackStackEntryCount() > 0)
       mFragmentManager.popBackStackImmediate();
    else super.onBackPressed();
}

Чтобы это сработало надо ещё добавить фрагмент в стек
FragmentManager mFragmentManager = ((FragmentActivity) context).getSupportFragmentManager();
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.addToBackStack("Тег добавляемого фрагмента");
fragmentTransaction.add("container id", fragment);
fragmentTransaction.commit();


text:
Q: Fresh Ubuntu 16.04 Nginx Configuration is Serving Old Static Files I have a very basic landing page for a domain of mine. For the last couple days I have been fighting a very peculiar issue.
For example, the directory contains:
vanilla>
    ./files/
    ./index.html
    ./main_style.css

    files>
        ./back.gif
        ./back1.gif
        ./logo.png

The contents of index.html:
<!DOCTYPE html>

        <title>Vanilla</title>
        <link rel="stylesheet" type="text/css" href="main_style.css"/>

The contents of main_style.css:
html {
    background-image: url("files/back1.gif");
    background-repeat: repeat;
}

img.logo {
    width: 471px;
    height: 384px;
    position: absolute;
    top: 50%;
    left:  50%;
    margin-left: -235px;
    margin-top: -192px;
}

The problem I'm facing is this:
Immediately following a reboot or something of that sort, and I open the website, all static files load properly, to the versions that are present on the server.
However, beyond this point, if I make a change to the main_style.css, for example, it does not reflect the change whatsoever. Even opening the main_style.css in my browser does not reflect the changes, and it shows the old version of the file.
Also just recently, I renamed a photo from test.png, to logo.png, and changed it accordingly in the index.html. The index.html file reflected the appropriate change, however, it doesn't see the photo "logo.png", and it returns a 404 error... It is clearly in the web root directory, but it is not served. Even so, I can still access the OLD photo "test.png" via URL, even though no such file is present on the server.
What I have tried:
I understand that this issue is certainly related, in some way, to caching, and I have tried many solutions on the web in my search, and none seemed to have any effect at all on my system.
I see also that in many cases, this situation can be caused by VirtualBox or something called Vagrant VM. My machine has never had either of these things run on it, and my server is running on a physical PC under my desk.
I thought that the issue could have been caused by my running of over 100 updates, as I hadn't run my server in a while, so I went so far as to back up my personal data and web data from the server and reinstall the operating system to the latest version, and reinstall software from there.
I just finished doing that, and reconfiguring all of the web software, but surely enough, it is still having the same issue.
The only things that I installed on the machine after doing a fresh reinstallation of the operating system are:

*

*openssh-server

*samba

*nginx

*mysql-server

*php-fpm

*php-mysql

I have read that this could be solved by setting sendfile in the nginx.conf file to off, but this didn't resolve anything.
My nginx.conf file and php.ini file are both default.
nginx.conf:
user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

Site Configuration:
server {
        listen 80;
        root /usr/share/nginx/vanilla/;
        index index.html index.php index.htm;
        server_name www.website.com website.com;
        keepalive_timeout 10000;
        client_max_body_size 1024M;

        location / {
                try_files $uri $uri/ =404;
                #try_files $uri $uri/ /index.php?$args;
        }

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        }

}

A: In this situation, it was indeed related to caching. Simply not on the server's side, or my browser's side.
The caching that was causing the issues was on Cloudflare's side. I use this service as I host on my home network and wish to conceal my IP address.
I've never run into this problem with Cloudflare in the past, strangely enough. Maybe something has changed since I last used it.
How I fixed it:
I setup page rules to stop caching completely on the following configurations:

*

**.website.com/*

*website.com/*

And then wiped Cloudflare's stored cache completely, and now I'm no longer having issues with caching or the serving of old files.


text:
Q: In Minecraft, do clocks still work while in item frames? Do clocks still work when in item frames?

A: Yes, they work correctly in item frames.
From the wiki for clocks, emphasis mine:

The dial can be read from a clock in any of its representations: held in a player's hand, placed in any inventory or crafting grid, in an item frame, and even as a dropped item.


text:
Q: Measure heap memory used by individual objects Just curious, Is there a way to measure the heap memory consumed by each individual object from inside the code in realtime?
(I know I can use VisualVM and Eclipse Memory Analyzer as answered here, but is there a way to do this from the inside?)

A: Since you don't want to you the free tools available, you can look into the Hprof (freely available)code, try to change it in your own way. Hprof internally uses JVMTI . It will work.


text:
Q: create sequence vector for each level of other column I have a data table something like this. This is just a sample. col1 has a lot more levels
col1      col2
A          231
A          532
A          764
A          532
B          432
B          432
B          443
B          343
B          643
B          322
B          334

What I want is the following
col1      col2      squence_per_col1
A          231           1
A          532           2
A          764           3
A          532           4
B          432           1
B          432           2
B          443           3
B          343           4
B          643           5
B          322           6
B          334           7

Basically I want to create sequence column for each level of col1 in a very efficient manner. Please not that this is a data.table. Please provide a solution with data table syntax.
How do I do it?


text:
Q: Laravel - JQuery Dropdown Display not working as expected I am developing a project using Laravel-5.8. In the project, I am using JQuery to hide and show div.
Controller
public $rating_points = [
"1" => "Three Star Rating",
"2" => "Four Star Rating",
"3" => "Five Star Rating",
"4" => "Six Star Rating"];

public function create()
{
  return view('appraisal.ratings.create')->with('rating_points', $this->rating_points);
}

public function store(Request $request)
{
$rating = AppraisalRating::create([
    'rating_point'               => $request->rating_point,
    'rating_type'               => $request->rating_type,
    'rating_value'              => $request->rating_value,
    'rating_description'        => $request->rating_description,
    'company_id'                => Auth::user()->company_id,
    'created_by'                => Auth::user()->id,
    'created_at'                => date("Y-m-d H:i:s"),
    'is_active'                 => 1,
]);
Session::flash('success', 'Appraisal Rating is created successfully');
return redirect()->route('appraisal.ratings.index');
}

By default, when the form is loaded only the dropdownlist is visible as shown in the diagram:

view

       <form  action="{{route('appraisal.ratings.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
           {{csrf_field()}}

                                        Rating Point*

                                            <select class="form-control select2" data-placeholder="Choose Rating Value" tabindex="1" name="rating_type[]">
                                                <option value="">Select point</option>
                                                @foreach($rating_points as $k => $rating_point)
                                                    <option value="{{$k}}" @if(old("rating_point") == "$k") selected @endif>{{$rating_point}}</option>
                                                @endforeach
                                            </select>

                                        Rating Type*

                                            <input  type="text" name="rating_type" placeholder="Enter rating type here" class="form-control" value="{{old('rating_type')}}" readonly>

                                        Rating Value*

                                            <input  type="number" name="rating_value" placeholder="Rating Value" class="form-control" value="{{old('rating_value')}}">

                                        Description*

                                            <input  type="text" name="rating_description" placeholder="Enter rating description here" class="form-control" value="{{old('rating_description')}}">

                   <button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
                <button type="button" onclick="window.location.href='{{route('appraisal.ratings.index')}}'" class="btn btn-default">Cancel</button>

        </form>

I expect that the dropdownlist on change should determine the div tag to be displayed. This is not happening. The Divs remains hidden.
How do I resolve this?
Thank you.

A: I've eventually solved it myself. I found out that I added id='rating-point' as

instead of
<select id='rating-point' class="form-control select2" data-placeholder="Choose Rating Value" tabindex="1" name="rating_type[]">

Thanks a lot @AlbertoSinigaglia


text:
Q: Matlab- How to plot waveform selected by threshold value. (by fetching data from array) and plotting it 20 wave forms fetched out of 1000I wanted to fetch waveform from array.
I am using following code.
clc
clear('all');
close('all');

Load ('w.mat'); % w.mat is actually file holding 1000 wave forms)

x= 1:length(w(1,:));

Subplot(321);
Plot(x,w(1:20,:)); %Plotting First 20 wave forms out of 1000

Now by visually looking at plot I found out that 0.6 is X axis threshold  and about 15 point mark is the Y axis Threshold ( I would have posted picture here but i am new to stack flow forum it is not allowing me to post it).
How can I fetch waveforms on basis of X Axis threshold of 0.6 and Y axis Index value of about 15. and stored them in different files.
I know Save command to save it into a file on basis of different arguments assigned to it. But How to access X Axis and Y Axis values and compare the waveforms.
I wanted to compare to wave 2 actually which is more close , any too high values i have to avoid.
Any help Idea, as I am from C++ background. Matlab is a bit new to me.
Thanks Heaps
Kind Regards
K Haroon

A: I suppose what you are asking is how can we save the data whole value is greater than 0.6 on the x-axis and 15 on the y-axis
you can store the data/matrix in a variable by using
data=load('filename.txt')

and then applying a condition on  its variables and then store them in a text-file using
dlmwrite('filename.txt',extracted_data_array)

if that's what you are asking