答:
You can transfer any data through a bundle like below :

```<code>Bundle bundle = new Bundle();
bundle.putInt(key, value);
your_fragment.setArguments(bundle);
</code>```

Then in your Fragment, retrieve the data (e.g. in onCreate() method) with:

```<code>Bundle bundle = this.getArguments();
if (bundle != null) {
        int myInt = bundle.getInt(key, defaultValue);
}
</code>```

Title: Send data from Activity to Fragment already created

Body:
I only have found information about how to create a Fragment sending some data to it, but only in its instantiation with the constructor.

But I want to know if it is possible to send some data (for instance, two Double objects) to a Fragment from an Activity without having to create a new instance of the Fragment.

A Fragment that has been previously created.

Body:
You can transfer any data through a bundle like below :

Bundle bundle = new Bundle();
bundle.putInt(key, value);
your_fragment.setArguments(bundle);

Then in your Fragment, retrieve the data (e.g. in onCreate() method) with:

Bundle bundle = this.getArguments();
if (bundle != null) {
        int myInt = bundle.getInt(key, defaultValue);
}


来源: stackexchange

问:
Many to Many Relationship with extra columns in EF 6 Code?
Say if I have the classic example of Student and Courses. A student can have many courses and course can have many students.

How do I make the middle table in EF 6 code if I wanted to add an extra field on the many table part?

Do I just make in code another class and then hook it up somehow?

DB Context

```<code>public class MyContext : DbContext
{
    public MyContext (string nameOrConnectionString) : base(nameOrConnectionString)
    {
        // this.Configuration.ProxyCreationEnabled = false;
        Database.SetInitializer(new CreateDatabaseIfNotExists<OSPContext>());
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }

    public DbSet<StudentCourse> StudentCourses { get; set; }

}

public class StudentCourse
{
    [Key]
    public Guid StudentCourseId { get; set; }

    public Guid StudentId { get; set; }

    [ForeignKey("StudentId")]
    public virtual Student Student { get; set; } // Include this so you can access it later

    public Guid CourseId { get; set; }

    [ForeignKey("CourseId")]
    public virtual Course Course { get; set; }

    public int Permissions { get; set; }
}

public class Course
{
    [Key]
    public  Guid Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Student> Students { get; set; } = new >();
}

public class Student
{
    [Key]
    public  Guid Id { get; set; }
    public  string Email { get; set; }
    public virtual ICollection<Course> Courses { get; set; } = new List<Course>();

}
</code>```

答:
Given you are code first I would do something like the following.

```<code>public class Student
{
    [Key]
    public int StudentId { get; set; }
    public string Name { get; set; }

    public List<StudentCourse> Courses { get; set; } // So you can access Courses for a student
}

public class Course
{
    [Key]
    public int CourseId { get; set; }
    public string Name { get; set; }

    public List<StudentCourse> Students { get; set; }
}

public class StudentCourse
{
    [Key]
    public int StudentCourseId { get; set; }

    public int StudentId { get; set; }
    [ForeignKey("StudentId")]
    public Student Student { get; set; } // Include this so you can access it later

    public int CourseId { get; set; }
    [ForeignKey("CourseId")]
    public Course Course { get; set; }
}
</code>```

EDIT: Wanted to note relationships are established with Data Attributes, you could also use EF Fluent API to establish your relationships.  The properties will look the same, but without the [ForeignKey("")]

ContentLicense: CC BY-SA 3.0

Body:
Say if I have the classic example of Student and Courses. A student can have many courses and course can have many students.

How do I make the middle table in EF 6 code if I wanted to add an extra field on the many table part?

Do I just make in code another class and then hook it up somehow?

DB Context

public class MyContext : DbContext
{
    public MyContext (string nameOrConnectionString) : base(nameOrConnectionString)
    {
        // this.Configuration.ProxyCreationEnabled = false;
        Database.SetInitializer(new CreateDatabaseIfNotExists<OSPContext>());
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }

    public DbSet<StudentCourse> StudentCourses { get; set; }

}

public class StudentCourse
{
    [Key]
    public Guid StudentCourseId { get; set; }

    public Guid StudentId { get; set; }

    [ForeignKey("StudentId")]
    public virtual Student Student { get; set; } // Include this so you can access it later

    public Guid CourseId { get; set; }

    [ForeignKey("CourseId")]
    public virtual Course Course { get; set; }

    public int Permissions { get; set; }
}

public class Course
{
    [Key]
    public  Guid Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Student> Students { get; set; } = new >();
}

public class Student
{
    [Key]
    public  Guid Id { get; set; }
    public  string Email { get; set; }
    public virtual ICollection<Course> Courses { get; set; } = new List<Course>();

}

Body:
Given you are code first I would do something like the following.

public class Student
{
    [Key]
    public int StudentId { get; set; }
    public string Name { get; set; }

    public List<StudentCourse> Courses { get; set; } // So you can access Courses for a student
}

public class Course
{
    [Key]
    public int CourseId { get; set; }
    public string Name { get; set; }

    public List<StudentCourse> Students { get; set; }
}

public class StudentCourse
{
    [Key]
    public int StudentCourseId { get; set; }

    public int StudentId { get; set; }
    [ForeignKey("StudentId")]
    public Student Student { get; set; } // Include this so you can access it later

    public int CourseId { get; set; }
    [ForeignKey("CourseId")]
    public Course Course { get; set; }
}

EDIT: Wanted to note relationships are established with Data Attributes, you could also use EF Fluent API to establish your relationships.  The properties will look the same, but without the [ForeignKey("")]


问:
Trace.WriteLine in ASP.NET Azure
when I use

```<code>Diagnostics.Trace.WriteLine("message", "Information");
</code>```

in my azure-asp.net this does not show up in my  azure compute emulator,
but if I do the same from my worker-role it works, any idea why?

Thanks!

答:
Use Trace.TraceInformation instead:

Writes an informational message to the trace listeners in the Listeners collection using the specified message.

ContentLicense: CC BY-SA 2.5

Title: Trace.WriteLine in ASP.NET Azure

Body:
when I use

Diagnostics.Trace.WriteLine("message", "Information");

in my azure-asp.net this does not show up in my  azure compute emulator,
but if I do the same from my worker-role it works, any idea why?

Thanks!


问:
Terminology: "live-dvr" in mpeg-dash streaming
I'm working with live MPEG-DASH streaming, and I would like to know if there exists a stardard terminology for a given functionality.

It's the "live-dvr" functionality. That is, a mix between a live stream and VOD features: a live stream with the seeking bar in the player allowing to watch past stream time. This involves a series of infrastructure tweaks.

The term "live-dvr" for this setup is kind of informal, and different parties call it in its own way: "live catch-up", "live-vod", "cached live", some vendors set the name for this based on their product lines, and so on. I would like to know if there's a standard term for this kind of setup. Specially because interpreting the standard in order to understand setup parameters for the manifests may be confusing or even misleading without proper terminology.

答:
DVR (Digital Video Recording, also known as nDVR - network DVR) is a functionality that allows recording the live stream and perform its playback from any moment of recorded period. Live stream can still run while the end-user may rewind it to any particular moment in past.
Typically media servers (like our Nimble Streamer) also provide time-shift and time range selection - see our links for details.</p>


问:
Data coming back as undefined in react
I'm trying to pass data down to a component with react router. I've tested that the end point works correctly, so it's not a server issue.

This is my function that is supposed to grab the page data based on the ID param:

```<code>    instance.get(`/admin/page/${id}`).then((response) => {
      return response.data
    }).catch((error) => {
      console.log(error)
    })
  }
</code>```

And my React Route:

```<code>    <Route path="/admin/edit-page/:id" render={ (props) => (
      <AddEditPage {...props} page={this.setPage(props.match.params.id)} />
    )} />
</code>```

But page is coming back undefined when I goto

localhost:3000/admin/edit-page/1

If I console.log(response.data) inside the setPage function, I can see the correct data in the console. This is so weird.

Am I not supposed to return response.data ??

This is the whole App.js container file:

```<code>import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom'
import axios from 'axios'

import Header from '../components/Header'

import Dashboard from './Dashboard'
import AddEditPage from './AddEditPage'

const instance = axios.create({baseURL: 'http://localhost:1337'})

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      "pages": []
    }
    this.createPage = this.createPage.bind(this)
    this.getPages = this.getPages.bind(this)
    this.setPage = this.setPage.bind(this)

  }

  componentDidMount() {
    this.getPages()
  }

  getPages() {
    instance.get('/admin/listPages')
      .then(
        (response) => {
          this.setState(
            {
              "pages": response.data
            }
          )
        })
      .catch((error) => {console.log(error)})
  }

  createPage(page) {
    instance.post('/admin/createPage',page).then((response) => {
      this.getPages();
      //TODO: Create my own history object as props, then use router to push route.
      window.location.replace('/')
    }).catch((error) => {
      console.log(error)
    })
  }

  setPage(id) {
    instance.get(`/admin/page/${id}`).then((response) => {
      return response.data
    }).catch((error) => {
      console.log(error)
    })
  }

  render() {
    return (
      <Router>
        <div className="Router">
          <div className="Navbar">
            <Header />
          </div>
          <div className="Wrapper">
            <Route exact path="/" render={ (props) => (
              <Dashboard {...props} pages={this.state.pages} />
            )} />
            <Route path="/admin/new-page" render={ (props) => (
              <AddEditPage {...props} createPage={this.createPage} />
            )} />
            <Route path="/admin/edit-page/:id" render={ (props) => (
              <AddEditPage {...props} page={this.setPage(props.match.params.id)} />
            )} />
          </div>
        </div>
      </Router>

    );
  }
}

export default App;
</code>```

答: In your example, this.setPage() is an asynchronous function. Therefore, the return value will be undefined. There are a couple different ways to fix this. One way would be to set the ‘page’ the same way you set the ‘pages’. That is, using state.

Title: Data coming back as undefined in react

Body:
I'm trying to pass data down to a component with react router. I've tested that the end point works correctly, so it's not a server issue.

This is my function that is supposed to grab the page data based on the ID param:

    instance.get(`/admin/page/${id}`).then((response) => {
      return response.data
    }).catch((error) => {
      console.log(error)
    })
  }

And my React Route:

    <Route path="/admin/edit-page/:id" render={ (props) => (
      <AddEditPage {...props} page={this.setPage(props.match.params.id)} />
    )} />

But page is coming back undefined when I goto

localhost:3000/admin/edit-page/1

If I console.log(response.data) inside the setPage function, I can see the correct data in the console. This is so weird.

Am I not supposed to return response.data ??

This is the whole App.js container file:

import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom'
import axios from 'axios'

import Header from '../components/Header'

import Dashboard from './Dashboard'
import AddEditPage from './AddEditPage'

const instance = axios.create({baseURL: 'http://localhost:1337'})

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      "pages": []
    }
    this.createPage = this.createPage.bind(this)
    this.getPages = this.getPages.bind(this)
    this.setPage = this.setPage.bind(this)

  }

  componentDidMount() {
    this.getPages()
  }

  getPages() {
    instance.get('/admin/listPages')
      .then(
        (response) => {
          this.setState(
            {
              "pages": response.data
            }
          )
        })
      .catch((error) => {console.log(error)})
  }

  createPage(page) {
    instance.post('/admin/createPage',page).then((response) => {
      this.getPages();
      //TODO: Create my own history object as props, then use router to push route.
      window.location.replace('/')
    }).catch((error) => {
      console.log(error)
    })
  }

  setPage(id) {
    instance.get(`/admin/page/${id}`).then((response) => {
      return response.data
    }).catch((error) => {
      console.log(error)
    })
  }

  render() {
    return (
      <Router>

            <Route exact path="/" render={ (props) => (
              <Dashboard {...props} pages={this.state.pages} />
            )} />
            <Route path="/admin/new-page" render={ (props) => (
              <AddEditPage {...props} createPage={this.createPage} />
            )} />
            <Route path="/admin/edit-page/:id" render={ (props) => (
              <AddEditPage {...props} page={this.setPage(props.match.params.id)} />
            )} />

      </Router>

    );
  }
}

export default App;


问:
Ideal mysqldump options for backups
I'm creating a backup script for our database servers, and thought I'd ask if there are any preferred options to include with mysqldump. The script will be called from cron every 6-24 hours.

We use InnoDB exclusively.

Our databases are rather large, and I'll most likely dump clusters of tables individually, as opposed to the entire database in one go.

For now, I'm thinking of including:

```<code>--opt # enabled by default
--quote-names # enabled by default
--single-transaction
--skip-comments
</code>```

Any other suggestions or pointers for creating good, reliable dump files?

答:
I propose you to just set up one more server (slave) with mysql and replicate data there (from the main, master one).

If you'll need a plain text dump - you can always do it from the slave without hurting master.

Title: Ideal mysqldump options for backups

Body:
I'm creating a backup script for our database servers, and thought I'd ask if there are any preferred options to include with mysqldump. The script will be called from cron every 6-24 hours.

We use InnoDB exclusively.

Our databases are rather large, and I'll most likely dump clusters of tables individually, as opposed to the entire database in one go.

For now, I'm thinking of including:

--opt # enabled by default
--quote-names # enabled by default
--single-transaction
--skip-comments

Any other suggestions or pointers for creating good, reliable dump files?


问:
Google maps places api and express error Can't set headers after they are sent
I am trying to use google maps places api to build a simple web application. For now am just inserting the data gotten from the api into my mongodb database.

The google maps places npm module @google/maps has a places method for returning data based on longitude and latitude. What i am trying to achieve is this

When a request is made to the api route it should check the database and return some data.

if the database is empty is should query the google maps places api for the data, insert it into the database and then perform a find request from the database.  here is my [code][1], the error is this :

Error: Can't set headers after they are sent.
        at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)
        at ServerResponse.header (C:\Express\pizza\node_modules\express\lib\response.js:730:10)
        at ServerResponse.send (C:\Express\pizza\node_modules\express\lib\response.js:170:12)
        at ServerResponse.json (C:\Express\pizza\node_modules\express\lib\response.js:256:15)
        at sendJsonResponse (C:\Express\pizza\app_api\controllers\locations.js:9:9)
        at C:\Express\pizza\app_api\controllers\locations.js:73:39
        at Query.<anonymous> (C:\Express\pizza\node_modules\mongoose\lib\model.js:3800:16)
        at C:\Express\pizza\node_modules\kareem\index.js:277:21
        at C:\Express\pizza\node_modules\kareem\index.js:131:16
        at _combinedTickCallback (internal/process/next_tick.js:73:7)
        at process._tickCallback (internal/process/next_tick.js:104:9)

if there is a better approach to solve my problem I am open to suggestions

var mongoose = require('mongoose');
var Location = require('../models/locations');
var googleMapsClient = require('@google/maps').createClient({
    key: process.env.MAP_API_KEY
});

var sendJsonResponse = function(res, status, content) {
    res.status(status);
    res.json(content);
};
//function to filter data returned from api
var buildLocations = function(results) {
    results === Array;
    var newList = [];
    var j = 3;
    for (var i = 0; i < j; i++) {
        if (results[i].photos) {

            newList.push({
                place_id: results[i].place_id,
                name: results[i].name,
                rating: results[i].rating,
                address: results[i].formatted_address,
                photos: results[i].photos,
                location: results[i].geometry.location
            })
        }
    }
    return newList
}

//function to save data to database from api
var saveToDbFromApi = function(locations,req,res,callback){
    for(var i=0; i<locations.length; i++){
        Location.create({
            name: locations[i].name
        },function(err,locations){
            if(err){
               console.log(err);
            }
            else{
             callback(req,res);
            }
        })
    }
}

module.exports.locationList = function(req, res) {
    Location.find({}, function(err, locations) {
        if (err) {
            console.log(err);
            sendJsonResponse(res, 400, err);
        }
        if (!locations.length) {
            googleMapsClient.places({
                location: [5.526679, -0.48085],
                radius: 50000,
                type: 'restaurant'
            }, function(err, response){
                if(err){
                    sendJsonResponse(res,400,err);
                }
                else{
                    var locations = buildLocations(response.json.results);
                    saveToDbFromApi(locations,req,res,function(req,res){
                        Location.find({},function(err,locations){
                            if(err){
                             console.log(err)
                            }
                            else{
       //this line brings up the 'cant set headers after they are sent error'
                             return   sendJsonResponse(res,200,locations);
                            }
                        })
                    });
                }
            })

        } else {
            sendJsonResponse(res, 200, locations);
        }
    })

}```

答:
Notice that

```<code>    if (err) {
        console.log(err);
        sendJsonResponse(res, 400, err);
    }
</code>```

If err,  It is sending a response but there is not a retun, so you could reach the line you commented and try to send headers again.

Body:
Notice that

    if (err) {
        console.log(err);
        sendJsonResponse(res, 400, err);
    }

If err,  It is sending a response but there is not a retun, so you could reach the line you commented and try to send headers again.


问:
bootstrap position fixed doesn't work with one column
I started making my new layout with bootstrap grid system i actually made rows and columns First row is my headerrow i embed the column in the header section
i made a class in css and i put the position:fixed thing into it. then i added the class to the column. The class contains red background etc it works but the position:fixed doesnt work when i try to scroll down its just stays there. position:fixed; is outlined in chrome :/ why?

http://kephost.com/images/2017/07/07/riiiii.jpg

答:
```<code><div style="position:fixed"
      class="headerUpper col-md-12 col-sm-12 col-xs-12 bg-white"
>
</code>```

It solved everything.

Body:
<div style="position:fixed"
      class="headerUpper col-md-12 col-sm-12 col-xs-12 bg-white"
>

It solved everything.


问:
Increase EC2 Resource Count in Terraform and applying Ansible
Having some issue with increasing the EC2 resources for terraform and applying the changes with Ansible. I currently have a basic template with:

```<code>resource "aws_instance" "linux_node" {
  count = 2
  ami           = "ami-6df1e514"
  instance_type = "t2.micro"
  key_name = ""
  vpc_security_group_ids = [""]
  iam_instance_profile = ""
  user_data = "${file("userdata.sh")}"

  tags {
    Name = "linux-node"
  }

  provisioner "local-exec" {
        command = "sleep 120; ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook --private-key ~/.ssh/aws-patrick-oregon.pem -i '${aws_instance.linux_node.public_ip},' ../install_packages.yml"
    }
}
</code>```

The issue when I increase the count to anything more than 1, I get an error on aws_instance.linux_node.public_ip where the error says:

```<code>* aws_instance.linux_node[1]: 1 error(s) occurred:

* Resource 'aws_instance.linux_node' not found for variable 'aws_instance.linux_node.public_ip'
</code>```

I think it stems from the bracket [1]. I'm wondering how to write a ansible command to pick up the change when I make the change to add an EC2 instance.

答:
When a resource has count set, it needs to be addressed in a different way to specify which of the instances you wish to use.

For provisioners in particular it's a common case to want to take actions based on the "current" instance the provisioner is running for, so a shorthand is provided with the self variable type:

```<code>provisioner "local-exec" {
  command = "sleep 120; ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook --private-key ~/.ssh/aws-patrick-oregon.pem -i '${self.public_ip},' ../install_packages.yml"
}
</code>```

Body:
Having some issue with increasing the EC2 resources for terraform and applying the changes with Ansible. I currently have a basic template with:

resource "aws_instance" "linux_node" {
  count = 2
  ami           = "ami-6df1e514"
  instance_type = "t2.micro"
  key_name = ""
  vpc_security_group_ids = [""]
  iam_instance_profile = ""
  user_data = "${file("userdata.sh")}"

  tags {
    Name = "linux-node"
  }

  provisioner "local-exec" {
        command = "sleep 120; ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook --private-key ~/.ssh/aws-patrick-oregon.pem -i '${aws_instance.linux_node.public_ip},' ../install_packages.yml"
    }
}

The issue when I increase the count to anything more than 1, I get an error on aws_instance.linux_node.public_ip where the error says:

* aws_instance.linux_node[1]: 1 error(s) occurred:

* Resource 'aws_instance.linux_node' not found for variable 'aws_instance.linux_node.public_ip'

I think it stems from the bracket [1]. I'm wondering how to write a ansible command to pick up the change when I make the change to add an EC2 instance.

Body:
When a resource has count set, it needs to be addressed in a different way to specify which of the instances you wish to use.

For provisioners in particular it's a common case to want to take actions based on the "current" instance the provisioner is running for, so a shorthand is provided with the self variable type:

provisioner "local-exec" {
  command = "sleep 120; ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook --private-key ~/.ssh/aws-patrick-oregon.pem -i '${self.public_ip},' ../install_packages.yml"
}


问:
Is there an Ansible/Jinja2 subgroup variables unique filter?
We are using Ansible to generate some iptables rules from a Jinja2 template. The hosts are in nested groups, and their subnets are stored as variables in the child group variables within the inventory file like this:

```<code>[parent_group]
[parent_group:children]
child_group1
    [child_group1]
    FQDN1
    FQDN2
    [child_group1:vars]
    subnet=10.0.0.0/24
</code>```

We have many child groups, each with their own subnet/mask for their respective host groups. Most of the Ansible/Jinja2 documentation points to referencing the group variables by using a for-loop to iterate over their member hosts, which would result in duplicate lines in our template file. What is the best way to grab the child_group vars of parent_group only once? Is there a way to filter for unique values in a Jinja2 for-loop?

答:
After some fumbling around with Jinja2 expressions, I was able to come up with the following template to create rules based on child group variables without duplicates:

```<code>{% set subnets = [] %}
{% for host in groups['parent_group'] %}
{% if hostvars[host].subnet not in subnets %}
-A INPUT -s {{hostvars[host].subnet}} -j ACCEPT {{subnets.append(hostvars[host].subnet)}}
{% endif %}
{% endfor %}
</code>```

It feels rather clunky to me, so if anyone knows a better way, I would really appreciate it.

Body:
We are using Ansible to generate some iptables rules from a Jinja2 template. The hosts are in nested groups, and their subnets are stored as variables in the child group variables within the inventory file like this:

[parent_group]
[parent_group:children]
child_group1
    [child_group1]
    FQDN1
    FQDN2
    [child_group1:vars]
    subnet=10.0.0.0/24

We have many child groups, each with their own subnet/mask for their respective host groups. Most of the Ansible/Jinja2 documentation points to referencing the group variables by using a for-loop to iterate over their member hosts, which would result in duplicate lines in our template file. What is the best way to grab the child_group vars of parent_group only once? Is there a way to filter for unique values in a Jinja2 for-loop?

Body:
After some fumbling around with Jinja2 expressions, I was able to come up with the following template to create rules based on child group variables without duplicates:

{% set subnets = [] %}
{% for host in groups['parent_group'] %}
{% if hostvars[host].subnet not in subnets %}
-A INPUT -s {{hostvars[host].subnet}} -j ACCEPT {{subnets.append(hostvars[host].subnet)}}
{% endif %}
{% endfor %}

It feels rather clunky to me, so if anyone knows a better way, I would really appreciate it.


问:
Cloud Dataflow:Reading entire json array file from Cloud Storage and create a PCollection of json object
I have a json array file with content as below   </p>

```<code>[ {
  "MemberId" : "1234",
  "Date" : "2017-07-03",
  "Interactions" : [ {
    "Number" : "1327",
    "DwellTime" : "00:03:05"
  } ]
}, {
  "MemberId" : "5678",
  "Date" : "2017-07-03",
  "Interactions" : [ {
    "Number" : "1172",
    "DwellTime" : "00:01:26"
  } ]
} ]
</code>```

<p>I wanted to create a PCollection of Java Object mapped to each Json present in Json array </p>

答:
JSON formatted like this (records spread over multiple lines instead of one per line) is hard for a data processing tool like beam/dataflow to process in parallel - from a random point in the file, you cannot be sure where the next record begins. You can do it by reading from the beginning of the file, but then you're not really reading in parallel.

If it's possible, reformatting it so that it's one record per line would let you use something like TextIO to read in the file.

If not, you'll need to read the file in one go.

I would suggest a couple possible approaches:

Write a ParDo that reads from the file using the gcs API

This is pretty straight forward. You'll do all the reading in one ParDo and you'll need to implement the connection code inside of that pardo. Inside the pardo you would write the same code you would as if you're reading the file in a normal java program. The pardo will emit each java object as a record.

Implement a filebasedsource

File based sources will work - when the fileOrPatternSpec is "gs://..." it knows how to read from GCS. You'll need to make sure to set fileMetadata.isReadSeekEfficient to false so that it won't try to split the file. I haven't tried it, but I believe the correct way to do that is to set it inside of the single file constructor of FBS (ie, your class's override of FileBaseSource(MetaData, long, long)

TextSource/XmlSource (and their accompanying wrappers TextIO/XmlIO) are examples of this, except that they try to implement splitting - yours will be much simpler since it won't.

Body:
I have a json array file with content as below

[ {
  "MemberId" : "1234",
  "Date" : "2017-07-03",
  "Interactions" : [ {
    "Number" : "1327",
    "DwellTime" : "00:03:05"
  } ]
}, {
  "MemberId" : "5678",
  "Date" : "2017-07-03",
  "Interactions" : [ {
    "Number" : "1172",
    "DwellTime" : "00:01:26"
  } ]
} ]

I wanted to create a PCollection of Java Object mapped to each Json present in Json array


问:
poll() c function on windows
I want to know if I can use the poll() function on a MinGW development chain. I have CodeBlocks+MinGW. Thanks a lot.</p>

答:
Windows also provides a WSAPoll() function but the performance is worse than select(), from MSDN blog it was only implemented to improvement portability:

http://blogs.msdn.com/b/wndp/archive/2006/10/26/wsapoll.aspx

Title: poll() c function on windows


问:
GPIO pins no errors but not getting the expected result?
Sorry I am a beginner to both Raspberry Pi and python. I am write a simple python program to use the pulse width modulator, Here is the code.

```<code>import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(12,GPIO.OUT)
pwm=GPIO.PWM(12,50)
pwm.start(0)
while True:
        for i in range(50):
                pwm.ChangeDutyCycle(i)
                time.sleep(0.05)
        for i in range(50,0,-1):
                pwm.ChangeDutyCycle(i)
                time.sleep(0.05)
</code>```

I connected the led between 12 and ground with the suitable resistor. But when I execute, I don't get any error but it wont work.

答: The code seems to work fine on my Rpi-3. So we cannot help you if we can't see the circuit design. I can make a guess that you probably used the normal numbering to connect the led, but used the BCM numbering in your program. So either change it to board numbering by GPIO.setmode(GPIO.BOARD) or refer the below chart for correct numbers.

Body:
Sorry I am a beginner to both Raspberry Pi and python. I am write a simple python program to use the pulse width modulator, Here is the code.

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(12,GPIO.OUT)
pwm=GPIO.PWM(12,50)
pwm.start(0)
while True:
        for i in range(50):
                pwm.ChangeDutyCycle(i)
                time.sleep(0.05)
        for i in range(50,0,-1):
                pwm.ChangeDutyCycle(i)
                time.sleep(0.05)

I connected the led between 12 and ground with the suitable resistor. But when I execute, I don't get any error but it wont work.


问:
Bootstrap dropdowns menus appearing behind other elements - IE7
I'm using Bootstrap 2.3.1 http://twitter.github.io/bootstrap/index.html

So I'm using their 'dropdown-menu' class to create some simple quick use dropdown menus, but for some reason on IE7 they are appearing behind text and other elements on my site.

Test Link: http://leongaban.com/_projects/defakto/CDS/

I added z-index to my CSS, but still doesn't seem to do anything, please help!

```<code>.header .header-nav ul#nav-account ul.dropdown-menu,
.header .header-nav ul#nav-library ul.dropdown-menu {
    z-index: 10000;
}
</code>```

IE9, Chrome, FF and other modern no headache browsers:

IE7 >:(

HTML

```<code><div class="header-nav">

<ul id="nav-account" role="navigation" class="pull-right">

    <!-- Language Dropdown Button -->
    <li id="language-btn">
        <a href="#" id="drop1" class="dropdown-toggle" data-toggle="dropdown">English</a>
        <img src="img/header-small-down-arrow.png" alt="grey triangle"/><!-- <span class="grey_triangle"></span>-->

        <!-- Language Dropdown Menu-->
        <ul class="dropdown-menu" role="menu" aria-labelledby="drop1">
            <li role="presentation"><a role="menuitem" tabindex="-1" href="#">English</a></li>
            <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Spanish</a></li>
            <li role="presentation"><a role="menuitem" tabindex="-1" href="#">German</a></li>
            <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Japanese</a></li>
            <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Chinese</a></li>
        </ul>
    </li>

    <!-- User Dropdown Button -->
    <li id="account-btn">
        <a href="#" id="drop2" class="dropdown-toggle" data-toggle="dropdown">Logout</a>
        <img src="img/header-small-down-arrow.png" alt="grey triangle"/>
        <!-- <span class="grey_triangle"></span> -->

        <!-- User Dropdown Menu-->
        <ul class="dropdown-menu" role="menu" aria-labelledby="drop2">
            <li role="presentation"><a role="menuitem" tabindex="-1" href="http://google.com">Logout</a></li>
            <li role="presentation"><a role="menuitem" tabindex="-1" href="#anotherAction">Account</a></li>
        </ul>
    </li>
</ul>
</code>```

答:
If increasing the z-index of the parent element(as mentioned in other answers) did not work for you, it could be that one of the parent elements has the following property:

```<code>overflow: hidden;
</code>```

Try changing it to:

```<code>overflow: visible;
</code>```

and see if it works.

Body:
I'm using Bootstrap 2.3.1 http://twitter.github.io/bootstrap/index.html

So I'm using their 'dropdown-menu' class to create some simple quick use dropdown menus, but for some reason on IE7 they are appearing behind text and other elements on my site.

Test Link: http://leongaban.com/_projects/defakto/CDS/

I added z-index to my CSS, but still doesn't seem to do anything, please help!

.header .header-nav ul#nav-account ul.dropdown-menu,
.header .header-nav ul#nav-library ul.dropdown-menu {
    z-index: 10000;
}

IE9, Chrome, FF and other modern no headache browsers:

IE7 >:(

HTML

        English

English

Spanish

German

Japanese

Chinese

        Logout

Logout

Account

Body:
If increasing the z-index of the parent element(as mentioned in other answers) did not work for you, it could be that one of the parent elements has the following property:

overflow: hidden;

Try changing it to:

overflow: visible;

and see if it works.

ContentLicense: CC BY-SA 4.0


问:
How to use aliases defined in .bashrc in other scripts?
In ~/.bashrc, I defined some aliases. But I cannot use them in other shell scripts, where I can only use aliases defined right there. Even though I sourced bashrc, it still did not work. What should I do?

PS. I'm in bash.

答:
The simplest answer is to do the 2 important things or it wont' work.

```<code>#!/bin/bash -i

# Expand aliases defined in the shell ~/.bashrc
shopt -s expand_aliases
</code>```

After this, your aliases that you have defined in ~/.bashrc they will be available in your shell script (giga.sh or any.sh) and to any function or child shell within such script.

If you don't do that, you'll get an error:

```<code>your_cool_alias: command not found
</code>```

Body:
The simplest answer is to do the 2 important things or it wont' work.

#!/bin/bash -i

# Expand aliases defined in the shell ~/.bashrc
shopt -s expand_aliases

After this, your aliases that you have defined in ~/.bashrc they will be available in your shell script (giga.sh or any.sh) and to any function or child shell within such script.

If you don't do that, you'll get an error:

your_cool_alias: command not found


问:
MVC data annotaion for validating data type
How do you customize data annotation validation for this scenario.

I am receiving this error:

The value 'Select Province' is not
  valid for Province.

I want it like this

Please select a country

My ViewModel looks like this:

```<code>    [DisplayName("Province")]
    [UIHint("ProvinceDropDown")]
    public long? ProvinceId { get; set; }
</code>```

My View is a select list :

```<code><select name="ProvinceId" id="ProvinceId" class="input-validation-error">
    <option value="">Select Province</option>
    <option value="613">Allen </option>
    <option value="614">Anderson</option>
   // data truncated ....
</select>
</code>```

答:
You need to add ErrorMessage = "Please Select a Country" to your annotation attribute, similar to the example here:

```<code>[Range(0, 50, ErrorMessage = "Quantity on order must be between 0 and 50.")]
public int OnOrder { get; set; }
</code>```

Body:
How do you customize data annotation validation for this scenario.

I am receiving this error:

The value 'Select Province' is not
  valid for Province.

I want it like this

Please select a country

My ViewModel looks like this:

    [DisplayName("Province")]
    [UIHint("ProvinceDropDown")]
    public long? ProvinceId { get; set; }

My View is a select list :

<select name="ProvinceId" id="ProvinceId" class="input-validation-error">
    <option value="">Select Province</option>
    <option value="613">Allen </option>
    <option value="614">Anderson</option>
   // data truncated ....
</select>

Body:
You need to add ErrorMessage = "Please Select a Country" to your annotation attribute, similar to the example here:

[Range(0, 50, ErrorMessage = "Quantity on order must be between 0 and 50.")]
public int OnOrder { get; set; }


问:
Feather icons usage in Vue.JS
I've been trying to use feather-icons in a new vue project.
I first initialized the project using the vue-clie tools:

```<code>vue init webpack
</code>```

once done, I ran:

```<code>npm install
npm run dev
</code>```

After that I installed feather-icons through npm as follows:

```<code>npm install --save feather-icons
</code>```

Once done, I tried using the icons by importing the module in my main.js file:

main.js:

```<code>import 'feather-icons'

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: {
    App
  }
})
</code>```

Then I tried using an icon in a Hello component:

Hello.vue:

```<code><template>
  <div>
    <h1> Hello World!</h1>
    <i data-feather="flag"></i>
  </div>
</template>

<script>
  export default {
    name: 'hello',
    data() {
      return {
        msg: 'Welcome to Your Vue.js App'
      }
    }
  }

</script>
<style>
</style>
</code>```

No error is detected during execution, yet the icon set refuses to work. I've tried including the feather-icons directly on the index.html file, but the problem persists.

I'm guessing whatever is causing this is related to the data-feather attribute on the i tag required to invoke feather-icons.

I've been at it for almost a couple hours, but nothing I tried seems to work.
Any help would be appreciated. Thanks.

UPDATE 1:
As per  @yuriy636's suggestion, I imported feather-icons in my App component then called feather.replace() in mounted:

App.vue:

```<code><template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>

  import feather from 'feather-icons'

  export default {
    name: 'app',

    mounted() {
      feather.replace();
    }
  }

</script>

<style>
</style>
</code>```

UPDATE 2:

As pointed out by @smarx, there is a module named vue-feather-icons that facilitates the usage of feather-icons with vue. just install it, import it and use it.
This seems to have solved the issue.

答:
Summarizing the comment thread and presenting another solution for posterity:

The issue with the original code is that there's a missing call to feather.replace, which finds all the elements with data-feather attributes and replaces them with the appropriate icon's SVG.

Calling feather.replace in the mounted hook is good enough for simple use cases, but it doesn't allow for icons changing. (In general, it strikes me as a bad idea to let non-Vue code modify the HTML you're using Vue to render.) E.g.,  isn't going to allow for subsequent updates.

vue-feather-icon appears to be a project that integrates better with Vue.

Below is a better way to use "vanilla" feather-icons without running into the above issues. Here, we're dynamically updating the HTML content of a div with the appropriate icon SVG by using a computed property that calls feather.toSvg:

```<code><template>
  <div id="app">
    <h1>{{ message }}</h1>
    <div v-html="iconSvg"></div>
    <button @click="clicky">Click me</button>
  </div>
</template>

<script>
import feather from 'feather-icons'

export default {
  name: 'app',
  data: function () {
    return {
      message: 'Hello, World!',
      icon: 'flag'
    }
  },
  computed: {
    iconSvg: function () {
      return feather.toSvg(this.icon)
    }
  },
  methods: {
    clicky: function () {
      this.message = 'clicked'
      this.icon = 'circle'
    }
  }
}
</script>
</code>```

Title: Feather icons usage in Vue.JS

Body:
I've been trying to use feather-icons in a new vue project.
I first initialized the project using the vue-clie tools:

vue init webpack

once done, I ran:

npm install
npm run dev

After that I installed feather-icons through npm as follows:

npm install --save feather-icons

Once done, I tried using the icons by importing the module in my main.js file:

main.js:

import 'feather-icons'

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: {
    App
  }
})

Then I tried using an icon in a Hello component:

Hello.vue:

<template>

 Hello World!

</template>

No error is detected during execution, yet the icon set refuses to work. I've tried including the feather-icons directly on the index.html file, but the problem persists.

I'm guessing whatever is causing this is related to the data-feather attribute on the i tag required to invoke feather-icons.

I've been at it for almost a couple hours, but nothing I tried seems to work.
Any help would be appreciated. Thanks.

UPDATE 1:
As per  @yuriy636's suggestion, I imported feather-icons in my App component then called feather.replace() in mounted:

App.vue:

<template>

    <router-view></router-view>

</template>

UPDATE 2:

As pointed out by @smarx, there is a module named vue-feather-icons that facilitates the usage of feather-icons with vue. just install it, import it and use it.
This seems to have solved the issue.

Body:
Summarizing the comment thread and presenting another solution for posterity:

The issue with the original code is that there's a missing call to feather.replace, which finds all the elements with data-feather attributes and replaces them with the appropriate icon's SVG.

Calling feather.replace in the mounted hook is good enough for simple use cases, but it doesn't allow for icons changing. (In general, it strikes me as a bad idea to let non-Vue code modify the HTML you're using Vue to render.) E.g., <i v-bind:data-feather="iconName"></i> isn't going to allow for subsequent updates.

vue-feather-icon appears to be a project that integrates better with Vue.

Below is a better way to use "vanilla" feather-icons without running into the above issues. Here, we're dynamically updating the HTML content of a div with the appropriate icon SVG by using a computed property that calls feather.toSvg:

<template>
  <div id="app">
    <h1>{{ message }}</h1>
    <div v-html="iconSvg"></div>
    <button @click="clicky">Click me</button>
  </div>
</template>

<script>
import feather from 'feather-icons'

export default {
  name: 'app',
  data: function () {
    return {
      message: 'Hello, World!',
      icon: 'flag'
    }
  },
  computed: {
    iconSvg: function () {
      return feather.toSvg(this.icon)
    }
  },
  methods: {
    clicky: function () {
      this.message = 'clicked'
      this.icon = 'circle'
    }
  }
}
</script>


问:
script shell: To tell how many times a user is logged on
I have got the following:

```<code>count=$(who | grep $user | wc -l)
echo "$user is logged on $count times."

but it gives me the following output:
 is logged on      0 times.
</code>```

what am I missing here?
appreciate any help

答:
You are using $user, but need $USER. Like,

```<code>count=$(who | grep $USER | wc -l)
echo "$USER is logged on $count times."
</code>```

I get

```<code>efrisch is logged on 4 times.
</code>```

Another option is printf like

```<code>printf "%s is logged on %s times.\n" $USER $(who | grep $USER | wc -l)
</code>```

for the same result.

Body:
I have got the following:

count=$(who | grep $user | wc -l)
echo "$user is logged on $count times."

but it gives me the following output:
 is logged on      0 times.

what am I missing here?
appreciate any help

Body:
You are using $user, but need $USER. Like,

count=$(who | grep $USER | wc -l)
echo "$USER is logged on $count times."

I get

efrisch is logged on 4 times.

Another option is printf like

printf "%s is logged on %s times.\n" $USER $(who | grep $USER | wc -l)

for the same result.


问:
Why bash alias doesn't work in scripts?
I'm using a Mac and I have this alias defined in .bashrc:

```<code>$cat .bashrc | grep la
alias la='ls -la'
</code>```

then I try to use it in a script:

```<code>$cat ./mytest.sh
#!/bin/bash
la
</code>```

It runs and says it cannot find la:

```<code>./mytest.sh: line 2: la: command not found
</code>```

Why is this? I tried on both Mac and Linux, same error!

答:
The simplest answer is to fix this issue is to do the 2 important things in your script -or it wont' work, if you just do one thing.

```<code>#!/bin/bash -i

# Expand aliases defined in the shell ~/.bashrc
shopt -s expand_aliases
</code>```

After this, your aliases that you have defined in ~/.bashrc they will be available in your shell script (giga.sh or any.sh) and to any function or child shell within such script.

If you don't do that, you'll get an error:

```<code>your_cool_alias: command not found
</code>```

Title: Why bash alias doesn't work in scripts?

Body:
I'm using a Mac and I have this alias defined in .bashrc:

$cat .bashrc | grep la
alias la='ls -la'

then I try to use it in a script:

$cat ./mytest.sh
#!/bin/bash
la

It runs and says it cannot find la:

./mytest.sh: line 2: la: command not found

Why is this? I tried on both Mac and Linux, same error!

Body:
The simplest answer is to fix this issue is to do the 2 important things in your script -or it wont' work, if you just do one thing.

#!/bin/bash -i

# Expand aliases defined in the shell ~/.bashrc
shopt -s expand_aliases

After this, your aliases that you have defined in ~/.bashrc they will be available in your shell script (giga.sh or any.sh) and to any function or child shell within such script.

If you don't do that, you'll get an error:

your_cool_alias: command not found


问:
Libarchive to extract to a specified folder?
Anybody can help show examples of using libarchive to extract ZIP files to a specified folder?   It looks like the sample programs provided (untar.c, tarfilter.c and minitar) all extracts the archive to the current working directory.  Is there a way to say "extract to this folder and below" to libarchive and not clobber the program's active folder?

One of the main drivers is that the extraction code will be run in a background thread, and thus changing the program working directory may create problems.  Also this will be used in an iOS application (iPhone, iPad), which is picky on what folders that the application can write to.

Thanks in advance.

答:
untar.c can be easily modified to do this by prepending the path you want to use to the pathname that is passed to create_dir() and create_file() from untar().

Note that untar.c is a standalone decompressor, seperate from libarchive.

The same effect is easily achievable with libarchive - it gives you full control over the creation of files and directories when unarchiving.


问:
How to improve performance of multi field search in MongoDB?
I have a collection (~900k of docs and counting). The doc scheme you can see in attachment. I want to search by almost every field in any sub document in any field combination. For example:

```<code># search 1
updated_at > now() and make.id = 10 and model.id = 20

# search 2
region.id = 10 and details.year >= 2000 and details.body = 'sedan'
</code>```

Hardware: 4 x Intel Xeon E5-2650 at 2.60GHz, 16 gb RAM, SSD disk, 8gb swap on SDD drive.

App dependencies: python 3.6, Django, mongoengine, pymongo.

Here more info:

Sample document,
Indices setup,
Database and server status

答:
You may want to consider a data model that would be more efficient for this type of access pattern.

Performance in MongoDB is achieved by making sure your queries are fully indexed, and that the indexes being used can fit in memory (or in cache, for WiredTiger). Access patterns that would allow for querying on any combination of a number of fields will be expensive, as it will inevitably lead to trying to index every combination of fields, which would be fighting a losing battle.

Consider a faceted search data model, which would allow for a limited set of indexes to better cover a wide range of query filters.

Body:
I have a collection (~900k of docs and counting). The doc scheme you can see in attachment. I want to search by almost every field in any sub document in any field combination. For example:

# search 1
updated_at > now() and make.id = 10 and model.id = 20

# search 2
region.id = 10 and details.year >= 2000 and details.body = 'sedan'

Hardware: 4 x Intel Xeon E5-2650 at 2.60GHz, 16 gb RAM, SSD disk, 8gb swap on SDD drive.

App dependencies: python 3.6, Django, mongoengine, pymongo.

Here more info:

Sample document,
Indices setup,
Database and server status


问:
Reading strings and primitive data types from a file and creating objects
I'm reading from a file and using a scanner to read the inputs but am having difficulty understanding how to apply next() and nextLine() to assign data from the text to variables to be sent to my rectangle class constructor for printing these objects to the console. I get parsing the input (nextInt...etc.), but when strings and primitive data mix on the same line on multiple lines of a scanner read text file how do you handle this? Do I create multiple scanner loops for ints and String(s) to loop through it all to ensure the read data gets assigned to the array elements correctly?

TLDR: How do I read multiple strings and primitives from one .txt file, populate that data into my class fields to then create an array of objects and print *'s to the console to symbolize my created "rectangular" objects from said .txt file?

答:
When you get your string with nextLine() you have to split it with:

something like String#substing(int begin, int end) more information

or you use String#split(" ") and get a string array, which contains in index i the ith word. more information

I think it is also possible to get your Data with nextInt() and your Reader will only give you the first piece of data. With another nextInt() the second number, and so on. But I'm not sure about this solution (But you can try it, through)

After that you can convert it to a datatyp you want to have. For example if you want a double you can use Double.parseDouble(stringVar).

At Last you create your objects and you only have to find a way to print it.


问:
bash script not reading alias in bashrc
I have created an alias in the .bashrc file:

```<code>alias java='java -Xmx1200m'
</code>```

This alias works when I run a java command from my shell directly.

However, when the java command is inside a bash script (script.sh), this alias does not get activated. How do I ensure that the aliases in .bashrc file are accepted in a bash script ??

答:
The simplest answer is to do the 2 important things or it wont' work. In your other script, do the following: -i for interactive mode, and shopt part as mentioned below.

```<code>#!/bin/bash -i

# Expand aliases defined in the shell ~/.bashrc
shopt -s expand_aliases
</code>```

After this, your aliases that you have defined in ~/.bashrc they will be available in your shell script (giga.sh or any.sh) and to any function or child shell within such script.

If you don't do that, you'll get an error:

```<code>your_cool_alias: command not found
</code>```

Title: bash script not reading alias in bashrc

Body:
I have created an alias in the .bashrc file:

alias java='java -Xmx1200m'

This alias works when I run a java command from my shell directly.

However, when the java command is inside a bash script (script.sh), this alias does not get activated. How do I ensure that the aliases in .bashrc file are accepted in a bash script ??

Body:
The simplest answer is to do the 2 important things or it wont' work. In your other script, do the following: -i for interactive mode, and shopt part as mentioned below.

#!/bin/bash -i

# Expand aliases defined in the shell ~/.bashrc
shopt -s expand_aliases

After this, your aliases that you have defined in ~/.bashrc they will be available in your shell script (giga.sh or any.sh) and to any function or child shell within such script.

If you don't do that, you'll get an error:

your_cool_alias: command not found


问:
O(n) algorithm to find out the element appearing more than n/2 times
I was asked in an interview to give an O(n) algorithm to print an element that appears more than n/2 times in an array, if there is such an element. n is the size of the array.
I don't have any clue on how to do this. Can anyone help?</p>

答:
It's the Boyer's Voting algorithm.

It's also O(1) in space!.

Edit

For those complaining about the site color scheme (like me) ... here is the original paper.


问:
Why does git on Windows fail to recognise remote branches
I use git on Linux all the time without any issue. However I recently had to use git on Windows so I installed the command line client because that's how I work most happily.

My problem is that I tried to checkout a branch that I'd created on Linux using git checkout mybranchname but it didn't work. I had to specify git checkout -b mybranchname --track origin/mybranchname.

Since then, whenever I go to push I get told

```<code>fatal: The upstream branch of your current branch does not match
the name of your current branch.  To push to the upstream branch
on the remote, use

    git push origin HEAD:mybranchname

To push to the branch of the same name on the remote, use

    git push origin mybranchname

To choose either option permanently, see push.default in 'git help config'.
</code>```

Does anyone know why this happened or how to resolve it?

I'm using git version 2.12.0.windows.1 and 2.11.0 on Linux. My origin is GitHub Enterprise over SSH in both cases.

答:
In the first command, you are checking out out a local branch that must already exist. In the second command, you are creating a new local branch and associating with a remote branch.

The scenarios are different.

If the local branch didn't exist before, I would run:

```<code>git branch mybranchname origin/mybranchname -u
</code>```

The -u option sets up the remote branch to be upstream of the local branch, so  you can do:

```<code>git push
git pull
</code>```

Without having to qualify the remote:

```<code>git push origin mybranchname
git pull origin mybranchname
</code>```

Body:
I use git on Linux all the time without any issue. However I recently had to use git on Windows so I installed the command line client because that's how I work most happily.

My problem is that I tried to checkout a branch that I'd created on Linux using git checkout mybranchname but it didn't work. I had to specify git checkout -b mybranchname --track origin/mybranchname.

Since then, whenever I go to push I get told

fatal: The upstream branch of your current branch does not match
the name of your current branch.  To push to the upstream branch
on the remote, use

    git push origin HEAD:mybranchname

To push to the branch of the same name on the remote, use

    git push origin mybranchname

To choose either option permanently, see push.default in 'git help config'.

Does anyone know why this happened or how to resolve it?

I'm using git version 2.12.0.windows.1 and 2.11.0 on Linux. My origin is GitHub Enterprise over SSH in both cases.

Body:
In the first command, you are checking out out a local branch that must already exist. In the second command, you are creating a new local branch and associating with a remote branch.

The scenarios are different.

If the local branch didn't exist before, I would run:

git branch mybranchname origin/mybranchname -u

The -u option sets up the remote branch to be upstream of the local branch, so  you can do:

git push
git pull

Without having to qualify the remote:

git push origin mybranchname
git pull origin mybranchname


问:
embed my two latest youtube uploads on my site using javascript
I know that there have been older answers to this question but I cant seem to find one that currently works. I want to be able to have my two latest uploads displayed on my website so users can watch them right there and not have to go to youtube. I have no code currently since I have no clue as to how this would be done.</p>

答:
You can use iframe if you don't want to use the youtubeAPI(harder for a novice) :</p>

```<code><iframe width="420" height="315"
src="https://www.youtube.com/embed/XGSy3_Czz8k">
</iframe>
</code>```

Body:
You can use iframe if you don't want to use the youtubeAPI(harder for a novice) :

<iframe width="420" height="315"
src="https://www.youtube.com/embed/XGSy3_Czz8k">
</iframe>


问:
How to make a "switch" between functions, depending on attribute access type (using class or instance)?
Disclaimer:

This article is more a recipe than a question, but I found the subject quite interesting, with almost no references in the Web.

If there is any better place on StackOverflow to publish this kind of articles, please let me know.

Subject:

How can I force Python to invoke different function depending on the type of attribute access (using class or instance) - e.g. force Python to invoke different method for MyClass.my_method() and MyClass().my_method()?

Usecase:

Let's say, we have custom Enum implementation (based on Python36 Enum, but with some customization). As a user of this Enum, we want to create a CustomEnum, inherit not just from Enum, but also from str: class MyEnum(str, Enum).We also want to add encoding and decoding feature. Our idea is to use MyEnum.encode to encode any object, that includes our enum members, but leave the original str.encode in power for instances of our enum class.
In short: MyEnum.encode invoke our custom encoding function, and have perfectly sens, from this point of view. MyEnum() is a string, so MyEnum().encode should invoke encode function inherited from str class.

Solution:

Write a descriptor, which will work as a switch.
Full answer in my first post.

答:
I actually just asked this question (Python descriptors and inheritance I hadn't seen this question).  My solution uses descriptors and a metaclass for inheritance.

from my answer:

```<code>class dynamicmethod:
    '''
        Descriptor to allow dynamic dispatch on calls to class.Method vs obj.Method

        fragile when used with inheritence, to inherit and then overwrite or extend
        a dynamicmethod class must have dynamicmethod_meta as its metaclass
    '''
    def __init__(self, f=None, m=None):
        self.f = f
        self.m = m

    def __get__(self, obj, objtype=None):
        if obj is not None and self.f is not None:
            return types.MethodType(self.f, obj)
        elif objtype is not None and self.m is not None:
            return types.MethodType(self.m, objtype)
        else:
            raise AttributeError('No associated method')

    def method(self, f):
        return type(self)(f, self.m)

    def classmethod(self, m):
        return type(self)(self.f, m)

def make_dynamicmethod_meta(meta):
    class _dynamicmethod_meta(meta):
        def __prepare__(name, bases, **kwargs):
            d = meta.__prepare__(name, bases, **kwargs)
            for base in bases:
                for k,v in base.__dict__.items():
                    if isinstance(v, dynamicmethod):
                        if k in d:
                            raise ValueError('Multiple base classes define the same dynamicmethod')
                        d[k] = v
            return d

    return _dynamicmethod_meta

dynamicmethod_meta=make_dynamicmethod_meta(type)

class A(metaclass=dynamicmethod_meta):
    @dynamicmethod
    def a(self):
       print('Called from obj {} defined in A'.format(self))

    @a.classmethod
    def a(cls)
       print('Called from class {} defined in A'.format(cls))

class B(A):
   @a.method
   def a(self):
       print('Called from obj {} defined in B'.format(self))

A.a()
A().a()
B.a()
B().a()
</code>```

results in:

```<code>Called from class <class 'A'> defined in A
Called from obj <A object at ...> defined in A
Called from class <class 'B'> defined in A
Called from obj <B object at ...> defined in B
</code>```

Body:
I actually just asked this question (Python descriptors and inheritance I hadn't seen this question).  My solution uses descriptors and a metaclass for inheritance.

from my answer:

class dynamicmethod:
    '''
        Descriptor to allow dynamic dispatch on calls to class.Method vs obj.Method

        fragile when used with inheritence, to inherit and then overwrite or extend
        a dynamicmethod class must have dynamicmethod_meta as its metaclass
    '''
    def __init__(self, f=None, m=None):
        self.f = f
        self.m = m

    def __get__(self, obj, objtype=None):
        if obj is not None and self.f is not None:
            return types.MethodType(self.f, obj)
        elif objtype is not None and self.m is not None:
            return types.MethodType(self.m, objtype)
        else:
            raise AttributeError('No associated method')

    def method(self, f):
        return type(self)(f, self.m)

    def classmethod(self, m):
        return type(self)(self.f, m)

def make_dynamicmethod_meta(meta):
    class _dynamicmethod_meta(meta):
        def __prepare__(name, bases, **kwargs):
            d = meta.__prepare__(name, bases, **kwargs)
            for base in bases:
                for k,v in base.__dict__.items():
                    if isinstance(v, dynamicmethod):
                        if k in d:
                            raise ValueError('Multiple base classes define the same dynamicmethod')
                        d[k] = v
            return d

    return _dynamicmethod_meta

dynamicmethod_meta=make_dynamicmethod_meta(type)

class A(metaclass=dynamicmethod_meta):
    @dynamicmethod
    def a(self):
       print('Called from obj {} defined in A'.format(self))

    @a.classmethod
    def a(cls)
       print('Called from class {} defined in A'.format(cls))

class B(A):
   @a.method
   def a(self):
       print('Called from obj {} defined in B'.format(self))

A.a()
A().a()
B.a()
B().a()

results in:

Called from class <class 'A'> defined in A
Called from obj <A object at ...> defined in A
Called from class <class 'B'> defined in A
Called from obj <B object at ...> defined in B


问:
How to limit the length of abline in ggplot2 using slope and intercept?
How I can limit the length of abline to only between year 1985 to 1990 using the slope and intercept. I know geom_segment but it does not take slope and intercept.
Here is my data and script

```<code>> dput(df)
structure(list(year = c(1979, 1980, 1981, 1982, 1983, 1984, 1985,
1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996,
1997, 1998), value = c(7.33, 10.32, 11.65, 6.19, 8.3, 9.24, 8.13,
9.94, 10.85, 11.37, 7.17, 9.18, 11.24, 11.38, 8.32, 9.29, 7.48,
8.63, 10.17, 8.94)), .Names = c("year", "value"), row.names = c(NA,
-20L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

Script

```<code>plt <- ggplot(df, aes(year, value)) +
    geom_line() +
    geom_abline(aes(slope = 0.00225, intercept = 4.85100), colour = "red", lty = "dashed")

plt
</code>```

答:
Just use geom_segment. It's trivial to calculate the y endpoints given the x endpoints and the slope and intercept.

```<code>xs = c(1985, 1990)
beta = c(4.851, .00225)
ys = cbind(1, xs) %*% beta

... +
geom_segment(aes(x = xs[1], xend = xs[2], y = ys[1], yend = ys[2]),
    colour = "red",lty = "dashed")
</code>```

Body:
How I can limit the length of abline to only between year 1985 to 1990 using the slope and intercept. I know geom_segment but it does not take slope and intercept.
Here is my data and script

> dput(df)
structure(list(year = c(1979, 1980, 1981, 1982, 1983, 1984, 1985,
1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996,
1997, 1998), value = c(7.33, 10.32, 11.65, 6.19, 8.3, 9.24, 8.13,
9.94, 10.85, 11.37, 7.17, 9.18, 11.24, 11.38, 8.32, 9.29, 7.48,
8.63, 10.17, 8.94)), .Names = c("year", "value"), row.names = c(NA,
-20L), class = c("tbl_df", "tbl", "data.frame"))

Script

plt <- ggplot(df, aes(year, value)) +
    geom_line() +
    geom_abline(aes(slope = 0.00225, intercept = 4.85100), colour = "red", lty = "dashed")

plt

Body:
Just use geom_segment. It's trivial to calculate the y endpoints given the x endpoints and the slope and intercept.

xs = c(1985, 1990)
beta = c(4.851, .00225)
ys = cbind(1, xs) %*% beta

... +
geom_segment(aes(x = xs[1], xend = xs[2], y = ys[1], yend = ys[2]),
    colour = "red",lty = "dashed")


问:
How to disable attribute menu item after it is clicked?
I can click on the Photos menu 4 times quickly, and the "$.get(..." is sent to the server 4 times.
I need to disable this menu (after it is clicked once) so it can not be clicked on again.
Environment: NodeJS, Express, Pug, Jquery
Thanks,
Pat</p>

```<code>--------------DOM----------------------------------
// file = photos.pug
div#wrapper2
    div#altnav
      ul
        include includes/altnav.pug
        include includes/navjs.pug
---------------------------------------------------
// file = includes/altnav.pug
li: a.navigation(href='#', data-level='/images/cs/Photos') Photos
---------------------------------------------------
// file = includes/navjs.pug
script.
    $(function(){ // jQuery DOM ready
        $('.navigation').click(function () {
            var level = 'm' + $(this).data('level');        // Append an 'm' so I know this came from navjs.pug
            var url = '/navigation?level=' + escape(level); // Send this to the /router/photos.js
            $.get(url, function (data) {
                $('body').html(data);           // data = new HTML page to be loaded by browser
            });
        });
    });
</code>```

答:
```<code>$(function(){ // jQuery DOM ready
   $('.navigation').click(function () {
      $(this).css({
        "pointer-events": "none",
        "cursor": "default"
      });
          /* then your code */
   });
});
</code>```

Body:
I can click on the Photos menu 4 times quickly, and the "$.get(..." is sent to the server 4 times.
I need to disable this menu (after it is clicked once) so it can not be clicked on again.
Environment: NodeJS, Express, Pug, Jquery
Thanks,
Pat

--------------DOM----------------------------------
// file = photos.pug
div#wrapper2
    div#altnav
      ul
        include includes/altnav.pug
        include includes/navjs.pug
---------------------------------------------------
// file = includes/altnav.pug
li: a.navigation(href='#', data-level='/images/cs/Photos') Photos
---------------------------------------------------
// file = includes/navjs.pug
script.
    $(function(){ // jQuery DOM ready
        $('.navigation').click(function () {
            var level = 'm' + $(this).data('level');        // Append an 'm' so I know this came from navjs.pug
            var url = '/navigation?level=' + escape(level); // Send this to the /router/photos.js
            $.get(url, function (data) {
                $('body').html(data);           // data = new HTML page to be loaded by browser
            });
        });
    });


问:
How do I bind the value on the button to my ng-model?
I am trying to bind the value on the button to my ng-model, but it doesn't seem to work. Does anyone have any suggestions on what I should do?

I am using the datepicker from https://github.com/rajeshwarpatlolla/ionic-datepicker

```<code><div class="col">
  <label class="item item-input small">
   Start Date: <br>

    <ionic-datepicker input-obj="datepickerObject">
      <input type="button" ng-model="vm.newObject.startDate" value="
        {{datepickerObject.inputDate|date:'dd - MMM - yy'}}">
    </ionic-datepicker>

   </label>
</div>
</code>```

答:
we can use button element with {{}} to display the data returned</p>

```<code><ionic-datepicker input-obj="datepickerObject">

    <button type="button">{{datepickerObject.inputDate|date:'dd - MMM - yy'}}
</button>

</ionic-datepicker>
</code>```

Body:
I am trying to bind the value on the button to my ng-model, but it doesn't seem to work. Does anyone have any suggestions on what I should do?

I am using the datepicker from https://github.com/rajeshwarpatlolla/ionic-datepicker

   Start Date:

    <ionic-datepicker input-obj="datepickerObject">
      <input type="button" ng-model="vm.newObject.startDate" value="
        {{datepickerObject.inputDate|date:'dd - MMM - yy'}}">
    </ionic-datepicker>

Body:
we can use button element with {{}} to display the data returned

<ionic-datepicker input-obj="datepickerObject">

    <button type="button">{{datepickerObject.inputDate|date:'dd - MMM - yy'}}
</button>

</ionic-datepicker>


问:
single quote in php from java string
I have a java (android) application that uses php to talk to the MS database. The problem is one part in my app. I have a string that is a sql statement, and that string will not insert into the database with the single quotes

```<code>String sql = "select * from table where col = 'testing' AND Col2 = 'Tester'";
</code>```

I get that in the php script by using: $script = $_REQUEST['Script'];

2 things, I want to insert that script into a a column with the datatype char
and i also want to run that script as well. Thanks!

I am not having the users run there own scripts on my DB. as they check a checkbox it a StringBuilder builds a script upon what they select. So if they check Female or male The String add the Select * from Table where Gender = 'Female' etc.

答:
As far as I remember, strings in MSSQL are represented with double quotes.

```<code>$var = "select ... where col = \"testing\"";
$var = 'select ... where col = "testing"'; // more readable
</code>```

Just use it this way.

If you only receive those queries, consider replacing ' with " using str_replace. I am aware of the fact it may not be correct for all cases but simple ones.

Title: single quote in php from java string

Body:
I have a java (android) application that uses php to talk to the MS database. The problem is one part in my app. I have a string that is a sql statement, and that string will not insert into the database with the single quotes

String sql = "select * from table where col = 'testing' AND Col2 = 'Tester'";

I get that in the php script by using: $script = $_REQUEST['Script'];

2 things, I want to insert that script into a a column with the datatype char
and i also want to run that script as well. Thanks!

I am not having the users run there own scripts on my DB. as they check a checkbox it a StringBuilder builds a script upon what they select. So if they check Female or male The String add the Select * from Table where Gender = 'Female' etc.

Body:
As far as I remember, strings in MSSQL are represented with double quotes.

$var = "select ... where col = \"testing\"";
$var = 'select ... where col = "testing"'; // more readable

Just use it this way.

If you only receive those queries, consider replacing ' with " using str_replace. I am aware of the fact it may not be correct for all cases but simple ones.


问:
Xcode Entity Core Data - NSDate wrong year?
When storing values to core data, the Date is stored as a TimeStamp but the year is incorrect. How can I sore the correct datetime to core storage?

Steps taken

Using Xcode and Swift I have created an iPhone project and added an Entity with the following attributes:

```<code>Attribute    Type
-------------------
name         String
date         Date
</code>```

I am using core data to save data entries. eg:

```<code> myEntity = MyEntity(context: self.viewContext)
 myEntity.name = nameString
 myEntity.date = Date() as NSDate
 self.appDelegate.saveContext()
</code>```

This creates records on the phone in a sqlite database. When I open the Sqlite database on the phone, I can see the records created as follows:

```<code>Z_PK    Z_NAME    Z_DATE
1       George    521035200
</code>```

Converting the Date value using the following command:

```<code>SELECT datetime(521035200, 'unixepoch');

OUTPUTS: 1986-07-06 12:00:00
</code>```

The day/month is correct but the year should be 2017.

What is the correct format of the timestamp in SQLite?

Is it possible to store a date using Xcode Entity instead of a time stamp?

答:
Core Data considers the layout of its SQLite file to be a private implementation detail. Although it's clearly valid to open and inspect the file to debug and to profile, you shouldn't plan to do that systematically as part of your application or a wider data flow. If you do then you're coupling yourself to a private implementation detail, so you should expect your code to break arbitrarily and without recourse.

That being said, the NSDate reference date is 00:00:00 UTC on 1 January 2001 so if you're a human being trying to inspect some data for verification, you're quite possibly looking at an offset from that.

You could store a time stamp as something other than an NSDate but there'd be no benefit to doing so as it wouldn't resolve your coupling to non-guaranteed structure, and it'd make your use of Core Data uglier.

Body:
When storing values to core data, the Date is stored as a TimeStamp but the year is incorrect. How can I sore the correct datetime to core storage?

Steps taken

Using Xcode and Swift I have created an iPhone project and added an Entity with the following attributes:

Attribute    Type
-------------------
name         String
date         Date

I am using core data to save data entries. eg:

 myEntity = MyEntity(context: self.viewContext)
 myEntity.name = nameString
 myEntity.date = Date() as NSDate
 self.appDelegate.saveContext()

This creates records on the phone in a sqlite database. When I open the Sqlite database on the phone, I can see the records created as follows:

Z_PK    Z_NAME    Z_DATE
1       George    521035200

Converting the Date value using the following command:

SELECT datetime(521035200, 'unixepoch');

OUTPUTS: 1986-07-06 12:00:00

The day/month is correct but the year should be 2017.

What is the correct format of the timestamp in SQLite?

Is it possible to store a date using Xcode Entity instead of a time stamp?


问:
Angular 4 Server Side Rendering ngx-bootstrap carousel makes response hang
So I'm trying to implement server side rendering on my angular 4 website and I think I'm pretty close. I have gotten all routes to render server side except for 1 specific route and the default route. The routes that do not work are /home, /anythingthatisntdefined, and (no route at all loads, but does not server side render the home page).

So the no route, just isn't getting picked up by my catch all route... the anything that isn't defined I'm assuming the server is not correctly processing the default route... and the /home route not loading, just doesn't make sense to me. Any tips?

Here is my server.ts

```<code>import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '@angular/platform-server';
import { enableProdMode } from '@angular/core';
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory';
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';

const PORT = 4000;

enableProdMode();

const app = express();

let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();

app.engine('html', (_, options, callback) => {
  console.log('url: ', options.req.url);
  const opts = { document: template, url: options.req.url };

  renderModuleFactory(AppServerModuleNgFactory, opts)
    .then(html => callback(null, html));
});

app.set('view engine', 'html');
app.set('views', 'src')

app.use(express.static(join(__dirname, '..', 'dist')));

app.get('*', (req, res) => {
  console.log('caught by *');
  res.render('../dist/index.html', {
    req: req,
    res: res
  });
});
app.listen(PORT, () => {
  console.log(`listening on http://localhost:${PORT}!`);
});
</code>```

Here is my router

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ServicesComponent } from './services/services.component';
import { ResourcesComponent } from './resources/resources.component';
import { ChurchesComponent } from './churches/churches.component';
import { GetAQuoteComponent } from './get-a-quote/get-a-quote.component';

const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent
  },
  {
    path: 'services',
    component: ServicesComponent
  },
  {
    path: 'resources',
    component: ResourcesComponent
  },
  {
    path: 'about',
    component: AboutComponent
  },
  {
    path: 'churches',
    component: ChurchesComponent
  },
  {
    path: 'get-a-quote',
    component: GetAQuoteComponent
  },
  {
    path: '**',
    component: HomeComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

答:
Good news, I figured out why the one route/ random routes weren't loading. The ngx-bootstrap carousel (which I had on my home route) has an interval that needs to be disabled server side. Otherwise the route will hang forever and never load.

Reference: https://github.com/valor-software/ngx-bootstrap/issues/1353

And last, the fact of the no route not working was because of my static assets route which was intercepting the request before my express.get was.

Body:
So I'm trying to implement server side rendering on my angular 4 website and I think I'm pretty close. I have gotten all routes to render server side except for 1 specific route and the default route. The routes that do not work are /home, /anythingthatisntdefined, and (no route at all loads, but does not server side render the home page).

So the no route, just isn't getting picked up by my catch all route... the anything that isn't defined I'm assuming the server is not correctly processing the default route... and the /home route not loading, just doesn't make sense to me. Any tips?

Here is my server.ts

import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '@angular/platform-server';
import { enableProdMode } from '@angular/core';
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory';
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';

const PORT = 4000;

enableProdMode();

const app = express();

let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();

app.engine('html', (_, options, callback) => {
  console.log('url: ', options.req.url);
  const opts = { document: template, url: options.req.url };

  renderModuleFactory(AppServerModuleNgFactory, opts)
    .then(html => callback(null, html));
});

app.set('view engine', 'html');
app.set('views', 'src')

app.use(express.static(join(__dirname, '..', 'dist')));

app.get('*', (req, res) => {
  console.log('caught by *');
  res.render('../dist/index.html', {
    req: req,
    res: res
  });
});
app.listen(PORT, () => {
  console.log(`listening on http://localhost:${PORT}!`);
});

Here is my router

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ServicesComponent } from './services/services.component';
import { ResourcesComponent } from './resources/resources.component';
import { ChurchesComponent } from './churches/churches.component';
import { GetAQuoteComponent } from './get-a-quote/get-a-quote.component';

const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent
  },
  {
    path: 'services',
    component: ServicesComponent
  },
  {
    path: 'resources',
    component: ResourcesComponent
  },
  {
    path: 'about',
    component: AboutComponent
  },
  {
    path: 'churches',
    component: ChurchesComponent
  },
  {
    path: 'get-a-quote',
    component: GetAQuoteComponent
  },
  {
    path: '**',
    component: HomeComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


问:
Django - change app name in admin
I don't know how can I change name of my external app in my django admin panel. I can change verbose name of Constance app ('my constance settings'):

```<code>class ConstanceConfig(AppConfig):
    name = 'constance'
    verbose_name = 'My constance settings'
</code>```

I don't have any idea how can I change "config" name. Any idea?

My models.py:

```<code>from datetime import datetime
from datetime import timedelta
from urllib.parse import urlparse
from django.db import models
from django.urls import reverse
from mainapp.widgets import MyTextField
from django.template.defaultfilters import slugify
from smart_selects.db_fields import ChainedForeignKey
from django.db.models import Q
from constance import config

class Category(models.Model):
    category_name = models.CharField(max_length=30, unique=True,
                                 verbose_name='Nazwa kategorii')
    slug = models.SlugField()
    image = models.ImageField(upload_to='category_images',
                          verbose_name="Obrazek kategorii",
                          blank=True)
    category_description = models.TextField(default='Opis',
                                        verbose_name="Opis kategorii")

    class Meta:
        verbose_name_plural = " Kategorie"

    def save(self, *args, **kwargs):
        self.slug = slugify(self.category_name)
        super(Category, self).save(*args, **kwargs)

    def admin_image_thumb(self):
        '''
        Miniaturka obrazka kategorii dla panelu admina
        '''
        if self.image:
            return('<img src="/media/%s" height="42" width="42" />') %
(self.image)
        else:
            return('<img src="/media/category_images/default.ico" alt="" />')

    admin_image_thumb.short_description = 'Miniaturka'
    admin_image_thumb.allow_tags = True

    def image_thumb(self):
        '''
        Miniaturka obrazka kategorii
        '''
        if self.image:
            return('/media/%s') % (self.image)
        else:
            return('/media/category_images/default.ico')

    def get_active_sites(self):
        return Site.objects.filter(Q(category=self) | Q(category1=self),
is_active=True)

    image_thumb.short_description = 'Miniaturka'
    image_thumb.allow_tags = True

    def __str__(self):
        return self.category_name

class SubCategory(models.Model):
    category = models.ForeignKey(
        'Category',
        related_name='subcategory',
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        verbose_name='Kategoria nadrzędna'
    )
    name = models.CharField(max_length=30, verbose_name="Nazwa subkategorii")
    slug = models.SlugField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(SubCategory, self).save(*args, **kwargs)

    def get_active_sites(self):
        return Site.objects.filter(Q(subcategory=self) | Q(subcategory1=self), is_active=True)

    class Meta:
        verbose_name_plural = " Subkategorie"

    def __str__(self):
        return self.name

def get_deadline():
    return datetime.today() + timedelta(days=20)

class Site(models.Model):
    category = models.ForeignKey('Category')
    subcategory = ChainedForeignKey(
        'SubCategory',
         chained_field='category',
        chained_model_field='category',
        show_all=False,
        auto_choose=True,
        default=None)
    name = models.CharField(max_length=config.TITLE_LENGTH_MAX,
verbose_name="Tytuł")
    slug = models.SlugField()
    description = models.TextField(max_length=config.DESCRIPTION_LENGTH_MAX,
verbose_name="Opis")
    # importuje zmienione TextFields widgets.py
    keywords = MyTextField(max_length=config.KEYWORDS_LENGTH_MAX,
verbose_name="Słowa kluczowe")
    date = models.DateTimeField(default=datetime.now)
    date_end = models.DateTimeField(null=True, blank=True, default=None)
    url = models.URLField()
    is_active = models.BooleanField(default=False, verbose_name='Aktywna')

    flagged = models.TextField(max_length=400, verbose_name="Flagowanie",
null=True, blank=True, default='')
    flagged_true = models.BooleanField(default=False, verbose_name='Oflagowana')

    category1 = models.ForeignKey('Category', related_name='category',
blank=True, null=True, default=None)
    subcategory1 = ChainedForeignKey(
         'SubCategory',
        chained_field='category1',
        chained_model_field='category',
        related_name='subcategory',
        show_all=False,
        auto_choose=True, blank=True, null=True)

    group = models.ForeignKey('Group', default='Podstawowy',
                          help_text="<div id='group'><ul><li>Możesz dodać
wpis do 1 kategorii</b></li></ul></div>")

    email = models.EmailField(help_text='Podaj adres email')
    user = models.CharField(max_length=100)
    kod = models.CharField(max_length=20)

    def save(self, *args, **kwargs):
         self.slug = slugify(self.name)
         # if len(self.flagged.splitlines() > 3):
         #     self.flagged_true = True
        super(Site, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('site', args=[str(self.category.slug),
                                 str(self.subcategory.slug), str(self.slug),
str(self.id)])

    def get_thumb(self):
        host = urlparse(self.url).hostname
        if host.startswith('www.'):
            host = host[4:]
        thumb = 'http://free.pagepeeker.com/thumbs.php?size=l&url=http://' + host
        # thumb = 'https://api.thumbalizr.com/?url=http://' + host + '&width=500'
        return thumb

    class Meta:
        verbose_name_plural = "Strony"

    def __str__(self):
        return self.name

class Group(models.Model):
    group_name = models.CharField(max_length=30, verbose_name='Nazwa grupy',
unique=True)
    codes = models.TextField(null=True, blank=True)
    pay = models.CharField(
        max_length=10,
        choices=(('PAID', 'PŁATNY'), ('FREE', 'DARMOWY')),
        default='FREE',
        verbose_name="Czy płatny")
    time = models.CharField(
        max_length=3,
        choices=(('T', 'TAK'), ('N', 'NIE')),
        default='N',
        help_text='Czy wpis ma być wyłączony po jakimś czasie czy
bezterminowy')
    days = models.IntegerField(default=1)
    premium_box = models.CharField(
         max_length=3,
    choices=(('T', 'TAK'), ('N', 'NIE')),
    default='N',
    help_text='Czy wpis ma być wyświetlany w okienku reklamowym')
category = models.CharField(
    max_length=2,
    choices=(('1', '1'), ('2', '2')),
)

is_active = models.BooleanField(default=True, verbose_name='Aktywna')

class Meta:
    verbose_name_plural = "Grupy wpisów"

def __str__(self):
    return self.group_name
</code>```

And part of my admin.py:

```<code>from constance.admin import ConstanceAdmin, ConstanceForm, Config

class CustomConfigForm(ConstanceForm):
    def __init__(self, *args, **kwargs):
        super(CustomConfigForm, self).__init__(*args, **kwargs)

class ConfigAdmin(ConstanceAdmin):
    change_list_form = CustomConfigForm
    change_list_template = 'admin/config/change_list.html'

admin.site.unregister([Config])
admin.site.register([Config], ConfigAdmin)
</code>```

In my venvs files I found admin.py (inside constance directory). There is:

```<code>class Config(object):
    class Meta(object):
        app_label = 'constance'
        object_name = 'Config'
        model_name = module_name = 'config'
        verbose_name_plural = _('config')
        abstract = False
        swapped = False

        def get_ordered_objects(self):
            return False

        def get_change_permission(self):
            return 'change_%s' % self.model_name

        @property
        def app_config(self):
            return apps.get_app_config(self.app_label)

   _meta = Meta()
</code>```

I can change

```<code>verbose_name_plural = _('config')
</code>```

to:

```<code>verbose_name_plural = _('My config label')
</code>```

I still can't change this from my admin.py file...

答:
I found a solution. Two days trials and errors...;)</p>

```<code>class MyConfig(Config):
    class Meta(Config.Meta):
        verbose_name_plural = _('Zmiana ustawień')
    _meta = Meta()

admin.site.unregister([Config])
admin.site.register([MyConfig], ConfigAdmin)
</code>```

Title: Django - change app name in admin

Body:
I don't know how can I change name of my external app in my django admin panel. I can change verbose name of Constance app ('my constance settings'):

class ConstanceConfig(AppConfig):
    name = 'constance'
    verbose_name = 'My constance settings'

I don't have any idea how can I change "config" name. Any idea?

My models.py:

from datetime import datetime
from datetime import timedelta
from urllib.parse import urlparse
from django.db import models
from django.urls import reverse
from mainapp.widgets import MyTextField
from django.template.defaultfilters import slugify
from smart_selects.db_fields import ChainedForeignKey
from django.db.models import Q
from constance import config

class Category(models.Model):
    category_name = models.CharField(max_length=30, unique=True,
                                 verbose_name='Nazwa kategorii')
    slug = models.SlugField()
    image = models.ImageField(upload_to='category_images',
                          verbose_name="Obrazek kategorii",
                          blank=True)
    category_description = models.TextField(default='Opis',
                                        verbose_name="Opis kategorii")

    class Meta:
        verbose_name_plural = " Kategorie"

    def save(self, *args, **kwargs):
        self.slug = slugify(self.category_name)
        super(Category, self).save(*args, **kwargs)

    def admin_image_thumb(self):
        '''
        Miniaturka obrazka kategorii dla panelu admina
        '''
        if self.image:
            return('') %
(self.image)
        else:
            return('')

    admin_image_thumb.short_description = 'Miniaturka'
    admin_image_thumb.allow_tags = True

    def image_thumb(self):
        '''
        Miniaturka obrazka kategorii
        '''
        if self.image:
            return('/media/%s') % (self.image)
        else:
            return('/media/category_images/default.ico')

    def get_active_sites(self):
        return Site.objects.filter(Q(category=self) | Q(category1=self),
is_active=True)

    image_thumb.short_description = 'Miniaturka'
    image_thumb.allow_tags = True

    def __str__(self):
        return self.category_name

class SubCategory(models.Model):
    category = models.ForeignKey(
        'Category',
        related_name='subcategory',
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        verbose_name='Kategoria nadrzędna'
    )
    name = models.CharField(max_length=30, verbose_name="Nazwa subkategorii")
    slug = models.SlugField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(SubCategory, self).save(*args, **kwargs)

    def get_active_sites(self):
        return Site.objects.filter(Q(subcategory=self) | Q(subcategory1=self), is_active=True)

    class Meta:
        verbose_name_plural = " Subkategorie"

    def __str__(self):
        return self.name

def get_deadline():
    return datetime.today() + timedelta(days=20)

class Site(models.Model):
    category = models.ForeignKey('Category')
    subcategory = ChainedForeignKey(
        'SubCategory',
         chained_field='category',
        chained_model_field='category',
        show_all=False,
        auto_choose=True,
        default=None)
    name = models.CharField(max_length=config.TITLE_LENGTH_MAX,
verbose_name="Tytuł")
    slug = models.SlugField()
    description = models.TextField(max_length=config.DESCRIPTION_LENGTH_MAX,
verbose_name="Opis")
    # importuje zmienione TextFields widgets.py
    keywords = MyTextField(max_length=config.KEYWORDS_LENGTH_MAX,
verbose_name="Słowa kluczowe")
    date = models.DateTimeField(default=datetime.now)
    date_end = models.DateTimeField(null=True, blank=True, default=None)
    url = models.URLField()
    is_active = models.BooleanField(default=False, verbose_name='Aktywna')

    flagged = models.TextField(max_length=400, verbose_name="Flagowanie",
null=True, blank=True, default='')
    flagged_true = models.BooleanField(default=False, verbose_name='Oflagowana')

    category1 = models.ForeignKey('Category', related_name='category',
blank=True, null=True, default=None)
    subcategory1 = ChainedForeignKey(
         'SubCategory',
        chained_field='category1',
        chained_model_field='category',
        related_name='subcategory',
        show_all=False,
        auto_choose=True, blank=True, null=True)

    group = models.ForeignKey('Group', default='Podstawowy',
                          help_text="

Możesz dodać
wpis do 1 kategorii

")

    email = models.EmailField(help_text='Podaj adres email')
    user = models.CharField(max_length=100)
    kod = models.CharField(max_length=20)

    def save(self, *args, **kwargs):
         self.slug = slugify(self.name)
         # if len(self.flagged.splitlines() > 3):
         #     self.flagged_true = True
        super(Site, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('site', args=[str(self.category.slug),
                                 str(self.subcategory.slug), str(self.slug),
str(self.id)])

    def get_thumb(self):
        host = urlparse(self.url).hostname
        if host.startswith('www.'):
            host = host[4:]
        thumb = 'http://free.pagepeeker.com/thumbs.php?size=l&url=http://' + host
        # thumb = 'https://api.thumbalizr.com/?url=http://' + host + '&width=500'
        return thumb

    class Meta:
        verbose_name_plural = "Strony"

    def __str__(self):
        return self.name

class Group(models.Model):
    group_name = models.CharField(max_length=30, verbose_name='Nazwa grupy',
unique=True)
    codes = models.TextField(null=True, blank=True)
    pay = models.CharField(
        max_length=10,
        choices=(('PAID', 'PŁATNY'), ('FREE', 'DARMOWY')),
        default='FREE',
        verbose_name="Czy płatny")
    time = models.CharField(
        max_length=3,
        choices=(('T', 'TAK'), ('N', 'NIE')),
        default='N',
        help_text='Czy wpis ma być wyłączony po jakimś czasie czy
bezterminowy')
    days = models.IntegerField(default=1)
    premium_box = models.CharField(
         max_length=3,
    choices=(('T', 'TAK'), ('N', 'NIE')),
    default='N',
    help_text='Czy wpis ma być wyświetlany w okienku reklamowym')
category = models.CharField(
    max_length=2,
    choices=(('1', '1'), ('2', '2')),
)

is_active = models.BooleanField(default=True, verbose_name='Aktywna')

class Meta:
    verbose_name_plural = "Grupy wpisów"

def __str__(self):
    return self.group_name

And part of my admin.py:

from constance.admin import ConstanceAdmin, ConstanceForm, Config

class CustomConfigForm(ConstanceForm):
    def __init__(self, *args, **kwargs):
        super(CustomConfigForm, self).__init__(*args, **kwargs)

class ConfigAdmin(ConstanceAdmin):
    change_list_form = CustomConfigForm
    change_list_template = 'admin/config/change_list.html'

admin.site.unregister([Config])
admin.site.register([Config], ConfigAdmin)

In my venvs files I found admin.py (inside constance directory). There is:

class Config(object):
    class Meta(object):
        app_label = 'constance'
        object_name = 'Config'
        model_name = module_name = 'config'
        verbose_name_plural = _('config')
        abstract = False
        swapped = False

        def get_ordered_objects(self):
            return False

        def get_change_permission(self):
            return 'change_%s' % self.model_name

        @property
        def app_config(self):
            return apps.get_app_config(self.app_label)

   _meta = Meta()

I can change

verbose_name_plural = _('config')

to:

verbose_name_plural = _('My config label')

I still can't change this from my admin.py file...

Body:
I found a solution. Two days trials and errors...;)

class MyConfig(Config):
    class Meta(Config.Meta):
        verbose_name_plural = _('Zmiana ustawień')
    _meta = Meta()

admin.site.unregister([Config])
admin.site.register([MyConfig], ConfigAdmin)