问:
problem with using two datasources with hibernate?
greeting all
I tried to use two different datasources with hibernate (two different sessionFactories and two different transactionManagers )
but I got the application failed to start

it stops in the step of

```<code>Creating new JDBC DriverManager Connection to [jdbc:mysql://some-ip-here/mydb]
</code>```

here's the configuration:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.myapp" />
    <context:annotation-config />
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- ================PostgreSQL/Hibernate================ -->

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.myapp.domain.myDomain1</value>
            </list>

        </property>

        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
            </value>
        </property>

    </bean>

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="org.postgresql.Driver" />

        <property name="url">
        <value>${db.url}</value>
        </property>

        <property name="username" >
        <value>${db.username}</value>
        </property>

        <property name="password">
        <value>${db.password}</value>
        </property>

    </bean>

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- ================MySQL/Hibernate================ -->

    <bean id="mysqlSessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

        <property name="dataSource" ref="mysqlDataSource" />
        <property name="annotatedClasses">
            <list>
            <value>com.myapp.domain.myDomain2</value>
            </list>
        </property>

        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.MySQLDialect
            </value>
        </property>
    </bean>

    <bean id="mysqlDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />

        <property name="url">
        <value>${db.mysql.url}</value>
        </property>

        <property name="username" >
        <value>${db.mysql.username}</value>
        </property>

        <property name="password">
        <value>${db.mysql.password}</value>
        </property>

    </bean>

    <bean id="mysqltransactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="mysqlSessionFactory" />
    </bean>

        <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

        <!-- ================End of MySQL/Hibernate================ -->

</beans>
</code>```

答: problem fixed, it was with the remote server firewall.</p>

Body:
greeting all
I tried to use two different datasources with hibernate (two different sessionFactories and two different transactionManagers )
but I got the application failed to start

it stops in the step of

Creating new JDBC DriverManager Connection to [jdbc:mysql://some-ip-here/mydb]

here's the configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.myapp" />
    <context:annotation-config />
    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.myapp.domain.myDomain1</value>
            </list>

        </property>

        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
            </value>
        </property>

    </bean>

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="org.postgresql.Driver" />

        <property name="url">
        <value>${db.url}</value>
        </property>

        <property name="username" >
        <value>${db.username}</value>
        </property>

        <property name="password">
        <value>${db.password}</value>
        </property>

    </bean>

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="mysqlSessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

        <property name="dataSource" ref="mysqlDataSource" />
        <property name="annotatedClasses">
            <list>
            <value>com.myapp.domain.myDomain2</value>
            </list>
        </property>

        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.MySQLDialect
            </value>
        </property>
    </bean>

    <bean id="mysqlDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />

        <property name="url">
        <value>${db.mysql.url}</value>
        </property>

        <property name="username" >
        <value>${db.mysql.username}</value>
        </property>

        <property name="password">
        <value>${db.mysql.password}</value>
        </property>

    </bean>

    <bean id="mysqltransactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="mysqlSessionFactory" />
    </bean>

        <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

</beans>


来源: stackexchange

问:
Call to undefined method Image::resize()
I am having problem with changing logo image in my admin panel, it was working before but after update it outputs an error. Now I am not sure what happens and here is the error:

```<code> Call to undefined method Image::resize() …/system/controllers/settings.php
</code>```

This below is the code from that area:

```<code>case 'logo-post':
    if($_app_stage == 'Demo'){
        r2(U.'appearance/customize/','e',$_L['disabled_in_demo']);
    }
    $validextentions = array("jpeg", "jpg", "png");
    $temporary = explode(".", $_FILES["file"]["name"]);
    $file_extension = end($temporary);
    $file_name = '';
    if(($_FILES["file"]["type"] == "image/png")){
        $file_name = 'logo-tmp.png';
    }
    elseif(($_FILES["file"]["type"] == "image/jpg")){
        $file_name = 'logo-tmp.jpg';
    }
    elseif(($_FILES["file"]["type"] == "image/jpeg")){
        $file_name = 'logo-tmp.jpeg';
    }
    elseif(($_FILES["file"]["type"] == "image/gif")){
        $file_name = 'logo-tmp.gif';
    }
    else{

    }
    if ((($_FILES["file"]["type"] == "image/png")
            || ($_FILES["file"]["type"] == "image/jpg")
            || ($_FILES["file"]["type"] == "image/jpeg"))
        && ($_FILES["file"]["size"] < 1000000)//approx. 100kb files can be uploaded
        && in_array($file_extension, $validextentions)){
        move_uploaded_file($_FILES["file"]["tmp_name"], 'storage/system/'. $file_name);
        $image = new Image();
        $image->source_path = 'storage/system/'. $file_name;
        $image->target_path = 'storage/system/logo.png';
       // $image->resize('0','40',ZEBRA_IMAGE_BOXED,'-1');
        $image->resize(0,0,ZEBRA_IMAGE_BOXED,'-1');

        // now delete the tmp image

        unlink('storage/system/'. $file_name);

       // r2(U.'settings/app','s',$_L['Settings Saved Successfully']);

        r2(U.'appearance/customize/','s',$_L['Settings Saved Successfully']);
    }

    else{

        r2(U.'appearance/customize/','e',$_L['Invalid Logo File']);

    }

    break;
</code>```

Line where the error is happening:

$image->resize(0,0,ZEBRA_IMAGE_BOXED,'-1');

I'd appreciate any help, thanks!

答:
I think the main thing here is after update, the function Image::resize() was gone away from your file  …/system/controllers/settings.php

Did you have any backup before update code? Please compare your file before and after the update, you will have the answer in this case.

ContentLicense: CC BY-SA 3.0

Body:
I am having problem with changing logo image in my admin panel, it was working before but after update it outputs an error. Now I am not sure what happens and here is the error:

 Call to undefined method Image::resize() …/system/controllers/settings.php

This below is the code from that area:

case 'logo-post':
    if($_app_stage == 'Demo'){
        r2(U.'appearance/customize/','e',$_L['disabled_in_demo']);
    }
    $validextentions = array("jpeg", "jpg", "png");
    $temporary = explode(".", $_FILES["file"]["name"]);
    $file_extension = end($temporary);
    $file_name = '';
    if(($_FILES["file"]["type"] == "image/png")){
        $file_name = 'logo-tmp.png';
    }
    elseif(($_FILES["file"]["type"] == "image/jpg")){
        $file_name = 'logo-tmp.jpg';
    }
    elseif(($_FILES["file"]["type"] == "image/jpeg")){
        $file_name = 'logo-tmp.jpeg';
    }
    elseif(($_FILES["file"]["type"] == "image/gif")){
        $file_name = 'logo-tmp.gif';
    }
    else{

    }
    if ((($_FILES["file"]["type"] == "image/png")
            || ($_FILES["file"]["type"] == "image/jpg")
            || ($_FILES["file"]["type"] == "image/jpeg"))
        && ($_FILES["file"]["size"] < 1000000)//approx. 100kb files can be uploaded
        && in_array($file_extension, $validextentions)){
        move_uploaded_file($_FILES["file"]["tmp_name"], 'storage/system/'. $file_name);
        $image = new Image();
        $image->source_path = 'storage/system/'. $file_name;
        $image->target_path = 'storage/system/logo.png';
       // $image->resize('0','40',ZEBRA_IMAGE_BOXED,'-1');
        $image->resize(0,0,ZEBRA_IMAGE_BOXED,'-1');

        // now delete the tmp image

        unlink('storage/system/'. $file_name);

       // r2(U.'settings/app','s',$_L['Settings Saved Successfully']);

        r2(U.'appearance/customize/','s',$_L['Settings Saved Successfully']);
    }

    else{

        r2(U.'appearance/customize/','e',$_L['Invalid Logo File']);

    }

    break;

Line where the error is happening:

$image->resize(0,0,ZEBRA_IMAGE_BOXED,'-1');

I'd appreciate any help, thanks!


问:
Having a casting issue with traveling salesperson using a greedy algorithm
I figure I have the general idea down for how to solve the algorithm but the implementation seems to elude me. What I have thus far is this:

```<code>public class GreedySalesman {

public static int[] greedySalesmanSolution(int[][] distances) {
    List cityList = new ArrayList();
            for(int[] array: distances) {
               cityList.add(Arrays.asList(array));
            }
    List<Integer> initialResult = new ArrayList();
    initialResult.add(0);
    List<Integer> finalResult = findMinDistance(cityList, cityList, initialResult, 0);
          /*int finalResultArray = new int[finalResult.size()+1];
    int i = 0;
    while (!(finalResult.isEmpty)) {
                finalResultArray[i] = finalResult.poll();
                i++;
    }

    return finalResultArray;
    */
          return null;
        }

public static List<Integer> findMinDistance(List<List<Integer>> initialCityInput, List<List<Integer>> cityInput, List<Integer> distanceResult, int index) {
        if(cityInput.isEmpty()) {
            distanceResult.add(0);
            return distanceResult;
        }
        int min = Collections.min(initialCityInput.get(index));
        List<Integer> city = initialCityInput.get(index);
        index = city.indexOf(min);
        distanceResult.add(index);
        cityInput.remove(city);

        return findMinDistance(initialCityInput,cityInput,distanceResult,index);

}
}
</code>```

That is, the algorithm will take an two dimensional array of ints as an input, then make a List cityList referring to distances, then pass it into findMinDistance. The commented out part is where the result from findMinDistance will be converted into an array of ints and returned as finalResultArray but that part is not important yet.

findMinDistance will take in a two dimensional list of Integers twice, a List of Integers that will become the result and an int representing an index.
The function will return the distanceResult when cityInput has been emptied. Otherwise it will start with the first city based on the index, get the minimum distance from that List and its index and add the index to the distanceResult.
Once that has been done, the city will be removed from the cityInput and the program will go into recursion until cityInput has been emptied.

The issue I am getting currently is
I cannot be cast to java.lang.Integer
at

```<code>int min = Collections.min(initialCityInput.get(index));
</code>```

And in main upon trying to run the program with some test data.
Any help will be appreciated.

======

Edit:

I made some changes to my code

```<code>public class GreedyTSP {

    public int[] greedySalesmanSolution(int[][] distances) {
                List<List<Integer>> cityList = new ArrayList();
                List<List<Integer>> initialCityList = new ArrayList();
                int iLength = distances.length;
                for (int i = 0; i < iLength; ++i) {
                    int jLength = distances[0].length;
                    cityList.add(new ArrayList(jLength));
                    initialCityList.add(new ArrayList(jLength));
                    for (int j = 0; j < jLength; ++j) {
                      cityList.get(i).add(distances[i][j]);
                      initialCityList.get(i).add(distances[i][j]);
                    }
                }

        List<Integer> initialResult = new ArrayList();
        initialResult.add(0);
        List<Integer> finalResult = findMinDistance(initialCityList, cityList, initialResult, 0);
                int[] finalResultArray = new int[finalResult.size()];
                Iterator<Integer> iterator = finalResult.iterator();
                for (int i = 0; i < finalResultArray.length; i++){
                    finalResultArray[i] = iterator.next().intValue();
                }
        return finalResultArray;

            }

        public List<Integer> findMinDistance(List<List<Integer>> initialCityInput, List<List<Integer>> cityInput, List<Integer> distanceResult, int initialIndex) {
            if(cityInput.isEmpty()) {
                distanceResult.add(0);
                return distanceResult;
            }
            List<Integer> city = initialCityInput.get(initialIndex);
            Integer min = findMin(city, distanceResult, initialIndex);
            int resultIndex = city.indexOf(min);
            distanceResult.add(resultIndex);
            cityInput.remove(city);
            return findMinDistance(initialCityInput,cityInput,distanceResult,resultIndex);
    }

        public Integer findMin(List<Integer> city, List<Integer> distanceResult, int inputIndex) {
            Integer min = Integer.MAX_VALUE;
            for(int i = 0; i < city.size();i++) {
                if (city.get(i) > inputIndex && city.get(i) < min) min = city.get(i);
            }
            int resultIndex = city.indexOf(min);
            if(distanceResult.contains(resultIndex)) {
                return findMin(city, distanceResult, inputIndex);
            }

            return min;
        }
}
</code>```

Im not having any cast errors at the moment but it seems that the parts of my program dealing with recursion are causing StackOverflowError-s. I've been messing with this thing for literally 16 hours now and I'm all out of ideas as to why. Any ideas?

答:
Well, I looked around a bit and I was basically overcomplicating the task through using multidimensional arraylists. I changed the code quite a bit:

```<code>public class GreedyTSP {

  public static int[] greedySolution(int[][] adjacencyMatrix) {
      List<Integer> visitedCities = new ArrayList<>();
        int min = Integer.MAX_VALUE;
        int startLocation = 0;
        int tempStartLocation = 0;
        int[] resultArray = new int[adjacencyMatrix.length+1];
        visitedCities.add(0);

        while(visitedCities.size() < adjacencyMatrix.length ){
            for(int i = 0; i < adjacencyMatrix.length; i++){
                if(!visitedCities.contains(i) && adjacencyMatrix[startLocation][i] < min){
                    min = adjacencyMatrix[startLocation][i];
                    tempStartLocation = i;
                }

            }
            startLocation = tempStartLocation;
            visitedCities.add(tempStartLocation);
            min = Integer.MAX_VALUE;
        }

        visitedCities.add(0);
        for(int i = 0; i < resultArray.length; i++){
            int temp = visitedCities.get(i);
            resultArray[i] = temp;
        }
        return resultArray;
    }
}
</code>```

This will solve the task using a greedy algorithm

Body:
I figure I have the general idea down for how to solve the algorithm but the implementation seems to elude me. What I have thus far is this:

public class GreedySalesman {

public static int[] greedySalesmanSolution(int[][] distances) {
    List cityList = new ArrayList();
            for(int[] array: distances) {
               cityList.add(Arrays.asList(array));
            }
    List<Integer> initialResult = new ArrayList();
    initialResult.add(0);
    List<Integer> finalResult = findMinDistance(cityList, cityList, initialResult, 0);
          /*int finalResultArray = new int[finalResult.size()+1];
    int i = 0;
    while (!(finalResult.isEmpty)) {
                finalResultArray[i] = finalResult.poll();
                i++;
    }

    return finalResultArray;
    */
          return null;
        }

public static List<Integer> findMinDistance(List<List<Integer>> initialCityInput, List<List<Integer>> cityInput, List<Integer> distanceResult, int index) {
        if(cityInput.isEmpty()) {
            distanceResult.add(0);
            return distanceResult;
        }
        int min = Collections.min(initialCityInput.get(index));
        List<Integer> city = initialCityInput.get(index);
        index = city.indexOf(min);
        distanceResult.add(index);
        cityInput.remove(city);

        return findMinDistance(initialCityInput,cityInput,distanceResult,index);

}
}

That is, the algorithm will take an two dimensional array of ints as an input, then make a List cityList referring to distances, then pass it into findMinDistance. The commented out part is where the result from findMinDistance will be converted into an array of ints and returned as finalResultArray but that part is not important yet.

findMinDistance will take in a two dimensional list of Integers twice, a List of Integers that will become the result and an int representing an index.
The function will return the distanceResult when cityInput has been emptied. Otherwise it will start with the first city based on the index, get the minimum distance from that List and its index and add the index to the distanceResult.
Once that has been done, the city will be removed from the cityInput and the program will go into recursion until cityInput has been emptied.

The issue I am getting currently is
I cannot be cast to java.lang.Integer
at

int min = Collections.min(initialCityInput.get(index));

And in main upon trying to run the program with some test data.
Any help will be appreciated.

======

Edit:

I made some changes to my code

public class GreedyTSP {

    public int[] greedySalesmanSolution(int[][] distances) {
                List<List<Integer>> cityList = new ArrayList();
                List<List<Integer>> initialCityList = new ArrayList();
                int iLength = distances.length;
                for (int i = 0; i < iLength; ++i) {
                    int jLength = distances[0].length;
                    cityList.add(new ArrayList(jLength));
                    initialCityList.add(new ArrayList(jLength));
                    for (int j = 0; j < jLength; ++j) {
                      cityList.get(i).add(distances[i][j]);
                      initialCityList.get(i).add(distances[i][j]);
                    }
                }

        List<Integer> initialResult = new ArrayList();
        initialResult.add(0);
        List<Integer> finalResult = findMinDistance(initialCityList, cityList, initialResult, 0);
                int[] finalResultArray = new int[finalResult.size()];
                Iterator<Integer> iterator = finalResult.iterator();
                for (int i = 0; i < finalResultArray.length; i++){
                    finalResultArray[i] = iterator.next().intValue();
                }
        return finalResultArray;

            }

        public List<Integer> findMinDistance(List<List<Integer>> initialCityInput, List<List<Integer>> cityInput, List<Integer> distanceResult, int initialIndex) {
            if(cityInput.isEmpty()) {
                distanceResult.add(0);
                return distanceResult;
            }
            List<Integer> city = initialCityInput.get(initialIndex);
            Integer min = findMin(city, distanceResult, initialIndex);
            int resultIndex = city.indexOf(min);
            distanceResult.add(resultIndex);
            cityInput.remove(city);
            return findMinDistance(initialCityInput,cityInput,distanceResult,resultIndex);
    }

        public Integer findMin(List<Integer> city, List<Integer> distanceResult, int inputIndex) {
            Integer min = Integer.MAX_VALUE;
            for(int i = 0; i < city.size();i++) {
                if (city.get(i) > inputIndex && city.get(i) < min) min = city.get(i);
            }
            int resultIndex = city.indexOf(min);
            if(distanceResult.contains(resultIndex)) {
                return findMin(city, distanceResult, inputIndex);
            }

            return min;
        }
}

Im not having any cast errors at the moment but it seems that the parts of my program dealing with recursion are causing StackOverflowError-s. I've been messing with this thing for literally 16 hours now and I'm all out of ideas as to why. Any ideas?

Body:
Well, I looked around a bit and I was basically overcomplicating the task through using multidimensional arraylists. I changed the code quite a bit:

public class GreedyTSP {

  public static int[] greedySolution(int[][] adjacencyMatrix) {
      List<Integer> visitedCities = new ArrayList<>();
        int min = Integer.MAX_VALUE;
        int startLocation = 0;
        int tempStartLocation = 0;
        int[] resultArray = new int[adjacencyMatrix.length+1];
        visitedCities.add(0);

        while(visitedCities.size() < adjacencyMatrix.length ){
            for(int i = 0; i < adjacencyMatrix.length; i++){
                if(!visitedCities.contains(i) && adjacencyMatrix[startLocation][i] < min){
                    min = adjacencyMatrix[startLocation][i];
                    tempStartLocation = i;
                }

            }
            startLocation = tempStartLocation;
            visitedCities.add(tempStartLocation);
            min = Integer.MAX_VALUE;
        }

        visitedCities.add(0);
        for(int i = 0; i < resultArray.length; i++){
            int temp = visitedCities.get(i);
            resultArray[i] = temp;
        }
        return resultArray;
    }
}

This will solve the task using a greedy algorithm


问:
When Distributed workers use shared_queue in distributed tensorflow
When Distributed workers use shared_queue in distributed tensorflow,
Is the shared_queue works to mutex exclusively?</p>

答: TensorFlow queue objects, such as tf.FIFOQueue, are thread-safe. This applies both to multiple users in a single process, and multiple jobs sharing the queue via shared_name in a distributed setting.


问:
How to save a struct to realm in swift?
It is easy to use Realm with classes by inheriting from Object. But how would I save a struct containing several fields to realm in Swift? E.g.

```<code>struct DataModel {
    var id = 0
    var test = "test"
}
</code>```

I know the documentation is clear about supported types. But maybe there is nice workaround or - even better - someone from realm could write about future plans about structs.

答:
Swift 4 shortest answer

Save structs as Data in Realm

```<code>struct MyStruct : Codable { // Variables here }

class MyRealObject : Object {

    @objc private dynamic var structData:Data? = nil

    var myStruct : MyStruct? {
        get {
            if let data = structData {
                return try? JSONDecoder().decode(MyStruct.self, from: data)
            }
            return nil
        }
        set {
            structData = try? JSONEncoder().encode(newValue)
        }
    }
}
</code>```

Use the magic

```<code>let realm = try! Realm()
try! realm.write {
      let myReal = MyRealObject()
      myReal.myStruct = MyStruct(....)
      realm.add(myReal)
}
</code>```

Title: How to save a struct to realm in swift?

Body:
It is easy to use Realm with classes by inheriting from Object. But how would I save a struct containing several fields to realm in Swift? E.g.

struct DataModel {
    var id = 0
    var test = "test"
}

I know the documentation is clear about supported types. But maybe there is nice workaround or - even better - someone from realm could write about future plans about structs.

Body:
Swift 4 shortest answer

Save structs as Data in Realm

struct MyStruct : Codable { // Variables here }

class MyRealObject : Object {

    @objc private dynamic var structData:Data? = nil

    var myStruct : MyStruct? {
        get {
            if let data = structData {
                return try? JSONDecoder().decode(MyStruct.self, from: data)
            }
            return nil
        }
        set {
            structData = try? JSONEncoder().encode(newValue)
        }
    }
}

Use the magic

let realm = try! Realm()
try! realm.write {
      let myReal = MyRealObject()
      myReal.myStruct = MyStruct(....)
      realm.add(myReal)
}

ContentLicense: CC BY-SA 4.0


问:
How to concatenate multiple VARCHAR columns into single CLOB or LONG column in Oracle
So I have several VARCHAR(4000) columns that are filled to the MAX in my Oracle SQL Table. I am trying to concatenate/combine them into a single column (LONG or CLOB). How do I do this? I've tried concatentate and obviously that doesn't work... I receive 'a result of string concatenation is too long' error.

I've tried the following:
   select id, (comment_1 || comment_2)
   from table
   group by id;

Thanks in advance!

答: You can use select id, to_clob(comment1) || comment2 from table group by id. But generally better way is modify the database design and add clob column into the table.


问:
What is "stdafx.h" used for in Visual Studio?
A file named stdafx.h is automatically generated when I start a project in Visual Studio 2010. I need to make a cross-platform C++ library, so I don't/can't use this header file.

What is stdafx.h used for? Is it OK that I just remove this header file?

答:
All C++ compilers have one serious performance problem to deal with. Compiling C++ code is a long, slow process.

Compiling headers included on top of C++ files is a very long, slow process. Compiling the huge header structures that form part of Windows API and other large API libraries is a very, very long, slow process. To have to do it over, and over, and over for every single Cpp source file is a death knell.

This is not unique to Windows but an old problem faced by all compilers that have to compile against a large API like Windows.

The Microsoft compiler can ameliorate this problem with a simple trick called precompiled headers. The trick is pretty slick: although every CPP file can potentially and legally give a sligthly different meaning to the chain of header files included on top of each Cpp file (by things like having different macros #define'd in advance of the includes, or by including the headers in different order), that is most often not the case. Most of the time, we have dozens or hundreds of included files, but they all are intended to have the same meaning for all the Cpp files being compiled in your application.

The compiler can make huge time savings if it doesn't have to start to compile every Cpp file plus its dozens of includes literally from scratch every time.

The trick consists of designating a special header file as the starting point of all compilation chains, the so called 'precompiled header' file, which is commonly a file named stdafx.h simply for historical reasons.

Simply list all your big huge headers for your APIs in your stdafx.h file, in the appropriate order, and then start each of your CPP files at the very top with an #include "stdafx.h", before any meaningful content (just about the only thing allowed before is comments).

Under those conditions, instead of starting from scratch, the compiler starts compiling from the already saved results of compiling everything in stdafx.h.

I don't believe that this trick is unique to Microsoft compilers, nor do I think it was an original development.

For Microsoft compilers, the setting that controls the use of precompiled headers is controlled by a command line argument to the compiler: /Yu "stdafx.h". As you can imagine, the use of the stdafx.h file name is simply a convention; you can change the name if you so wish.

In Visual Studio 2010, this setting is controlled from the GUI via Right-clicking on a CPP Project, selecting 'Properties' and navigating to "Configuration Properties\C/C++\Precompiled Headers". For other versions of Visual Studio, the location in the GUI will be different.

Note that if you disable precompiled headers (or run your project through a tool that doesn't support them), it doesn't make your program illegal; it simply means that your tool will compile everything from scratch every time.

If you are creating a library with no Windows dependencies, you can easily comment out or remove #includes from the stdafx.h file. There is no need to remove the file per se, but clearly you may do so as well, by disabling the precompile header setting above.


问:
Search boolean matrix using pyspark
I have a boolean matrix of M x N, where M = 6000 and N = 1000

```<code>1 | 0 1 0 0 0 1 ----> 1000
2 | 1 0 1 0 1 0 ----> 1000
3 | 0 0 1 1 0 0 ----> 1000
  V
6000
</code>```

Now for each column, I want to find the first occurrence where the value is 1. For the above example, in the first 5 columns, I want 2 1 2 3 2 1.

Now the code I have is

```<code>    sig_matrix = list()
    num_columns = df.columns
    for col_name in num_columns:
        print('Processing column {}'.format(col_name))
        sig_index = df.filter(df[col_name] == 1).\
                    select('perm').limit(1).collect()[0]['perm']
        sig_matrix.append(sig_index)
</code>```

Now the above code is really slow and it takes 5~7 minutes for me to parse 1000 columns is there any faster ways to do this instead of what I am doing? I am also willing to use pandas data frame instead of pyspark dataframe if that is faster.

答:
Here is a numpy version that runs <1s for me, so should be preferable for this size of data:

```<code>arr=np.random.choice([0,1], size=(6000,1000))
[np.argwhere(arr[:,i]==1.)[0][0] for i in range(1000)]
</code>```

There could well be more efficient numpy solutions.

Title: Search boolean matrix using pyspark

Body:
I have a boolean matrix of M x N, where M = 6000 and N = 1000

1 | 0 1 0 0 0 1 ----> 1000
2 | 1 0 1 0 1 0 ----> 1000
3 | 0 0 1 1 0 0 ----> 1000
  V
6000

Now for each column, I want to find the first occurrence where the value is 1. For the above example, in the first 5 columns, I want 2 1 2 3 2 1.

Now the code I have is

    sig_matrix = list()
    num_columns = df.columns
    for col_name in num_columns:
        print('Processing column {}'.format(col_name))
        sig_index = df.filter(df[col_name] == 1).\
                    select('perm').limit(1).collect()[0]['perm']
        sig_matrix.append(sig_index)

Now the above code is really slow and it takes 5~7 minutes for me to parse 1000 columns is there any faster ways to do this instead of what I am doing? I am also willing to use pandas data frame instead of pyspark dataframe if that is faster.

Body:
Here is a numpy version that runs <1s for me, so should be preferable for this size of data:

arr=np.random.choice([0,1], size=(6000,1000))
[np.argwhere(arr[:,i]==1.)[0][0] for i in range(1000)]

There could well be more efficient numpy solutions.


问:
Not able to change data stored in mongoDb database in Nodejs
I wanna change button value after it submits a data into database,I've assigned a variable to button text and tried to set it's value from backend
but it is not working

Here's my code

BACKEND

```<code>//after click action
 router.post('/accept/:id',isLoggedIn,function(req,res){

 User.findByIdAndUpdate(req.user._id, {$set:
        {'friendRequest.Status':'Accepted'}},function(err,founduser){
          if (err) {
            console.log(err);
          } else {

               res.render('friendrequest',{user:founduser});
          }
        })
    })
</code>```

DATABASE MODEL

Here I put default value of button to "Accept" which should change to Accepted

```<code>    var  mongoose = require('mongoose');
    var passportLocalMongoose = require('passport-local-mongoose');

    var UserSchema = new mongoose.Schema({
    username:String,
    password :String,

      friendRequest:[{      //Target database model
        id:{
        type : mongoose.Schema.Types.ObjectId,
        ref : "User"
      },
        username: String,
     Status:{type:String,default:"Accept" }  //default value of button
    }]

    UserSchema.plugin(passportLocalMongoose);

    module.exports = mongoose.model("User",UserSchema);
</code>```

FRONT END

```<code> <h3 id='username'><%= request.username %></h3>

</div>
<div  class="four wide column">
<form  action = "/accept/<%=user.id%>" method = "post">
<button id="add" class="ui  medium  blue button"><%=request.Status%>
</button>
</form>
</code>```

Or ,If any other method you can suggest which can work this out

答:
To update object in an array use $ to match all indexes :

```<code>{$set: {'friendRequest.$.Status':'Accepted'}}
</code>```

This will update all friendRequest of the user to the status Accepted.

Body:
I wanna change button value after it submits a data into database,I've assigned a variable to button text and tried to set it's value from backend
but it is not working

Here's my code

BACKEND

//after click action
 router.post('/accept/:id',isLoggedIn,function(req,res){

 User.findByIdAndUpdate(req.user._id, {$set:
        {'friendRequest.Status':'Accepted'}},function(err,founduser){
          if (err) {
            console.log(err);
          } else {

               res.render('friendrequest',{user:founduser});
          }
        })
    })

DATABASE MODEL

Here I put default value of button to "Accept" which should change to Accepted

    var  mongoose = require('mongoose');
    var passportLocalMongoose = require('passport-local-mongoose');

    var UserSchema = new mongoose.Schema({
    username:String,
    password :String,

      friendRequest:[{      //Target database model
        id:{
        type : mongoose.Schema.Types.ObjectId,
        ref : "User"
      },
        username: String,
     Status:{type:String,default:"Accept" }  //default value of button
    }]

    UserSchema.plugin(passportLocalMongoose);

    module.exports = mongoose.model("User",UserSchema);

FRONT END

<%= request.username %>

<form  action = "/accept/<%=user.id%>" method = "post">
<button id="add" class="ui  medium  blue button"><%=request.Status%>
</button>
</form>

Or ,If any other method you can suggest which can work this out

Body:
To update object in an array use $ to match all indexes :

{$set: {'friendRequest.$.Status':'Accepted'}}

This will update all friendRequest of the user to the status Accepted.


问:
Personal Access token in Gist
I've created a personal access token (https://github.com/settings/tokens) giving Gist perms.

I'm trying to use it to create a gist but I'm getting

```<code>{
  "message": "Not Found",
  "documentation_url": "https://developer.github.com/v3"
}
</code>```

My request is:

```<code>POST /gist HTTP/1.1
Host: api.github.com
Connection: close
X-Client-Data: CJO2yQEIorbJAQjBtskBCPqcygEIqZ3KAQjSncoBCKijygE=
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
Accept-Language: en-US,en;q=0.8,es;q=0.6
Authorization: Basic blablablablablabla
Content-Length: 142

{
  "description": "the description for this gist",
  "files": {
    "file1.txt": {
      "content": "String file contents"
    }
  }
}
</code>```

Can't personal tokens being used to post in gist?

答:
The problem is that Basic authentication should not be used but a specific header to provide the token. The request should be:</p>

```<code>POST /gist HTTP/1.1
Host: api.github.com
Connection: close
X-Client-Data: CJO2yQEIorbJAQjBtskBCPqcygEIqZ3KAQjSncoBCKijygE=
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
Accept-Language: en-US,en;q=0.8,es;q=0.6
Authorization: token aabbaabbaabbabababababababababababababab
Content-Length: 142

{
  "description": "the description for this gist",
  "files": {
    "file1.txt": {
      "content": "String file contents"
    }
  }
}
</code>```

Title: Personal Access token in Gist

Body:
I've created a personal access token (https://github.com/settings/tokens) giving Gist perms.

I'm trying to use it to create a gist but I'm getting

{
  "message": "Not Found",
  "documentation_url": "https://developer.github.com/v3"
}

My request is:

POST /gist HTTP/1.1
Host: api.github.com
Connection: close
X-Client-Data: CJO2yQEIorbJAQjBtskBCPqcygEIqZ3KAQjSncoBCKijygE=
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
Accept-Language: en-US,en;q=0.8,es;q=0.6
Authorization: Basic blablablablablabla
Content-Length: 142

{
  "description": "the description for this gist",
  "files": {
    "file1.txt": {
      "content": "String file contents"
    }
  }
}

Can't personal tokens being used to post in gist?

Body:
The problem is that Basic authentication should not be used but a specific header to provide the token. The request should be:

POST /gist HTTP/1.1
Host: api.github.com
Connection: close
X-Client-Data: CJO2yQEIorbJAQjBtskBCPqcygEIqZ3KAQjSncoBCKijygE=
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
Accept-Language: en-US,en;q=0.8,es;q=0.6
Authorization: token aabbaabbaabbabababababababababababababab
Content-Length: 142

{
  "description": "the description for this gist",
  "files": {
    "file1.txt": {
      "content": "String file contents"
    }
  }
}


问:
Getting Access-Control-Allow-Headers in preflight error
I have created angular js app in which I have integrate twitch api , the api is

```<code> return $http({
        url: "https://api.twitch.tv/kraken/streams",
        method: "GET",
        params: { channel: channel, limit: 1 },
        headers: { "Client-Id": "XXXXXXXXXXXXXXX" }
    })
</code>```

the problem is when I reload the page the api is working but when my state changes without page reload I am getting cross origin error from this api.
the error is

Failed to load https://api.twitch.tv/kraken/streams?channel=eliazOne&limit=1: Request header field RefreshToken is not allowed by Access-Control-Allow-Headers in preflight response.

anyone has idea how to resolve cross error

答:
You need to add a ?callback=? with the URL you are passing along with a callback function. Please follow the link How to use JQuery to Access Twitch streams
This is JQuery example but the concept is same.

$.getJSON('https://api.twitch.tv/kraken/streams/' + name + '?callback=?',
    function(channel){
        if (channel["stream"] == null) {
            $("#all").append("
" + channel._links.self + "
");
        }
        else {
           $("#all").append("
Fail
");
        }
    });
});```

Body:
I have created angular js app in which I have integrate twitch api , the api is

 return $http({
        url: "https://api.twitch.tv/kraken/streams",
        method: "GET",
        params: { channel: channel, limit: 1 },
        headers: { "Client-Id": "XXXXXXXXXXXXXXX" }
    })

the problem is when I reload the page the api is working but when my state changes without page reload I am getting cross origin error from this api.
the error is

Failed to load https://api.twitch.tv/kraken/streams?channel=eliazOne&limit=1: Request header field RefreshToken is not allowed by Access-Control-Allow-Headers in preflight response.

anyone has idea how to resolve cross error

Body:
You need to add a ?callback=? with the URL you are passing along with a callback function. Please follow the link How to use JQuery to Access Twitch streams
This is JQuery example but the concept is same.

$.getJSON('https://api.twitch.tv/kraken/streams/' + name + '?callback=?',
    function(channel){
        if (channel["stream"] == null) {
            $("#all").append("<p>" + channel._links.self + "</p>");
        }
        else {
           $("#all").append("<p>Fail</p>");
        }
    });
});


问:
Java Loop CSV reading
I have CSV reader that reads each line of data and prints it out to the console, the code that does this is below:

```<code>public void getFiles() throws IOException {

    String fileName = "CSV_FILENAME";

    try (CSVReader reader = new CSVReader(new FileReader(fileName))) {
        HeaderColumnNameMappingStrategy<Steps> steps =
                new HeaderColumnNameMappingStrategy<>();
        steps.setType(Steps.class);

        CsvToBean<Steps> csvToBean = new CsvToBean<>();
        List<Steps> beanList = csvToBean.parse(steps, reader);

        for (Steps step : beanList) {
            System.out.println(step);
        }

        Steps();
    }
}
</code>```

My question is how do I get this to print out just the first row, then keep looping backround and printing each row.

So call that method, print out row 1.
Then go back round and do the next row and so on until its read every single row.

答:
You can check the count by doing this:

```<code>int count = 0;
int stop = 1;
for (Steps step : beanList) {
    if(count != stop){
        System.out.println(step);
    }
    count++;
}
</code>```

this way you can even change the number of times it prints if you want to increase it

Title: Java Loop CSV reading

Body:
I have CSV reader that reads each line of data and prints it out to the console, the code that does this is below:

public void getFiles() throws IOException {

    String fileName = "CSV_FILENAME";

    try (CSVReader reader = new CSVReader(new FileReader(fileName))) {
        HeaderColumnNameMappingStrategy<Steps> steps =
                new HeaderColumnNameMappingStrategy<>();
        steps.setType(Steps.class);

        CsvToBean<Steps> csvToBean = new CsvToBean<>();
        List<Steps> beanList = csvToBean.parse(steps, reader);

        for (Steps step : beanList) {
            System.out.println(step);
        }

        Steps();
    }
}

My question is how do I get this to print out just the first row, then keep looping backround and printing each row.

So call that method, print out row 1.
Then go back round and do the next row and so on until its read every single row.

Body:
You can check the count by doing this:

int count = 0;
int stop = 1;
for (Steps step : beanList) {
    if(count != stop){
        System.out.println(step);
    }
    count++;
}

this way you can even change the number of times it prints if you want to increase it


问:
How can I get property name strings used in a Func of T
I have a scenario where I have to get an array of strings that represent each of the property names used within a Func parameter.  Here is an example implementation:

```<code>public class CustomClass<TSource>
{
  public string[] GetPropertiesUsed
  {
    get
    {
      // do magical parsing based upon parameter passed into CustomMethod
    }
  }

  public void CustomMethod(Func<TSource, object> method)
  {
    // do stuff
  }
}
</code>```

Here would be an example usage:

```<code>var customClass = new CustomClass<Person>();
customClass.CustomMethod(src => "(" + src.AreaCode + ") " + src.Phone);

...

var propertiesUsed = customClass.GetPropertiesUsed;
// propertiesUsed should contain ["AreaCode", "Phone"]
</code>```

The part I'm stuck on in the above is the "do magical parsing based upon parameter passed into CustomMethod."

答:
You'll need to change your CustomMethod to take an Expression<Func<TSource, object>>, and probably subclass the ExpressionVisitor, overriding VisitMember:

```<code>public void CustomMethod(Expression<Func<TSource, object>> method)
{
     PropertyFinder lister = new PropertyFinder();
     properties = lister.Parse((Expression) expr);
}

// this will be what you want to return from GetPropertiesUsed
List<string> properties;

public class PropertyFinder : ExpressionVisitor
{
    public List<string> Parse(Expression expression)
    {
        properties.Clear();
        Visit(expression);
        return properties;
    }

    List<string> properties = new List<string>();

    protected override Expression VisitMember(MemberExpression m)
    {
        // look at m to see what the property name is and add it to properties
        ... code here ...
        // then return the result of ExpressionVisitor.VisitMember
        return base.VisitMember(m);
    }
}
</code>```

This should get you started in the right direction.  Let me know if you need some help figuring out the "... code here ..." part.

Useful links:

Expression Trees

How to Modify Expression Trees

ExpressionVisitor

VisitMember

MemberExpression

ContentLicense: CC BY-SA 2.5

Body:
I have a scenario where I have to get an array of strings that represent each of the property names used within a Func parameter.  Here is an example implementation:

public class CustomClass<TSource>
{
  public string[] GetPropertiesUsed
  {
    get
    {
      // do magical parsing based upon parameter passed into CustomMethod
    }
  }

  public void CustomMethod(Func<TSource, object> method)
  {
    // do stuff
  }
}

Here would be an example usage:

var customClass = new CustomClass<Person>();
customClass.CustomMethod(src => "(" + src.AreaCode + ") " + src.Phone);

...

var propertiesUsed = customClass.GetPropertiesUsed;
// propertiesUsed should contain ["AreaCode", "Phone"]

The part I'm stuck on in the above is the "do magical parsing based upon parameter passed into CustomMethod."

Body:
You'll need to change your CustomMethod to take an Expression<Func<TSource, object>>, and probably subclass the ExpressionVisitor, overriding VisitMember:

public void CustomMethod(Expression<Func<TSource, object>> method)
{
     PropertyFinder lister = new PropertyFinder();
     properties = lister.Parse((Expression) expr);
}

// this will be what you want to return from GetPropertiesUsed
List<string> properties;

public class PropertyFinder : ExpressionVisitor
{
    public List<string> Parse(Expression expression)
    {
        properties.Clear();
        Visit(expression);
        return properties;
    }

    List<string> properties = new List<string>();

    protected override Expression VisitMember(MemberExpression m)
    {
        // look at m to see what the property name is and add it to properties
        ... code here ...
        // then return the result of ExpressionVisitor.VisitMember
        return base.VisitMember(m);
    }
}

This should get you started in the right direction.  Let me know if you need some help figuring out the "... code here ..." part.

Useful links:

Expression Trees

How to Modify Expression Trees

ExpressionVisitor

VisitMember

MemberExpression


问:
Write to a file Xcode MacOS
I'm unable to run this piece of code which writes the pid to a file.

```<code>NSString *text = [NSString stringWithFormat:@"%d\n", getpid()];
NSError *error = nil;

if (![text writeToFile:@"/tmp/Frontend.pid" atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
    NSLog(@"Cannot write PID file %@: %@", @"/tmp/Frontend.pid", error);
    return NO;
}
</code>```

This is the error I get.

2017-11-13 20:19:18.742171+0530 TestThread[7648:273326] Cannot write PID file /tmp/Frontend.pid: Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “Frontend.pid” in the folder “tmp”." UserInfo={NSFilePath=/tmp/Frontend.pid, NSUnderlyingError=0x6040000432a0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

I've changed the permission for the directory to 777 and it still doesn't have enough permissions. Please help.

答:
/tmp is a symlink to /private/tmp on macOS. Did you change the permissions of the link, or of the destination?

For example, on my machine I see the following:

```<code>$ ls -ld /tmp
lrwxr-xr-x@ 1 root  wheel  11 Oct 14 14:55 /tmp -> private/tmp
$ ls -ld /private/tmp
drwxrwxrwt  16 root  wheel  512 Nov 13 06:43 /private/tmp
</code>```

This means that only root can modify the link, but anyone should be able to write to the directory. Indeed, I can write files in that directory just fine. Because of the t sticky bit, only users that own the file itself in /tmp (or root or wheel) can delete/rename the file.

I would check that you don't already have a file at /tmp/Frontend.pid with permissions set in such a way that it cannot be overwritten (writeToFile:atomically:encoding:error will overwrite existing files).

Title: Write to a file Xcode MacOS

Body:
I'm unable to run this piece of code which writes the pid to a file.

NSString *text = [NSString stringWithFormat:@"%d\n", getpid()];
NSError *error = nil;

if (![text writeToFile:@"/tmp/Frontend.pid" atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
    NSLog(@"Cannot write PID file %@: %@", @"/tmp/Frontend.pid", error);
    return NO;
}

This is the error I get.

2017-11-13 20:19:18.742171+0530 TestThread[7648:273326] Cannot write PID file /tmp/Frontend.pid: Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “Frontend.pid” in the folder “tmp”." UserInfo={NSFilePath=/tmp/Frontend.pid, NSUnderlyingError=0x6040000432a0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

I've changed the permission for the directory to 777 and it still doesn't have enough permissions. Please help.

Body:
/tmp is a symlink to /private/tmp on macOS. Did you change the permissions of the link, or of the destination?

For example, on my machine I see the following:

$ ls -ld /tmp
lrwxr-xr-x@ 1 root  wheel  11 Oct 14 14:55 /tmp -> private/tmp
$ ls -ld /private/tmp
drwxrwxrwt  16 root  wheel  512 Nov 13 06:43 /private/tmp

This means that only root can modify the link, but anyone should be able to write to the directory. Indeed, I can write files in that directory just fine. Because of the t sticky bit, only users that own the file itself in /tmp (or root or wheel) can delete/rename the file.

I would check that you don't already have a file at /tmp/Frontend.pid with permissions set in such a way that it cannot be overwritten (writeToFile:atomically:encoding:error will overwrite existing files).


问:
How to shrink-wrap a css grid?
Assuming the following grid layout:

div {
  display: grid;
  grid-template-columns: auto auto;
  grid-row-gap: 1em;
  border: 5px solid green;
  margin: 50px;
}
h3 {
  grid-column: 1 / -1;
  margin: 0;
}
span {
  background-color: pink;
}
h3, span {
  padding: 0.5em;
}
span + span {
  background-color: salmon;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h3>1. A heading here</h3>
  <span>some text here</span>
  <span>some  more text here as well thanks</span>
</div></code>```

I would like to 'shrink-wrap' the grid items so that

1) the maximum width of the grid will only be as wide as the content, but

2) if there's not enough room for the content - the items will wrap accordingly.

In the above demo, the first constraint fails - the grid columns stretch to fit their respective content and all the extra viewport width is split equally (added) between the columns.

Codepen demo - (Resize to see what I'm talking about)

I've tried a few approaches to fix this, but they all 'shrink-wrap' the grid items as apposed to the actual grid itself:

1) Set max-content as the track length instead of auto

```<code>grid-template-columns: max-content max-content;
</code>```

div {
  display: grid;
  grid-template-columns: max-content max-content;
  grid-row-gap: 1em;
  border: 5px solid green;
  margin: 50px;
}
h3 {
  grid-column: 1 / -1;
  margin: 0;
}
span {
  background-color: pink;
}
h3, span {
  padding: 0.5em;
}
span + span {
  background-color: salmon;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h3>1. A heading here</h3>
  <span>some text here</span>
  <span>some text here</span>
</div></code>```

2) Set justify-content: flex-start; on the grid container

div {
  display: grid;
  grid-template-columns: auto auto;
  grid-row-gap: 1em;
  border: 5px solid green;
  margin: 50px;
  justify-content: flex-start;
}
h3 {
  grid-column: 1 / -1;
  margin: 0;
}
span {
  background-color: pink;
}
h3, span {
  padding: 0.5em;
}
span + span {
  background-color: salmon;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h3>1. A heading here</h3>
  <span>some text here</span>
  <span>some text here</span>
</div></code>```

3) Add a bogus 3rd column which fills the remaining viewport width with an empty third column:

```<code>grid-template-columns: auto auto 1fr;
</code>```

div {
  display: grid;
  grid-template-columns: auto auto 1fr;
  grid-row-gap: 1em;
  border: 5px solid green;
  margin: 50px;
}
h3 {
  grid-column: 1 / -1;
  margin: 0;
}
span {
  background-color: pink;
}
h3, span {
  padding: 0.5em;
}
span + span {
  background-color: salmon;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h3>1. A heading here</h3>
  <span>some text here</span>
  <span>some text here</span>
</div></code>```

So how would I 'shrink-wrap' the grid?

答:
Setting display: grid on an element causes it to generate a block-level grid container box.

This is what causes the grid to fill the viewport width and stretch the items accordingly.

That being the case, we can stop the grid from stretching by setting one of the following on the grid container:

1) display: inline-grid;

div {
  display: inline-grid; /* <-- modified */
  grid-template-columns: auto auto;
  grid-row-gap: 1em;
  border: 5px solid green;
  margin: 50px;
}
h3 {
  grid-column: 1 / -1;
  margin: 0;
}
span {
  background-color: pink;
}
h3, span {
  padding: 0.5em;
}
span + span {
  background-color: salmon;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h3>1. A heading here</h3>
  <span>some text here</span>
  <span>some text here</span>
</div></code>```

2) float: left; /* or right */

div {
  display: grid;
  float: left; /* <-- added */
  grid-template-columns: auto auto;
  grid-row-gap: 1em;
  border: 5px solid green;
  margin: 50px;
}
h3 {
  grid-column: 1 / -1;
  margin: 0;
}
span {
  background-color: pink;
}
h3, span {
  padding: 0.5em;
}
span + span {
  background-color: salmon;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h3>1. A heading here</h3>
  <span>some text here</span>
  <span>some text here</span>
</div></code>```

3) position: absolute;

div {
  display: grid;
  position: absolute; /* <--- added */
  grid-template-columns: auto auto;
  grid-row-gap: 1em;
  border: 5px solid green;
  margin: 50px;
}
h3 {
  grid-column: 1 / -1;
  margin: 0;
}
span {
  background-color: pink;
}
h3, span {
  padding: 0.5em;
}
span + span {
  background-color: salmon;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h3>1. A heading here</h3>
  <span>some text here</span>
  <span>some text here</span>
</div></code>```

Alternatively, we could set width: fit-content on grid container.

div {
  display: grid;
  grid-template-columns: auto auto;
  grid-row-gap: 1em;
  border: 5px solid green;
  margin: 50px;
  width: fit-content; /* <-- added */
}
h3 {
  grid-column: 1 / -1;
  margin: 0;
}
span {
  background-color: pink;
}
h3, span {
  padding: 0.5em;
}
span + span {
  background-color: salmon;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h3>1. A heading here</h3>
  <span>some text here</span>
  <span>some text here</span>
</div></code>```

Title: How to shrink-wrap a css grid?

Body:
Assuming the following grid layout:

div {
  display: grid;
  grid-template-columns: auto auto;
  grid-row-gap: 1em;
  border: 5px solid green;
  margin: 50px;
}
h3 {
  grid-column: 1 / -1;
  margin: 0;
}
span {
  background-color: pink;
}
h3, span {
  padding: 0.5em;
}
span + span {
  background-color: salmon;
}

1. A heading here

  some text here
  some  more text here as well thanks

I would like to 'shrink-wrap' the grid items so that

1) the maximum width of the grid will only be as wide as the content, but

2) if there's not enough room for the content - the items will wrap accordingly.

In the above demo, the first constraint fails - the grid columns stretch to fit their respective content and all the extra viewport width is split equally (added) between the columns.

Codepen demo - (Resize to see what I'm talking about)

I've tried a few approaches to fix this, but they all 'shrink-wrap' the grid items as apposed to the actual grid itself:

1) Set max-content as the track length instead of auto

grid-template-columns: max-content max-content;

div {
  display: grid;
  grid-template-columns: max-content max-content;
  grid-row-gap: 1em;
  border: 5px solid green;
  margin: 50px;
}
h3 {
  grid-column: 1 / -1;
  margin: 0;
}
span {
  background-color: pink;
}
h3, span {
  padding: 0.5em;
}
span + span {
  background-color: salmon;
}

1. A heading here

  some text here
  some text here

2) Set justify-content: flex-start; on the grid container

div {
  display: grid;
  grid-template-columns: auto auto;
  grid-row-gap: 1em;
  border: 5px solid green;
  margin: 50px;
  justify-content: flex-start;
}
h3 {
  grid-column: 1 / -1;
  margin: 0;
}
span {
  background-color: pink;
}
h3, span {
  padding: 0.5em;
}
span + span {
  background-color: salmon;
}

1. A heading here

  some text here
  some text here

3) Add a bogus 3rd column which fills the remaining viewport width with an empty third column:

grid-template-columns: auto auto 1fr;

div {
  display: grid;
  grid-template-columns: auto auto 1fr;
  grid-row-gap: 1em;
  border: 5px solid green;
  margin: 50px;
}
h3 {
  grid-column: 1 / -1;
  margin: 0;
}
span {
  background-color: pink;
}
h3, span {
  padding: 0.5em;
}
span + span {
  background-color: salmon;
}

1. A heading here

  some text here
  some text here

So how would I 'shrink-wrap' the grid?

Body:
Setting display: grid on an element causes it to generate a block-level grid container box.

This is what causes the grid to fill the viewport width and stretch the items accordingly.

That being the case, we can stop the grid from stretching by setting one of the following on the grid container:

1) display: inline-grid;

div {
  display: inline-grid; /* <-- modified */
  grid-template-columns: auto auto;
  grid-row-gap: 1em;
  border: 5px solid green;
  margin: 50px;
}
h3 {
  grid-column: 1 / -1;
  margin: 0;
}
span {
  background-color: pink;
}
h3, span {
  padding: 0.5em;
}
span + span {
  background-color: salmon;
}

<div>
  <h3>1. A heading here</h3>
  <span>some text here</span>
  <span>some text here</span>
</div>

2) float: left; /* or right */

div {
  display: grid;
  float: left; /* <-- added */
  grid-template-columns: auto auto;
  grid-row-gap: 1em;
  border: 5px solid green;
  margin: 50px;
}
h3 {
  grid-column: 1 / -1;
  margin: 0;
}
span {
  background-color: pink;
}
h3, span {
  padding: 0.5em;
}
span + span {
  background-color: salmon;
}

<div>
  <h3>1. A heading here</h3>
  <span>some text here</span>
  <span>some text here</span>
</div>

3) position: absolute;

div {
  display: grid;
  position: absolute; /* <--- added */
  grid-template-columns: auto auto;
  grid-row-gap: 1em;
  border: 5px solid green;
  margin: 50px;
}
h3 {
  grid-column: 1 / -1;
  margin: 0;
}
span {
  background-color: pink;
}
h3, span {
  padding: 0.5em;
}
span + span {
  background-color: salmon;
}

<div>
  <h3>1. A heading here</h3>
  <span>some text here</span>
  <span>some text here</span>
</div>

Alternatively, we could set width: fit-content on grid container.

div {
  display: grid;
  grid-template-columns: auto auto;
  grid-row-gap: 1em;
  border: 5px solid green;
  margin: 50px;
  width: fit-content; /* <-- added */
}
h3 {
  grid-column: 1 / -1;
  margin: 0;
}
span {
  background-color: pink;
}
h3, span {
  padding: 0.5em;
}
span + span {
  background-color: salmon;
}

<div>
  <h3>1. A heading here</h3>
  <span>some text here</span>
  <span>some text here</span>
</div>


问:
Removing supplementary characters from a Java string
I have a Java string that contains supplementary characters (characters in the Unicode standard whose code points are above U+FFFF). These characters could for example be emojis. I want to remove those characters from the string, i.e. replace them with the empty string "".

How do I remove supplementary characters from a string?

How do I remove characters from an arbitrary code point range? (For example all characters in the range 1F000–1FFFF)?

答:
There are a couple of approaches. As regex replace is expensive, maybe do:</p>

```<code>String basic(String s) {
    StringBuilder sb = new StringBuilder();
    for (char ch : s.toCharArray()) {
        if (!Character.isLowSurrogate(ch) && !Character.isHighSurrogate(ch)) {
            sb.append(ch);
        }
    }
    return sb.length() == s.length() ? s : sb.toString();
}
</code>```

Body:
There are a couple of approaches. As regex replace is expensive, maybe do:

String basic(String s) {
    StringBuilder sb = new StringBuilder();
    for (char ch : s.toCharArray()) {
        if (!Character.isLowSurrogate(ch) && !Character.isHighSurrogate(ch)) {
            sb.append(ch);
        }
    }
    return sb.length() == s.length() ? s : sb.toString();
}


问:
WPForms textarea doesn't display when published on a page in WordPress?
I'm using Be Theme in WordPress, and I'm using WPForms to create a contact form.

The form was set up correctly in the WPForms Builder (as far as I am aware), and I'm using the following shortcode in the SiteOrigin Editor (with paragraph turned off): [wpforms id="397" title="false" description="false"]

And this is the result:

Contact form with no textareas

I was thinking maybe there was a conflict between the SiteOrigin / WPForms / Be Theme, but I'm not sure. I also did some searching on Google, but I couldn't seem to find anything that addressed this exact situation that I'm dealing with.

Thank you to anyone who decides to help!

答:
I found a solution!

I was using some CSS (to get rid of this ugly line that went through the page), and I guess it also disabled the input fields.

It's fixed now!


问:
Add text inside select tag next to the value
I would like to know how to add a text next to a value inside ? Do I have to use CSS for this?

I'm not really sure how to specify the question, hopefully someone will understand from the pictures!

How the select looks per default

How it looks when choosing a value

Edit:

I don't have the actual code for this example, so I'm starting from scratch with:

```<code>    <strong>I represent:</strong>
    <select name="select">
        <option value="media">Media</option>
        <option value="travel-trade">Travel Trade</option>
        <option value="congress-org">Congress organization</option>
        <option value="cityhelsinki">City of Helsinki</option>
        <option value="other">Other</option>
     </select>
</code>```

So I would like the "I represent:" text inside the select

答:
Add label infront of the select and style it with css to look like you want to.
If you want it inside the select you can add it to every option.</p>

Body:
I would like to know how to add a text next to a value inside ? Do I have to use CSS for this?

I'm not really sure how to specify the question, hopefully someone will understand from the pictures!

How the select looks per default

How it looks when choosing a value

Edit:

I don't have the actual code for this example, so I'm starting from scratch with:

    I represent:
    <select name="select">
        <option value="media">Media</option>
        <option value="travel-trade">Travel Trade</option>
        <option value="congress-org">Congress organization</option>
        <option value="cityhelsinki">City of Helsinki</option>
        <option value="other">Other</option>
     </select>

So I would like the "I represent:" text inside the select


问:
Use of GetGuiResources
Is it a good idea to use GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS) at the start of WinMain, and before the last return to detect GDI leaks or, more specifically, objects I forgot to release?
Also I'm currently wondering why the first call in my program returns 4 when there's no window yet.

答:
While this will tell you if you've leaked any GDI objects, it won't tell you anything about which GDI objects you've leaked. In a non-trivial program, I don't see this helping very much.

If you want to track GDI objects, I believe that there are some Performance Counters that display the number of GDI object handles that are currently allocated in a process. You could watch that over time to get a better idea of where your program is leaking.

OwnerDisplayName: Zub

Title: Use of GetGuiResources

OwnerDisplayName: Andy


问:
How Do I collapse rows on null values in t-sql?
I'm in a weird situation with my query. My objective is to display the total deposits and withdrawals from multiple transactions for each person and display them. I am getting multiple rows that I need to collapse into one. This all needs to happen in one query

```<code>SELECT
       lastname,
       firsname,
       case when upper(category) = 'W' then sum(abs(principal)) end as Withdrawal,
       case when upper(category) = 'D' then sum(abs(principal)) end as Deposit,
       description
FROM
       table1
       JOIN table2 ON table1.id = table2.id
       JOIN table3 ON table2.c = table3.c
WHERE
       description = 'string'
GROUP BY
       lastname,
       firstname,
       description,
       category
</code>```

my result is

```<code> lastname    firstname    Withdrawal    Deposit    description
 john         smith       null           140.34    string
 john         smith       346.00          null     string
 jane         doe         null           68.03     string
 jane         doe         504.00          null     string
</code>```

and I am looking for

```<code> lastname    firstname    Withdrawal    Deposit    description
 john         smith       346.00        140.34     string
 jane         doe         504.00        68.03      string
</code>```

adding principal into the group does not work. any help on solving this will be greatly appreciated!

答:
Solution using Subquery</p>

```<code>select t.lastname, t.firsname,sum(t.Withdrawal) Withdrawal ,sum(t.Deposit) Deposit,t.description from(
select lastname, firsname,
       isnull(case when upper(category) = 'W' then abs(principal) end,0) as Withdrawal,
       isnull(case when upper(category) = 'D' then abs(principal) end,0) as Deposit,
description
from table1 join
     table2
     on table2.id = table1.id join
     table3
     on table3.c = table2.c
where description = 'string'
)t group by t.lastname, t.firstname, t.description, t.category
</code>```

Body:
I'm in a weird situation with my query. My objective is to display the total deposits and withdrawals from multiple transactions for each person and display them. I am getting multiple rows that I need to collapse into one. This all needs to happen in one query

SELECT
       lastname,
       firsname,
       case when upper(category) = 'W' then sum(abs(principal)) end as Withdrawal,
       case when upper(category) = 'D' then sum(abs(principal)) end as Deposit,
       description
FROM
       table1
       JOIN table2 ON table1.id = table2.id
       JOIN table3 ON table2.c = table3.c
WHERE
       description = 'string'
GROUP BY
       lastname,
       firstname,
       description,
       category

my result is

 lastname    firstname    Withdrawal    Deposit    description
 john         smith       null           140.34    string
 john         smith       346.00          null     string
 jane         doe         null           68.03     string
 jane         doe         504.00          null     string

and I am looking for

 lastname    firstname    Withdrawal    Deposit    description
 john         smith       346.00        140.34     string
 jane         doe         504.00        68.03      string

adding principal into the group does not work. any help on solving this will be greatly appreciated!

Body:
Solution using Subquery

select t.lastname, t.firsname,sum(t.Withdrawal) Withdrawal ,sum(t.Deposit) Deposit,t.description from(
select lastname, firsname,
       isnull(case when upper(category) = 'W' then abs(principal) end,0) as Withdrawal,
       isnull(case when upper(category) = 'D' then abs(principal) end,0) as Deposit,
description
from table1 join
     table2
     on table2.id = table1.id join
     table3
     on table3.c = table2.c
where description = 'string'
)t group by t.lastname, t.firstname, t.description, t.category


问:
What's happening when inheriting a Proxy of Class (Function) in JavaScript
I want to inherit a function with proxied constructor, like SubB below;

```<code>const Base = function () {};
Base.prototype.baseMethod = function () { return 'base method'; }

class SubA extends (new Proxy(Base, {})) {
    subMethod () { return 'sub method'; }
}

const handler = { construct: (target, args) => new target(...args) };
class SubB extends (new Proxy(Base, handler)) {
    subMethod () { return 'sub method'; }
}
</code>```

However, it does not work collectly; Subclass methods seems not to be bound in SubB.

```<code>(new SubA()).baseMethod(); //=> "base method"
(new SubB()).baseMethod(); //=> "base method"

(new SubA()).subMethod(); //=> "sub method"
(new SubB()).subMethod();
  //=> Uncaught TypeError: (intermediate value).subMethod is not a function
</code>```

What's happening in class SubB and how can I fix it (or is it possible)?

答:
You are ignoring new.target, which is why the instance that your proxied constructor creates always inherits from the Base (the target in the proxy handler) only, and not from the SubB.

You should use Reflect.construct as the default action of the construct trap:

```<code>const handler = {
  construct(target, args, newTarget) {
    return Reflect.construct(target, args, newTarget);
  }
};
class SubB extends (new Proxy(Base, handler)) {
  subMethod () { return 'sub method'; }
}
</code>```

Body:
I want to inherit a function with proxied constructor, like SubB below;

const Base = function () {};
Base.prototype.baseMethod = function () { return 'base method'; }

class SubA extends (new Proxy(Base, {})) {
    subMethod () { return 'sub method'; }
}

const handler = { construct: (target, args) => new target(...args) };
class SubB extends (new Proxy(Base, handler)) {
    subMethod () { return 'sub method'; }
}

However, it does not work collectly; Subclass methods seems not to be bound in SubB.

(new SubA()).baseMethod(); //=> "base method"
(new SubB()).baseMethod(); //=> "base method"

(new SubA()).subMethod(); //=> "sub method"
(new SubB()).subMethod();
  //=> Uncaught TypeError: (intermediate value).subMethod is not a function

What's happening in class SubB and how can I fix it (or is it possible)?

Body:
You are ignoring new.target, which is why the instance that your proxied constructor creates always inherits from the Base (the target in the proxy handler) only, and not from the SubB.

You should use Reflect.construct as the default action of the construct trap:

const handler = {
  construct(target, args, newTarget) {
    return Reflect.construct(target, args, newTarget);
  }
};
class SubB extends (new Proxy(Base, handler)) {
  subMethod () { return 'sub method'; }
}


问:
How to assign Django object ownership without explicitly declaring an owner field on all models?
I'm currently trying to figure out per user object permissions for our Django website API.

I have several models with sensitive information, that I need to be able to filter on a user basis.

For a simplified example of one of the models:

Restaurant, main customer of the website.

User, each user gets assigned a restaurant when the user account is
created. As such, a restaurant can have many users and they all
should only be able to access that restaurant's information.

Oven, which belong to a specific restaurant. A restaurant can have
many ovens.

Recipe, which belong to an oven. An oven can have many different
recipes.

Recipe Results, which belong to a recipe. There can be many different
Recipe Results belonging to the same Recipe (different ingredients
tried, etc).

There are at least 12+ different models. All models from a particular restaurant have to be hidden from other restaurants, we don't want them to be able to look at other restaurant recipes after all!

Not all models have a user = models.ForeignKey(User)

Without having to go into each one of my models and declaring owner = models.ForeignKey(User), is there a way to filter them in my API List Views and Detail Views?

Currently my List API View looks like this (simplified example):

```<code>class RecipeResultsListAPIView(ListAPIView):
    queryset = RecipeResults.objects.all()
    queryset = queryset.prefetch_related('oven')
    serializer_class = RecipeResultsListSerializer
    filter_backends = (DjangoFilterBackend,)
    filter_fields = ('id', 'time', 'oven', 'recipe_name', 'recipe_description')
    pagination_class = ExpertPageNumberPagination

    def list(self, request):
       user = User.objects.get(username=request.user)
       restaurant = Restaurant.objects.get(user=user)
       ovens = Oven.objects.filter(restaurant=restaurant)
       queryset = RecipeResults.objects.filter(oven__in=ovens)
       serializer = RecipeResultsListSerializer(queryset, many=True, context={'request':request})
       return Response(serializer.data)
</code>```

And the model for that looks like this:

```<code>class RecipeResults(models.Model):
    time = models.DateTimeField()
    oven = models.ForeignKey(Oven, on_delete=models.CASCADE)
    recipe_name = models.CharField(max_length=20)
    recipe_description = models.CharField(max_length=50)

    def __str__(self):
        return str(self.time) + ': ' + self.recipe_name + ' = ' + self.recipe_description

    def __key(self):
        return self.oven, self.time, self.recipe_name

    def __eq__(self, y):
        return isinstance(y, self.__class__) and self.__key() == y.__key()

    def __hash__(self):
        return hash(self.__key())

    class Meta:
        unique_together=(('time','recipe_name', 'oven-'),)
</code>```

Specifically looking at the modified list method, currently this works properly to filter API call results to display only those Recipe Results that belong to the user that is logged in.

What I'm trying to figure out is if there's an easier way to do this, as for each model I would have to trace back ownership to the specific restaurant which would get confusing fast as I have 12+ different models.

What I'm not sure is if declaring "owner = models.ForeignKey(User)" on each of those models is the way to go. It feels like it would create many extra steps when retrieving the data.

I have also tried

```<code>class IsOwnerOrAdmin(BasePermission):
    """
    Custom permission to only allow owners of an object to see and edit it.
    Admin users however have access to all.
    """
    def has_object_permission(self, request, view, obj):
        # Permissions are only allowed to the owner of the snippet
        if request.user.is_staff:
            return True
        return obj.user == request.user
</code>```

But this didn't seem to filter properly, and besides, not all of the models have a user field assigned to them.

Please keep in mind I'm a junior developer and I'm learning a lot as I go. I'm only working on the API side of the company. The website and schema is already a work in progress and other systems depend on it, and so I'm trying not to modify the schema or models too much (I would like to avoid this if possible, but will do it if it's the only way). I was also brought in just to work on the API at first. The company understands I'm a junior developer and I'm extremely grateful to have been given the opportunity to grow while learning this project, but this one issue seems to be giving me a lot more trouble than actually building the rest of the API for the website.

I would greatly appreciate any help I can get with this!

答:
I think you might benefit from model inheritance in this case.

You can define a base model for your owner-affected objects.

An example can look like:

```<code>class OwnedModel(models.Model):
    owner = models.ForeignKey(User)

    class Meta:
        abstract = True
</code>```

Then you can simply add this as the base for your other models:

```<code>class SomeModel(OwnedModel):
    """
    This class already has the owner field
    """
</code>```

A big downside of this approach is that you will still need a migration that will alter every involved table.

If you aren't allowed to do that, you might be able to do it with a loose, non relational approach, for example with django's permission model. You can assign automatically generated permission strings, eg: myapp.mymodel.pkey:

A final alternative is this third party source app that handles things for you: django-guardian

Body:
I'm currently trying to figure out per user object permissions for our Django website API.

I have several models with sensitive information, that I need to be able to filter on a user basis.

For a simplified example of one of the models:

Restaurant, main customer of the website.

User, each user gets assigned a restaurant when the user account is
created. As such, a restaurant can have many users and they all
should only be able to access that restaurant's information.

Oven, which belong to a specific restaurant. A restaurant can have
many ovens.

Recipe, which belong to an oven. An oven can have many different
recipes.

Recipe Results, which belong to a recipe. There can be many different
Recipe Results belonging to the same Recipe (different ingredients
tried, etc).

There are at least 12+ different models. All models from a particular restaurant have to be hidden from other restaurants, we don't want them to be able to look at other restaurant recipes after all!

Not all models have a user = models.ForeignKey(User)

Without having to go into each one of my models and declaring owner = models.ForeignKey(User), is there a way to filter them in my API List Views and Detail Views?

Currently my List API View looks like this (simplified example):

class RecipeResultsListAPIView(ListAPIView):
    queryset = RecipeResults.objects.all()
    queryset = queryset.prefetch_related('oven')
    serializer_class = RecipeResultsListSerializer
    filter_backends = (DjangoFilterBackend,)
    filter_fields = ('id', 'time', 'oven', 'recipe_name', 'recipe_description')
    pagination_class = ExpertPageNumberPagination

    def list(self, request):
       user = User.objects.get(username=request.user)
       restaurant = Restaurant.objects.get(user=user)
       ovens = Oven.objects.filter(restaurant=restaurant)
       queryset = RecipeResults.objects.filter(oven__in=ovens)
       serializer = RecipeResultsListSerializer(queryset, many=True, context={'request':request})
       return Response(serializer.data)

And the model for that looks like this:

class RecipeResults(models.Model):
    time = models.DateTimeField()
    oven = models.ForeignKey(Oven, on_delete=models.CASCADE)
    recipe_name = models.CharField(max_length=20)
    recipe_description = models.CharField(max_length=50)

    def __str__(self):
        return str(self.time) + ': ' + self.recipe_name + ' = ' + self.recipe_description

    def __key(self):
        return self.oven, self.time, self.recipe_name

    def __eq__(self, y):
        return isinstance(y, self.__class__) and self.__key() == y.__key()

    def __hash__(self):
        return hash(self.__key())

    class Meta:
        unique_together=(('time','recipe_name', 'oven-'),)

Specifically looking at the modified list method, currently this works properly to filter API call results to display only those Recipe Results that belong to the user that is logged in.

What I'm trying to figure out is if there's an easier way to do this, as for each model I would have to trace back ownership to the specific restaurant which would get confusing fast as I have 12+ different models.

What I'm not sure is if declaring "owner = models.ForeignKey(User)" on each of those models is the way to go. It feels like it would create many extra steps when retrieving the data.

I have also tried

class IsOwnerOrAdmin(BasePermission):
    """
    Custom permission to only allow owners of an object to see and edit it.
    Admin users however have access to all.
    """
    def has_object_permission(self, request, view, obj):
        # Permissions are only allowed to the owner of the snippet
        if request.user.is_staff:
            return True
        return obj.user == request.user

But this didn't seem to filter properly, and besides, not all of the models have a user field assigned to them.

Please keep in mind I'm a junior developer and I'm learning a lot as I go. I'm only working on the API side of the company. The website and schema is already a work in progress and other systems depend on it, and so I'm trying not to modify the schema or models too much (I would like to avoid this if possible, but will do it if it's the only way). I was also brought in just to work on the API at first. The company understands I'm a junior developer and I'm extremely grateful to have been given the opportunity to grow while learning this project, but this one issue seems to be giving me a lot more trouble than actually building the rest of the API for the website.

I would greatly appreciate any help I can get with this!

Body:
I think you might benefit from model inheritance in this case.

You can define a base model for your owner-affected objects.

An example can look like:

class OwnedModel(models.Model):
    owner = models.ForeignKey(User)

    class Meta:
        abstract = True

Then you can simply add this as the base for your other models:

class SomeModel(OwnedModel):
    """
    This class already has the owner field
    """

A big downside of this approach is that you will still need a migration that will alter every involved table.

If you aren't allowed to do that, you might be able to do it with a loose, non relational approach, for example with django's permission model. You can assign automatically generated permission strings, eg: myapp.mymodel.pkey:

A final alternative is this third party source app that handles things for you: django-guardian


问:
Get precise position of user device with GPS
In my Android application i need to get the traveled road with car and i check it with google android directions API and GPS.

But the problem is that some times the GPS location is not precise and i can get an error of 10Km for some lecture and that means that in a total travel of 150km my "distance traveled" can be 250km and it's wrong!

Yesterday i test it in highway and the problem is that when the marker is located out from highway, the calculation of distance traveled from my current position and the last marker located by road is very wrong (in this case out of the highway).

There is some best way for getting traveled distance with car using the phone?
Maybe some better code for getting more precise GPS position?
Here is my code:

```<code>private void getUserLocation() {

    Log.d(TAG, "getUserLocation()");
    checkLocationPermission();
    mFusedLocationClient.getLastLocation()
            .addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // Got last known location. In some rare situations this can be null.
                    if (location != null) {
                        // Logic to handle location object
                        String stringStartLat, stringStartLng;

                        double lat = location.getLatitude();
                        double lng = location.getLongitude();

                        //Start position of device
                        if (travelInfo.getStartLat() == 0 && travelInfo.getStartLng() == 0) {
                            travelInfo.setStartLat(lat);
                            travelInfo.setStartLng(lng);
                            //Set lastcoordinates equals to start
                            travelInfo.setLastLat(lat);
                            travelInfo.setLastLng(lng);
                        }
                        //Current position of device
                        travelInfo.setCurrentLat(lat);
                        travelInfo.setCurrentLng(lng);

                        stringStartLat = Double.toString(travelInfo.getStartLat());
                        stringStartLng = Double.toString(travelInfo.getStartLng());
                        //Set the TextView in the fragment with start coordinates
                        Log.d(TAG,"LatitudeStart: " + stringStartLat);
                        Log.d(TAG,"LongitudeStart: " + stringStartLng);

                        if (startMarker == null) {
                            //Add the user location to the map with a marker
                            LatLng userLoction = new LatLng(travelInfo.getStartLat(), travelInfo.getStartLng());
                            startMarker = googleMap.addMarker(new MarkerOptions()
                                    .position(userLoction)
                                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
                                    .title("Start Position")
                                    .snippet("Show the start position of user"));

                            // For zooming automatically to the location of the marker
                            CameraPosition cameraPosition = new CameraPosition.Builder().target(userLoction).zoom(9).build();
                            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        } else {

                            LatLng currentLocation = new LatLng(travelInfo.getCurrentLat(), travelInfo.getCurrentLng());
                            currentPositionMarker = googleMap.addMarker(new MarkerOptions()
                                    .position(currentLocation)
                                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
                                    .title("Current Position")
                                    .snippet("Show the current position of user during travel"));

                            // For zooming automatically to the location of the marker
                            CameraPosition cameraPosition = new CameraPosition.Builder().target(currentLocation).zoom(11).build();
                            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        }

                        if (travelInfo.getEndLat() != 0 && travelInfo.getEndLng() != 0) {
                            Log.i(TAG, "Dentro if userlocation");
                            //Get total distance of travel
                            getTotalDistanceTime(travelInfo);
                            //Get the percurred distance from last known coordinates
                            getPercurredDistance(travelInfo);
                        }
                    }
                }
            });
}
</code>```

And getpercurredDistance use google direction API with this url

```<code>    String url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + obj.getLastLat() + "," + obj.getLastLng() + "&destination=" + obj.getCurrentLat() + "," + obj.getCurrentLng() + "&mode=driving&key=AI*******************I";
</code>```

For getting distance traveled from last marker and current position marker.
But some times it put the localized position too far from real position... how avoid this?

EDIT

The method that i use is good for my work? mFusedLocationClient.getLastLocation()

答:
For real-time location purposes, location updates allow you to request location updates at different intervals. See the android developer location documentation. The function you want is FusedLocationProviderClient.requestLocationUpdates.

There is no reason GPS (or any other widely used location technology) should ever give you 10km error for a single location estimate. If you are getting this, there is a large mismatch between when you the location estimate was made and when you are requesting it.

Body:
In my Android application i need to get the traveled road with car and i check it with google android directions API and GPS.

But the problem is that some times the GPS location is not precise and i can get an error of 10Km for some lecture and that means that in a total travel of 150km my "distance traveled" can be 250km and it's wrong!

Yesterday i test it in highway and the problem is that when the marker is located out from highway, the calculation of distance traveled from my current position and the last marker located by road is very wrong (in this case out of the highway).

There is some best way for getting traveled distance with car using the phone?
Maybe some better code for getting more precise GPS position?
Here is my code:

private void getUserLocation() {

    Log.d(TAG, "getUserLocation()");
    checkLocationPermission();
    mFusedLocationClient.getLastLocation()
            .addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // Got last known location. In some rare situations this can be null.
                    if (location != null) {
                        // Logic to handle location object
                        String stringStartLat, stringStartLng;

                        double lat = location.getLatitude();
                        double lng = location.getLongitude();

                        //Start position of device
                        if (travelInfo.getStartLat() == 0 && travelInfo.getStartLng() == 0) {
                            travelInfo.setStartLat(lat);
                            travelInfo.setStartLng(lng);
                            //Set lastcoordinates equals to start
                            travelInfo.setLastLat(lat);
                            travelInfo.setLastLng(lng);
                        }
                        //Current position of device
                        travelInfo.setCurrentLat(lat);
                        travelInfo.setCurrentLng(lng);

                        stringStartLat = Double.toString(travelInfo.getStartLat());
                        stringStartLng = Double.toString(travelInfo.getStartLng());
                        //Set the TextView in the fragment with start coordinates
                        Log.d(TAG,"LatitudeStart: " + stringStartLat);
                        Log.d(TAG,"LongitudeStart: " + stringStartLng);

                        if (startMarker == null) {
                            //Add the user location to the map with a marker
                            LatLng userLoction = new LatLng(travelInfo.getStartLat(), travelInfo.getStartLng());
                            startMarker = googleMap.addMarker(new MarkerOptions()
                                    .position(userLoction)
                                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
                                    .title("Start Position")
                                    .snippet("Show the start position of user"));

                            // For zooming automatically to the location of the marker
                            CameraPosition cameraPosition = new CameraPosition.Builder().target(userLoction).zoom(9).build();
                            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        } else {

                            LatLng currentLocation = new LatLng(travelInfo.getCurrentLat(), travelInfo.getCurrentLng());
                            currentPositionMarker = googleMap.addMarker(new MarkerOptions()
                                    .position(currentLocation)
                                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
                                    .title("Current Position")
                                    .snippet("Show the current position of user during travel"));

                            // For zooming automatically to the location of the marker
                            CameraPosition cameraPosition = new CameraPosition.Builder().target(currentLocation).zoom(11).build();
                            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        }

                        if (travelInfo.getEndLat() != 0 && travelInfo.getEndLng() != 0) {
                            Log.i(TAG, "Dentro if userlocation");
                            //Get total distance of travel
                            getTotalDistanceTime(travelInfo);
                            //Get the percurred distance from last known coordinates
                            getPercurredDistance(travelInfo);
                        }
                    }
                }
            });
}

And getpercurredDistance use google direction API with this url

    String url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + obj.getLastLat() + "," + obj.getLastLng() + "&destination=" + obj.getCurrentLat() + "," + obj.getCurrentLng() + "&mode=driving&key=AI*******************I";

For getting distance traveled from last marker and current position marker.
But some times it put the localized position too far from real position... how avoid this?

EDIT

The method that i use is good for my work? mFusedLocationClient.getLastLocation()