问:
Django Rest Framework Am I doing it right?
I have studied DRF myself and one question bothers me, unfortunately I have no one to ask and this question bothers me all the time. Is writing application logic in views (as in the attached code) a good approach? When sending a query to the server with the intention, for example, to accept an order, I have to update the values from models other than the order or carry out validation of statuses, change the data on their basis. In the first tutorials from which I learned, among others, JustDjango all logic is in the view. However, after writing some code and watching other tutorials, I feel that this is not the right approach. Should not save and update models be done through a serializer? If so, whether through one large serializer or several smaller serializers.</p>
```<code>class ZK_AddUpdateItemWithInstaReservation(APIView):
permission_classes = (IsAuthenticated,)
def post(self, request, *args, **kwargs):
    pzitem_id = request.data.get('pzitem_id')
    ordered_quantity  = request.data.get('ordered_quantity')
    order_id = request.data.get('order_id')
    user_id = request.data.get('user_id')
    item_id = request.data.get('item_id')

    if ordered_quantity:
        if int(ordered_quantity) < 0:
            return Response({'error': 'Próbujesz zamówić ujemną wartość'})
    try:
        item = Item.objects.get(id=item_id)
    except:
        return Response({'error': 'Item with given id does not exists'})
    try:
        order = Order.objects.get(id=order_id)
    except:
        return Response({'error': 'Order with given id does not exist'})
    if order.status not in ['SD', 'WTZ']:
        return Response({'message': 'Nie można zmieniać ilości na zamówionym zamówieniu lub w realizacji'})
    order.status = 'WTZ'
    order.save()
    # ORDERED ITEM WITHOUT PZITEM ON STOCK
    if not pzitem_id:
        # CHECK IF ORDER CONTAINS ORDERITEM
        try:
            orderitem = OrderItem.objects.get(pzitem=None, order=order, item=item)
            prev_ordered_quantity = orderitem.quantity
            # UPDATE ORDER ITEM VALUES
            orderitem.quantity = ordered_quantity
            orderitem.quantity_do_wydania = ordered_quantity
            orderitem.status = 'ZBR'
            orderitem.save()
            # UPDATE ITEM VALUES
            item = Item.objects.get(id=orderitem.item_id)
            prev_item_not_ordered_plus_qty_prevordered = item.quantity_not_ordered + prev_ordered_quantity
            item.quantity_not_ordered = int(prev_item_not_ordered_plus_qty_prevordered) - int(ordered_quantity)
            item.save()
            return Response({'message': 'Zaktualizowano ilość przedmiotu bez rezerwacji stanu'})
        except:
            # IF NOT CREATE ONE
            orderitem = OrderItem.objects.create(user_id=user_id, pzitem=None, item=item, quantity=ordered_quantity, quantity_do_wydania=ordered_quantity, status='ZBR', order=order)
            orderitem.save()
            # UPDATE ITEM VALUES
            item = Item.objects.get(id=orderitem.item_id)
            item.quantity_not_ordered -= int(ordered_quantity)
            item.save()
            return Response({'messsage': 'Dodano nowy przedmiot do zamowienia, status bez rezerwacji stanu.'})
    # ORDERED WITH STOCK
    else:
        try:
            pzitem = PZItem.objects.get(id=pzitem_id)
        except:
            return Response({'error': 'Nie znaleziono pzitem z podanym pzitem_id'})
        # CHECK IF ORDER CONTAINS ORDERITEM
        try:
            orderitem = OrderItem.objects.get(pzitem=pzitem, order=order, item=item)
            prev_ordered_quantity = orderitem.quantity
            if int(ordered_quantity) <= prev_ordered_quantity + orderitem.pzitem.quantity_available_to_order:
                prev_ordered_quantity = orderitem.quantity
                # UPDATE ORDER ITEM VALUES
                orderitem.status = 'ZZR'
                orderitem.quantity = ordered_quantity
                orderitem.quantity_do_wydania = ordered_quantity
                orderitem.save()

                # UPDATE ITEM VALUES
                item = Item.objects.get(id=orderitem.item_id)
                prev_item_not_ordered_plus_qty_prevordered = item.quantity_not_ordered + prev_ordered_quantity
                item.quantity_not_ordered = int(prev_item_not_ordered_plus_qty_prevordered) - int(ordered_quantity)
                item.save()
                # UPDATE PZITEM VALUES
                prev_pzitem_quantity_ordered = int(orderitem.pzitem.quantity_ordered)
                orderitem.pzitem.quantity_ordered =  int(orderitem.pzitem.quantity_ordered) - int(prev_ordered_quantity) + int(ordered_quantity)
                orderitem.pzitem.save()
                return Response({'message': 'Zaktualizowano ilość przedmiotu z rezerwacją stanu'})
            else:
                return Response({'warning': 'Zamówiono więcej niż dostępne'})
        except:
            # IF NOT CREATE ONE
            if int(ordered_quantity) or 0 <= pzitem.quantity_available_to_order:
                orderitem = OrderItem.objects.create(user_id=user_id, pzitem=pzitem, item=item, quantity=ordered_quantity, quantity_do_wydania=ordered_quantity, status='ZZR', order=order)
                orderitem.save()
                # UPDATE ITEM VALUES
                item = Item.objects.get(id=orderitem.item_id)
                item.quantity_not_ordered -= int(ordered_quantity)
                item.save()
                # UPDATE PZITEM VALUES
                orderitem.pzitem.quantity_ordered += int(ordered_quantity)
                orderitem.pzitem.save()
                return Response({'messsage': 'Dodano nowy przedmiot do zamowienia, status zamówiono z rezerwacją stanu.'})
            else:
                return Response({'warning': 'Zamówiono więcej niż dostępne'})
</code>```

答:
You have so much logic in views.py its not a best way. Separate your model actions to other views and serializer. For example for your order operations you can implement view and serializers like this.

```<code>class UpdateOrderSerializer(serializers.ModelSerializer):
    pzitem_id = serializers.CharField()
    ordered_quantity = serializers.IntegerField()
    user = serializers.PrimaryKeyRelatedField(User.objects.all())
    item = serializers.PrimaryKeyRelatedField(OrderItem.objects.all())

    class Meta:
        model = Order

    def validate(self, attrs):
        attrs = super().validate(attrs)
        if attrs["ordered_quantity"] < 0:
            raise serializers.ValidationError(dict(ordered_quantity="Próbujesz zamówić ujemną wartość"))

    def update(self, instance, validated_data):
        instance.status = "WTZ"
        # do some other things
        instance.save()
        return instance

class ZK_AddUpdateItemWithInstaReservation(ModelViewSet):
    permission_classes = (IsAuthenticated,)
    serializer_class = OrderSerializer
    queryset = Order.objects.all()

    @action(detail=True)
    def update_order(self, request, pk):
        serializer = self.get_serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(status=HTTP_200_OK, data={})
</code>```

If you have so much operations which is related between them. You can create a pipelines. Like this;

```<code>class YourPipeline:
    def __init__(self, past_some_data):
        self.past_some_data = past_some_data

    def update_order_status(self):
        # update your order

    def create_order_item(self):
        # do something else

    def some_function(self):
        # another operation

    def run(self):
        self.update_order_status()
        self.create_order_item()
        self.some_function()
        return instance

class UpdateOrderSerializer(serializers.ModelSerializer):
    pzitem_id = serializers.CharField()
    ordered_quantity = serializers.IntegerField()
    user = serializers.PrimaryKeyRelatedField(User.objects.all())
    item = serializers.PrimaryKeyRelatedField(OrderItem.objects.all())

    class Meta:
        model = Order

    def validate(self, attrs):
        attrs = super().validate(attrs)
        if attrs["ordered_quantity"] < 0:
            raise serializers.ValidationError(dict(ordered_quantity="Próbujesz zamówić ujemną wartość"))

    def update(self, instance, validated_data):
        pipeline = YourPipeline(past_some_data=past_some_data)
        return pipeline.run()

class ZK_AddUpdateItemWithInstaReservation(ModelViewSet):
    permission_classes = (IsAuthenticated,)
    serializer_class = OrderSerializer
    queryset = Order.objects.all()

    @action(detail=True)
    def update_order(self, request, pk):
        serializer = self.get_serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(status=HTTP_200_OK)
</code>```

Body:
I have studied DRF myself and one question bothers me, unfortunately I have no one to ask and this question bothers me all the time. Is writing application logic in views (as in the attached code) a good approach? When sending a query to the server with the intention, for example, to accept an order, I have to update the values from models other than the order or carry out validation of statuses, change the data on their basis. In the first tutorials from which I learned, among others, JustDjango all logic is in the view. However, after writing some code and watching other tutorials, I feel that this is not the right approach. Should not save and update models be done through a serializer? If so, whether through one large serializer or several smaller serializers.

class ZK_AddUpdateItemWithInstaReservation(APIView):
permission_classes = (IsAuthenticated,)
def post(self, request, *args, **kwargs):
    pzitem_id = request.data.get('pzitem_id')
    ordered_quantity  = request.data.get('ordered_quantity')
    order_id = request.data.get('order_id')
    user_id = request.data.get('user_id')
    item_id = request.data.get('item_id')

    if ordered_quantity:
        if int(ordered_quantity) < 0:
            return Response({'error': 'Próbujesz zamówić ujemną wartość'})
    try:
        item = Item.objects.get(id=item_id)
    except:
        return Response({'error': 'Item with given id does not exists'})
    try:
        order = Order.objects.get(id=order_id)
    except:
        return Response({'error': 'Order with given id does not exist'})
    if order.status not in ['SD', 'WTZ']:
        return Response({'message': 'Nie można zmieniać ilości na zamówionym zamówieniu lub w realizacji'})
    order.status = 'WTZ'
    order.save()
    # ORDERED ITEM WITHOUT PZITEM ON STOCK
    if not pzitem_id:
        # CHECK IF ORDER CONTAINS ORDERITEM
        try:
            orderitem = OrderItem.objects.get(pzitem=None, order=order, item=item)
            prev_ordered_quantity = orderitem.quantity
            # UPDATE ORDER ITEM VALUES
            orderitem.quantity = ordered_quantity
            orderitem.quantity_do_wydania = ordered_quantity
            orderitem.status = 'ZBR'
            orderitem.save()
            # UPDATE ITEM VALUES
            item = Item.objects.get(id=orderitem.item_id)
            prev_item_not_ordered_plus_qty_prevordered = item.quantity_not_ordered + prev_ordered_quantity
            item.quantity_not_ordered = int(prev_item_not_ordered_plus_qty_prevordered) - int(ordered_quantity)
            item.save()
            return Response({'message': 'Zaktualizowano ilość przedmiotu bez rezerwacji stanu'})
        except:
            # IF NOT CREATE ONE
            orderitem = OrderItem.objects.create(user_id=user_id, pzitem=None, item=item, quantity=ordered_quantity, quantity_do_wydania=ordered_quantity, status='ZBR', order=order)
            orderitem.save()
            # UPDATE ITEM VALUES
            item = Item.objects.get(id=orderitem.item_id)
            item.quantity_not_ordered -= int(ordered_quantity)
            item.save()
            return Response({'messsage': 'Dodano nowy przedmiot do zamowienia, status bez rezerwacji stanu.'})
    # ORDERED WITH STOCK
    else:
        try:
            pzitem = PZItem.objects.get(id=pzitem_id)
        except:
            return Response({'error': 'Nie znaleziono pzitem z podanym pzitem_id'})
        # CHECK IF ORDER CONTAINS ORDERITEM
        try:
            orderitem = OrderItem.objects.get(pzitem=pzitem, order=order, item=item)
            prev_ordered_quantity = orderitem.quantity
            if int(ordered_quantity) <= prev_ordered_quantity + orderitem.pzitem.quantity_available_to_order:
                prev_ordered_quantity = orderitem.quantity
                # UPDATE ORDER ITEM VALUES
                orderitem.status = 'ZZR'
                orderitem.quantity = ordered_quantity
                orderitem.quantity_do_wydania = ordered_quantity
                orderitem.save()

                # UPDATE ITEM VALUES
                item = Item.objects.get(id=orderitem.item_id)
                prev_item_not_ordered_plus_qty_prevordered = item.quantity_not_ordered + prev_ordered_quantity
                item.quantity_not_ordered = int(prev_item_not_ordered_plus_qty_prevordered) - int(ordered_quantity)
                item.save()
                # UPDATE PZITEM VALUES
                prev_pzitem_quantity_ordered = int(orderitem.pzitem.quantity_ordered)
                orderitem.pzitem.quantity_ordered =  int(orderitem.pzitem.quantity_ordered) - int(prev_ordered_quantity) + int(ordered_quantity)
                orderitem.pzitem.save()
                return Response({'message': 'Zaktualizowano ilość przedmiotu z rezerwacją stanu'})
            else:
                return Response({'warning': 'Zamówiono więcej niż dostępne'})
        except:
            # IF NOT CREATE ONE
            if int(ordered_quantity) or 0 <= pzitem.quantity_available_to_order:
                orderitem = OrderItem.objects.create(user_id=user_id, pzitem=pzitem, item=item, quantity=ordered_quantity, quantity_do_wydania=ordered_quantity, status='ZZR', order=order)
                orderitem.save()
                # UPDATE ITEM VALUES
                item = Item.objects.get(id=orderitem.item_id)
                item.quantity_not_ordered -= int(ordered_quantity)
                item.save()
                # UPDATE PZITEM VALUES
                orderitem.pzitem.quantity_ordered += int(ordered_quantity)
                orderitem.pzitem.save()
                return Response({'messsage': 'Dodano nowy przedmiot do zamowienia, status zamówiono z rezerwacją stanu.'})
            else:
                return Response({'warning': 'Zamówiono więcej niż dostępne'})

Body:
You have so much logic in views.py its not a best way. Separate your model actions to other views and serializer. For example for your order operations you can implement view and serializers like this.

class UpdateOrderSerializer(serializers.ModelSerializer):
    pzitem_id = serializers.CharField()
    ordered_quantity = serializers.IntegerField()
    user = serializers.PrimaryKeyRelatedField(User.objects.all())
    item = serializers.PrimaryKeyRelatedField(OrderItem.objects.all())

    class Meta:
        model = Order

    def validate(self, attrs):
        attrs = super().validate(attrs)
        if attrs["ordered_quantity"] < 0:
            raise serializers.ValidationError(dict(ordered_quantity="Próbujesz zamówić ujemną wartość"))

    def update(self, instance, validated_data):
        instance.status = "WTZ"
        # do some other things
        instance.save()
        return instance

class ZK_AddUpdateItemWithInstaReservation(ModelViewSet):
    permission_classes = (IsAuthenticated,)
    serializer_class = OrderSerializer
    queryset = Order.objects.all()

    @action(detail=True)
    def update_order(self, request, pk):
        serializer = self.get_serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(status=HTTP_200_OK, data={})

If you have so much operations which is related between them. You can create a pipelines. Like this;

class YourPipeline:
    def __init__(self, past_some_data):
        self.past_some_data = past_some_data

    def update_order_status(self):
        # update your order

    def create_order_item(self):
        # do something else

    def some_function(self):
        # another operation

    def run(self):
        self.update_order_status()
        self.create_order_item()
        self.some_function()
        return instance

class UpdateOrderSerializer(serializers.ModelSerializer):
    pzitem_id = serializers.CharField()
    ordered_quantity = serializers.IntegerField()
    user = serializers.PrimaryKeyRelatedField(User.objects.all())
    item = serializers.PrimaryKeyRelatedField(OrderItem.objects.all())

    class Meta:
        model = Order

    def validate(self, attrs):
        attrs = super().validate(attrs)
        if attrs["ordered_quantity"] < 0:
            raise serializers.ValidationError(dict(ordered_quantity="Próbujesz zamówić ujemną wartość"))

    def update(self, instance, validated_data):
        pipeline = YourPipeline(past_some_data=past_some_data)
        return pipeline.run()

class ZK_AddUpdateItemWithInstaReservation(ModelViewSet):
    permission_classes = (IsAuthenticated,)
    serializer_class = OrderSerializer
    queryset = Order.objects.all()

    @action(detail=True)
    def update_order(self, request, pk):
        serializer = self.get_serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(status=HTTP_200_OK)


来源: stackexchange

问:
How to get the name from an ID in another table
```<code><% @contacts.each do |contact| %>
    <%= contact.company_id %>
<% end %>
</code>```

I want to get the company_id's name somehow from the other table.

I've tried <%= contact.company_id.collect(&:name) %>

without success can i get some help here?

答:
```<code># Models
class Contact < ActiveRecord::Base
  belongs_to :company
end

class Company < ActiveRecord::Base
  has_many :contacts
end

<% @contacts.each do |contact| %>
  <%= contact.company.name %>
<% end %>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
<% @contacts.each do |contact| %>
    <%= contact.company_id %>
<% end %>

I want to get the company_id's name somehow from the other table.

I've tried <%= contact.company_id.collect(&:name) %>

without success can i get some help here?


问:
SAS to HIVE2 Cloudera - Error trying to write
I have the following error while trying to write on the hive2 db :

```<code>ERROR: java.io.IOException: Could not get block locations. Source file "/tmp/sasdata-e1-...dlv - Aborting...block==null
</code>```

the error appears when trying to write a new table or append rows to an existing table. I can connect correctly to the db (through a libname), read tables from the schema and when trying to create a new table the new table get created but empty because the error above happens .
Can someone help pls?

Thank you

答:
Remember that hive is mostly just a metadatastore that helps you to read files from HDFS.  Yes, it does this through a database paradigm but it's really operating on HDFS.  Each table is created in an HDFS directory, and files are created.

This sounds like you don't have write permissions to the hdfs folder you are writing to. (but you have read)

To solve this problem you need to understand what user you are using and where the data is being written.

If you are creating a simple table you need to check if you can write to the hive warehouse directory.  If you are purposely creating files in a specific hDFS folder you should check that.
Here's a command to help you determine where the data is being written to.

```<code>show create table [mytable]
</code>```

If it doesn't mention a HDFS location you need to find get permissions to the hive warehouse. (Typicallys located hdfs:/user/hive/warehouse  , but is actually defined in $HIVE_HOME/conf/hive-default.xml if it's located elsewhere).

ContentLicense: CC BY-SA 4.0

Body:
I have the following error while trying to write on the hive2 db :

ERROR: java.io.IOException: Could not get block locations. Source file "/tmp/sasdata-e1-...dlv - Aborting...block==null

the error appears when trying to write a new table or append rows to an existing table. I can connect correctly to the db (through a libname), read tables from the schema and when trying to create a new table the new table get created but empty because the error above happens .
Can someone help pls?

Thank you

Body:
Remember that hive is mostly just a metadatastore that helps you to read files from HDFS.  Yes, it does this through a database paradigm but it's really operating on HDFS.  Each table is created in an HDFS directory, and files are created.

This sounds like you don't have write permissions to the hdfs folder you are writing to. (but you have read)

To solve this problem you need to understand what user you are using and where the data is being written.

If you are creating a simple table you need to check if you can write to the hive warehouse directory.  If you are purposely creating files in a specific hDFS folder you should check that.
Here's a command to help you determine where the data is being written to.

show create table [mytable]

If it doesn't mention a HDFS location you need to find get permissions to the hive warehouse. (Typicallys located hdfs:/user/hive/warehouse  , but is actually defined in $HIVE_HOME/conf/hive-default.xml if it's located elsewhere).


问:
Get a portion of numbers from a pandas column with dtype int
How do I get the first 8 digits from a column with 15 digits?

```<code>data = [['tom', 355552107972100], ['nick', 356557107972103], ['juli', 455552107972100]]

df = pd.DataFrame(data, columns = ['Name', 'Code'])
</code>```
```<code>    Name    Code
0   tom     355552107972100
1   nick    356557107972103
2   juli    455552107972100
</code>```

I want to create a new column with the first 8 digits from the code column

答:
Convert values to strings and use indexing:

```<code>df['Code'] =  df['Code'].astype(str).str[:8].astype(int)
</code>```

Or:

```<code>df['Code'] =  df['Code'].map(lambda x: int(str(x)[:8]))
</code>```

Or use integer division (working correct if always 15 digits):

```<code>df['Code'] = df['Code'] // 10000000
</code>```

Body:
How do I get the first 8 digits from a column with 15 digits?

data = [['tom', 355552107972100], ['nick', 356557107972103], ['juli', 455552107972100]]

df = pd.DataFrame(data, columns = ['Name', 'Code'])

    Name    Code
0   tom     355552107972100
1   nick    356557107972103
2   juli    455552107972100

I want to create a new column with the first 8 digits from the code column

Body:
Convert values to strings and use indexing:

df['Code'] =  df['Code'].astype(str).str[:8].astype(int)

Or:

df['Code'] =  df['Code'].map(lambda x: int(str(x)[:8]))

Or use integer division (working correct if always 15 digits):

df['Code'] = df['Code'] // 10000000


问:
Can we add buttons for input on a Splash screen?
I have to work on an app where the user has to interact with the app fast ( its for an emergency)

Is there a way to implement a pair of buttons on a preloader screen / splash screen on a PWA ?

PS:- I am a beginner please excuse me if this is a dumb question

答:
No, you cannot add buttons to the splash screen.

You can customize it by selecting a background color or icon (through the manifest.json file). The splash screen disappears as soon as the PWA is loaded.

If you are interested in learning more about PWAs, I wrote a series of articles about this topic.


问:
How to pass a generic type into an object property callback function
I'm trying to pass a generic type to a callback lambda function

```<code>interface Interface {
   onChange: <T = string>(val: T) => void
}

const handleOnChange = (val: MY_ENUM) => {...}

const myConfig: Interface[] = [{
    onChange: <MY_ENUM>(val) => handleOnChange(val);
}]
</code>```

the code above doesn't work.

答:
```<code>interface Interface {
  onChange: <T = string>(val: T) => void
}

const handleOnChange = <T,>(val: T) => { }

const myConfig: Interface[] = [{
  onChange: handleOnChange
}]
</code>```

You had to add a COMMA at the beginning of your config function when passing the generic

Thanks to,
@captain-yossarian

Body:
I'm trying to pass a generic type to a callback lambda function

interface Interface {
   onChange: <T = string>(val: T) => void
}

const handleOnChange = (val: MY_ENUM) => {...}

const myConfig: Interface[] = [{
    onChange: <MY_ENUM>(val) => handleOnChange(val);
}]

the code above doesn't work.

Body:
interface Interface {
  onChange: <T = string>(val: T) => void
}

const handleOnChange = <T,>(val: T) => { }

const myConfig: Interface[] = [{
  onChange: handleOnChange
}]

You had to add a COMMA at the beginning of your config function when passing the generic

Thanks to,
@captain-yossarian


问:
Call Function out of React Component
I want to update a shopping cart when I click on a Product. But I don't know, how to call the function in another component.

This is, where the function is written and the state of the cart is hold.

```<code>    export const Cart = () => {
    const [userId, setUserId] = useState(7);
    const [cart, setCart] = useState([]);
    const [outfitName, setOutfitName] = useState("");

    const sendOutfit = () => {
        axios.post(`{url}/postOutfit`, {
            userId,
            outfitName,
            cart,
        });
    };

    function addToCart(id) {
        cart.push(id);
        setCart(cart);
    }
...
}
</code>```

Here I want to call the addToCart function.

```<code>import { Cart } from "../../sites/Cart/Cart";
...

 <div className="product-name">
                    <button
                        className="button is-small is-outlined is-primary"
                        onClick={() =>
                            Cart.addToCart(product.id) & changeButtonText
                        }
                    >
                        {buttonText}
                    </button>
                </div>
</code>```

When I try to execute this, I get the following error message:

Do you have any suggestion for me?

Thank you very much!

答:
You can not do this like that. Below I wrote simple example and here is nice article I suggest to read it first: Components and Props</p>
```<code>const AddToCartButton = ({ setCart }) => {
  return (
    <button
      onClick={() => {
        setCart("item");
      }}
    ></button>
  );
};
const Cart = () => {
  const [cart, setCart] = React.useState([]);
  return <AddToCartButton setCart={setCart} />;
};
</code>```

Title: Call Function out of React Component

Body:
I want to update a shopping cart when I click on a Product. But I don't know, how to call the function in another component.

This is, where the function is written and the state of the cart is hold.

    export const Cart = () => {
    const [userId, setUserId] = useState(7);
    const [cart, setCart] = useState([]);
    const [outfitName, setOutfitName] = useState("");

    const sendOutfit = () => {
        axios.post(`{url}/postOutfit`, {
            userId,
            outfitName,
            cart,
        });
    };

    function addToCart(id) {
        cart.push(id);
        setCart(cart);
    }
...
}

Here I want to call the addToCart function.

import { Cart } from "../../sites/Cart/Cart";
...

                    <button
                        className="button is-small is-outlined is-primary"
                        onClick={() =>
                            Cart.addToCart(product.id) & changeButtonText
                        }
                    >
                        {buttonText}
                    </button>

When I try to execute this, I get the following error message:

Do you have any suggestion for me?

Thank you very much!

Body:
You can not do this like that. Below I wrote simple example and here is nice article I suggest to read it first: Components and Props

const AddToCartButton = ({ setCart }) => {
  return (
    <button
      onClick={() => {
        setCart("item");
      }}
    ></button>
  );
};
const Cart = () => {
  const [cart, setCart] = React.useState([]);
  return <AddToCartButton setCart={setCart} />;
};


问:
I don't know what is wrong with my condition statements
Its not working  this is what I am trying to do.

finding out the tax of a person and subtract some based on their status and dependents my expected output is the user will enter its income then will multiply how much tax will be deducted and will also deduct some based on their status and how many dependents

They have:

```<code>Income: 500000
Status: Married
Dependents= 3
Tax = 25000
</code>```
```<code>income = float(input("your income: "))
if income <= 100000:
    initialIncome = income * .5
elif income in range (100001,250000):
    initialIncome = income * .10
elif income in range (250001,500000):
    initialIncome = income * .15
elif income >= 500001:
    initialIncome = income * .20

status = input("status (s,m,w,d) ")
if status == "S":
    S = 10000
elif status == "M":
    S = 20000
elif status == "W":
    S = 10000
elif status == "D":
    S = 30000

dependents = float(input("dependents num: "))
if dependents >= 5:
    dependentsPrice = 50000
if dependents <= 5:
    dependentsPrice = 10000 * dependents

totalTax = initialIncome - (status + dependents)

print(totalTax)
</code>```

答:
Code:

You are using status in totalTax instead of S.

You must add .upper() to convert all the input strings to upper case as you have used uppercase in if statements.

```<code>income = float(input("your income: "))
if income <= 100000:
    initialIncome = income * .5
elif income in range (100001,250000):
    initialIncome = income * .10
elif income in range (250001,500001):
    initialIncome = income * .15
elif income >= 500001:
    initialIncome = income * .20
else:
    print("Invalid input")
    initaialIncome = 0

# Here you must add upper to convert all the strings to upper case
status = input("status (s,m,w,d) ").upper()
#To prevent undefined error
S =
if status == "S":
    S = 10000
elif status == "M":
    S = 20000
elif status == "W":
    S = 10000
elif status == "D":
    S = 30000
#In case user enters wrong input.
else:
    print("Invalid input")

dependents = float(input("dependents num: "))
if dependents >= 5:
    dependentsPrice = 50000 *dependents
if dependents <= 5:
    dependentsPrice = 10000 * dependents

# Here status is string. I suppose you are trying to use S.
#here use dependsPrice
totalTax = initialIncome - (S + dependentsPrice)

print(totalTax)
</code>```

Body:
Its not working  this is what I am trying to do.

finding out the tax of a person and subtract some based on their status and dependents my expected output is the user will enter its income then will multiply how much tax will be deducted and will also deduct some based on their status and how many dependents

They have:

Income: 500000
Status: Married
Dependents= 3
Tax = 25000

income = float(input("your income: "))
if income <= 100000:
    initialIncome = income * .5
elif income in range (100001,250000):
    initialIncome = income * .10
elif income in range (250001,500000):
    initialIncome = income * .15
elif income >= 500001:
    initialIncome = income * .20

status = input("status (s,m,w,d) ")
if status == "S":
    S = 10000
elif status == "M":
    S = 20000
elif status == "W":
    S = 10000
elif status == "D":
    S = 30000

dependents = float(input("dependents num: "))
if dependents >= 5:
    dependentsPrice = 50000
if dependents <= 5:
    dependentsPrice = 10000 * dependents

totalTax = initialIncome - (status + dependents)

print(totalTax)

Body:
Code:

You are using status in totalTax instead of S.

You must add .upper() to convert all the input strings to upper case as you have used uppercase in if statements.

income = float(input("your income: "))
if income <= 100000:
    initialIncome = income * .5
elif income in range (100001,250000):
    initialIncome = income * .10
elif income in range (250001,500001):
    initialIncome = income * .15
elif income >= 500001:
    initialIncome = income * .20
else:
    print("Invalid input")
    initaialIncome = 0

# Here you must add upper to convert all the strings to upper case
status = input("status (s,m,w,d) ").upper()
#To prevent undefined error
S =
if status == "S":
    S = 10000
elif status == "M":
    S = 20000
elif status == "W":
    S = 10000
elif status == "D":
    S = 30000
#In case user enters wrong input.
else:
    print("Invalid input")

dependents = float(input("dependents num: "))
if dependents >= 5:
    dependentsPrice = 50000 *dependents
if dependents <= 5:
    dependentsPrice = 10000 * dependents

# Here status is string. I suppose you are trying to use S.
#here use dependsPrice
totalTax = initialIncome - (S + dependentsPrice)

print(totalTax)


问:
How do i set the domain of an axis to a value that isn't a multiple of five in Altair?
I'm trying to set the x-axis domain to between 0-36, as some data I'm processing was collected in 6-week increments. Following the documentation i used the scale=alt.Scale(domain=[0,36]).  However, this continues to show the chart up to 40.

```<code>df = pd.DataFrame({'x':[0,6,12,18,24,30,36],'y':[0,3,1,4,2,5,3]})
alt.Chart(df).mark_line(point=True).encode(
    x=alt.X('x:Q',
            axis=alt.Axis(values=[0,6,12,18,24,30,36]),
            scale=alt.Scale(domain=[0,36])),
    y=alt.Y('y:Q'),
)
</code>```

Output of code above

Changing the above code to cut off between 30 and 35 i.e., scale=alt.Scale(domain=[0,31]) generates this behavior, where the chart axis gets truncated at 30 (but shows the data after 30, appropriately since the data hasn't been clipped).

But why can't I cut off the graph at values that aren't multiples of 5?

I'm using Altair v4.0.1

答:
The Vega-Lite renderer defaults to choosing "nice" values for the scale. If you want to disable this behavior, you can pass nice=False:

import pandas as pd
import altair as alt

df = pd.DataFrame({'x':[0,6,12,18,24,30,36],'y':[0,3,1,4,2,5,3]})
alt.Chart(df).mark_line(point=True).encode(
    x=alt.X('x:Q',
            axis=alt.Axis(values=[0,6,12,18,24,30,36]),
            scale=alt.Scale(domain=[0,36], nice=False)),
    y=alt.Y('y:Q'),
)
```

Body:
I'm trying to set the x-axis domain to between 0-36, as some data I'm processing was collected in 6-week increments. Following the documentation i used the scale=alt.Scale(domain=[0,36]).  However, this continues to show the chart up to 40.

df = pd.DataFrame({'x':[0,6,12,18,24,30,36],'y':[0,3,1,4,2,5,3]})
alt.Chart(df).mark_line(point=True).encode(
    x=alt.X('x:Q',
            axis=alt.Axis(values=[0,6,12,18,24,30,36]),
            scale=alt.Scale(domain=[0,36])),
    y=alt.Y('y:Q'),
)

Output of code above

Changing the above code to cut off between 30 and 35 i.e., scale=alt.Scale(domain=[0,31]) generates this behavior, where the chart axis gets truncated at 30 (but shows the data after 30, appropriately since the data hasn't been clipped).

But why can't I cut off the graph at values that aren't multiples of 5?

I'm using Altair v4.0.1


问:
Categorize foreach loop results with subheaders
I am displaying the result of a repeater field (wordpress/acf) with the following code :

```<code><?php
$rows = get_field('resa_table');
if( $rows ) {

echo '<table>';

foreach( $rows as $row ) {
$name = $row['name'];
$department = $row['department'];
?>

<tr>
    <td><?php echo $name; ?></td>
    <td><?php echo $department; ?></td>
</tr>

<?php } echo '</table>'; } ?>
</code>```

I would like - at least - to sort the results by "department" values. I looked it up on other threads and it doesn't seem too complicated.

I haven't tried it yet though, because what I want to do is a little more complex : I would like to categorize the results by position values AND add a header row before each new "department", in order to get to this result :

```<code><table>
<tr class="department"><td>Marketing</td></tr>
<tr><td>John</td></tr>
<tr><td>Mary</td></tr>
<tr class="department"><td>Finance</td></tr>
<tr><td>Jack</td></tr>
<tr><td>Jane</td></tr>
</table>
</code>```

Is this doable ?

答:
I make one array like yours data and try make what you want..
Here php codes;

```<code>        <?php

    $rows =  array(
        array("name" => "jhon", "department" => "Marketing"),
        array("name" => "mary", "department" => "Marketing"),
        array("name" => "Jack", "department" => "Finance"),
        array("name" => "Jane", "department" => "Finance")
    );

    // update
    // these codes will sort the array by department.
    $department = array_column($rows, 'department');
    array_multisort($department, SORT_DESC, $rows);
    // update

    if ($rows) {
        echo '<table>';
        $check_department = "";

        foreach ($rows as $row) {
            $name = $row['name'];
            $department = $row['department'];

            if ($check_department !=  $department) {
                $check_department  = $row['department'];
                echo "<tr class=\"" . $department . "\"><td>" . $department . "</td></tr>";
            } else {
            }
    ?>
            <tr>
                <td><?php echo $name; ?></td>
            </tr>
    <?php

        }
        echo '</table>';
    } ?>
</code>```

This codes result is;

```<code>     <table>
     <tr class="Marketing"><td>Marketing</td></tr>
     <tr><td>jhon</td></tr>
     <tr><td>mary</td></tr>
     <tr class="Finance"><td>Finance</td></tr>
     <tr><td>Jack</td></tr>
     <tr><td>Jane</td></tr>
     </table>
</code>```

Body:
I am displaying the result of a repeater field (wordpress/acf) with the following code :

<?php
$rows = get_field('resa_table');
if( $rows ) {

echo '
';

foreach( $rows as $row ) {
$name = $row['name'];
$department = $row['department'];
?>

    <?php echo $name; ?>
    <?php echo $department; ?>

<?php } echo '
'; } ?>

I would like - at least - to sort the results by "department" values. I looked it up on other threads and it doesn't seem too complicated.

I haven't tried it yet though, because what I want to do is a little more complex : I would like to categorize the results by position values AND add a header row before each new "department", in order to get to this result :

Marketing

John

Mary

Finance

Jack

Jane

Is this doable ?

Body:
I make one array like yours data and try make what you want..
Here php codes;

        <?php

    $rows =  array(
        array("name" => "jhon", "department" => "Marketing"),
        array("name" => "mary", "department" => "Marketing"),
        array("name" => "Jack", "department" => "Finance"),
        array("name" => "Jane", "department" => "Finance")
    );

    // update
    // these codes will sort the array by department.
    $department = array_column($rows, 'department');
    array_multisort($department, SORT_DESC, $rows);
    // update

    if ($rows) {
        echo '<table>';
        $check_department = "";

        foreach ($rows as $row) {
            $name = $row['name'];
            $department = $row['department'];

            if ($check_department !=  $department) {
                $check_department  = $row['department'];
                echo "<tr class=\"" . $department . "\"><td>" . $department . "</td></tr>";
            } else {
            }
    ?>
            <tr>
                <td><?php echo $name; ?></td>
            </tr>
    <?php

        }
        echo '</table>';
    } ?>

This codes result is;

     <table>
     <tr class="Marketing"><td>Marketing</td></tr>
     <tr><td>jhon</td></tr>
     <tr><td>mary</td></tr>
     <tr class="Finance"><td>Finance</td></tr>
     <tr><td>Jack</td></tr>
     <tr><td>Jane</td></tr>
     </table>


问:
Using ctrl+arrow to jump between punctuation in VSCode?
VSCode has a handy keybinding to jump by identifier using ctrl+arrow. However, I would like to change the behaviour of this slightly.

For example, my code looks like this: (| stands for the cursor)

```<code>|bar(foo.baz)
</code>```

ctrl+right:

```<code>bar(|foo.baz)
</code>```

I would like VSCode to treat the parentheses and other punctuation such as . as identifiers when I press ctrl+arrow so that each one has its own "stop". In my previous example I would like this to happen after repeated ctrl+right presses:

```<code>|bar(foo.baz)
bar|(foo.baz)
bar(|foo.baz)
bar(foo|.baz)
bar(foo.|baz)
bar(foo.baz|)
bar(foo.baz)|
</code>```

This is what actually happens:

```<code>|bar(foo.baz)
bar(|foo.baz)
bar(foo.|baz)
bar(foo.baz)|
</code>```

I've discovered that the Stack Exchange text editor has the behaviour I want, so you can try navigating some code in the Answer box using ctrl+arrow yourself to see what I mean.

Is there a setting or even extension that does this? I've tried googling but this problem is quite hard to describe in a short query.

答:
You can use the extension Select By

Define the following keybinding:

  {
    "key": "ctrl+right",  // or any other key combo
    "when": "editorTextFocus",
    "command": "moveby.regex",
    "args": {
      "regex": "(\\w+|.)",
      "properties": ["next", "end"]
    }
  }
```

You can tweak the regex if you want different behavior.

Body:
VSCode has a handy keybinding to jump by identifier using ctrl+arrow. However, I would like to change the behaviour of this slightly.

For example, my code looks like this: (| stands for the cursor)

|bar(foo.baz)

ctrl+right:

bar(|foo.baz)

I would like VSCode to treat the parentheses and other punctuation such as . as identifiers when I press ctrl+arrow so that each one has its own "stop". In my previous example I would like this to happen after repeated ctrl+right presses:

|bar(foo.baz)
bar|(foo.baz)
bar(|foo.baz)
bar(foo|.baz)
bar(foo.|baz)
bar(foo.baz|)
bar(foo.baz)|

This is what actually happens:

|bar(foo.baz)
bar(|foo.baz)
bar(foo.|baz)
bar(foo.baz)|

I've discovered that the Stack Exchange text editor has the behaviour I want, so you can try navigating some code in the Answer box using ctrl+arrow yourself to see what I mean.

Is there a setting or even extension that does this? I've tried googling but this problem is quite hard to describe in a short query.

Body:
You can use the extension Select By

Define the following keybinding:

  {
    "key": "ctrl+right",  // or any other key combo
    "when": "editorTextFocus",
    "command": "moveby.regex",
    "args": {
      "regex": "(\\w+|.)",
      "properties": ["next", "end"]
    }
  }

You can tweak the regex if you want different behavior.


问:
REST API query from chat bot built via RASA to any server
I am planning to build a chatbot via RASA. My goal is to build a chat bot which does following.

Get query from user

Convert it to json/html/xml query based on query.

POST to a server(supports REST API interface which understand json/xml queries)

GET answer from server and reply to user.

I heard that we have to write a script which does this ssh and get data - as a custom action. But I would like to know whether we can do POST and GET via REST APIs. Is this possible via chatbot implemented via RASA? If so, please let me know the pointers.

Thanks.

答:
To make requests to external apis you will need to implement a custom action. You can take a look at a simple chatbot I implemented with Rasa here: https://github.com/carlad/jackson

You'll see in my actions/actions.py file I implement a custom action to submit a query to the external API. In my case it's a GET request, but you can implement POST requests too.

My action then displays part of the response payload to the user in the chat conversation.


问:
how to integrate 3 language (html,javascript,css) proper php format to put in function.php file

how to integrate 3 language (HTML,javascript,CSS) proper PHP format to put in function.php file.

I made animation in 3 formats HTML, javascript, CSS but when I have seen the function.php file in PHP language I am a little stuck because I can't able to write/integrate these 3 formats in the PHP language.

here is 3 format code I need to integrate into php format-

(function() {
  var previousScroll = 0;

  $(window).scroll(function() {
    var currentScroll = $(this).scrollTop();
    if (currentScroll > previousScroll) {
      //down scroll code
      $("#repel").addClass("repel");
      $("#repel").on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function() {
        $('#repel').removeClass('repel');
      });

    } else {
      // upscroll code
      $("#repel").addClass("climb");
      $("#repel").on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function() {
        $('#repel').removeClass('climb');
      });
    }
    previousScroll = currentScroll;
  });
}());```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: 2000px;
 background:white;
  background-repeat: no-repeat;
  background-size: cover;
}

#repel {
  position: fixed;
  top: -850px;
  right: 0px;
}

.repel {
  -webkit-animation: repel 1s;
  animation: repel 1s;
}

.climb {
  -webkit-animation: climb 1s;
  animation: climb 1s;
}

@-webkit-keyframes climb {
  0% {
    -webkit-transform: translatey(0px);
  }

  50% {
    -webkit-transform: translatey(-55px);
  }

  100% {
    -webkit-transform: translatey(0px);
  }
}

@keyframes climb {
  0% {
    transform: translatey(0px);
  }

  50% {
    transform: translatey(-25px);
  }

  100% {
    transform: translatey(0px);
  }
}

@-webkit-keyframes repel {
  0% {
    -webkit-transform-origin: top right;
    -webkit-transform: rotate(0deg);
  }

  50% {
    -webkit-transform-origin: top right;
    -webkit-transform: rotate(2.5deg)skewy(-5deg);
  }

  100% {
    -webkit-transform-origin: top right;
    -webkit-transform: rotate(0deg);
  }
}

@keyframes repel {
  0% {
    transform-origin: top right;
    transform: rotate(0deg);
  }

  50% {
    transform-origin: top right;
    transform: rotate(2.5deg)skewy(-5deg);
  }

  100% {
    transform-origin: top right;
    transform: rotate(0deg);
  }
}</code>```

```
</div>
</div>
</p>
<ul>
<li>here is what I tried to implement these 3 format in PHP format but didn't work-</li>
</ul>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
    //code
$string =  '<img id="repel" src="http://s3.amazonaws.com/dfc_attachments/images/3246705/Repel.png" />';

 echo $string;

?>

<script type=\"text/javascript\">
(function() {
  var previousScroll = 0;

  $(window).scroll(function() {
    var currentScroll = $(this).scrollTop();
    if (currentScroll > previousScroll) {
      //down scroll code
      $("#repel").addClass("repel");
      $("#repel").on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function() {
        $('#repel').removeClass('repel');
      });

    } else {
      // upscroll code
      $("#repel").addClass("climb");
      $("#repel").on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function() {
        $('#repel').removeClass('climb');
      });
    }
    previousScroll = currentScroll;
  });
}());
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script></code>```

function.php file is in the WordPress theme editor. reason to integrate 3 code format in the function.php file is that after that I able to call this animation on a specific page.

any idea?

答:
You can use use nowdoc in PHP to achieve this. Try this

```<code>function somefunction(){
    return <<<'EOD'
        <style type="text/css">
            #repel {
                position: fixed;
                top: -850px;
                right: 0px;
            }

            .repel {
                -webkit-animation: repel 1s;
                animation: repel 1s;
            }

            .climb {
                -webkit-animation: climb 1s;
                animation: climb 1s;
            }

            @keyframes climb {
                0% {
                    transform: translatey(0px);
                }

                50% {
                    transform: translatey(-25px);
                }

                100% {
                    transform: translatey(0px);
                }
            }

            @keyframes repel {
                0% {
                    transform-origin: top right;
                    transform: rotate(0deg);
                }

                50% {
                    transform-origin: top right;
                    transform: rotate(2.5deg)skewy(-5deg);
                }

                100% {
                    transform-origin: top right;
                    transform: rotate(0deg);
                }
            }
        </style>
        <img id="repel" src="http://s3.amazonaws.com/dfc_attachments/images/3246705/Repel.png" />
        <script type="text/javascript">
            (function() {
                var previousScroll = 0;

                $(window).scroll(function(){
                    var currentScroll = $(this).scrollTop();
                    if(currentScroll > previousScroll){
                        //down scroll code
                        $("#repel").addClass("repel");
                        $("#repel").on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function() {
                            $('#repel').removeClass('repel');
                        });
                    }else{
                        // upscroll code
                        $("#repel").addClass("climb");
                        $("#repel").on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function() {
                            $('#repel').removeClass('climb');
                        });
                    }
                    previousScroll = currentScroll;
                });
            }());
        </script>
EOD;
}
</code>```

Then you use it like this

```<code><?php echo somefunction(); ?>
</code>```

Body:
how to integrate 3 language (HTML,javascript,CSS) proper PHP format to put in function.php file.

I made animation in 3 formats HTML, javascript, CSS but when I have seen the function.php file in PHP language I am a little stuck because I can't able to write/integrate these 3 formats in the PHP language.

here is 3 format code I need to integrate into php format-

(function() {
  var previousScroll = 0;

  $(window).scroll(function() {
    var currentScroll = $(this).scrollTop();
    if (currentScroll > previousScroll) {
      //down scroll code
      $("#repel").addClass("repel");
      $("#repel").on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function() {
        $('#repel').removeClass('repel');
      });

    } else {
      // upscroll code
      $("#repel").addClass("climb");
      $("#repel").on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function() {
        $('#repel').removeClass('climb');
      });
    }
    previousScroll = currentScroll;
  });
}());

body {
  height: 2000px;
 background:white;
  background-repeat: no-repeat;
  background-size: cover;
}

#repel {
  position: fixed;
  top: -850px;
  right: 0px;
}

.repel {
  -webkit-animation: repel 1s;
  animation: repel 1s;
}

.climb {
  -webkit-animation: climb 1s;
  animation: climb 1s;
}

@-webkit-keyframes climb {
  0% {
    -webkit-transform: translatey(0px);
  }

  50% {
    -webkit-transform: translatey(-55px);
  }

  100% {
    -webkit-transform: translatey(0px);
  }
}

@keyframes climb {
  0% {
    transform: translatey(0px);
  }

  50% {
    transform: translatey(-25px);
  }

  100% {
    transform: translatey(0px);
  }
}

@-webkit-keyframes repel {
  0% {
    -webkit-transform-origin: top right;
    -webkit-transform: rotate(0deg);
  }

  50% {
    -webkit-transform-origin: top right;
    -webkit-transform: rotate(2.5deg)skewy(-5deg);
  }

  100% {
    -webkit-transform-origin: top right;
    -webkit-transform: rotate(0deg);
  }
}

@keyframes repel {
  0% {
    transform-origin: top right;
    transform: rotate(0deg);
  }

  50% {
    transform-origin: top right;
    transform: rotate(2.5deg)skewy(-5deg);
  }

  100% {
    transform-origin: top right;
    transform: rotate(0deg);
  }
}

here is what I tried to implement these 3 format in PHP format but didn't work-

<?php
    //code
$string =  '';

 echo $string;

?>

function.php file is in the WordPress theme editor. reason to integrate 3 code format in the function.php file is that after that I able to call this animation on a specific page.

any idea?

Body:
You can use use nowdoc in PHP to achieve this. Try this

function somefunction(){
    return <<<'EOD'
        <style type="text/css">
            #repel {
                position: fixed;
                top: -850px;
                right: 0px;
            }

            .repel {
                -webkit-animation: repel 1s;
                animation: repel 1s;
            }

            .climb {
                -webkit-animation: climb 1s;
                animation: climb 1s;
            }

            @keyframes climb {
                0% {
                    transform: translatey(0px);
                }

                50% {
                    transform: translatey(-25px);
                }

                100% {
                    transform: translatey(0px);
                }
            }

            @keyframes repel {
                0% {
                    transform-origin: top right;
                    transform: rotate(0deg);
                }

                50% {
                    transform-origin: top right;
                    transform: rotate(2.5deg)skewy(-5deg);
                }

                100% {
                    transform-origin: top right;
                    transform: rotate(0deg);
                }
            }
        </style>
        <img id="repel" src="http://s3.amazonaws.com/dfc_attachments/images/3246705/Repel.png" />
        <script type="text/javascript">
            (function() {
                var previousScroll = 0;

                $(window).scroll(function(){
                    var currentScroll = $(this).scrollTop();
                    if(currentScroll > previousScroll){
                        //down scroll code
                        $("#repel").addClass("repel");
                        $("#repel").on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function() {
                            $('#repel').removeClass('repel');
                        });
                    }else{
                        // upscroll code
                        $("#repel").addClass("climb");
                        $("#repel").on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function() {
                            $('#repel').removeClass('climb');
                        });
                    }
                    previousScroll = currentScroll;
                });
            }());
        </script>
EOD;
}

Then you use it like this

<?php echo somefunction(); ?>


问:
FullCalendar - Sending view via ajax
I am trying to integrate the fullCalendar plugin into a website. The problem I am experiencing is that I am trying to send the current view, wether it be month, agendaDay etc..., as a custom parameter via the json/$.ajax method.

```<code>$('#calendar').fullCalendar({
events: {
    url: 'feed.php',
    type: 'POST',
    data: {
        view: $('#calendar').fullCalendar('getView').name
    },
    error: function() {
        alert('there was an error while fetching events!');
    }
}
});
</code>```

The above is returning any errors but the custom view variable is not being passed along with the normal values.

I have tried the following:

```<code>$('#calendar').fullCalendar({
    events: {
        url: 'feed.php?view=' + $('#calendar').fullCalendar('getView').name,
       .......
</code>```

But this just add ?view=undefined to the ajax call. I know that $('#calendar').fullCalendar('getView').name works as it returns the correct value so it must be something with the line view: $('#calendar').fullCalendar('getView').name but I unsure of what.

答:
FullCalendar v4 and after

// import FullCalendar like so:
// import { Calendar } from '@fullcalendar/core';

// then initialize Full Calendar on your element
let calendarEl = document.getElementById('calendar');
let calendar =  new Calendar(calendarEl, {
    // all your calendar settings except the events one
});

// then add your events source and configure it to send the calendar current view
calendar.addEventSource({
    url: "/url_of_your_events",
    extraParams: function() {
        return {
            viewName: calendar.view.type,
        };
    },
});

// then render your calendar
calendar.render();
```
<p><strong>FullCalendar v3 and before</strong> using jQuery</p>
<pre class="lang-js prettyprint-override"><code>$("#calendar").fullCalendar({
    // all your calendar settings
    // ...

    // configure the event source to send the calendar current view
    events: {
        url: "/url_of_your_events",
        data: function() {
            return { view: $('#calendar').fullCalendar('getView').name };
        },
    },
});
</code>```

Title: FullCalendar - Sending view via ajax

Body:
I am trying to integrate the fullCalendar plugin into a website. The problem I am experiencing is that I am trying to send the current view, wether it be month, agendaDay etc..., as a custom parameter via the json/$.ajax method.

$('#calendar').fullCalendar({
events: {
    url: 'feed.php',
    type: 'POST',
    data: {
        view: $('#calendar').fullCalendar('getView').name
    },
    error: function() {
        alert('there was an error while fetching events!');
    }
}
});

The above is returning any errors but the custom view variable is not being passed along with the normal values.

I have tried the following:

$('#calendar').fullCalendar({
    events: {
        url: 'feed.php?view=' + $('#calendar').fullCalendar('getView').name,
       .......

But this just add ?view=undefined to the ajax call. I know that $('#calendar').fullCalendar('getView').name works as it returns the correct value so it must be something with the line view: $('#calendar').fullCalendar('getView').name but I unsure of what.

Body:
FullCalendar v4 and after

// import FullCalendar like so:
// import { Calendar } from '@fullcalendar/core';

// then initialize Full Calendar on your element
let calendarEl = document.getElementById('calendar');
let calendar =  new Calendar(calendarEl, {
    // all your calendar settings except the events one
});

// then add your events source and configure it to send the calendar current view
calendar.addEventSource({
    url: "/url_of_your_events",
    extraParams: function() {
        return {
            viewName: calendar.view.type,
        };
    },
});

// then render your calendar
calendar.render();

FullCalendar v3 and before using jQuery

$("#calendar").fullCalendar({
    // all your calendar settings
    // ...

    // configure the event source to send the calendar current view
    events: {
        url: "/url_of_your_events",
        data: function() {
            return { view: $('#calendar').fullCalendar('getView').name };
        },
    },
});


问:
Content-length body with mixed latin and chinese characters
I am defining the Content-Length of an HTTP request but because sometimes it might contain chinese characters when it gets to the response side of things, it gets truncated.

I have been trying to get the right way to set the content-length of a mixed Chinese/Latin String but with no luck. it keeps getting truncated.

```<code>headers["Content-Length"] = data.length;   //fails
</code>```
```<code>{ \"query\": \"周杰伦\", \"type\": \"artist\"} //gets truncated

</code>```
```<code>{ \"query\": \"gennaro\", \"type\": \"artist\"} //successful request

</code>```

Can anyone suggest how to calculate the second string length for the content-length header properly?

NOTE: the body is stringified from JSON before it is sent over.

Thanks

答:
The fix this issue , I used TextEncoder which allow me to encode it to utf8 and then count it in the correct way.</p>
```<code>let bodyLength = (new TextEncoder().encode(dataBody)).length;
</code>```

Body:
I am defining the Content-Length of an HTTP request but because sometimes it might contain chinese characters when it gets to the response side of things, it gets truncated.

I have been trying to get the right way to set the content-length of a mixed Chinese/Latin String but with no luck. it keeps getting truncated.

headers["Content-Length"] = data.length;   //fails

{ \"query\": \"周杰伦\", \"type\": \"artist\"} //gets truncated

{ \"query\": \"gennaro\", \"type\": \"artist\"} //successful request

Can anyone suggest how to calculate the second string length for the content-length header properly?

NOTE: the body is stringified from JSON before it is sent over.

Thanks

Body:
The fix this issue , I used TextEncoder which allow me to encode it to utf8 and then count it in the correct way.

let bodyLength = (new TextEncoder().encode(dataBody)).length;


问:
Skip header AND columns if all columns are empty i CSV
Im trying to read som CSV files and clean it up a bit if columns under header has no values.

```<code>Name,ID,State
Tom,,California
Jim,,Texas
</code>```

Then the new CSV should only have the columns Name,State.

```<code>def clean_csv(csvfile):
    with open('./user.csv', 'r', encoding='UTF8') as infile, open('./user_clean.csv', 'w', encoding='UTF8') as outfile:
        writer = csv.writer(outfile)
        reader = csv.reader(infile)
        headers = next(reader, None)
        for row in reader:
            if any(row):
                writer.writerow(row)
</code>```

答:
You will have to read the whole file to know which ,columns are to be kept. So you only have 2 options:

read everything in memory, identify the empty columns and then write back the relevant ones. Simple but may exhaust memory if the file is huge

use 2 pass. Identify at first pass which columns are to be kept and do the real copy on second pass. Saves memory but reads the file twice

I will just show the second one, for the first one, just add each row to a list during the first pass and use that list on second pass:

```<code>with open('input.csv') as fd, open('output.csv', 'w', newline='') as fdout:
    rd = csv.reader(fd)
    cols = set()
    _ = next(rd)  # skip header line
    for row in rd:
        for i, val in enumerate(row):
            if val != '':
                cols.add(i)
    _ = fd.seek(io.SEEK_SET)
    wr = csv.writer(fdout)
    for row in rd:
        _ = wr.writerow(val for i, val in enumerate(row) if i in cols)
</code>```

With your example data, it gives as expected:

```<code>Name,State
Tom,California
Jim,Texas
</code>```

Body:
Im trying to read som CSV files and clean it up a bit if columns under header has no values.

Name,ID,State
Tom,,California
Jim,,Texas

Then the new CSV should only have the columns Name,State.

def clean_csv(csvfile):
    with open('./user.csv', 'r', encoding='UTF8') as infile, open('./user_clean.csv', 'w', encoding='UTF8') as outfile:
        writer = csv.writer(outfile)
        reader = csv.reader(infile)
        headers = next(reader, None)
        for row in reader:
            if any(row):
                writer.writerow(row)

Body:
You will have to read the whole file to know which ,columns are to be kept. So you only have 2 options:

read everything in memory, identify the empty columns and then write back the relevant ones. Simple but may exhaust memory if the file is huge

use 2 pass. Identify at first pass which columns are to be kept and do the real copy on second pass. Saves memory but reads the file twice

I will just show the second one, for the first one, just add each row to a list during the first pass and use that list on second pass:

with open('input.csv') as fd, open('output.csv', 'w', newline='') as fdout:
    rd = csv.reader(fd)
    cols = set()
    _ = next(rd)  # skip header line
    for row in rd:
        for i, val in enumerate(row):
            if val != '':
                cols.add(i)
    _ = fd.seek(io.SEEK_SET)
    wr = csv.writer(fdout)
    for row in rd:
        _ = wr.writerow(val for i, val in enumerate(row) if i in cols)

With your example data, it gives as expected:

Name,State
Tom,California
Jim,Texas


问:
Just out of curiosity, can console.log() send a console command?
Can console.log() send an executable command to the Console? Such as, console.log('pwd')? Or is there some other method for sending Console commands from the webpage?

FYI: This is not an XY problem. I am just curious.

答: No it is not possible. If it would be possible, the website could run actual programs on your computer which would be a huge security issue.</p>


问:
How to get the integral value of an Enum member using Reflection?
Consider the following Enum:

```<code>[Flags]
public enum Digit:
    UInt64
{
    None = 00 << 00,

    One = 01 << 00,
    Two = 01 << 01,
    Three = 01 << 02,
    // Etcetera...

    Other = UInt64.MaxValue - 1,
    Unknown = UInt64.MaxValue,
}

var type = typeof(Digit);
// Returns System.String [].
var names = Enum.GetNames(type);
// Returns System.Array.
var values = Enum.GetValues(type);
// Returns IEnumerable<object>.
var values = Enum.GetValues(type).Cast<object>();
</code>```

Now, I want to get the numeric value of the Enum members without having to cast them to a specific integral type. This is for code generation purposes so below is an example of the code I want to be able to generate:

```<code>[Flags]
public enum Digit:
    UInt64
{
    None = 0,

    One = 1,
    Two = 2,
    Three = 4,
    // Etcetera...

    Other = 18446744073709551614,
    Unknown = 18446744073709551615,
}
</code>```

Of course, I could check the underlying type of the enumeration by calling Enum.GetUnderlyingType(type); and use conditional code to cast each case but was wondering if there is a more direct way.

Please note that I am just looking for the textual representation of the integral value and do not need to do any arithmetic with it or manipulation on it.

Am I missing something simple or is there no way to achieve this without casting?

答:
I don't think there's a way to do this without some kind of conversion, but you can do it without having to use conditional code.

For example:

```<code>using System;
using System.Linq;

static class Program
{
    [Flags]
    public enum Digit :
        UInt64
    {
        None = 00 << 00,

        One   = 01 << 00,
        Two   = 01 << 01,
        Three = 01 << 02,
        // Etcetera...

        Other   = UInt64.MaxValue - 1,
        Unknown = UInt64.MaxValue,
    }

    public static void Main()
    {
        var type           = typeof(Digit);
        var values         = Enum.GetValues(type);
        var underlyingType = Enum.GetUnderlyingType(type);

        var strings =
            values.Cast<object>()
            .Select(item => Convert.ChangeType(item, underlyingType).ToString())
            .ToArray();

        Console.WriteLine(string.Join(", ", strings));
    }
}
</code>```

This outputs: 0, 1, 2, 4, 18446744073709551614, 18446744073709551615

Body:
Consider the following Enum:

[Flags]
public enum Digit:
    UInt64
{
    None = 00 << 00,

    One = 01 << 00,
    Two = 01 << 01,
    Three = 01 << 02,
    // Etcetera...

    Other = UInt64.MaxValue - 1,
    Unknown = UInt64.MaxValue,
}

var type = typeof(Digit);
// Returns System.String [].
var names = Enum.GetNames(type);
// Returns System.Array.
var values = Enum.GetValues(type);
// Returns IEnumerable<object>.
var values = Enum.GetValues(type).Cast<object>();

Now, I want to get the numeric value of the Enum members without having to cast them to a specific integral type. This is for code generation purposes so below is an example of the code I want to be able to generate:

[Flags]
public enum Digit:
    UInt64
{
    None = 0,

    One = 1,
    Two = 2,
    Three = 4,
    // Etcetera...

    Other = 18446744073709551614,
    Unknown = 18446744073709551615,
}

Of course, I could check the underlying type of the enumeration by calling Enum.GetUnderlyingType(type); and use conditional code to cast each case but was wondering if there is a more direct way.

Please note that I am just looking for the textual representation of the integral value and do not need to do any arithmetic with it or manipulation on it.

Am I missing something simple or is there no way to achieve this without casting?

Body:
I don't think there's a way to do this without some kind of conversion, but you can do it without having to use conditional code.

For example:

using System;
using System.Linq;

static class Program
{
    [Flags]
    public enum Digit :
        UInt64
    {
        None = 00 << 00,

        One   = 01 << 00,
        Two   = 01 << 01,
        Three = 01 << 02,
        // Etcetera...

        Other   = UInt64.MaxValue - 1,
        Unknown = UInt64.MaxValue,
    }

    public static void Main()
    {
        var type           = typeof(Digit);
        var values         = Enum.GetValues(type);
        var underlyingType = Enum.GetUnderlyingType(type);

        var strings =
            values.Cast<object>()
            .Select(item => Convert.ChangeType(item, underlyingType).ToString())
            .ToArray();

        Console.WriteLine(string.Join(", ", strings));
    }
}

This outputs: 0, 1, 2, 4, 18446744073709551614, 18446744073709551615


问:
ModuleNotFoundError: No module named 'yarnlib'
I am new to working with react js and just picked up a sample code and tried to run it using the "yarn" command but the error is

Traceback (most recent call last):
File "/usr/bin/yarn", line 32, in
import yarnlib
ModuleNotFoundError: No module named 'yarnlib'

soo I tried running

which yarn

cat /usr/bin/yarn

#! /usr/bin/python
# Copyright 2013  Lars Wirzenius
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# =*= License: GPL-3+ =*=

import cliapp
import collections
import locale
import logging
import os
import re
import shutil
import sys
import tempfile
import time
import ttystatus

import yarnlib```

and there on line 32, it has import yarnlib

I don't know how to install yarnlib

can somebody help me out with it?

答:
Did you downloaded the module? If no, go to Terminal (macOS) or Command Prompt (Windows) then enter
pip3 install yarnlib

Body:
I am new to working with react js and just picked up a sample code and tried to run it using the "yarn" command but the error is

Traceback (most recent call last):
File "/usr/bin/yarn", line 32, in
import yarnlib
ModuleNotFoundError: No module named 'yarnlib'

soo I tried running

which yarn

cat /usr/bin/yarn

#! /usr/bin/python
# Copyright 2013  Lars Wirzenius
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# =*= License: GPL-3+ =*=

import cliapp
import collections
import locale
import logging
import os
import re
import shutil
import sys
import tempfile
import time
import ttystatus

import yarnlib

and there on line 32, it has import yarnlib

I don't know how to install yarnlib

can somebody help me out with it?


问:
StringBuilder.Append Vs StringBuilder.AppendFormat
I was wondering about StringBuilder and I've got a question that I was hoping the community would be able to explain.

Let's just forget about code readability, which of these is faster and why?

StringBuilder.Append:

```<code>StringBuilder sb = new StringBuilder();
sb.Append(string1);
sb.Append("----");
sb.Append(string2);
</code>```

StringBuilder.AppendFormat:

```<code>StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}----{1}",string1,string2);
</code>```

答:
casperOne is entirely accurate that it depends on the data. However, suppose you're writing this as a class library for 3rd parties to consume - which would you use?

One option would be to get the best of both worlds - work out how much data you're actually going to have to append, and then use StringBuilder.EnsureCapacity to make sure we only need a single buffer resize.

If I weren't too bothered though, I'd use Append x3 - it seems "more likely" to be faster, as parsing the string format tokens on every call is clearly make-work.

Note that I've asked the BCL team for a sort of "cached formatter" which we could create using a format string and then re-use repeatedly. It's crazy that the framework has to parse the format string each time it's used.

EDIT: Okay, I've edited John's code somewhat for flexibility and added an "AppendWithCapacity" which just works out the necessary capacity first. Here are the results for the different lengths - for length 1 I used 1,000,000 iterations; for all other lengths I used 100,000. (This was just to get sensible running times.) All times are in millis.

Unfortunately tables don't really work in SO. The lengths were 1, 1000, 10000, 20000

Times:

Append: 162, 475, 7997, 17970

AppendFormat: 392, 499, 8541, 18993

AppendWithCapacity: 139, 189, 1558, 3085

So as it happened, I never saw AppendFormat beat Append - but I did see AppendWithCapacity win by a very substantial margin.

Here's the full code:

```<code>using System;
using System.Diagnostics;
using System.Text;

public class StringBuilderTest
{
    static void Append(string string1, string string2)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append(string1);
        sb.Append("----");
        sb.Append(string2);
    }

    static void AppendWithCapacity(string string1, string string2)
    {
        int capacity = string1.Length + string2.Length + 4;
        StringBuilder sb = new StringBuilder(capacity);
        sb.Append(string1);
        sb.Append("----");
        sb.Append(string2);
    }

    static void AppendFormat(string string1, string string2)
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat("{0}----{1}", string1, string2);
    }

    static void Main(string[] args)
    {
        int size = int.Parse(args[0]);
        int iterations = int.Parse(args[1]);
        string method = args[2];

        Action<string,string> action;
        switch (method)
        {
            case "Append": action = Append; break;
            case "AppendWithCapacity": action = AppendWithCapacity; break;
            case "AppendFormat": action = AppendFormat; break;
            default: throw new ArgumentException();
        }

        string string1 = new string('x', size);
        string string2 = new string('y', size);

        // Make sure it's JITted
        action(string1, string2);
        GC.Collect();

        Stopwatch sw = Stopwatch.StartNew();
        for (int i=0; i < iterations; i++)
        {
            action(string1, string2);
        }
        sw.Stop();
        Console.WriteLine("Time: {0}ms", (int) sw.ElapsedMilliseconds);
    }
}
</code>```

OwnerDisplayName: Sergio

ContentLicense: CC BY-SA 2.5

Body:
I was wondering about StringBuilder and I've got a question that I was hoping the community would be able to explain.

Let's just forget about code readability, which of these is faster and why?

StringBuilder.Append:

StringBuilder sb = new StringBuilder();
sb.Append(string1);
sb.Append("----");
sb.Append(string2);

StringBuilder.AppendFormat:

StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}----{1}",string1,string2);

LastEditorDisplayName: Samuel

Body:
casperOne is entirely accurate that it depends on the data. However, suppose you're writing this as a class library for 3rd parties to consume - which would you use?

One option would be to get the best of both worlds - work out how much data you're actually going to have to append, and then use StringBuilder.EnsureCapacity to make sure we only need a single buffer resize.

If I weren't too bothered though, I'd use Append x3 - it seems "more likely" to be faster, as parsing the string format tokens on every call is clearly make-work.

Note that I've asked the BCL team for a sort of "cached formatter" which we could create using a format string and then re-use repeatedly. It's crazy that the framework has to parse the format string each time it's used.

EDIT: Okay, I've edited John's code somewhat for flexibility and added an "AppendWithCapacity" which just works out the necessary capacity first. Here are the results for the different lengths - for length 1 I used 1,000,000 iterations; for all other lengths I used 100,000. (This was just to get sensible running times.) All times are in millis.

Unfortunately tables don't really work in SO. The lengths were 1, 1000, 10000, 20000

Times:

Append: 162, 475, 7997, 17970

AppendFormat: 392, 499, 8541, 18993

AppendWithCapacity: 139, 189, 1558, 3085

So as it happened, I never saw AppendFormat beat Append - but I did see AppendWithCapacity win by a very substantial margin.

Here's the full code:

using System;
using System.Diagnostics;
using System.Text;

public class StringBuilderTest
{
    static void Append(string string1, string string2)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append(string1);
        sb.Append("----");
        sb.Append(string2);
    }

    static void AppendWithCapacity(string string1, string string2)
    {
        int capacity = string1.Length + string2.Length + 4;
        StringBuilder sb = new StringBuilder(capacity);
        sb.Append(string1);
        sb.Append("----");
        sb.Append(string2);
    }

    static void AppendFormat(string string1, string string2)
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat("{0}----{1}", string1, string2);
    }

    static void Main(string[] args)
    {
        int size = int.Parse(args[0]);
        int iterations = int.Parse(args[1]);
        string method = args[2];

        Action<string,string> action;
        switch (method)
        {
            case "Append": action = Append; break;
            case "AppendWithCapacity": action = AppendWithCapacity; break;
            case "AppendFormat": action = AppendFormat; break;
            default: throw new ArgumentException();
        }

        string string1 = new string('x', size);
        string string2 = new string('y', size);

        // Make sure it's JITted
        action(string1, string2);
        GC.Collect();

        Stopwatch sw = Stopwatch.StartNew();
        for (int i=0; i < iterations; i++)
        {
            action(string1, string2);
        }
        sw.Stop();
        Console.WriteLine("Time: {0}ms", (int) sw.ElapsedMilliseconds);
    }
}

OwnerDisplayName: Jon Skeet

LastEditorDisplayName: Jon Skeet


问:
Can't access dictionary views in Oracle Database 19 with system user
i have a problem where i can not access the dictionary views like ALL_TABLES, ALL_USERS etc.

I have an Azure-VM with the Oracle Database 19.3.0.0 EE - Gen1 image installed.

How did i setup the machine:

set ORACLE_BASE, ORACLE_HOME, ORACLE_SID environment Variables

created dir
/u01/app/oracle/oradata

/u01/app/oracle/admin/DBname/adump

/u01/app/oracle/fast_recovery_area

created following /u01/app/oracle/product/19.0.0/dbhome_1/dbs/initDBName.ora

```<code>    db_name='<DBName>'
    memory_target=1G
    processes = 150
    audit_file_dest='$ORACLE_BASE/admin/<DBName>/adump'
    audit_trail ='db'
    db_block_size=8192
    db_domain=''
    db_recovery_file_dest='$ORACLE_BASE/fast_recovery_area'
    db_recovery_file_dest_size=2G
    diagnostic_dest='$ORACLE_BASE'
    dispatchers='(PROTOCOL=TCP) (SERVICE=ORCLXDB)'
    open_cursors=300
    remote_login_passwordfile='EXCLUSIVE'
    undo_management=AUTO
    undo_tablespace='undotbs'
    # You may want to ensure that control files are created on separate physical
    # devices
    control_files = (ora_control1)
    compatible ='11.2.0'
</code>```

i ran the sqlplus commands

```<code>    sqlplus / as sysdba
    startup nomount;
</code>```

created the Database with following command:

```<code>    CREATE DATABASE <DBName>
    USER SYS IDENTIFIED BY <Password>
    USER SYSTEM IDENTIFIED BY <Password>
    LOGFILE GROUP 1 ('/u01/logs/redo01a.log','/u01/logs/redo01b.log') SIZE 100M,
           GROUP 2 ('/u01/logs/redo02a.log','/u01/logs/redo02b.log') SIZE 100M,
           GROUP 3 ('/u01/logs/redo03a.log','/u01/logs/redo03b.log') SIZE 100M
    MAXLOGHISTORY 1
    MAXLOGFILES 16
    MAXLOGMEMBERS 3
    MAXDATAFILES 1024
    CHARACTER SET AL32UTF8
    NATIONAL CHARACTER SET AL16UTF16
    EXTENT MANAGEMENT LOCAL
    DATAFILE '/u01/app/oracle/oradata/<DBName>/system01.dbf'
     SIZE 700M REUSE AUTOEXTEND ON NEXT 10240K MAXSIZE UNLIMITED
    SYSAUX DATAFILE '/u01/app/oracle/oradata/<DBName>/sysaux01.dbf'
     SIZE 550M REUSE AUTOEXTEND ON NEXT 10240K MAXSIZE UNLIMITED
    DEFAULT TABLESPACE users
      DATAFILE '/u01/app/oracle/oradata/<DBName>/users01.dbf'
      SIZE 500M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED
    DEFAULT TEMPORARY TABLESPACE tempts1
      TEMPFILE '/u01/app/oracle/oradata/<DBName>/temp01.dbf'
      SIZE 20M REUSE AUTOEXTEND ON NEXT 640K MAXSIZE UNLIMITED
    UNDO TABLESPACE undotbs
      DATAFILE '/u01/app/oracle/oradata/<DBName>/undotbs01.dbf'
      SIZE 200M REUSE AUTOEXTEND ON NEXT 5120K MAXSIZE UNLIMITED
    USER_DATA TABLESPACE usertbs
      DATAFILE '/u01/app/oracle/oradata/<DBName>/usertbs01.dbf'
      SIZE 200M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED;
</code>```

And now i want to access the ALL_USERS View but get this error:

ORA-00942: table or view does not exist

Same happens with all other dictionary tables.

答: as @AlexPoole wrote i had to run the sql scripts as described in step 11</p>

Body:
i have a problem where i can not access the dictionary views like ALL_TABLES, ALL_USERS etc.

I have an Azure-VM with the Oracle Database 19.3.0.0 EE - Gen1 image installed.

How did i setup the machine:

set ORACLE_BASE, ORACLE_HOME, ORACLE_SID environment Variables

created dir
/u01/app/oracle/oradata

/u01/app/oracle/admin/DBname/adump

/u01/app/oracle/fast_recovery_area

created following /u01/app/oracle/product/19.0.0/dbhome_1/dbs/initDBName.ora

    db_name='<DBName>'
    memory_target=1G
    processes = 150
    audit_file_dest='$ORACLE_BASE/admin/<DBName>/adump'
    audit_trail ='db'
    db_block_size=8192
    db_domain=''
    db_recovery_file_dest='$ORACLE_BASE/fast_recovery_area'
    db_recovery_file_dest_size=2G
    diagnostic_dest='$ORACLE_BASE'
    dispatchers='(PROTOCOL=TCP) (SERVICE=ORCLXDB)'
    open_cursors=300
    remote_login_passwordfile='EXCLUSIVE'
    undo_management=AUTO
    undo_tablespace='undotbs'
    # You may want to ensure that control files are created on separate physical
    # devices
    control_files = (ora_control1)
    compatible ='11.2.0'

i ran the sqlplus commands

    sqlplus / as sysdba
    startup nomount;

created the Database with following command:

    CREATE DATABASE <DBName>
    USER SYS IDENTIFIED BY <Password>
    USER SYSTEM IDENTIFIED BY <Password>
    LOGFILE GROUP 1 ('/u01/logs/redo01a.log','/u01/logs/redo01b.log') SIZE 100M,
           GROUP 2 ('/u01/logs/redo02a.log','/u01/logs/redo02b.log') SIZE 100M,
           GROUP 3 ('/u01/logs/redo03a.log','/u01/logs/redo03b.log') SIZE 100M
    MAXLOGHISTORY 1
    MAXLOGFILES 16
    MAXLOGMEMBERS 3
    MAXDATAFILES 1024
    CHARACTER SET AL32UTF8
    NATIONAL CHARACTER SET AL16UTF16
    EXTENT MANAGEMENT LOCAL
    DATAFILE '/u01/app/oracle/oradata/<DBName>/system01.dbf'
     SIZE 700M REUSE AUTOEXTEND ON NEXT 10240K MAXSIZE UNLIMITED
    SYSAUX DATAFILE '/u01/app/oracle/oradata/<DBName>/sysaux01.dbf'
     SIZE 550M REUSE AUTOEXTEND ON NEXT 10240K MAXSIZE UNLIMITED
    DEFAULT TABLESPACE users
      DATAFILE '/u01/app/oracle/oradata/<DBName>/users01.dbf'
      SIZE 500M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED
    DEFAULT TEMPORARY TABLESPACE tempts1
      TEMPFILE '/u01/app/oracle/oradata/<DBName>/temp01.dbf'
      SIZE 20M REUSE AUTOEXTEND ON NEXT 640K MAXSIZE UNLIMITED
    UNDO TABLESPACE undotbs
      DATAFILE '/u01/app/oracle/oradata/<DBName>/undotbs01.dbf'
      SIZE 200M REUSE AUTOEXTEND ON NEXT 5120K MAXSIZE UNLIMITED
    USER_DATA TABLESPACE usertbs
      DATAFILE '/u01/app/oracle/oradata/<DBName>/usertbs01.dbf'
      SIZE 200M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED;

And now i want to access the ALL_USERS View but get this error:

ORA-00942: table or view does not exist

Same happens with all other dictionary tables.


问:
Heroku Shopify Application Error 'npm ERR! ERESOLVE unable to resolve dependency tree'
Greetings I have a problem with Heroku because it's don't want to install legacy packages for my Shopify app, my Shopify app is on Github and I just set up everything that my application needs, but when I deploy the main branch on Heroku I get this error in Heroku console below, can someone help me fix this?

```<code>-----> Building on the Heroku-20 stack
-----> Using buildpack: heroku/nodejs
-----> Node.js app detected

-----> Creating runtime environment

       NPM_CONFIG_LOGLEVEL=error
       USE_NPM_INSTALL=true
       NODE_VERBOSE=false
       NODE_ENV=production
       NODE_MODULES_CACHE=false

-----> Installing binaries
       engines.node (package.json):  unspecified
       engines.npm (package.json):   unspecified (use default)

       Resolving node version 16.x...
       Downloading and installing node 16.14.0...
       Using default npm version: 8.3.1

-----> Restoring cache
       Caching has been disabled because NODE_MODULES_CACHE=false

-----> Installing dependencies
       Installing node modules (package.json + package-lock)
       npm ERR! code ERESOLVE
       npm ERR! ERESOLVE unable to resolve dependency tree
       npm ERR!
       npm ERR! While resolving: shopify-app-node@1.0.0
       npm ERR! Found: react@16.14.0
       npm ERR! node_modules/react
       npm ERR!   react@"^16.10.1" from the root project
       npm ERR!
       npm ERR! Could not resolve dependency:
       npm ERR! peer react@"^17.0.2 || ^18.0.0-0" from next@12.0.10
       npm ERR! node_modules/next
       npm ERR!   next@"^12.0.2" from the root project
       npm ERR!
       npm ERR! Fix the upstream dependency conflict, or retry
       npm ERR! this command with --force, or --legacy-peer-deps
       npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
       npm ERR!
       npm ERR! See /tmp/npmcache.CTfHl/eresolve-report.txt for a full report.

       npm ERR! A complete log of this run can be found in:
       npm ERR!     /tmp/npmcache.CTfHl/_logs/2022-02-10T12_18_50_156Z-debug-0.log
-----> Build failed

       We're sorry this build is failing! You can troubleshoot common issues here:
       https://devcenter.heroku.com/articles/troubleshooting-node-deploys

       Some possible problems:

       - Node version not specified in package.json
         https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version

       Love,
       Heroku

 !     Push rejected, failed to compile Node.js app.
 !     Push failed
</code>```

My package.json

```<code>{
  "name": "shopify-app-node",
  "version": "1.0.0",
  "description": "Shopify's node app for CLI tool",
  "scripts": {
    "test": "jest",
    "dev": "cross-env NODE_ENV=development nodemon ./server/index.js --watch ./server/index.js",
    "build": "NEXT_TELEMETRY_DISABLED=1 next build",
    "start": "cross-env NODE_ENV=production node ./server/index.js"
  },
  "engines": {
    "node": "16.14.0",
    "npm": "8.4.1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Shopify/shopify-app-node.git"
  },
  "author": "Shopify Inc.",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/shopify/shopify-app-node/issues"
  },
  "dependencies": {
    "@babel/core": "7.12.10",
    "@babel/polyfill": "^7.6.0",
    "@babel/preset-env": "^7.12.11",
    "@babel/register": "^7.12.10",
    "@shopify/app-bridge-react": "^2.0.2",
    "@shopify/app-bridge-utils": "^2.0.2",
    "@shopify/koa-shopify-auth": "^4.1.2",
    "@shopify/polaris": "^6.2.0",
    "apollo-boost": "^0.4.9",
    "axios": "^0.25.0",
    "cross-env": "^7.0.3",
    "dotenv": "^8.2.0",
    "graphql": "^14.5.8",
    "isomorphic-fetch": "^3.0.0",
    "koa": "^2.13.1",
    "koa-bodyparser": "^4.3.0",
    "koa-compress": "^5.1.0",
    "koa-cors": "0.0.16",
    "koa-logger": "^3.2.1",
    "koa-router": "^10.0.0",
    "koa-session": "^6.1.0",
    "mysql2": "^2.3.3",
    "next": "^12.0.2",
    "next-env": "^1.1.0",
    "node-fetch": "^2.6.7",
    "react": "^16.10.1",
    "react-apollo": "^3.1.3",
    "react-dom": "^16.10.1",
    "sequelize": "^6.13.0",
    "slugify": "^1.6.5",
    "validator": "^13.7.0",
    "webpack": "^4.44.1"
  },
  "devDependencies": {
    "@babel/plugin-transform-runtime": "^7.12.10",
    "@babel/preset-stage-3": "^7.0.0",
    "babel-jest": "26.6.3",
    "babel-register": "^6.26.0",
    "enzyme": "3.11.0",
    "enzyme-adapter-react-16": "1.15.6",
    "husky": "^4.3.6",
    "jest": "26.6.3",
    "lint-staged": "^10.5.4",
    "nodemon": "^2.0.7",
    "prettier": "2.2.1",
    "react-addons-test-utils": "15.6.2",
    "react-test-renderer": "16.14.0"
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{js,css,json,md}": [
      "prettier --write"
    ]
  }
}
</code>```

答:
Your lock file contains conflicting dependencies. Since you were able to reproduce the error locally using npm ci we have a good way to test a fix locally.

It looks like you are depending directly on React 16. Is that something that you need directly, or is it just a dependency for Next.js?

If it's not something you need directly, upgrade it per the Next.js docs:

```<code>npm install react@latest react-dom@latest
</code>```

That should modify your package-lock.json. Then try installing from the lock file again with npm ci. If that fixes things, commit the change and redeploy.

On the other hand, if you are directly depending on React 16 and cannot upgrade you'll have to consider rolling back to an earlier version of Next.js.

Body:
Greetings I have a problem with Heroku because it's don't want to install legacy packages for my Shopify app, my Shopify app is on Github and I just set up everything that my application needs, but when I deploy the main branch on Heroku I get this error in Heroku console below, can someone help me fix this?

-----> Building on the Heroku-20 stack
-----> Using buildpack: heroku/nodejs
-----> Node.js app detected

-----> Creating runtime environment

       NPM_CONFIG_LOGLEVEL=error
       USE_NPM_INSTALL=true
       NODE_VERBOSE=false
       NODE_ENV=production
       NODE_MODULES_CACHE=false

-----> Installing binaries
       engines.node (package.json):  unspecified
       engines.npm (package.json):   unspecified (use default)

       Resolving node version 16.x...
       Downloading and installing node 16.14.0...
       Using default npm version: 8.3.1

-----> Restoring cache
       Caching has been disabled because NODE_MODULES_CACHE=false

-----> Installing dependencies
       Installing node modules (package.json + package-lock)
       npm ERR! code ERESOLVE
       npm ERR! ERESOLVE unable to resolve dependency tree
       npm ERR!
       npm ERR! While resolving: shopify-app-node@1.0.0
       npm ERR! Found: react@16.14.0
       npm ERR! node_modules/react
       npm ERR!   react@"^16.10.1" from the root project
       npm ERR!
       npm ERR! Could not resolve dependency:
       npm ERR! peer react@"^17.0.2 || ^18.0.0-0" from next@12.0.10
       npm ERR! node_modules/next
       npm ERR!   next@"^12.0.2" from the root project
       npm ERR!
       npm ERR! Fix the upstream dependency conflict, or retry
       npm ERR! this command with --force, or --legacy-peer-deps
       npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
       npm ERR!
       npm ERR! See /tmp/npmcache.CTfHl/eresolve-report.txt for a full report.

       npm ERR! A complete log of this run can be found in:
       npm ERR!     /tmp/npmcache.CTfHl/_logs/2022-02-10T12_18_50_156Z-debug-0.log
-----> Build failed

       We're sorry this build is failing! You can troubleshoot common issues here:
       https://devcenter.heroku.com/articles/troubleshooting-node-deploys

       Some possible problems:

       - Node version not specified in package.json
         https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version

       Love,
       Heroku

 !     Push rejected, failed to compile Node.js app.
 !     Push failed

My package.json

{
  "name": "shopify-app-node",
  "version": "1.0.0",
  "description": "Shopify's node app for CLI tool",
  "scripts": {
    "test": "jest",
    "dev": "cross-env NODE_ENV=development nodemon ./server/index.js --watch ./server/index.js",
    "build": "NEXT_TELEMETRY_DISABLED=1 next build",
    "start": "cross-env NODE_ENV=production node ./server/index.js"
  },
  "engines": {
    "node": "16.14.0",
    "npm": "8.4.1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Shopify/shopify-app-node.git"
  },
  "author": "Shopify Inc.",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/shopify/shopify-app-node/issues"
  },
  "dependencies": {
    "@babel/core": "7.12.10",
    "@babel/polyfill": "^7.6.0",
    "@babel/preset-env": "^7.12.11",
    "@babel/register": "^7.12.10",
    "@shopify/app-bridge-react": "^2.0.2",
    "@shopify/app-bridge-utils": "^2.0.2",
    "@shopify/koa-shopify-auth": "^4.1.2",
    "@shopify/polaris": "^6.2.0",
    "apollo-boost": "^0.4.9",
    "axios": "^0.25.0",
    "cross-env": "^7.0.3",
    "dotenv": "^8.2.0",
    "graphql": "^14.5.8",
    "isomorphic-fetch": "^3.0.0",
    "koa": "^2.13.1",
    "koa-bodyparser": "^4.3.0",
    "koa-compress": "^5.1.0",
    "koa-cors": "0.0.16",
    "koa-logger": "^3.2.1",
    "koa-router": "^10.0.0",
    "koa-session": "^6.1.0",
    "mysql2": "^2.3.3",
    "next": "^12.0.2",
    "next-env": "^1.1.0",
    "node-fetch": "^2.6.7",
    "react": "^16.10.1",
    "react-apollo": "^3.1.3",
    "react-dom": "^16.10.1",
    "sequelize": "^6.13.0",
    "slugify": "^1.6.5",
    "validator": "^13.7.0",
    "webpack": "^4.44.1"
  },
  "devDependencies": {
    "@babel/plugin-transform-runtime": "^7.12.10",
    "@babel/preset-stage-3": "^7.0.0",
    "babel-jest": "26.6.3",
    "babel-register": "^6.26.0",
    "enzyme": "3.11.0",
    "enzyme-adapter-react-16": "1.15.6",
    "husky": "^4.3.6",
    "jest": "26.6.3",
    "lint-staged": "^10.5.4",
    "nodemon": "^2.0.7",
    "prettier": "2.2.1",
    "react-addons-test-utils": "15.6.2",
    "react-test-renderer": "16.14.0"
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{js,css,json,md}": [
      "prettier --write"
    ]
  }
}

Body:
Your lock file contains conflicting dependencies. Since you were able to reproduce the error locally using npm ci we have a good way to test a fix locally.

It looks like you are depending directly on React 16. Is that something that you need directly, or is it just a dependency for Next.js?

If it's not something you need directly, upgrade it per the Next.js docs:

npm install react@latest react-dom@latest

That should modify your package-lock.json. Then try installing from the lock file again with npm ci. If that fixes things, commit the change and redeploy.

On the other hand, if you are directly depending on React 16 and cannot upgrade you'll have to consider rolling back to an earlier version of Next.js.