问:
Access function protocol in generic class
I want to access function in protocol, but XCode complaint

Instance member 'createColumns' cannot be used on type 'T'; did you
  mean to use a value of this type instead?

What I have done:

Create protocol:

```<code>protocol StorageModelDelegate {
   func createColumns(for tableBuilder: TableBuilder)
}
</code>```

Create class generic that receive StorageModelDelegate:

```<code>class SQLiteStorage<T: StorageModelDelegate> {
     func createTable(tableName: TableKey) -> Bool {
           let table = Table(tableName.rawValue)

           let query = table.create(ifNotExists: true) { (builder: TableBuilder) in
                T.createColumns(for: builder) // -> this is the error comes up.
           }
     }
}
</code>```

Create class that implement SQLiteStorage:

```<code>final class InfoStorageModel {
    private let sqlite: SQLiteStorage = SQLiteStorage<Info>()
}
</code>```

so, how to fix the error in SQLiteStorage class?

答:
The error indicates that you need an instance of T, not the type itself.

So you need something like:

```<code>class SQLiteStorage<T: StorageModelDelegate> {
    var delegate:T

    init (delegate:T) {
      self.delegate = delegate
    }

    func createTable(tableName: TableKey) -> Bool {
          let table = Table(tableName.rawValue)

          let query = table.create(ifNotExists: true) { (builder: TableBuilder) in
                self.delegate.createColumns(for: builder) // -> this is the error comes up.
          }
    }
}
</code>```

Body:
I want to access function in protocol, but XCode complaint

Instance member 'createColumns' cannot be used on type 'T'; did you
  mean to use a value of this type instead?

What I have done:

Create protocol:

protocol StorageModelDelegate {
   func createColumns(for tableBuilder: TableBuilder)
}

Create class generic that receive StorageModelDelegate:

class SQLiteStorage<T: StorageModelDelegate> {
     func createTable(tableName: TableKey) -> Bool {
           let table = Table(tableName.rawValue)

           let query = table.create(ifNotExists: true) { (builder: TableBuilder) in
                T.createColumns(for: builder) // -> this is the error comes up.
           }
     }
}

Create class that implement SQLiteStorage:

final class InfoStorageModel {
    private let sqlite: SQLiteStorage = SQLiteStorage<Info>()
}

so, how to fix the error in SQLiteStorage class?

Body:
The error indicates that you need an instance of T, not the type itself.

So you need something like:

class SQLiteStorage<T: StorageModelDelegate> {
    var delegate:T

    init (delegate:T) {
      self.delegate = delegate
    }

    func createTable(tableName: TableKey) -> Bool {
          let table = Table(tableName.rawValue)

          let query = table.create(ifNotExists: true) { (builder: TableBuilder) in
                self.delegate.createColumns(for: builder) // -> this is the error comes up.
          }
    }
}


来源: stackexchange

问:
Drawer menu not closing
I created a drawer menu using the DrawerNavigation feature of react-navigation. I wanted to create a button that would close the menu but the onPress function seems to not work

I've imported DrawerActions from 'react-navigation-drawer' and I've tried using different syntaxes

ex.) this.props.navigation.dispatch(DrawerActions.closeDrawer());
     this.props.navigation.closeDrawer();

```<code>import React, { Component } from 'react';
import {
  Image,
  StyleSheet,
  Text,
  ImageBackground,
  TouchableWithoutFeedback,
  View,
  Button,
  ScrollView,
} from 'react-native';
import {
  createDrawerNavigator,
  createStackNavigator,
  createAppContainer,
  DrawerItems,
  SafeAreaView,
  NavigationActions
   } from 'react-navigation';

import { DrawerActions, } from 'react-navigation-drawer';

const navigator = createDrawerNavigator(
{
  Home: Lander,
  Page1: Lander,
  Page2: Lander,
  Page3: Lander,
  Page4: Lander,
},

{
 contentComponent: (props) => (
     <SafeAreaView>
        <View style= {{backgroundColor:'black'}}>
            <TouchableWithoutFeedback onPress={() => this.props.navigation.dispatch(DrawerActions.closeDrawer())}>
              <Image source={require('./Images/x.png')} style = {styles.cross}/>
            </TouchableWithoutFeedback>
        </View>
        <ScrollView style= {{backgroundColor: 'black', paddingLeft: '5%'}}>
              <DrawerItems {...props} />
         </ScrollView>

   </SafeAreaView>

        )
    },

);
</code>```

I ultimately want to be able to click on the x button and let it redirect me to the home screen.

I'm getting the following error

Undefined is not an object (evaluating '_this.props.navigation')

答:
```<code>import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import { gestureHandlerRootHOC } from 'react-native-gesture-handler'

AppRegistry.registerComponent(appName, () => gestureHandlerRootHOC(App));
</code>```

hope is helps

ContentLicense: CC BY-SA 4.0

Title: Drawer menu not closing

Body:
I created a drawer menu using the DrawerNavigation feature of react-navigation. I wanted to create a button that would close the menu but the onPress function seems to not work

I've imported DrawerActions from 'react-navigation-drawer' and I've tried using different syntaxes

ex.) this.props.navigation.dispatch(DrawerActions.closeDrawer());
     this.props.navigation.closeDrawer();

import React, { Component } from 'react';
import {
  Image,
  StyleSheet,
  Text,
  ImageBackground,
  TouchableWithoutFeedback,
  View,
  Button,
  ScrollView,
} from 'react-native';
import {
  createDrawerNavigator,
  createStackNavigator,
  createAppContainer,
  DrawerItems,
  SafeAreaView,
  NavigationActions
   } from 'react-navigation';

import { DrawerActions, } from 'react-navigation-drawer';

const navigator = createDrawerNavigator(
{
  Home: Lander,
  Page1: Lander,
  Page2: Lander,
  Page3: Lander,
  Page4: Lander,
},

{
 contentComponent: (props) => (
     <SafeAreaView>
        <View style= {{backgroundColor:'black'}}>
            <TouchableWithoutFeedback onPress={() => this.props.navigation.dispatch(DrawerActions.closeDrawer())}>
              <Image source={require('./Images/x.png')} style = {styles.cross}/>
            </TouchableWithoutFeedback>
        </View>
        <ScrollView style= {{backgroundColor: 'black', paddingLeft: '5%'}}>
              <DrawerItems {...props} />
         </ScrollView>

   </SafeAreaView>

        )
    },

);

I ultimately want to be able to click on the x button and let it redirect me to the home screen.

I'm getting the following error

Undefined is not an object (evaluating '_this.props.navigation')

Body:
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import { gestureHandlerRootHOC } from 'react-native-gesture-handler'

AppRegistry.registerComponent(appName, () => gestureHandlerRootHOC(App));

hope is helps


问:
Changing JTable cell ForeGround color
I'm trying to change the JTable cell color (foreground). It is working but it's coloring the cell+1 and not the required cell (as you see in my code).

I'm trying to change the color of the current row and column 3 but, it's actually changing the color of next column.

This code is added in the custom code.

```<code>BaritemsTable = new javax.swing.JTable(){
@Override
public Component prepareRenderer (TableCellRenderer renderer, int rowIndex , int columnIndex ){
    Component component = super.prepareRenderer(renderer , rowIndex , columnIndex );
    Object value = getModel().getValueAt(rowIndex , columnIndex);

    if (columnIndex == 3){

        if (value.equals("Ready")){
            BaritemsTable.setForeground(new java.awt.Color(51, 204, 0));
            BaritemsTable.setFont(new Font("Tahoma", Font.PLAIN, 48));
        }
        if (value.equals("Process")){
            BaritemsTable.setForeground(new java.awt.Color(51, 51, 255));
            BaritemsTable.setFont(new Font("Tahoma", Font.PLAIN, 48));
        }
        if (value.equals("Queued")){
            BaritemsTable.setForeground(new java.awt.Color(255, 0, 0));
            BaritemsTable.setFont(new Font("Tahoma", Font.PLAIN, 48));
        }

    } else {
        BaritemsTable.setForeground(new java.awt.Color(0, 0, 0));
        BaritemsTable.setFont(new Font("Tahoma", Font.PLAIN, 48));
    }
    return component;
  }
};
</code>```

答:
Problem one in your code, is definitely this:

```<code>Object value = getModel().getValueAt(rowIndex , columnIndex);
</code>```

The indexes you are receiving in handlers and listener, methods etc in JTable are view indexes and can only be used to index the view. In other words, you should write:

```<code>Object value = getValueAt(rowIndex , columnIndex); // Use JTable.getValueAt
</code>```

The second problem: when referencing a column index directly in prepareRenderer you should be using a view index in that spot. You most likely need

```<code>if (convertColumnIndexToModel(columnIndex) == 3)
</code>```

JTable.convertColumnIndexToModel makes sure you are using an index from the model. Why is all this needed, and what is a view index and model index? How do they relate? I gave a bit more explanation here.

The third problem: if you want to set colors and fonts for a row/cell you need to set them on the component returned from super.prepareRenderer, not on the table. For instance:

```<code>if (value.equals("Ready")){
    component.setForeground(new java.awt.Color(51, 204, 0));
    component.setFont(new Font("Tahoma", Font.PLAIN, 48));
}
</code>```

Title: Changing JTable cell ForeGround color

Body:
I'm trying to change the JTable cell color (foreground). It is working but it's coloring the cell+1 and not the required cell (as you see in my code).

I'm trying to change the color of the current row and column 3 but, it's actually changing the color of next column.

This code is added in the custom code.

BaritemsTable = new javax.swing.JTable(){
@Override
public Component prepareRenderer (TableCellRenderer renderer, int rowIndex , int columnIndex ){
    Component component = super.prepareRenderer(renderer , rowIndex , columnIndex );
    Object value = getModel().getValueAt(rowIndex , columnIndex);

    if (columnIndex == 3){

        if (value.equals("Ready")){
            BaritemsTable.setForeground(new java.awt.Color(51, 204, 0));
            BaritemsTable.setFont(new Font("Tahoma", Font.PLAIN, 48));
        }
        if (value.equals("Process")){
            BaritemsTable.setForeground(new java.awt.Color(51, 51, 255));
            BaritemsTable.setFont(new Font("Tahoma", Font.PLAIN, 48));
        }
        if (value.equals("Queued")){
            BaritemsTable.setForeground(new java.awt.Color(255, 0, 0));
            BaritemsTable.setFont(new Font("Tahoma", Font.PLAIN, 48));
        }

    } else {
        BaritemsTable.setForeground(new java.awt.Color(0, 0, 0));
        BaritemsTable.setFont(new Font("Tahoma", Font.PLAIN, 48));
    }
    return component;
  }
};

Body:
Problem one in your code, is definitely this:

Object value = getModel().getValueAt(rowIndex , columnIndex);

The indexes you are receiving in handlers and listener, methods etc in JTable are view indexes and can only be used to index the view. In other words, you should write:

Object value = getValueAt(rowIndex , columnIndex); // Use JTable.getValueAt

The second problem: when referencing a column index directly in prepareRenderer you should be using a view index in that spot. You most likely need

if (convertColumnIndexToModel(columnIndex) == 3)

JTable.convertColumnIndexToModel makes sure you are using an index from the model. Why is all this needed, and what is a view index and model index? How do they relate? I gave a bit more explanation here.

The third problem: if you want to set colors and fonts for a row/cell you need to set them on the component returned from super.prepareRenderer, not on the table. For instance:

if (value.equals("Ready")){
    component.setForeground(new java.awt.Color(51, 204, 0));
    component.setFont(new Font("Tahoma", Font.PLAIN, 48));
}


问:
How do you balance fun feature creep with time constraints?
I enjoy programming, usually.  Tedious stuff is easy to get done as quickly and correctly as possible so I can get through it and not have to see it again.

But a lot of my coding is fun and when I get in the 'zone' I just really enjoy myself.

Which is where I make the mistake of spending too much time, perhaps adding features, perhaps writing it in a cool or elegant manner, or just doing neat prototypes.

How do you recognize this is happening before it exceeds your time frame?

What do you do before starting a potentially fun piece of code, or during, to get back on track?

When is it ok to let yourself go "hog wild" and just enjoy it without worrying about consequences?

-Adam

答: Keep a detailed prioritized feature list/bug list.  review it often then balance the fun work with bugs/features that need to get done.</p>

OwnerDisplayName: Adam Davis

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: dF

OwnerDisplayName: simon


问:
Unable to show Json html content data in textview in android
Right now i am trying to display images and texts from one html content in text-view in android. Actually i am getting those html contents from json,but the help of below code i can only able to show the available texts like the below image

and unable to show the images.Can any one tell me how to display both images and texts from html content?

suggestions please

Thanks for your precious time!..

```<code>String  htmlcontent = "\u003ch3 style=\"text-align: justify;\"\u003e \u003cspan style=\"color: #800080;\"\u003eJourneys Magazine -                     Sports                          Best of Rage\r\n\u003c/span\u003e\u003cspan style=\"color: #800080;\"\u003e New Ireland Journey                     Magazine                     Magazine\u003c/span\u003e\u003c/h3\u003e\r\n\u003cp style=\"text-align: justify;\"\u003e\u003cimg alt=\"\" src=\"http://dev.postcourier.com.pg/wp-content/uploads/2013/08/Journeys-NIP_-Front-cover.jpg\" width=\"180\" height=\"335\" /\u003e \u003cimg alt=\"\" src=\"http://dev.postcourier.com.pg/wp-content/uploads/2013/08/Sports-Magazine-Cover2.jpg\" width=\"184\" height=\"336\" /\u003e \u003cimg alt=\"\" src=\"http://dev.postcourier.com.pg/wp-content/uploads/2013/08/BOR_front-cvr.jpg\" width=\"184\" height=\"335\" /\u003e\u003c/p\u003e\r\n\u003cp style=\"text-align: justify;\"\u003e \u003c/p\u003e";

txt_date.setText(Html.fromHtml(htmlcontent));
</code>```

答:
```<code>public class SimpleMusicStream extends Activity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        WebView wv = (WebView) findViewById(R.id.WebView01);

        final String mimeType = "text/html";
        final String encoding = "UTF-8";
        final String baseUrl = "http://www.homeworknow.com/";
        String html = "<br /><br />Read the handouts please for tomorrow.<br /><br /><!--homework help homework" +
                "help help with homework homework assignments elementary school high school middle school" +
                "// --><font color='#60c000' size='4'><strong>Please!</strong></font>" +
                "<img src='http://www.homeworknow.com/hwnow/upload/images/tn_star300.gif'  />";

        wv.loadDataWithBaseURL(baseUrl, html, mimeType, encoding, "");
    }

}// only thing for show image in webview from html give **base url** of image like this http://www.homeworknow.com/
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Right now i am trying to display images and texts from one html content in text-view in android. Actually i am getting those html contents from json,but the help of below code i can only able to show the available texts like the below image

and unable to show the images.Can any one tell me how to display both images and texts from html content?

suggestions please

Thanks for your precious time!..

String  htmlcontent = "\u003ch3 style=\"text-align: justify;\"\u003e \u003cspan style=\"color: #800080;\"\u003eJourneys Magazine -                     Sports                          Best of Rage\r\n\u003c/span\u003e\u003cspan style=\"color: #800080;\"\u003e New Ireland Journey                     Magazine                     Magazine\u003c/span\u003e\u003c/h3\u003e\r\n\u003cp style=\"text-align: justify;\"\u003e\u003cimg alt=\"\" src=\"http://dev.postcourier.com.pg/wp-content/uploads/2013/08/Journeys-NIP_-Front-cover.jpg\" width=\"180\" height=\"335\" /\u003e \u003cimg alt=\"\" src=\"http://dev.postcourier.com.pg/wp-content/uploads/2013/08/Sports-Magazine-Cover2.jpg\" width=\"184\" height=\"336\" /\u003e \u003cimg alt=\"\" src=\"http://dev.postcourier.com.pg/wp-content/uploads/2013/08/BOR_front-cvr.jpg\" width=\"184\" height=\"335\" /\u003e\u003c/p\u003e\r\n\u003cp style=\"text-align: justify;\"\u003e \u003c/p\u003e";

txt_date.setText(Html.fromHtml(htmlcontent));


问:
Avoiding repetitive sub-class definitions in C++
I am new to C++ classes, and I have a question about defining multiple sub-classes of an abstract type/interface which would have identical definitions.

Take the following example which might appear in a header file with 3 sub-classes:

```<code>class Animal {
private:
    int a;
    int b;
public:
    explicit Animal(int a) {}
    virtual Animal* getFriend() = 0;
    virtual bool walk() = 0;
    virtual bool talk() = 0;
    virtual bool someFunction() = 0;
    virtual bool someOtherFunction() = 0;
    // ... many more functions
}

class Zebra: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

class Cow: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

class Salmon: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

// ... many more animals
</code>```

Declaring the sub-classes like this seems repetitive and potentially error prone. Because the class definitions are identical except for the name of the class, is there a more efficient way to declare the animal sub-classes in bulk?

In the context I am working in each animal would have a completely independent implementation in separate .cpp files.

Please let me know if i'm approaching this completely wrong. Any help would be greatly appreciated.

答:
I'm writing another answer as an alternative solution. Actually, If i faced with same 'issue' or 'problem', i would not declare as bulk, I would just create zebra.h, zebra.cpp, inherits from Animal and declare/define all members individually. In other words i would prefer not to be clever but if you want to be the piece of codes below could be an alternative.

Indeed, you just want to create a class declaration from a template. That's what template is doing. It is possible to mimic same behaviour with MACROs but I would prefer template rather than MACRO because it is what Bjarne did.

So here is the code

animal.h

```<code>#ifndef ANIMAL_H
#define ANIMAL_H

class Animal {
private:
    int a;
    int b;
public:
    explicit Animal(int a) {}
    virtual ~Animal() = default; // You should this virtual destructor
                                 // for polymorphic types.
    virtual Animal* getFriend() = 0;
    virtual bool walk() = 0;
    virtual bool talk() = 0;
    virtual bool someFunction() = 0;
    virtual bool someOtherFunction() = 0;
};

enum class animal_types
{
    zebra ,
    cow ,
    salmon ,
    special_animal
};

template< animal_types >
struct ugly_bulk_animal_inheritor : Animal
{
    using Animal::Animal; // Use parent constructor as is
    Animal* getFriend() override;
    bool walk() override;
    bool talk() override;
    bool someFunction() override;
    bool someOtherFunction() override;
};

using Zebra = ugly_bulk_animal_inheritor< animal_types::zebra >;
using Cow = ugly_bulk_animal_inheritor< animal_types::cow >;
using Salmon = ugly_bulk_animal_inheritor< animal_types::salmon >;

// So on..

#include "zebra.h"
#include "salmon.h"
#include "cow.h"
#include "special_animal.h"

#endif // ANIMAL_H
</code>```

cow.h

```<code>#ifndef COW_H
#define COW_H

#include "animal.h"

template<>
Animal* Cow::getFriend() {
    return nullptr;
}

template<>
bool Cow::walk() {
    return true;
}

template<>
bool Cow::talk() {
    return false;
}

template<>
bool Cow::someFunction() {
    return true;
}

template<>
bool Cow::someOtherFunction() {
    return true;
}

#endif // COW_H
</code>```

salmon.h

```<code>#ifndef SALMON_H
#define SALMON_H

#include "animal.h"

template<>
Animal* Salmon::getFriend() {
    return nullptr;
}

template<>
bool Salmon::walk() {
    return true;
}

template<>
bool Salmon::talk() {
    return true;
}

template<>
bool Salmon::someFunction() {
    return true;
}

template<>
bool Salmon::someOtherFunction() {
    return true;
}

#endif // SALMON_H
</code>```

zebra.h

```<code>#ifndef ZEBRA_H
#define ZEBRA_H

#include "animal.h"

template<>
Animal* Zebra::getFriend() {
    return nullptr;
}

template<>
bool Zebra::walk() {
    return true;
}

template<>
bool Zebra::talk() {
    return false;
}

template<>
bool Zebra::someFunction() {
    return true;
}

template<>
bool Zebra::someOtherFunction() {
    return true;
}

#endif // ZEBRA_H
</code>```

special_animal.h

```<code>#ifndef SPECIAL_ANIMAL_H
#define SPECIAL_ANIMAL_H

#include "animal.h"
#include <iostream>

template<>
struct ugly_bulk_animal_inheritor<animal_types::special_animal> : Animal
{
    using Animal::Animal; // Use parent constructor as is
    Animal* getFriend() override { return nullptr; }
    bool walk() override { return true; }
    bool talk() override { return true; }
    bool someFunction() override { return true; }
    bool someOtherFunction() override { return true; }

    void specility_fn() {
        std::cout << "A speciality" << std::endl;
    }

private:

    int some_extra_member;
    // etc..

};

using special_animal = ugly_bulk_animal_inheritor<animal_types::special_animal>;

#endif // SPECIAL_ANIMAL_H
</code>```

main.cpp

```<code>#include <iostream>
#include "animal.h"

int main(int argc, char *argv[])
{
    Animal* instance;
    Zebra z { 5 };
    Cow c  { 6 };
    Salmon t { 7 };

    instance = &z;
    std::cout << "Zebra can talk ? " << instance->talk() << std::endl;
    instance = &t;
    std::cout << "Salmon can talk ? " << instance->talk() << std::endl;

    special_animal s { 5 };
    s.specility_fn();

    return 0;
}
</code>```

Body:
I am new to C++ classes, and I have a question about defining multiple sub-classes of an abstract type/interface which would have identical definitions.

Take the following example which might appear in a header file with 3 sub-classes:

class Animal {
private:
    int a;
    int b;
public:
    explicit Animal(int a) {}
    virtual Animal* getFriend() = 0;
    virtual bool walk() = 0;
    virtual bool talk() = 0;
    virtual bool someFunction() = 0;
    virtual bool someOtherFunction() = 0;
    // ... many more functions
}

class Zebra: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

class Cow: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

class Salmon: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

// ... many more animals

Declaring the sub-classes like this seems repetitive and potentially error prone. Because the class definitions are identical except for the name of the class, is there a more efficient way to declare the animal sub-classes in bulk?

In the context I am working in each animal would have a completely independent implementation in separate .cpp files.

Please let me know if i'm approaching this completely wrong. Any help would be greatly appreciated.

Body:
I'm writing another answer as an alternative solution. Actually, If i faced with same 'issue' or 'problem', i would not declare as bulk, I would just create zebra.h, zebra.cpp, inherits from Animal and declare/define all members individually. In other words i would prefer not to be clever but if you want to be the piece of codes below could be an alternative.

Indeed, you just want to create a class declaration from a template. That's what template is doing. It is possible to mimic same behaviour with MACROs but I would prefer template rather than MACRO because it is what Bjarne did.

So here is the code

animal.h

#ifndef ANIMAL_H
#define ANIMAL_H

class Animal {
private:
    int a;
    int b;
public:
    explicit Animal(int a) {}
    virtual ~Animal() = default; // You should this virtual destructor
                                 // for polymorphic types.
    virtual Animal* getFriend() = 0;
    virtual bool walk() = 0;
    virtual bool talk() = 0;
    virtual bool someFunction() = 0;
    virtual bool someOtherFunction() = 0;
};

enum class animal_types
{
    zebra ,
    cow ,
    salmon ,
    special_animal
};

template< animal_types >
struct ugly_bulk_animal_inheritor : Animal
{
    using Animal::Animal; // Use parent constructor as is
    Animal* getFriend() override;
    bool walk() override;
    bool talk() override;
    bool someFunction() override;
    bool someOtherFunction() override;
};

using Zebra = ugly_bulk_animal_inheritor< animal_types::zebra >;
using Cow = ugly_bulk_animal_inheritor< animal_types::cow >;
using Salmon = ugly_bulk_animal_inheritor< animal_types::salmon >;

// So on..

#include "zebra.h"
#include "salmon.h"
#include "cow.h"
#include "special_animal.h"

#endif // ANIMAL_H

cow.h

#ifndef COW_H
#define COW_H

#include "animal.h"

template<>
Animal* Cow::getFriend() {
    return nullptr;
}

template<>
bool Cow::walk() {
    return true;
}

template<>
bool Cow::talk() {
    return false;
}

template<>
bool Cow::someFunction() {
    return true;
}

template<>
bool Cow::someOtherFunction() {
    return true;
}

#endif // COW_H

salmon.h

#ifndef SALMON_H
#define SALMON_H

#include "animal.h"

template<>
Animal* Salmon::getFriend() {
    return nullptr;
}

template<>
bool Salmon::walk() {
    return true;
}

template<>
bool Salmon::talk() {
    return true;
}

template<>
bool Salmon::someFunction() {
    return true;
}

template<>
bool Salmon::someOtherFunction() {
    return true;
}

#endif // SALMON_H

zebra.h

#ifndef ZEBRA_H
#define ZEBRA_H

#include "animal.h"

template<>
Animal* Zebra::getFriend() {
    return nullptr;
}

template<>
bool Zebra::walk() {
    return true;
}

template<>
bool Zebra::talk() {
    return false;
}

template<>
bool Zebra::someFunction() {
    return true;
}

template<>
bool Zebra::someOtherFunction() {
    return true;
}

#endif // ZEBRA_H

special_animal.h

#ifndef SPECIAL_ANIMAL_H
#define SPECIAL_ANIMAL_H

#include "animal.h"
#include <iostream>

template<>
struct ugly_bulk_animal_inheritor<animal_types::special_animal> : Animal
{
    using Animal::Animal; // Use parent constructor as is
    Animal* getFriend() override { return nullptr; }
    bool walk() override { return true; }
    bool talk() override { return true; }
    bool someFunction() override { return true; }
    bool someOtherFunction() override { return true; }

    void specility_fn() {
        std::cout << "A speciality" << std::endl;
    }

private:

    int some_extra_member;
    // etc..

};

using special_animal = ugly_bulk_animal_inheritor<animal_types::special_animal>;

#endif // SPECIAL_ANIMAL_H

main.cpp

#include <iostream>
#include "animal.h"

int main(int argc, char *argv[])
{
    Animal* instance;
    Zebra z { 5 };
    Cow c  { 6 };
    Salmon t { 7 };

    instance = &z;
    std::cout << "Zebra can talk ? " << instance->talk() << std::endl;
    instance = &t;
    std::cout << "Salmon can talk ? " << instance->talk() << std::endl;

    special_animal s { 5 };
    s.specility_fn();

    return 0;
}


问:
JavaFX - making Timeline object on multiple objects execute EventHandler once
I am working in JavaFX right now, and have run into a problem. I created a simple example to demonstrate the issue I am facing.

My issue is, I have a Timeline object setup on multiple anonymous Circle objects and I want an action to happen after the Timeline has finished its play() method. To do this, I setup a setOnFinished event handler to execute something after the animation has finished playing, However, it is executing this logic multiple times because it is working on multiple objects.

Here I have a simple program that adds 3 anonymous objects to a VBox and there is a button that will call the  flash() method to start a Timeline animation on the circles.

```<code>package sample;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        VBox root = new VBox();
        VBox circles = new VBox();

        Button btn = new Button("Touch me to make me flash ;)");
        btn.setOnAction(e -> flash(circles));

        for(int i = 0; i < 3; i++) {
            circles.getChildren().add(new Circle(25, Color.RED));
        }
        circles.setSpacing(10);
        circles.setAlignment(Pos.CENTER);

        root.getChildren().addAll(circles, btn);
        root.setSpacing(10);
        root.setAlignment(Pos.CENTER);

        primaryStage.setScene(new Scene(root, 500, 500));
        primaryStage.show();
    }

    private void flash(VBox root) {
        for(Node circle : root.getChildren()) {
            final Circle c = (Circle) circle;
            Timeline timeline = new Timeline(
                    new KeyFrame(Duration.seconds(0.5), e -> c.setFill(Color.GOLD)),
                    new KeyFrame(Duration.seconds(1.0), e -> c.setFill(Color.RED))
            );

            timeline.setCycleCount(5);
            timeline.play();
            timeline.setOnFinished(e -> System.out.println("Do something here"));
        }
    }
}
</code>```

You can see in the flash() method that there is an EventHandler that executes this line of code:

System.out.println("Do something here")

I want it to only be executing one time, but it executes 3 times because the Timeline object is setup on 3 circles.

How can I make it so the EventHandler only executes one time?

答:
Consider using one TimeLine object for all Circle objects:

```<code>import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Main extends Application {

    private ObjectProperty<Paint> colorProperty;

    @Override
    public void start(Stage primaryStage) throws Exception{

        colorProperty = new SimpleObjectProperty<>(Color.WHITE);
        VBox root = new VBox();
        VBox circles = new VBox();

        Button btn = new Button("Touch me to make me flash ;)");
        btn.setOnAction(e -> flash(circles));

        for(int i = 0; i < 3; i++) {
            circles.getChildren().add(new Circle(25, Color.RED));
        }
        circles.setSpacing(10);
        circles.setAlignment(Pos.CENTER);

        root.getChildren().addAll(circles, btn);
        root.setSpacing(10);
        root.setAlignment(Pos.CENTER);

        primaryStage.setScene(new Scene(root, 500, 500));
        primaryStage.show();
    }

    private void flash(VBox root) {

        Timeline timeline = new Timeline(
                new KeyFrame(Duration.seconds(0.5), e -> colorProperty.set(Color.GOLD)),
                new KeyFrame(Duration.seconds(1.0), e -> colorProperty.set(Color.RED))
        );

        timeline.setCycleCount(5);
        timeline.play();
        timeline.setOnFinished(e -> System.out.println("Do something here"));

        for(Node circle : root.getChildren()) {
            final Circle c = (Circle) circle;
            c.fillProperty().bind(colorProperty);
        }
    }

    public static void main(String[] args) {
        launch(null);
    }
}
</code>```

Body:
I am working in JavaFX right now, and have run into a problem. I created a simple example to demonstrate the issue I am facing.

My issue is, I have a Timeline object setup on multiple anonymous Circle objects and I want an action to happen after the Timeline has finished its play() method. To do this, I setup a setOnFinished event handler to execute something after the animation has finished playing, However, it is executing this logic multiple times because it is working on multiple objects.

Here I have a simple program that adds 3 anonymous objects to a VBox and there is a button that will call the  flash() method to start a Timeline animation on the circles.

package sample;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        VBox root = new VBox();
        VBox circles = new VBox();

        Button btn = new Button("Touch me to make me flash ;)");
        btn.setOnAction(e -> flash(circles));

        for(int i = 0; i < 3; i++) {
            circles.getChildren().add(new Circle(25, Color.RED));
        }
        circles.setSpacing(10);
        circles.setAlignment(Pos.CENTER);

        root.getChildren().addAll(circles, btn);
        root.setSpacing(10);
        root.setAlignment(Pos.CENTER);

        primaryStage.setScene(new Scene(root, 500, 500));
        primaryStage.show();
    }

    private void flash(VBox root) {
        for(Node circle : root.getChildren()) {
            final Circle c = (Circle) circle;
            Timeline timeline = new Timeline(
                    new KeyFrame(Duration.seconds(0.5), e -> c.setFill(Color.GOLD)),
                    new KeyFrame(Duration.seconds(1.0), e -> c.setFill(Color.RED))
            );

            timeline.setCycleCount(5);
            timeline.play();
            timeline.setOnFinished(e -> System.out.println("Do something here"));
        }
    }
}

You can see in the flash() method that there is an EventHandler that executes this line of code:

System.out.println("Do something here")

I want it to only be executing one time, but it executes 3 times because the Timeline object is setup on 3 circles.

How can I make it so the EventHandler only executes one time?

Body:
Consider using one TimeLine object for all Circle objects:

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Main extends Application {

    private ObjectProperty<Paint> colorProperty;

    @Override
    public void start(Stage primaryStage) throws Exception{

        colorProperty = new SimpleObjectProperty<>(Color.WHITE);
        VBox root = new VBox();
        VBox circles = new VBox();

        Button btn = new Button("Touch me to make me flash ;)");
        btn.setOnAction(e -> flash(circles));

        for(int i = 0; i < 3; i++) {
            circles.getChildren().add(new Circle(25, Color.RED));
        }
        circles.setSpacing(10);
        circles.setAlignment(Pos.CENTER);

        root.getChildren().addAll(circles, btn);
        root.setSpacing(10);
        root.setAlignment(Pos.CENTER);

        primaryStage.setScene(new Scene(root, 500, 500));
        primaryStage.show();
    }

    private void flash(VBox root) {

        Timeline timeline = new Timeline(
                new KeyFrame(Duration.seconds(0.5), e -> colorProperty.set(Color.GOLD)),
                new KeyFrame(Duration.seconds(1.0), e -> colorProperty.set(Color.RED))
        );

        timeline.setCycleCount(5);
        timeline.play();
        timeline.setOnFinished(e -> System.out.println("Do something here"));

        for(Node circle : root.getChildren()) {
            final Circle c = (Circle) circle;
            c.fillProperty().bind(colorProperty);
        }
    }

    public static void main(String[] args) {
        launch(null);
    }
}


问:
My Python code pass simple tests but not extended ones due to performance constrains
I'm teaching myself to code with Python and I've been completing kata's (mainly 7 kyu for now) on Codewars for a while. While trying to level up stumbled on following 6 kyu kata, that looked to be achievable with my knowledge:

Complete the function that takes a string as an input, and return a list of all the unpaired characters (i.e. they show up an odd number of times in the string), in the order they were encountered as an array.

In case of multiple appearances to choose from, take the last occurence of the unpaired character.

Notes:

A wide range of characters is used, and some of them may not render properly in your browser.
  Your solution should be linear in terms of string length to pass the last test.
  Examples:

"Hello World"   -->  ["H", "e", " ", "W", "r", "l", "d"]

"Codewars"      -->  ["C", "o", "d", "e", "w", "a", "r", "s"]

"woowee"        -->  []

"wwoooowweeee"  -->  []

"racecar"       -->  ["e"]

"Mamma"         -->  ["M"]

"Mama"          -->  ["M", "m"]

The following Python 3.6.0 code pass sample tests:

def function_name(s):
    result = []
    lengthS = len(s)
    dictResult = {}

    for item in s[-1:(-1 * lengthS - 1):-1]:
        numLetters = 0
        for number in range(lengthS):
            if item == s[number]:
                numLetters = numLetters + 1
        if numLetters % 2 != 0:
            dictResult[item] = numLetters

    for key in list(dictResult.keys())[-1:(-1 * (len(list(dictResult))) - 1):-1]:
        result.append(key)

    return result
```

Running a full round of tests fails due to :

Execution Timed Out (12000 ms)

Commenting some parts of code allows me to fail full round of tests quicker so I could see tests use very long strings.

It is clear that my code is not performance optimised. Read some articles on algorithms and I suspect my code lacks in performance due to for loop within another for loop, which is O(n²) complexity operation. And this is where I've stuck for a while. I'm not sure if this is the only piece of code that needs to be changed and if it is - just cannot get around understanding how this could be done.

Note. Please do not post answers with complete solution to this problem. I'd rather wish to figure the final code myself. So I would be glad if you could point to sections of my code that requires attention with suggestions, example code or further reading.

答:
One thing you could try is to use a dict to count the number of occurrences of each letter. this way you will only iterate once through your string.

sample example:

```<code>my_counter = {}
for letter in s:
    my_counter[letter] = my_counter.get(letter, 0) + 1
</code>```

Because you don't want the complete solution I let you figure the rest. Hope it helps.

doc of get() :
https://docs.python.org/3/library/stdtypes.html?highlight=get#dict.get

Body:
I'm teaching myself to code with Python and I've been completing kata's (mainly 7 kyu for now) on Codewars for a while. While trying to level up stumbled on following 6 kyu kata, that looked to be achievable with my knowledge:

Complete the function that takes a string as an input, and return a list of all the unpaired characters (i.e. they show up an odd number of times in the string), in the order they were encountered as an array.

In case of multiple appearances to choose from, take the last occurence of the unpaired character.

Notes:

A wide range of characters is used, and some of them may not render properly in your browser.
  Your solution should be linear in terms of string length to pass the last test.
  Examples:

"Hello World"   -->  ["H", "e", " ", "W", "r", "l", "d"]

"Codewars"      -->  ["C", "o", "d", "e", "w", "a", "r", "s"]

"woowee"        -->  []

"wwoooowweeee"  -->  []

"racecar"       -->  ["e"]

"Mamma"         -->  ["M"]

"Mama"          -->  ["M", "m"]

The following Python 3.6.0 code pass sample tests:

def function_name(s):
    result = []
    lengthS = len(s)
    dictResult = {}

    for item in s[-1:(-1 * lengthS - 1):-1]:
        numLetters = 0
        for number in range(lengthS):
            if item == s[number]:
                numLetters = numLetters + 1
        if numLetters % 2 != 0:
            dictResult[item] = numLetters

    for key in list(dictResult.keys())[-1:(-1 * (len(list(dictResult))) - 1):-1]:
        result.append(key)

    return result

Running a full round of tests fails due to :

Execution Timed Out (12000 ms)

Commenting some parts of code allows me to fail full round of tests quicker so I could see tests use very long strings.

It is clear that my code is not performance optimised. Read some articles on algorithms and I suspect my code lacks in performance due to for loop within another for loop, which is O(n²) complexity operation. And this is where I've stuck for a while. I'm not sure if this is the only piece of code that needs to be changed and if it is - just cannot get around understanding how this could be done.

Note. Please do not post answers with complete solution to this problem. I'd rather wish to figure the final code myself. So I would be glad if you could point to sections of my code that requires attention with suggestions, example code or further reading.

Body:
One thing you could try is to use a dict to count the number of occurrences of each letter. this way you will only iterate once through your string.

sample example:

my_counter = {}
for letter in s:
    my_counter[letter] = my_counter.get(letter, 0) + 1

Because you don't want the complete solution I let you figure the rest. Hope it helps.

doc of get() :
https://docs.python.org/3/library/stdtypes.html?highlight=get#dict.get


问:
TypeError: Object(...) is not a function. How is the solution for getting the error?
I want to run my react application with firebase.I do not receive an error in the visual studio Code program. but in my web browser, applymiddaware(thunk.withextraargument ({getFirebase,getFirestore})) : TypeError: Object (...) is giving a function error.I wonder what is the solution?

index.js

```<code>/* eslint-disable no-unused-vars */
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

import {createStore, applyMiddleware,compose} from 'redux';
import rootReducer from './store/rootReducer';
import {Provider} from 'react-redux'
import thunk from 'redux-thunk'
import {getFirestore,reduxFirestore } from 'redux-firestore'
import {getFirebase,reactReduxFirebase} from 'react-redux-firebase'
import fbConfig from './config/fbConfig'

const store=createStore(rootReducer,
    compose(
    applyMiddleware(thunk.withExtraArgument({getFirebase,getFirestore})),
    reduxFirestore(),
    reactReduxFirebase()
    )
    );

ReactDOM.render(<Provider store ={store}></Provider>><App />, document.getElementById('root'));
</code>```

package.json

```<code>{
  "name": "marioplan",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "firebase": "^7.8.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-redux": "^7.1.3",
    "react-redux-firebase": "^3.1.1",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.0",
    "redux": "^4.0.5",
    "redux-firestore": "^0.12.0",
    "redux-thunk": "^2.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "eslint-plugin-react": "^7.18.3"
  }
}
</code>```

答: In your package.json file, I see that you installed version 3.1.1 of react-redux-firebase but you are creating the store using the synthax for older version ( virsion 2). you have to either downgrade react-redux-firebase to version 2 or create your store folowing v3 migration guide here. used similar synthax for react-redux-firebase 2.2.4 in the past.</p>

Body:
I want to run my react application with firebase.I do not receive an error in the visual studio Code program. but in my web browser, applymiddaware(thunk.withextraargument ({getFirebase,getFirestore})) : TypeError: Object (...) is giving a function error.I wonder what is the solution?

index.js

/* eslint-disable no-unused-vars */
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

import {createStore, applyMiddleware,compose} from 'redux';
import rootReducer from './store/rootReducer';
import {Provider} from 'react-redux'
import thunk from 'redux-thunk'
import {getFirestore,reduxFirestore } from 'redux-firestore'
import {getFirebase,reactReduxFirebase} from 'react-redux-firebase'
import fbConfig from './config/fbConfig'

const store=createStore(rootReducer,
    compose(
    applyMiddleware(thunk.withExtraArgument({getFirebase,getFirestore})),
    reduxFirestore(),
    reactReduxFirebase()
    )
    );

ReactDOM.render(<Provider store ={store}></Provider>><App />, document.getElementById('root'));

package.json

{
  "name": "marioplan",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "firebase": "^7.8.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-redux": "^7.1.3",
    "react-redux-firebase": "^3.1.1",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.0",
    "redux": "^4.0.5",
    "redux-firestore": "^0.12.0",
    "redux-thunk": "^2.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "eslint-plugin-react": "^7.18.3"
  }
}


问:
Is there a self-hosted web-based web UI prototyping tool?
The question says it all, we know most of the hosted web-based UI prototyping tools out there, but we would like to have ours hosted on our own internal servers, preferably with on-line multi-user collaboration functionality (i.e. users modifying the prototype, making comments, etc. in parallel).

Any suggestions will be appreciated.

答:
Most tools are either desktop based or hosted. Seen very few which offer a downloadble multi user version. iRise is one choice with the editor as a desktop product and a centralized server for sharing among users. The budget is typically from $50K to $250K. A similar option exists for Serena composer as well, not sure of the price though.

Both iRise and Serena are not real collaborative tools, the central server is only for sharing the finished prototypes and getting feedback.

If the requirement is for a completely web based multi user tool then 10screens can be an option - http://www.10screens.com. The same product available on the site in a hosted mode can be downloaded and installed on your own servers.


问:
Parsing a specific element using JSoup
I'm wondering if anyone is familiar with parsing a specific part of a website's HTML, such as getting a current temperature or current conditions from a website using JSoup? I've searched all over and it seems like all the examples are people using for each loops to extract a list. For example in the picture I attached, I only want to parse the -3 degrees into my IDE. Any help would be greatly appreciated! Thanks!

Picture:

答:
You should be able to use standard selectors to get the data you want from the Document.select() method. The easiest way to get this would be to open the web page in your browser's inspector, inspect that element specifically, then context-click its node in the element viewer and select Copy -> Selector Path.

Personally, I've experienced pretty substantial trouble with JSoup and have found that injecting artoo.js is usually a quicker way to get what I want out of a page regardless of environment.

Title: Parsing a specific element using JSoup


问:
Is there a way to do this in a simple query?
I have a BIG (23 millions rows) table CONTRATOS which has these columns:

```<code>SELECT
    CONTRATO,
    CODIGO_ORIGEN,
    ORIGEN
FROM CONTRATOS;
</code>```

There are multiple rows with the same value for the column CODIGO_ORIGEN:

```<code>CODIGO_ORIGEN     CONTRATO       ORIGEN
-------------    ----------     --------
     1               345          CONT
     1               363          BKP
     1               645          BKP
     1               365          CONT
</code>```

I need to get only one CONTRATO per CODIGO_ORIGEN but always prioritizing the 'CONT' value. So in this sample it would be the CONTRATO with value 365

I was trying to to something like this:

```<code>SELECT
   CODIGO_ORIGEN,
   CASE
    WHEN ORIGEN = 'CONT' THEN
        FIRST_VALUE (CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY CONTRATO DESC)
    WHEN ORIGEN = 'BKP' THEN
        FIRST_VALUE (CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY CAMPO1 DESC, CAMPO2 DESC, CONTRATO DESC)
   END AS CONTRATO
FROM CONTRATOS;
</code>```

In case ORIGEN is 'CONTR' i should sort by the highest CONTRATO and get the CONTRATO column.
In case ORIGEN is 'BKP' i should sort by different columns and get the CONTRATO column.

Finally, i should be able to have one unique row with CODIGO_ORIGEN -> CONTRATO (1:1).

Is there a simple way to do this (1 query)?

Thanks in advance!

答:
I think i got it:

```<code>      SELECT
        C.contrato, C.codigo_origen,  NVL2(MX.CONTRATO, NULL, 'F') AS ESTADO, NVL2(MX.CONTRATO, NULL, '4008') AS ERROR
      FROM MGR_CUENTA_CTL C
      LEFT JOIN
      (
          select /*+ PARALLEL */
            DISTINCT CODIGO_ORIGEN,
            CASE
              WHEN ORIGEN_TABLA = 'CONT' THEN FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY CONTRATO DESC)
              WHEN ORIGEN_TABLA = 'BKP' THEN FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY CAMPO1 DESC, CAMPO2 DESC)
            END AS CONTRATO
          FROM
          (
             SELECT /*+ PARALLEL */ ctl.*
             FROM mgr_cuenta_ctl ctl
             LEFT JOIN
             (
                   select /*+ PARALLEL */ CODIGO_ORIGEN
                   from mgr_cuenta_ctl
                   group by codigo_origen having count(distinct origen) > 1
             ) CTL2 ON ctl.CODIGO_ORIGEN = ctl2.CODIGO_ORIGEN
             WHERE (CTL2.CODIGO_ORIGEN IS NOT NULL AND CTL.ORIGEN <> 'BKP') OR (CTL2.CODIGO_ORIGEN IS NULL)
          )
      ) MX ON MX.CONTRATO = C.CONTRATO;
</code>```

I think it does what i was trying to explain.

Does it has sense for you?

Thanks!

Body:
I have a BIG (23 millions rows) table CONTRATOS which has these columns:

SELECT
    CONTRATO,
    CODIGO_ORIGEN,
    ORIGEN
FROM CONTRATOS;

There are multiple rows with the same value for the column CODIGO_ORIGEN:

CODIGO_ORIGEN     CONTRATO       ORIGEN
-------------    ----------     --------
     1               345          CONT
     1               363          BKP
     1               645          BKP
     1               365          CONT

I need to get only one CONTRATO per CODIGO_ORIGEN but always prioritizing the 'CONT' value. So in this sample it would be the CONTRATO with value 365

I was trying to to something like this:

SELECT
   CODIGO_ORIGEN,
   CASE
    WHEN ORIGEN = 'CONT' THEN
        FIRST_VALUE (CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY CONTRATO DESC)
    WHEN ORIGEN = 'BKP' THEN
        FIRST_VALUE (CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY CAMPO1 DESC, CAMPO2 DESC, CONTRATO DESC)
   END AS CONTRATO
FROM CONTRATOS;

In case ORIGEN is 'CONTR' i should sort by the highest CONTRATO and get the CONTRATO column.
In case ORIGEN is 'BKP' i should sort by different columns and get the CONTRATO column.

Finally, i should be able to have one unique row with CODIGO_ORIGEN -> CONTRATO (1:1).

Is there a simple way to do this (1 query)?

Thanks in advance!

Body:
I think i got it:

      SELECT
        C.contrato, C.codigo_origen,  NVL2(MX.CONTRATO, NULL, 'F') AS ESTADO, NVL2(MX.CONTRATO, NULL, '4008') AS ERROR
      FROM MGR_CUENTA_CTL C
      LEFT JOIN
      (
          select /*+ PARALLEL */
            DISTINCT CODIGO_ORIGEN,
            CASE
              WHEN ORIGEN_TABLA = 'CONT' THEN FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY CONTRATO DESC)
              WHEN ORIGEN_TABLA = 'BKP' THEN FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY CAMPO1 DESC, CAMPO2 DESC)
            END AS CONTRATO
          FROM
          (
             SELECT /*+ PARALLEL */ ctl.*
             FROM mgr_cuenta_ctl ctl
             LEFT JOIN
             (
                   select /*+ PARALLEL */ CODIGO_ORIGEN
                   from mgr_cuenta_ctl
                   group by codigo_origen having count(distinct origen) > 1
             ) CTL2 ON ctl.CODIGO_ORIGEN = ctl2.CODIGO_ORIGEN
             WHERE (CTL2.CODIGO_ORIGEN IS NOT NULL AND CTL.ORIGEN <> 'BKP') OR (CTL2.CODIGO_ORIGEN IS NULL)
          )
      ) MX ON MX.CONTRATO = C.CONTRATO;

I think it does what i was trying to explain.

Does it has sense for you?

Thanks!


问:
Laravel Eloquent get data where comparison is true
I am creating a mini inventory stock for a fashion store. I am using Laravel/Voyager with BREAD and everything fine. I have 2 tables Sizes and Products with a column in common product_code.

I would like to get the results from Sizes where column product_code = Product 'product_code'.
I have this query in the controller:

```<code>$product_code = Product::all();
$allSizes = Size::where('product_code', ($product_code->product_code));
</code>```

and in browse.blade.php I have:

```<code>@foreach ($allSizes as $size)
    <tr>
        <td align="right">{{$size->size_name}}</td>
        <td align="right">{{$size->stock}}</td>
    </tr>
@endforeach
</code>```

I guess the where statement is not working as supposed to.
I want to get the corresponding stock based on product_code for each size from table Sizes

答:
Try This

```<code>$product_code = Product::pluck('product_code')->toArray();
$allSizes = Size::whereIn('product_code', $product_code)->get();
</code>```

and in browse.blade.php:

```<code>@foreach ($allSizes as $size)
    <tr>
        <td align="right">{{$size->size_name}}</td>
        <td align="right">{{$size->stock}}</td>
    </tr>
@endforeach
</code>```

Body:
I am creating a mini inventory stock for a fashion store. I am using Laravel/Voyager with BREAD and everything fine. I have 2 tables Sizes and Products with a column in common product_code.

I would like to get the results from Sizes where column product_code = Product 'product_code'.
I have this query in the controller:

$product_code = Product::all();
$allSizes = Size::where('product_code', ($product_code->product_code));

and in browse.blade.php I have:

@foreach ($allSizes as $size)

        {{$size->size_name}}
        {{$size->stock}}

@endforeach

I guess the where statement is not working as supposed to.
I want to get the corresponding stock based on product_code for each size from table Sizes

Body:
Try This

$product_code = Product::pluck('product_code')->toArray();
$allSizes = Size::whereIn('product_code', $product_code)->get();

and in browse.blade.php:

@foreach ($allSizes as $size)
    <tr>
        <td align="right">{{$size->size_name}}</td>
        <td align="right">{{$size->stock}}</td>
    </tr>
@endforeach


问:
OpenVPN on Linux: passing username and password in command line
I am using IPVanish for using a proxy while surfing; like:

```<code>sudo openvpn --config /home/ipv/conf/ipvanish-CA-Toronto-tor-a09.ovpn
</code>```

Now, I have to enter my username, after that my password.
How Can I pass those two params right as one command, so that I just use one command and the username/password are being passed automatically?

答:
Seems to me like you have a config file .ovpn with the configuration needed, you need to create a new file that contains the username and password, you can do it like this:

```<code>vi pass.txt
</code>```

Add this lines, save and exit

```<code>username
password
</code>```

Now go the the .ovpn config file and edit, there should be a line that reads
auth-user-pass

Add your username and password file

auth-user-pass pass.txt

Ok so now you should be able to authenticate to the VPN just by executing your .ovpn file

If you need to do something like RDP there is also a way to authenticate without typing the password everytime using a #!/bin/bash script.

Body:
I am using IPVanish for using a proxy while surfing; like:

sudo openvpn --config /home/ipv/conf/ipvanish-CA-Toronto-tor-a09.ovpn

Now, I have to enter my username, after that my password.
How Can I pass those two params right as one command, so that I just use one command and the username/password are being passed automatically?

Body:
Seems to me like you have a config file .ovpn with the configuration needed, you need to create a new file that contains the username and password, you can do it like this:

vi pass.txt

Add this lines, save and exit

username
password

Now go the the .ovpn config file and edit, there should be a line that reads
auth-user-pass

Add your username and password file

auth-user-pass pass.txt

Ok so now you should be able to authenticate to the VPN just by executing your .ovpn file

If you need to do something like RDP there is also a way to authenticate without typing the password everytime using a #!/bin/bash script.


问:
Problems getting next page when scraping with scrapy
I have a scrapy code which doesn't crawl pagination links and i'm stuck.

The source of the page is:

https://www.levenhuk.bg/katalog/teleskopi/?page=1

My code is:

```<code>

import scrapy

class TelescopesSpider(scrapy.Spider):
    name = 'telescopes'
    allowed_domains = ['https://www.levenhuk.bg/']
    start_urls = ['https://www.levenhuk.bg/katalog/teleskopi/?page=1']
    download_delay = 3

    def parse(self, response):
        for product in response.xpath('//div[@class="catalog-item"]'):
            yield {

                # 'name': product.xpath('.//span[@itemprop="name" and contains(text(), "Levenhuk")]/text()').get(),
                'name': product.xpath('.//span[@itemprop="name"]/text()').get(),
                # 'price': product.xpath('.//div[@class="price"]/span/text()').get(),
                'price': product.xpath('.//span[@itemprop="price"]/text()').re_first(r'[0-9]+,[0-9]+'),
                'short_discr': product.xpath('.//div[@class="opis-item"]/p/strong/text()').get()

            }

            next_page_url = response.xpath('//*[@class="pagesCount"][1]//@href').get()
            if next_page_url is not None:
                yield scrapy.Request(response.urljoin(next_page_url))

</code>```

答:
I feel like the problem is simply that you are not specifying a callback in your pagination request. Specify your parse function as callback and that should work. please comment if it still doesn't work.

Edit:

In this case I feel like your logic needs an overhaul. I suggest separating the pagination and item extraction login. Try the following:

```<code>    def parse(self, response):
        self.extract_item(response)
        next_page_urls = response.xpath('//*[@class="pagesCount"] [1]//@href').getall()
        if next_page_urls is not None:
            for url in next_page_urls:
                yield scrapy.Request(response.urljoin(url), callback=self.extract_item)

    def extract_item(self, response):
        for product in response.xpath('//div[@class="catalog-item"]'):
           yield {

            # 'name': product.xpath('.//span[@itemprop="name" and contains(text(), "Levenhuk")]/text()').get(),
            'name': product.xpath('.//span[@itemprop="name"]/text()').get(),
            # 'price': product.xpath('.//div[@class="price"]/span/text()').get(),
            'price': product.xpath('.//span[@itemprop="price"]/text()').re_first(r'[0-9]+,[0-9]+'),
            'short_discr': product.xpath('.//div[@class="opis-item"]/p/strong/text()').get()

        }
</code>```

so now the parse function handles pagination and the extract_item function extracts items for every page.

Modify allowed_domains as well as specified by Pasindu.

Body:
I have a scrapy code which doesn't crawl pagination links and i'm stuck.

The source of the page is:

https://www.levenhuk.bg/katalog/teleskopi/?page=1

My code is:

import scrapy

class TelescopesSpider(scrapy.Spider):
    name = 'telescopes'
    allowed_domains = ['https://www.levenhuk.bg/']
    start_urls = ['https://www.levenhuk.bg/katalog/teleskopi/?page=1']
    download_delay = 3

    def parse(self, response):
        for product in response.xpath('//div[@class="catalog-item"]'):
            yield {

                # 'name': product.xpath('.//span[@itemprop="name" and contains(text(), "Levenhuk")]/text()').get(),
                'name': product.xpath('.//span[@itemprop="name"]/text()').get(),
                # 'price': product.xpath('.//div[@class="price"]/span/text()').get(),
                'price': product.xpath('.//span[@itemprop="price"]/text()').re_first(r'[0-9]+,[0-9]+'),
                'short_discr': product.xpath('.//div[@class="opis-item"]/p/strong/text()').get()

            }

            next_page_url = response.xpath('//*[@class="pagesCount"][1]//@href').get()
            if next_page_url is not None:
                yield scrapy.Request(response.urljoin(next_page_url))

Body:
I feel like the problem is simply that you are not specifying a callback in your pagination request. Specify your parse function as callback and that should work. please comment if it still doesn't work.

Edit:

In this case I feel like your logic needs an overhaul. I suggest separating the pagination and item extraction login. Try the following:

    def parse(self, response):
        self.extract_item(response)
        next_page_urls = response.xpath('//*[@class="pagesCount"] [1]//@href').getall()
        if next_page_urls is not None:
            for url in next_page_urls:
                yield scrapy.Request(response.urljoin(url), callback=self.extract_item)

    def extract_item(self, response):
        for product in response.xpath('//div[@class="catalog-item"]'):
           yield {

            # 'name': product.xpath('.//span[@itemprop="name" and contains(text(), "Levenhuk")]/text()').get(),
            'name': product.xpath('.//span[@itemprop="name"]/text()').get(),
            # 'price': product.xpath('.//div[@class="price"]/span/text()').get(),
            'price': product.xpath('.//span[@itemprop="price"]/text()').re_first(r'[0-9]+,[0-9]+'),
            'short_discr': product.xpath('.//div[@class="opis-item"]/p/strong/text()').get()

        }

so now the parse function handles pagination and the extract_item function extracts items for every page.

Modify allowed_domains as well as specified by Pasindu.


问:
Django | update requirements.txt automatically after installing new package
I am new to Django.

Every time I install new library using pip, I have to run pip freeze -l > requirements.txt and sometimes I forget this ( and error happens at my production environment).

What's the best way to run this command automatically when I install new packages...?

I am using:

```<code>Django==1.11.5
Python 3.6.1
</code>```

答:
For Python 3 use below to update requirements.txt file.
'''
pip3 freeze > requirements.txt
'''</p>

Body:
I am new to Django.

Every time I install new library using pip, I have to run pip freeze -l > requirements.txt and sometimes I forget this ( and error happens at my production environment).

What's the best way to run this command automatically when I install new packages...?

I am using:

Django==1.11.5
Python 3.6.1


问:
This IP, site or mobile application is not authorized to use this API key
I am using https://maps.googleapis.com/maps/api/geocode/json? link with server key and user IP to find the latitude and longitude of any address, when I'm trying I find the error as

I have a server access key from google and I have put my server's IP address in the their white list.

The URL that I am trying to access via PHP CURL is:

https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true&key=XXXXXXXXXXXX

The result that I am getting:

```<code>Array ([error_message] => This IP, site or mobile application is not authorized to use this API key. [results] => Array ( ) [status] => REQUEST_DENIED)
</code>```

Is there anything that I need to configure.The geocoding API is also switched on.

答:
Disable both direction api and geocoding api and re-enable.

it works for only 5-10 seconds and than automatically disabled itself.

it means you have only 5-10 sec to test you assignment.

Body:
I am using https://maps.googleapis.com/maps/api/geocode/json? link with server key and user IP to find the latitude and longitude of any address, when I'm trying I find the error as

I have a server access key from google and I have put my server's IP address in the their white list.

The URL that I am trying to access via PHP CURL is:

https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true&key=XXXXXXXXXXXX

The result that I am getting:

Array ([error_message] => This IP, site or mobile application is not authorized to use this API key. [results] => Array ( ) [status] => REQUEST_DENIED)

Is there anything that I need to configure.The geocoding API is also switched on.


问:
Hibernate search: Indexed data with Ngram filter and while searching it gives incorrect result due to tokenizing while querying
I have an analyzer with this configuration,

```<code>searchMapping//
        .analyzerDef(BaseEntity.CUSTOM_SEARCH_INDEX_ANALYZER, WhitespaceTokenizerFactory.class)//
        .filter(LowerCaseFilterFactory.class)//
        .filter(ASCIIFoldingFilterFactory.class)//
        .filter(NGramFilterFactory.class).param("minGramSize", "1").param("maxGramSize", "200");
</code>```

This is how my entity field is configured

```<code>@Field(analyzer = @Analyzer(definition = CUSTOM_SEARCH_INDEX_ANALYZER))
private String bookName;
</code>```

This is how I create a search query

```<code>queryBuilder.keyword().onField(prefixedPath).matching(matchingString).createQuery()
</code>```

I have an entity with value bookName="Gulliver" and another entity with bookName="xGulliver";

If I tried to search with data bookName = xG then am getting both entities where I would expect entity only with bookName="xGulliver";
Also looked on the query that is produced by hibernate-search.

Executing Lucene query '+(+(+(+(
          bookName:x
          bookName:xg
          bookName:g))))

Above Lucene query is prepared using BooleanJunction::must conditions by Lucene I guess which means it should match all the conditions.
Still why its giving me both entity data. I dont understand here.

I can also override the analyzer while querying by having KeywordTokenizer instead of NGramFilterFactory but this is like I have to override for each and every field before creating QueryBuilder which doesnt looks good because then I have to override all index fields which I have about 100 fields and some are dynamic fields and I create individual query for each field.

Is there any other way to override the analyzer in 5.11 version or is it handled in some other way in hibernate-search 6.x version in easier way?

Hibernate versions that I use are,

hibernate-search-elasticsearch, hibernate-search-orm = 5.11.4.Final

答:
Above Lucene query is prepared using BooleanJunction::must conditions by Lucene I guess which means it should match all the conditions. Still why its giving me both entity data. I dont understand here.

When you create a keyword query using Hibernate Search, the string passed to that query is analyzed, and if there are multiple tokens, Hibernate Search creates a boolean query with one "should" clause for each token. You can see it here " bookName:x bookName:xg bookName:g": there is no "+" sign before "bookName", which means those are not "must" clauses, they are "should" clauses.

I can also override the analyzer while querying by having KeywordTokenizer instead of NGramFilterFactory but this is like I have to override for each and every field before creating QueryBuilder which doesnt looks good because then I have to override all index fields which I have about 100 fields and some are dynamic fields and I create individual query for each field.

True, that's annoying.

Is there any other way to override the analyzer in 5.11 version

In 5.11, I don't think there is any other way to override analyzers.

If necessary and if you're using the Lucene backend, I believe you should be able to bypass the Hibernate Search DSL just for this specific query:

Get the analyzer you want: something like Analyzer analyzer = fullTextSession.getSearchFactory().getAnalyzer("myAnalyzerWithoutNGramTokenFilter").

Analyze the search terms: call analyzer.tokenStream(...) and use the TokenStream as appropriate. You'll get a list of tokens.

Create the Lucene Query: essentially it will be a boolean query with one TermQuery for each token.

Pass the resulting Query to Hibernate Search as usual.

or is it handled in some other way in hibernate-search 6.x version in easier way?

It's dead simple in Hibernate Search 6.0.0.Beta4. There are two solutions:

Implicitly: in your mapping, you can specify not only an analyzer (using @FullTextField(analyzer = "myAnalyzer")), but also a "search" analyzer using @FullTextField(analyzer = "myAnalyzer", searchAnalyzer = "mySearchAnalyzer"). The "default" analyzer will be used when indexing, while the "search" analyzer will be used when searching (querying).

Explicitly: at query time, you can override the analyzer on a given predicate by calling .analyzer("mySearchAnalyzer") while building the predicate. There is one example in this section of the documentation.

Note however that dynamic fields are not supported yet in Hibernate Search 6: HSEARCH-3273.

Body:
I have an analyzer with this configuration,

searchMapping//
        .analyzerDef(BaseEntity.CUSTOM_SEARCH_INDEX_ANALYZER, WhitespaceTokenizerFactory.class)//
        .filter(LowerCaseFilterFactory.class)//
        .filter(ASCIIFoldingFilterFactory.class)//
        .filter(NGramFilterFactory.class).param("minGramSize", "1").param("maxGramSize", "200");

This is how my entity field is configured

@Field(analyzer = @Analyzer(definition = CUSTOM_SEARCH_INDEX_ANALYZER))
private String bookName;

This is how I create a search query

queryBuilder.keyword().onField(prefixedPath).matching(matchingString).createQuery()

I have an entity with value bookName="Gulliver" and another entity with bookName="xGulliver";

If I tried to search with data bookName = xG then am getting both entities where I would expect entity only with bookName="xGulliver";
Also looked on the query that is produced by hibernate-search.

Executing Lucene query '+(+(+(+(
          bookName:x
          bookName:xg
          bookName:g))))

Above Lucene query is prepared using BooleanJunction::must conditions by Lucene I guess which means it should match all the conditions.
Still why its giving me both entity data. I dont understand here.

I can also override the analyzer while querying by having KeywordTokenizer instead of NGramFilterFactory but this is like I have to override for each and every field before creating QueryBuilder which doesnt looks good because then I have to override all index fields which I have about 100 fields and some are dynamic fields and I create individual query for each field.

Is there any other way to override the analyzer in 5.11 version or is it handled in some other way in hibernate-search 6.x version in easier way?

Hibernate versions that I use are,

hibernate-search-elasticsearch, hibernate-search-orm = 5.11.4.Final


问:
Passing a php session variable to HTML Select tag and show from the available list as the selected value
Currently I have a HTML select tag with some options available. For that Select tag I need to pass a session  variable and show as the selected value. Kindly provide your support to achieve this task. </p>

```<code><?php

 session_start()

 //Variable need to show in Select tag
 //Session value Equals to - Junior Executive Assistant
 $_SESSION['Designation'];

?>

<select id="designation" class="form-control" name="designation" required>

    <option value="Banking Trainee">Banking Trainee</option>
    <option value="Junior Executive Assistant">Junior Executive Assistant</option>
    <option value="Junior Executive Officer">Junior Executive Officer</option>
    <option value="Executive officer">Executive officer</option>
    <option value="Manager">Manager</option>
    <option value="Senior Manager">Senior Manager</option>
    <option value="Chief Manager">Chief Managerr</option>
</select>
</code>```

答:
You need to add a check to each of your select options to see if its value matches the value in $_SESSION['Designation'] and if so, set the selected attribute on that option. For example:

```<code><option value="Banking Trainee"<?php echo $_SESSION['Designation'] == 'Banking Trainee' ? ' selected' : ''; ?> >Banking Trainee</option>
</code>```

For the other options you would change the comparison string appropriately.

If you have PHP short tags enabled, you can simplify the code slightly by using <?= in place of <?php echo e.g.

```<code><option value="Banking Trainee"<?= $_SESSION['Designation'] == 'Banking Trainee' ? ' selected' : '' ?> >Banking Trainee</option>
</code>```

Body:
Currently I have a HTML select tag with some options available. For that Select tag I need to pass a session  variable and show as the selected value. Kindly provide your support to achieve this task.

<?php

 session_start()

 //Variable need to show in Select tag
 //Session value Equals to - Junior Executive Assistant
 $_SESSION['Designation'];

?>

<select id="designation" class="form-control" name="designation" required>

    <option value="Banking Trainee">Banking Trainee</option>
    <option value="Junior Executive Assistant">Junior Executive Assistant</option>
    <option value="Junior Executive Officer">Junior Executive Officer</option>
    <option value="Executive officer">Executive officer</option>
    <option value="Manager">Manager</option>
    <option value="Senior Manager">Senior Manager</option>
    <option value="Chief Manager">Chief Managerr</option>
</select>

Body:
You need to add a check to each of your select options to see if its value matches the value in $_SESSION['Designation'] and if so, set the selected attribute on that option. For example:

<option value="Banking Trainee"<?php echo $_SESSION['Designation'] == 'Banking Trainee' ? ' selected' : ''; ?> >Banking Trainee</option>

For the other options you would change the comparison string appropriately.

If you have PHP short tags enabled, you can simplify the code slightly by using <?= in place of <?php echo e.g.

<option value="Banking Trainee"<?= $_SESSION['Designation'] == 'Banking Trainee' ? ' selected' : '' ?> >Banking Trainee</option>


问:
How can I use different colors for different labels in TensorBoard embedding visualization?
I am visualizing sentence embedding using tensorboard. I have label for each sentence embedding. How can I set a color for each label?
For example

```<code>  embedding vector                        Labels
  [0.2342 0.2342 0.234 0.8453]             A
  [0.5342 0.9342 0.234 0.1453]             B
  [0.7342 0.0342 0.124 0.8453]             C
  [0.8342 0.5342 0.834 0.5453]             A
</code>```

I am able to visualize the embedding vector where each row is labeled by its label. I want to set colors also so that I see points with same label will have same color. Like all "A" will be red, "B" will be green, "C" will be blue and so on?

I searched on Google but didn't get any sample.
Could anyone please share some code to get it done?

Thank you in advanced.

答:
There should be a colour by drop down that you can use.
In case that is not showing up, one of the possible reason could be that you have more than 50 unique labels, which is the hardcoded limit in the current tensorflow code.

Refer to this thread for details.

https://github.com/tensorflow/tensorboard/issues/61

Body:
I am visualizing sentence embedding using tensorboard. I have label for each sentence embedding. How can I set a color for each label?
For example

  embedding vector                        Labels
  [0.2342 0.2342 0.234 0.8453]             A
  [0.5342 0.9342 0.234 0.1453]             B
  [0.7342 0.0342 0.124 0.8453]             C
  [0.8342 0.5342 0.834 0.5453]             A

I am able to visualize the embedding vector where each row is labeled by its label. I want to set colors also so that I see points with same label will have same color. Like all "A" will be red, "B" will be green, "C" will be blue and so on?

I searched on Google but didn't get any sample.
Could anyone please share some code to get it done?

Thank you in advanced.


问:
Kubernetes YAML deploy for multiple images in same pod?
I would to deploy, through kubernetes, two applications in local docker images (no docker hub/artifactory). I want them to see each other through name (no ip), so I should deploy them in the same POD and load the name of the first as system environment variable in the second container.

They should be both visible from the external, so I need NodePort deploy and I would be able to choose the port.

I know how to reach this goal through kubectl cli commands, but I would to have the result through a YAML configuration file so I can apply with the command kubectl apply -f deploy.yml

答:
Technically, You can deploy multiple app containers in same POD but you should avoid that as

you want to scale them independently (X replicas of APP1 and Y replicas of APP2)

also to keep resource allocation dedicated to one kind of application

and many more benefits of isolation

As far as communicating them via name (no IP) kubernetes has the concept of services to achieve that with ease.

All of this can be written in YAML format

You can see this:

https://kubernetes.io/docs/tasks/access-application-cluster/connecting-frontend-backend/

https://kubernetes.io/docs/tutorials/stateless-application/guestbook/

BUT STILL If you want to do this........
Then containers inside same pod can communicate with each other using localhost and in YML can you define spec for multiple container

```<code>apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app: myapp
spec:
  containers:
  - name: app1-container
    image: app1
  - name: .... for app 2
    image: app2
</code>```

Body:
Technically, You can deploy multiple app containers in same POD but you should avoid that as

you want to scale them independently (X replicas of APP1 and Y replicas of APP2)

also to keep resource allocation dedicated to one kind of application

and many more benefits of isolation

As far as communicating them via name (no IP) kubernetes has the concept of services to achieve that with ease.

All of this can be written in YAML format

You can see this:

https://kubernetes.io/docs/tasks/access-application-cluster/connecting-frontend-backend/

https://kubernetes.io/docs/tutorials/stateless-application/guestbook/

BUT STILL If you want to do this........
Then containers inside same pod can communicate with each other using localhost and in YML can you define spec for multiple container

apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app: myapp
spec:
  containers:
  - name: app1-container
    image: app1
  - name: .... for app 2
    image: app2


答:
Change this to :

    allowed_domains = ['https://www.levenhuk.bg/']
```

<pre class="lang-py prettyprint-override"><code>    allowed_domains = ['levenhuk.bg']
</code>```

You also need to change:

   next_page_url = response.xpath('//*[@class="pagesCount"][1]//@href').get()
```

This will only work for the first page, for page 2,3,4.., this will extract a link to the first page.

And also add a callback as mentioned by UzairAhmed.

Title: Problems getting next page when scraping with scrapy

Body:
Change this to :

    allowed_domains = ['https://www.levenhuk.bg/']

    allowed_domains = ['levenhuk.bg']

You also need to change:

   next_page_url = response.xpath('//*[@class="pagesCount"][1]//@href').get()

This will only work for the first page, for page 2,3,4.., this will extract a link to the first page.

And also add a callback as mentioned by UzairAhmed.


问:
How to Push ViewController in new window
I need to push viewController in the new window by code. I am doing below code but its not working.

```<code>let win = UIWindow(frame: UIScreen.main.bounds)
let nc = UINavigationController(rootViewController: self)
nc.view.backgroundColor = .clear
win.rootViewController = nc

win.windowLevel = UIWindow.Level.alert + 1
win.makeKeyAndVisible()
</code>```

Does anyone have idea, how to push a viewController in new window?

答:
Swift 5.x

Below code works

took global variable:

```<code>var window2 : UIWindow?
</code>```

Modified code with below

```<code>let win = UIWindow(frame: UIScreen.main.bounds)
let nc = UINavigationController()
nc.pushViewController(self, animated: true)
nc.navigationBar.isHidden = true
nc.view.backgroundColor = .clear
win.rootViewController = nc
window2 = win
win.windowLevel = UIWindow.Level.alert + 1
win.makeKeyAndVisible()
</code>```

And dismiss new window I did below

```<code>if let nc = window2?.rootViewController as? UINavigationController {
    nc.popViewController(animated: true)
}

window2?.resignKey()
window2 = nil
</code>```

Note: It is not showing push and pop default animation, rather currently it is working w/o any kind of animation.

Ref : To create a new UIWindow over the main window

Body:
I need to push viewController in the new window by code. I am doing below code but its not working.

let win = UIWindow(frame: UIScreen.main.bounds)
let nc = UINavigationController(rootViewController: self)
nc.view.backgroundColor = .clear
win.rootViewController = nc

win.windowLevel = UIWindow.Level.alert + 1
win.makeKeyAndVisible()

Does anyone have idea, how to push a viewController in new window?

Body:
Swift 5.x

Below code works

took global variable:

var window2 : UIWindow?

Modified code with below

let win = UIWindow(frame: UIScreen.main.bounds)
let nc = UINavigationController()
nc.pushViewController(self, animated: true)
nc.navigationBar.isHidden = true
nc.view.backgroundColor = .clear
win.rootViewController = nc
window2 = win
win.windowLevel = UIWindow.Level.alert + 1
win.makeKeyAndVisible()

And dismiss new window I did below

if let nc = window2?.rootViewController as? UINavigationController {
    nc.popViewController(animated: true)
}

window2?.resignKey()
window2 = nil

Note: It is not showing push and pop default animation, rather currently it is working w/o any kind of animation.

Ref : To create a new UIWindow over the main window


问:
the closest Sunday before given date with JavaScript
I need to know the date for last Sunday for given date in php & javascript

Let's have a function give_me_last_Sunday

```<code>give_me_last_Sunday('20110517') is 20110515
give_me_last_Sunday('20110604') is 20110529
</code>```

The full backup is done on Sundays = weekly. If I want to restore daily backup I need full (weekly) and daily backup. I need to copy backup files before restoring to temp directory so I restoring daily backup I need to know what weekly backup file I need to copy along the daily file.

My thought was to get Julian representation (or something similar) for the given date and then subtract 1 and check if it is Sunday ... Not sure if this is the best idea and how to convert given date into something I can subtract.

答:
final code (big thanks to @Thomas & @Rob)</p>

```<code>function lastSunday(d) {
  var d = d.replace(/(^\d{4})(\d{2})(\d{2}$)/,'$1/$2/$3');

  d = new Date(d);
  d.setDate(d.getDate() - d.getDay());

  year = d.getFullYear()+'';
  month = d.getMonth()+1+'';
  day = d.getDate()+'';
  if ( month.length == 1 ) month = "0" + month; // Add leading zeros to month and date if required
  if ( day.length == 1 ) day = "0" + day;

  return year+month+day;
}
</code>```

Body:
I need to know the date for last Sunday for given date in php & javascript

Let's have a function give_me_last_Sunday

give_me_last_Sunday('20110517') is 20110515
give_me_last_Sunday('20110604') is 20110529

The full backup is done on Sundays = weekly. If I want to restore daily backup I need full (weekly) and daily backup. I need to copy backup files before restoring to temp directory so I restoring daily backup I need to know what weekly backup file I need to copy along the daily file.

My thought was to get Julian representation (or something similar) for the given date and then subtract 1 and check if it is Sunday ... Not sure if this is the best idea and how to convert given date into something I can subtract.

Body:
final code (big thanks to @Thomas & @Rob)

function lastSunday(d) {
  var d = d.replace(/(^\d{4})(\d{2})(\d{2}$)/,'$1/$2/$3');

  d = new Date(d);
  d.setDate(d.getDate() - d.getDay());

  year = d.getFullYear()+'';
  month = d.getMonth()+1+'';
  day = d.getDate()+'';
  if ( month.length == 1 ) month = "0" + month; // Add leading zeros to month and date if required
  if ( day.length == 1 ) day = "0" + day;

  return year+month+day;
}