text:
Q: How to get all data associate with serializers.PrimaryKeyRelatedField I am trying to get all the data associated with this interest_category serializer. This is what I am currently getting:
{
        "project_title": "Dogs",
        "project_description": "and cats",
        "interest_category": [
            4,
            7
        ],
        "created_by": 1,
        "created_at": "2022-09-17T04:31:40.884357Z",
        "updated_at": "2022-09-17T04:31:40.884357Z"
    },

What I am trying to get:
{
        "project_title": "Dogs",
        "project_description": "and cats",
        "interest_category": [
            {
                "id": 4,
                "interest_name": "Test"
            },
            {
                "id": 7,
                "interest_name": "Business"
            }
        ],
        "created_by": 1,
        "created_at": "2022-09-17T04:31:40.884357Z",
        "updated_at": "2022-09-17T04:31:40.884357Z"
    },

The issue I am having is if I use the below code, I cannot get the interest_category "interest_name" and only have the IDs displayed in a GET request:
class InterestSerializer(serializers.ModelSerializer):
    interest_name = serializers.CharField()
    class Meta:
        model = Interests
        fields = ('id', 'interest_name')

class ProjectsSerializer(serializers.ModelSerializer):
    interest_category = serializers.PrimaryKeyRelatedField(
        many=True, read_only=True
    )
    class Meta:
        model = Project
        fields = [
            'project_title',
            'project_description',
            'interest_category',
            'created_by',
            'created_at',
            'updated_at',
        ]

    def create(self, validated_data):
        project_category = validated_data.pop("interest_category", None)
        project_create = Project.objects.create(**validated_data)
        if project_category:
            project_create.interest_category.set(project_category)

        return project_create

I have tried using this to GET the data and I can, however when I use this code, I cannot write and set the interest_category, it will just be blank:
class InterestSerializer(serializers.ModelSerializer):
    interest_name = serializers.CharField()
    class Meta:
        model = Interests
        fields = ('id', 'interest_name')

class ProjectsSerializer(serializers.ModelSerializer):
    interest_category = InterestSerializer(
        many=True, read_only=True
    )
    class Meta:
        model = Project
        fields = [
            'project_title',
            'project_description',
            'interest_category',
            'created_by',
            'created_at',
            'updated_at',
        ]

    def create(self, validated_data):
        project_category = validated_data.pop("interest_category", None)
        project_create = Project.objects.create(**validated_data)
        if project_category:
            project_create.interest_category.set(project_category)

        return project_create

If I use one or the other, I cannot POST the interest_category or I cannot GET the interest_category. How can I make it so I can get the data that I need to GET and POST the request with the same serializer. Any and all help is greatly appreciated!

A: You can simply override the to_representation() method or inherit InterestSerializer in ProjectsSerializer.

A: The change that I made is on ProjectsSerializers and Project's views
# The Base of ProjectsSerializers
class BaseProjectsSerializer(serializers.ModelSerializer):
    interest_category = serializers.PrimaryKeyRelatedField(
        many=True, read_only=True
    )
    class Meta:
        model = Project
        fields = [
            'project_title',
            'project_description',
            'interest_category',
            'created_by',
            'created_at',
            'updated_at',
        ]

    def create(self, validated_data):
        project_category = validated_data.pop("interest_category", None)
        project_create = Project.objects.create(**validated_data)
        if project_category:
            project_create.interest_category.set(project_category)

        return project_create

class WriteProjectsSerializer(BaseProjectsSerializer):  # <<<< -------- HERE
    interest_category = serializers.PrimaryKeyRelatedField(
        many=True, read_only=True
    )

class ReadProjectsSerializer(BaseProjectsSerializer):   # <<<< -------- HERE
    interest_category = serializers.SerializerMethodField(read_only=True)
    def get_interest_category(self, instance):
        interest_category = instance.interest_category.all()
        serializer = InterestSerializer(instance=interest_category, many=True)
        return serializer.data

# In your View, add a dict of serializer_classes and set a default serializer
class ProjectViewSet(viewsets.ModelViewSet):
    """Project Viewset"""
    queryset = Project.objects.all()
    default_serializer_class = ReadProjectsSerializer # < --------- HERE
    serializer_classes = {  # < ---------------------------------- HERE
        'create': WriteProjectsSerializer,
        'update': WriteProjectsSerializer,
        'partial_update': WriteProjectsSerializer,
    }

A: I think now I understand what you are trying to do. You want to create a writable nested serializer. Try this:
class InterestSerializer(serializers.ModelSerializer):
    interest_name = serializers.CharField()
    class Meta:
        model = Interests
        fields = ('id', 'interest_name')

class ProjectsSerializer(serializers.ModelSerializer):
    interest_category = InterestSerializer(many=True)# new

    class Meta:
        model = Project
        fields = [
            'project_title',
            'project_description',
            'interest_category',
            'created_by',
            'created_at',
            'updated_at',
        ]

    # new edits
    def create(self, validated_data):
        interests_data = validated_data.pop("interest_category")
        project = Project.objects.create(**validated_data)
        for interest_data in interests_data:
            Interests.objects.create(project=project, **interest_data)

        return project

This can get you:
{
        "project_title": "Dogs",
        "project_description": "and cats",
        "interest_category": [
            {
                "id": 4,
                "interest_name": "Test"
            },
            {
                "id": 7,
                "interest_name": "Business"
            }
        ],
        "created_by": 1,
        "created_at": "2022-09-17T04:31:40.884357Z",
        "updated_at": "2022-09-17T04:31:40.884357Z"
    },

You can read more here.

A: It can be solved using context data and read_only options.
views.py
...

ProjectsSerializer(data=request.data, context={'request': request}

serializers.py

class InterestSerializer(serializers.ModelSerializer):
    class Meta:
        model = Interests
        fields = ('id', 'interest_name')

class ProjectsSerializer(serializers.ModelSerializer):
    interest_category = InterestSerializer(read_only=True, many=True)

    class Meta:
        model = Project
        fields = [
            'project_title',
            'project_description',
            'interest_category',
            'created_by',
            'created_at',
            'updated_at',
            'interest_category',
        ]

    def create(self, validated_data):
        interest_category = self.context['request'].data.get("interest_category", None)
        project = Project.objects.create(**validated_data)
        if interest_category:
            interests = Interests.objects.filter(id__in=interest_category)
            project_create.interest_category.set(interests)

        return project


text:
Q: Нужен игровой движок python, который работает в termux Я уже давно пользуюсь утилитой vncserver в termux для того, чтобы работала графическая оболочка.
С этой утилитой можно создать виртуальные дисплеи, но когда к ним ничего не подключено (никакая утилита для виртуальных экранов, например xfce4), то экран показывается черным.
Это меня натолкнуло на мысль: Есть ли библиотека на Python, которая будет работать в Termux, обрабатывать 2D/3D графику и выводить ее на виртуальный экран?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Modify default "dismiss" behavior of Bootstrap modals The way the Bootstrap modal JS is written, a click event anywhere within the ".modal" element will dismiss the modal. On any and all children of the ".modal" class, the dismiss behavior is disabled, allowing the user to interact with the modal's content.
My question - how could I modify this behavior slightly so that clicking children of ".modal" will dismiss it, but clicking children of children will not?

In this instance, the desired behavior is that a click on ".foo" should dismiss the modal while a click on ".bar" would NOT dismiss the modal, and go about its usual business.
The reason for this is I am doing some advanced positioning and need two wrapper elements around the actual modal content, which will both still dismiss the modal when clicked upon.
See the JSFiddle - http://jsfiddle.net/8w7fxtyr/

A: This pair of delegated handlers should do the trick, and you only need to set them up once, not per-modal: Updated Fiddle
$(document).on("click", ".modal .bar", false);
$(document).on("click", ".modal .foo", function(e) {
    $(this).closest(".modal").modal("hide");
});

Note that the order is important, we need to ignore clicks on .bar before we act on clicks on .foo.
Or if avoiding the use of the .foo and .bar classes is important, you can do it with child selectors: Fiddle
$(document).on("click", ".modal > * > *", false);
$(document).on("click", ".modal > *", function(e) {
    $(this).closest(".modal").modal("hide");
});

A: Add standard data-dismiss attribute to the foo element:

but prevent click propagation further than bar:
$(".modal .bar").on("click", function () { return false; });

A: This works, and you don't need to specify any classes other than .modal so it remains extensible.
$(".modal > *").click(function(e) {
    $(this).parent().modal('hide');
}).children().click(function(e) {
    return false;
});


text:
Q: Fatal Exception: java.lang.OutOfMemoryError When add Polyline to google map I have an application that tracks location when moving, every 5 sec I send the broadcast receiver to draw a polyline in google map, I use the method below:
    ArrayList<Location> locationList = Service.locationList;

    if (locationList.size() == 2) {
        Location fromLocation = locationList.get(0);
        Location toLocation = locationList.get(1);

        LatLng from = new LatLng(((fromLocation.getLatitude())),
                ((fromLocation.getLongitude())));

        LatLng to = new LatLng(((toLocation.getLatitude())),
                ((toLocation.getLongitude())));

        polyline = mMap.addPolyline(new PolylineOptions()
                .add(from, to)
                .width(10).color(Color.parseColor("#801B60FE")).geodesic(true));

    } else if (locationList.size() > 2 && polyline.getPoints()!=null) {
        Location toLocation = locationList.get(locationList.size() - 1);
        LatLng to = new LatLng(((toLocation.getLatitude())),
                ((toLocation.getLongitude())));

           points = polyline.getPoints();
            points.add(to);
            polyline.setPoints(points);

    }

After some time it causes OOM :

Fatal Exception: java.lang.OutOfMemoryError
      Failed to allocate a 603979784 byte allocation with 16777216 free bytes and 197MB until OOM
java.util.Arrays.copyOf (Arrays.java:3352)
java.lang.AbstractStringBuilder.expandCapacity (AbstractStringBuilder.java:130)
  com.android.volley.NetworkDispatcher.run (NetworkDispatcher.java:87)

Can anyone give me a solution ??

A: I think you are trying to allocate an array that has more than Integer.MAX_VALUE elements in this line. You can not allocate more than Integer.MAX_VALUE.
ArrayList<Location> locationList = Service.locationList;

Check the size of Service.locationList

A: use PolyUtil method .simplyfy() to handle the memory utilization more conservatively.
here's the repository and the documentation.

A: Create Global variable of List of LatLng,
ArrayList alData =new ArrayList<>();
on your broadcast receiver add below code,
LatLng position = new LatLng(((ocation.getLatitude())),
                ((location.getLongitude())));
        alData.add(position);

        if (polyline!=null)polyline.remove();

        polyline = googleMap.addPolyline(new PolylineOptions().addAll(alData));


text:
Q: XML with multiple XSLT stylesheets I have an xml file which opens with an xslt file:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="eventsoverview.xsl"?>
<events>
  <item>
    <date>7/5/2013</date>
    <time>18:00</time>
    <title>Some title</title>
    <location>Earth</location>
    <id>505</id>
    <category>Comedy</category>
    <description>Some description</description>
  </item>
  <item>
    <date>7/5/2013</date>
    <time>18:00</time>
    <title>Some title</title>
    <location>Earth</location>
    <id>506</id>
    <category>Comedy</category>
    <description>Some description</description>
  </item>
  <item>
    <date>7/5/2013</date>
    <time>18:00</time>
    <title>Some title</title>
    <location>Earth</location>
    <id>507</id>
    <category>Comedy</category>
    <description>Some description</description>
  </item>
</events>

eventsoverview.xsl:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="/">

                <xsl:for-each select="events/item">

                                <xsl:value-of select="title"/>

                                <xsl:value-of select="description"/>

                </xsl:for-each>

    </xsl:template>

</xsl:stylesheet>

Right now, this xslt is displaying brief data about the event. What I want to do is that when I click on the event, it should display the details of the event using the same xml file. How would I go about doing this? Can this be done using multiple xslt files?

A: In the following example I assume that a click on an event calls the page with a Get-Parameter id, containing the ID of the event. You would need some server-side logic to insert this ID into your XSL (parameter eventid in my example). Of course you could also insert this parameter into the XML.
If eventid != 0 you see the details of the events with the respective ID. In my example the details of event 506 are displayed.
If eventid = 0 you see the list of events.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:param name="eventid">506</xsl:param>

    <xsl:template match="/">

                <xsl:choose>
                    <xsl:when test="$eventid = 0">
                        <xsl:apply-templates/>
                    </xsl:when>
                    <xsl:when test="$eventid != 0">
                        <xsl:apply-templates select="/events/item"/>
                    </xsl:when>
                </xsl:choose>

    </xsl:template>

    <xsl:template match="/events/item">
        <xsl:if test="id/text() = $eventid">

                    <xsl:value-of select="title"/>

Description: <xsl:value-of select="description"/>

Time: <xsl:value-of select="time"/>

Location: <xsl:value-of select="location"/>

ID: <xsl:value-of select="id"/>

Category: <xsl:value-of select="category"/>

        </xsl:if>
    </xsl:template>

    <xsl:template match="/events">
        <xsl:for-each select="item">

                        <xsl:value-of select="title"/>

                        <xsl:value-of select="description"/>

                    <xsl:element name="a">
                        <xsl:attribute name="href">?id=<xsl:value-of select="id"/>
                        </xsl:attribute>more</xsl:element>

        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

A: When you want to do something a bit more sophisticated than just using the same XSLT to render the same XML every time, the xml-stylesheet processing instruction runs out of steam.
You'll need to look at using a Javascript API to invoke the transformations - or better still, look at Saxon-CE, which allows you to write the whole application including the interaction and event handling in XSLT.

A: With client-side XSLT I would suggest to have the XSLT create HTML with Javascript that hides respectively shows the details when a click event occurs.


text:
Q: LINQ Entity Framework 4.2 datetime comparison fails Followind describes an issue I am running into using EF 4.2 and LINQ.  I've tried this on multiple systems, and multiple flavors of SQL (SQL Express and SQL 2008 R2 Sp1), VS 2010 Pro and Premium, both in 64 bit and 32 binaries, both with the debugger, and attempting to run the binary directly.  I'm wondering what I've stumbled against, if it's an issue with EF, or more likely an issue with my code and I'm missing some nuance either related to LINQ or EF.  Any assistance would be greatly appreciated, been at it for 6 hours, my Google JuJu is not strong enough I'm afraid.
I have a simple model named session consisting of an ID (Guid), Name (String), and Timestamp (DateTime).  I am able to add a session to the dbcontext, and have verified in debugging that the session record is indeed stored in the database.  The timestamp used to create the session object is stored in a local variable, and immediately after storing, I attempt to retrieve the session into a new instance of a session object.  The code that retrieves the session (LINQ) throws 'System.InvalidOperationException "Sequence contains no elements"' with the following stacktrace:
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__0[TResult](IEnumerable`1 sequence)
at System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
at System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.First[TSource](IQueryable`1 source)
at efwtf.Program.Main(String[] args) in d:\vs2010\efwtf\efwtf\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

I am able to drill into ctx.Sessions in the debugger and see in the resultset that the session that I am trying to retrieve actually does exist, and if I iterate over the result set and manually compare the two timestamps I can extract the session as expected.  If I run the code and pass a timestamp value for a record that was added to the database in a previous run, it works.  I can find work arounds, worst case, changing the datatype to a string perhaps, but it bugs me that this doesn't work, I'm assuming, which may be part of the problem, that the functionality should be supported.  Code follows.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations;

    namespace efwtf
    {
       class Program
       {
          static void Main ( string[] args )
          {
             Context ctx = new Context ();
             DateTime ts = DateTime.UtcNow;
             Session s1 = new Session () { Id = Guid.NewGuid(), Name = "Testing", TimeStamp = ts };
             ctx.Sessions.Add ( s1 );
             ctx.SaveChanges ();

             Session s2 = ( from s in ctx.Sessions
                            where ( s.Name == "Testing" && s.TimeStamp.Equals ( ts ) )
                            select s ).First ();

             Console.WriteLine ( s2.Name, s2.TimeStamp );
          }
       }

       class Context : DbContext
       {
          public DbSet<Session> Sessions { get; set; }
       }

       class Session
       {
          [Key]
          public Guid Id { get; set; }
          public string Name { get; set; }
          public DateTime TimeStamp { get; set; }
       }
    }

I've tried variations on the LINQ statement, including s.datetime.equals(ts) and datetime.compare(s.datetime, ts) == 0 but every time it throws the same exception.
Anyone have any ideas?  Is it me?  Does this code make my binary look big? =^)
Thanks in advance

A: Check out the below code, it works! However the way it works is not logical. Because if you look at note1 and note2 values you see that date value is saved correctly, but is not applied in the query as it is.
var date = new DateTime(ts.Year, ts.Month, ts.Day, ts.Hour, ts.Minute, ts.Second, ts.Millisecond);
Session s2 = (from s in ctx.Sessions
            where (s.Name == "Testing" && s.TimeStamp == date)
            select s).First();

var note1 = s2.TimeStamp == date;
var note2 = s2.TimeStamp == ts;

I guess this is some error related to how Entity Framework assigns the value to @p_linq_0 parameter. This is the query I traced being executed but I could not find what is the value assigned to @p_linq_0.
SELECT TOP (1)
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
[Extent1].[TimeStamp] AS [TimeStamp]
FROM [dbo].[Sessions] AS [Extent1]
WHERE (N'Testing' = [Extent1].[Name]) AND ([Extent1].[TimeStamp] = @p__linq__0)

A: In order to get this to work, I modified the datacolumn for the TimeStamp to be a DateTime2 datatype in the database as follows.
class Session
{
   [Key]
   public Guid Id { get; set; }
   public string Name { get; set; }

   [Column(TypeName = "datetime2")]
   public DateTime TimeStamp { get; set; }
}

Ultimately consider this to be a work around given that the issue appears to lie with LINQ in some way, however it helped me to get past the hurdle and thought I would post here in case anyone else runs into this.


text:
Q: Nginx caching strategy based on request Lets say my backend takes a horrific 2 seconds to respond (out of our control say), and I never EVER want a visitor to experience this delay, we are not influenced by cookies or user session.
What I want to do in nginx is something like this:
server {
  location / {
    # server requests from cache unless for some reason its not in cache
    proxy_pass http://backend/
    proxy_cache mycache
    proxy_cache_is_valid 2m
  }

  location / where request IP = 127.0.0.1 {
     proxy_pass http://backend/
     do_not_use_cache
     but_store response in cache
  }
}

This way I can have a simple curl task from localhost run every 30 seconds that keeps the cache fresh/hot with the several pages I need, I never want the visitor to be the one that warms up the cache.  I've read the docs but cant see how to make this happen.

A: Try this configuration.
http {
  # http section directives

  proxy_cache_path /path/to/cache levels=1:2 keys_zone=mycache;

  geo $bypass_by_ip {
    default   0;
    127.0.0.1 1;
  }

  server {
    # other server directives

    location / {
      proxy_cache mycache;
      proxy_cache_valid any 2m;
      proxy_cache_use_stale timeout updating;
      proxy_cache_bypass $bypass_by_ip;

      proxy_pass ...;
    }
  }
}

proxy_cache_bypass makes a direct request, bypassing the cache. This is controlled by its argument(s) -- if any of them is not an empty string or 0. I am using geo to provide such a value (0 by default and 1 when remote IP is 127.0.0.1)
NOTE you need Nginx version 1.0.4 at least for this configuration to work. Earlier versions had a bug in proxy_cache_bypass / proxy_cache_nocache logic.


text:
Q: Probability for a graph algorithm Let $G = (V, E)$ a graph. A 'dominant set' $W ⊆ V$is a set of nodes, so that for each node $v \in V$ holds that either $v$ itself or a neighbor of $v$ is contained in $W$.
Assume that $G$ has minimum degree at least $d > 1$, i.e. each node $v \in V$ has degree $deg(v) ≥ d$.
The algorithm consists of two rounds. In the first round we mark each node independently from the other nodes with probability $p$. In the second round we look at each node $v \in V$ , if neither $v$ nor any of its neighbours were marked in the first lap, we mark $v$ .
Let $X$ be the number of knots marked in the first round.
So $E(X) = |V|*p$, because $X \sim Bin(|V|,p)$, right ?
Let $v ∈ V $any (but fixed) node. If think the probability that neither v nor one of the neighbors of v was marked in the first round would be $(1-p)^{deg(v)}$ right ? But how can i finde a upper bound  which is only dependent from $d$ and $p$ (and not from $v$).
Let $Y$ be the number of knots marked in the second round. How can i finde a upper bound for $E(Y)$.

A: The probability of being selected in the second round is $(1-p)^{\text{deg}(v)\color{red}{+1}}$.
Use the fact that $\deg v \ge d$ to conclude that $(1-p)^{\deg v+1}\le (1-p)^{d+1}$. Then $EY\le |V|(1-p)^{d+1}$.


text:
Q: Ms Access: How do I populate a table using a field in a form? I want to populate a table in Access that I've just created. I gave it 6 columns. I also made a form that has 6 field inputs. But now I'm confused as to how exactly you make the form write to the table. I want the table to populate downwards, not just re-updating one row every time (in a previous attempt I managed to have the fields save over the same row, but this isn't what I want). I can provide any extra info as needed.

A: The Record Source property of your form should be set to the name of your table and Allow Additions set to Yes. The Control Source property of each field on your form should be set to the required column name.
You can create an Add New Record button on your form using the new button wizard, select Categories: Record Operations & Actions: Add New Record.
That is the bare minimum to start creating new records in your table from a new form.


text:
Q: How do I setState when my drum-pad triggers an onClick function? I'm a newbie to React and currently building a drum-machine. I have wired up the drum-machine to play an audio contained inside its DrumPad child component.My problem is am failing make an id representing each audio display whenever its parent drum-pad div is clicked. I know I need to initialize state and then setState but I dont know how to implement it in my code.
here is my code
import React from 'react';
import './App.css';
import soundData from "./soundData.js"
import DrumPad from "./drumPad.js"

class App extends React.Component {
  constructor(props){
   super(props)
     this.state = {
       display : "hello",
      }
      this.handleDisplay = this.handleDisplay.bind(this)
    }

 handleDisplay (){
   this.setState({display: }) //what do i need to do here?
 }

    render(){

    return(
     <div
     id="drum-machine"
     >

     <div
     id="display"
     >
       {this.state.display}
     </div>
     {soundData.map((data) =>
     (
        <DrumPad
        data={data}
        key={data.letter}
        id = {data.id}
        handleDisplay = {this.handleDisplay}

         />
      ))}
     </div>

    )
     }
  }

export default App;

**drumPad.js**
import React from "react"

function DrumPad(props){

  function handleClick(){

        const audio =  new Audio(props.data.src)
        audio.play()
        audio.currentTime = 0

        }

        return(
            <div
            className= "drum-pad"
            id = {props.data.id}
            onClick = {handleClick}

            >
                <h1>{props.data.letter}</h1>
                <audio
                className = "clip"
                id = {props.data.letter}
                src = {props.data.src}

                />

            </div>

        )

}

export default DrumPad

**soundData.js**

const soundData = [{

 letter:"Q",
 src:"https://raw.githubusercontent.com/wesbos/JavaScript30/master/01%20-%20JavaScript%20Drum%20Kit/sounds/clap.wav",
 id: "clap"

},{

 letter:"W",
    src: "https://raw.githubusercontent.com/wesbos/JavaScript30/master/01%20-%20JavaScript%20Drum%20Kit/sounds/hihat.wav",
    id:"hihat"
 }, {

    letter:"E",
    src: "https://raw.githubusercontent.com/wesbos/JavaScript30/master/01%20-%20JavaScript%20Drum%20Kit/sounds/kick.wav",
    id:"kick"
  },{

    letter:"A",
    src: "https://raw.githubusercontent.com/wesbos/JavaScript30/master/01%20-%20JavaScript%20Drum%20Kit/sounds/openhat.wav",
    id:"openhat"
   },{

    letter:"S",
    src: "https://raw.githubusercontent.com/wesbos/JavaScript30/master/01%20-%20JavaScript%20Drum%20Kit/sounds/boom.wav",
    id:"boom"
 },{

    letter:"D",
    src: "https://raw.githubusercontent.com/wesbos/JavaScript30/master/01%20-%20JavaScript%20Drum%20Kit/sounds/ride.wav",
    id:"ride"
 },{

    letter:"Z",
    src: "https://raw.githubusercontent.com/wesbos/JavaScript30/master/01%20-%20JavaScript%20Drum%20Kit/sounds/snare.wav",
    id:"snare"
 },{

    letter:"X",
    src: "https://raw.githubusercontent.com/wesbos/JavaScript30/master/01%20-%20JavaScript%20Drum%20Kit/sounds/tom.wav",
    id:"tom"
 },
{

    letter:"C",
    src: "https://raw.githubusercontent.com/wesbos/JavaScript30/master/01%20-%20JavaScript%20Drum%20Kit/sounds/tink.wav",
    id:"tink"
 }]

   export default soundData

A: for updating the state, you need to pass the function handleDisplay to DrumPad and call the handleDisplay inside handleClick, passing the required data as parameters.
CodeSandbox
//App.js
handleDisplay(key) {
    this.setState({
      display: key
    });
  }

//DrumPad.js
  function handleClick() {
    const audio = new Audio(props.data.src);
    audio.play();
    audio.currentTime = 0;
    props.handleDisplay(`${props.data.letter} : ${props.data.id}`);
  }


text:
Q: How to add JPanel in a JFrame that is a BufferedImage() So far I have this:

The logic is that:
a.)I will press the keybutton 'S' then the game will start
b.)The JTextArea will show the conversation of the users(note: I didn't disable it for debugging purposes)
c.)The JTextField will be the field the user will type text.
I have these working code:
package game;

//import

public class Game extends JFrame {

public static final String SERVER_IP = "localhost";

public static final int WIDTH = 1200;
public static final int HEIGHT = 800;
public static final int SCALE = 1;

private final int FPS = 60;
private final long targetTime = 1000 / FPS;

private BufferedImage backBuffer;

public KeyboardInput input;
private Stage stage;

public String username = "";

public GameClient client;
public static Game game;

public static String message = "";

private Tank tank;

private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;

public Game() throws HeadlessException {
    setSize(1000, 1000);
    addWindowListener(new WinListener());
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setResizable(false);
    setVisible(true);
    //setUndecorated(false);
    addKeyListener(input);
    setVisible(true);
}
public void init() {
    this.game = this;
    input = new KeyboardInput();

    //this.setSize(WIDTH, HEIGHT);
    //this.setLocationRelativeTo(null);
    //this.setResizable(false);

  Dimension expectedDimension = new Dimension(900, 50);
  Dimension expectedDimension2 = new Dimension(100, 50);
   jButton1 = new JButton("jButton1");

jTextArea1 = new JTextArea(6,6);
jTextArea1.setBounds(0,200,200,200);
jTextArea1.setBackground(Color.BLUE);
//jTextArea1.setFocusable(false);
jTextField1 = new JTextField("jTextField1");
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
panel2.add(jTextField1);
panel2.add(jButton1);
panel2.setBackground(Color.BLACK); // for debug only
panel2.setPreferredSize(expectedDimension);
panel2.setMaximumSize(expectedDimension);
panel2.setMinimumSize(expectedDimension);
jPanel1 = new JPanel();
jPanel1.setLayout(new BoxLayout(jPanel1, BoxLayout.Y_AXIS));
jPanel1.add(jTextArea1);
jPanel1.add(panel2);
jPanel1.setBackground(Color.RED); // for debug only
jPanel1.setPreferredSize(expectedDimension2);
jPanel1.setMaximumSize(expectedDimension2);
jPanel1.setMinimumSize(expectedDimension2);
jScrollPane1 = new JScrollPane(jPanel1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
setContentPane(jScrollPane1);

System.out.println("init");
revalidate();

    client = new GameClient(SERVER_IP, this);

    backBuffer = new BufferedImage(800* SCALE,600 * SCALE, BufferedImage.TYPE_INT_RGB);
}

public Stage getStage() {
    return stage;
}

public class WinListener extends WindowAdapter {

    @Override
    public void windowClosing(WindowEvent e) {
        disconnect();
        System.exit(0);
    }

}

public void disconnect() {
    Packet01Disconnect p = new Packet01Disconnect(username);
    p.writeData(client);
    client.closeSocket();
    System.exit(0);
}

private Font font = new Font("Munro Small", Font.PLAIN, 96);
private Font font2 = new Font("Munro Small", Font.PLAIN, 50);
private Font fontError = new Font("Munro Small", Font.PLAIN, 25);
private int op = 0;

public void updateMenu() {
    if (input.up.isPressed()) {
        if (op == 1) {
            op = 0;
        } else {
            op++;
        }
        input.up.toggle(false);
    } else if (input.down.isPressed()) {
        if (op == 0) {
            op = 1;
        } else {
            op--;
        }
        input.down.toggle(false);
    } else if (input.enter.isPressed() && op == 0) {
        runningMenu = false;
        input.enter.toggle(false);
    } else if (input.enter.isPressed() && op == 1) {
        System.exit(0);
    }
}

public void drawMenu() {
    Graphics g = getGraphics();
    Graphics bbg = backBuffer.getGraphics();
    bbg.setFont(font);
    bbg.setColor(Color.white);

    bbg.drawString("Sample", 189, 180);
    bbg.setFont(font2);
    if (op == 0) {
        bbg.setColor(Color.red);
        bbg.drawString("Start", 327, 378);
        bbg.setColor(Color.white);
        bbg.drawString("Quit", 342, 425);
    } else if (op == 1) {
        bbg.setColor(Color.white);
        bbg.drawString("Start", 327, 378);
        bbg.setColor(Color.red);
        bbg.drawString("Quit", 342, 425);
    }

    g.drawImage(backBuffer, 0, 0, this);
}

public void draw() {
    Graphics g = getGraphics();
    Graphics bbg = backBuffer.getGraphics();
    bbg.setColor(Color.black);
    bbg.fillRect(0, 0, WIDTH, HEIGHT);
    stage.drawStage(bbg, this);
    for (Tank t : stage.getPlayers()) {
        t.draw(bbg, SCALE, this);
    }
    g.drawImage(backBuffer, 0, 0, this);
}

public void update() {

    tank.update(stage);

    stage.update();
}

private long time = 0;

public void updateLogin() {
    if (username.length() < 8) {
        if (input.letter.isPressed()) {
            username += (char) input.letter.getKeyCode();
            input.letter.toggle(false);
        }
    }

    if (input.erase.isPressed() && username.length() > 0) {
        username = username.substring(0, username.length() - 1);
        input.erase.toggle(false);
    }

    if (input.enter.isPressed() && username.length() > 0) {
        input.enter.toggle(false);
        time = System.currentTimeMillis();
        Packet00Login packet = new Packet00Login(username, 0, 0, 0);
        packet.writeData(client);
    }

    if (message.equalsIgnoreCase("connect server success")) {
        time = 0;
        runningLogin = false;
        return;
    }

    if (message.equalsIgnoreCase("Username already exists")) {
        drawLogin();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
        }
        message = "";
        username = "";
        time = 0;
    }

    if (message.equalsIgnoreCase("Server full")) {
        drawLogin();
        try {
            Thread.sleep(2000);
        } catch (Exception e) {
        }
        System.exit(0);
    }

    if (time != 0 && message.equals("") && (System.currentTimeMillis() - time) >= 5000) {
        message = "cannot connect to the server";
        drawLogin();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
        }
        message = "";
        time = 0;
    }
}

public void drawLogin() {
    Graphics g = getGraphics();
    Graphics bbg = backBuffer.getGraphics();
    bbg.setColor(Color.black);
    bbg.fillRect(0, 0, 800, 600);
    bbg.setColor(Color.red);
    bbg.setFont(fontError);
    bbg.drawString(message, 100, 100);
    bbg.setFont(font2);
    bbg.setColor(Color.white);
    bbg.drawString("Username", 284, 254);
    bbg.setColor(Color.red);
    bbg.drawString(username, 284, 304);
    g.drawImage(backBuffer, 0, 0, this);
}

public static String waitPlayers = "Waiting for others players";
public String auxWaitPlayers = waitPlayers;
public static int quantPlayers = 0;

public class StringWait extends Thread {

    public void run() {
        while (true) {
            try {
                waitPlayers = "waiting  for  others  players";
                Thread.sleep(1000);
                waitPlayers = "waiting  for  others  players.";
                Thread.sleep(1000);
                waitPlayers = "waiting  for  others  players..";
                Thread.sleep(1000);
                waitPlayers = "waiting  for  others  players...";
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
            }
        }
    }
}

public void updateWaitPlayers() {
    if (quantPlayers == 1) {
        runningWaitPlayer = false;
    }
}

public void drawWaitPlayers() {
    Graphics g = getGraphics();
    Graphics bbg = backBuffer.getGraphics();
    bbg.setColor(Color.black);
    bbg.fillRect(0, 0, 800, 600);
    bbg.setColor(Color.white);
    bbg.setFont(fontError);
    bbg.drawString(waitPlayers, 100, 100);
    g.drawImage(backBuffer, 0, 0, this);
}

public boolean runningMenu = true, runningLogin = true, runningWaitPlayer = true, runningGame = true;

public int op2 = 0;

public void start() {
    long start;
    long elapsed;
    long wait;
    init();
    while (true) {
        runningGame = true;
        runningMenu = true;
        runningWaitPlayer = true;
        runningLogin = true;
        switch (op2) {
            //..
    }
}

public void setGameState(boolean state) {
   //...
}

public static void main(String[] args) throws InterruptedException {
    Game g = new Game();
    Thread.sleep(1000);
    g.start();
}

}
And these is my objective interface:
I hope someone will help me with my problem.

A: *

*Set the "main" containers layout manager to BorderLayout

*On to this, add the GameInterface in the BorderLayout.CENTER position

*Create another ("interaction") container and set it's layout manager to BorderLayout, add this to the "main" container's BorderLayout.SOUTH position

*Wrap the JTextArea in a JScrollPane and add it to the BorderLayout.CENTER position of your "interaction" container

*Create another container ("message"), this could use a GridBagLayout.  On to this add the JTextField (with GridBagConstraints#weightx set to 0 and GridBagConstraints#weightx set to 1) and add the button to the next cell (GridBagConstraints#gridx set to 1 and GridBagConstraints#weightx set to 0)

For more details, see:

*

*Laying Out Components Within a Container

*How to Use Borders

*How to Use GridBagLayout
Note:
Graphics g = getGraphics(); is NOT how custom painting should be done. Instead, override the paintComponent of a component like JPanel and perform your custom painting there!
For more details see

*

*Painting in AWT and Swing

*Performing Custom Painting
Example

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JPanel master = new JPanel(new BorderLayout());
                master.setBackground(Color.BLUE);

                JPanel gameInterface = new JPanel() {
                    @Override
                    public Dimension getPreferredSize() {
                        return new Dimension(400, 400);
                    }
                };
                gameInterface.setBackground(Color.MAGENTA);

                master.add(gameInterface);

                JPanel interactions = new JPanel(new BorderLayout());
                interactions.add(new JScrollPane(new JTextArea(5, 20)));

                JTextField field = new JTextField(15);
                JButton btn = new JButton("Button");

                JPanel message = new JPanel(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridx = 0;
                gbc.weightx = 1;
                gbc.fill = GridBagConstraints.HORIZONTAL;
                message.add(field, gbc);
                gbc.gridx = 1;
                gbc.weightx = 0;
                message.add(btn, gbc);

                interactions.add(message, BorderLayout.SOUTH);

                master.add(interactions, BorderLayout.SOUTH);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(master);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}


text:
Q: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error I'm using php and pdo
Here is my code:
try {
    $sql="LOCK TABLE appleid WRITE, appleid AS appleid1 READ;";
    $stmt = $GLOBALS['$connection']->prepare($sql);
    $stmt->execute();
    $sql="SELECT MAX(num) FROM appleid;";//to know how many rows it has
    $stmt = $GLOBALS['$connection']->prepare($sql);
    $stmt->execute();
    $result=$stmt->fetch();
    $table_top=$result[0];

    if (empty($head)) $head = 1;
    $check=$table_top - $head;
    $check++;//number of available rows that are ready to use

    if($check>=$this->apple_id_num)
    {
        $sql = "SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
        appleid AS appleid1
        WHERE num>=$head LIMIT $this->apple_id_num ORDER BY `TimeStamp`
        DESC;";
        $stmt = $GLOBALS['$connection']->prepare($sql);
        $stmt->execute();
        $this->pre_head=$head;
        $head=1+$head+$this->apple_id_num;
        $sql="UNLOCK TABLES;";
        $this->num_rows = $stmt->rowCount();
        echo $stmt->rowCount();
    }
}
catch(PDOException $e)
{
    echo $sql . "<br>" . $e->getMessage();
}

I get this error :

SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM appleid AS
  appleid1 WHERE num>=1 LIMIT 1 ORDER BY TimeStamp DESC;
  SQLSTATE[42000]: Syntax error
or access violation: 1064 You have an error in your SQL syntax; check
  the manual that corresponds to your MySQL server version for the right
  syntax to use near 'ORDER BY TimeStamp DESC' at line 2

I got confused and I don't know what is wrong with this query and how to fix it.

A: Use orderby clause before limit clause.
$sql = "SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
appleid AS appleid1
WHERE num>=$head ORDER BY `TimeStamp` DESC LIMIT $this->apple_id_num;";

A: Change
"SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
    appleid AS appleid1
    WHERE num>=$head LIMIT $this->apple_id_num ORDER BY `TimeStamp`
    DESC;";

to
"SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
    appleid AS appleid1
    WHERE num>=$head LIMIT {$this->apple_id_num} ORDER BY `TimeStamp`
    DESC;";

since the double quotes would not know whether to parse the ->apple_id_num as string or part of a variable.

A: SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
        appleid AS appleid1
        WHERE num>=$head ORDER BY `TimeStamp`
        DESC LIMIT $this->apple_id_num ;

put your limit after orderby

A: I have not tested, but timeStamp sound like a reserved word of mysql,
maybe you can try a correct quote of this field, or best pratice change the name of the field.


text:
Q: Pop a largest number in a list to another list, python I want to get the max() nubmer in a list and then pop it to another list, (list1).
x = [66,1,4,3,6,55]

list1 = []
for i in x:
    x.pop(max(x))
    #poped item saved to list1
print(list1)

This is my approach but i get the error " pop index out of range". What am i doing wrong ? And i really dont know how to further pop() an item and return it to an empty list.The result should be a list1 with numbers from highest to lowest. Please, dont post any other algorithm with built in functions like sort(). Thanks.

A: You need to provide the index of the max element in a list to pop
x = [66,1,4,3,6,55]
list1 = [x.pop(x.index(max(x)))]
print(list1)

Output
[66]

Request from Comments:
x = [66,1,4,3,6,55]
list1 = []
while x:
    list1.append(x.pop(x.index(max(x))))
print(list1)

A: In python pop method's argument is index, But you are passing values.
x = [66,1,4,3,6,55]
list1 = []
for i in range(len(x)):
    list1.append(x.pop(x.index(max(x))))
print(list1)

Try this.

A: You can try:
>>> x = [66,1,4,3,6,55]
>>> list_popped = []
>>> list_popped.append(x.pop(x.index(max(x))))
>>> print list_popped
[66]
>>> print x
[1, 4, 3, 6, 55]

A: List pop method takes index of the element as argument. you are providing the item itself. In your example the first value will be 66 and you are trying pop(66), there is no item at 66th index(the length of the list is less than 66).
try the following code
x = [66,1,4,3,6,55]

list1 = []
for i in range(len(x)):
    max_val = max(x)
    max_val_index = x.index(max_val)
    list1.append(max_val)
    x.pop(max_val_index)
print(list1)

Output: [66, 55, 6, 4, 3, 1]


text:
Q: Why is assigning a template variable to ngModel in Angular not working? I have the following segment of code in a format that is quite common in Angular:

    <input class="form-control" type="text" [(ngModel)]="siteUrl"
      #siteUrl="ngModel" name="siteUrl" required>

          siteUrl is required

During transpile I get the following error:

An unhandled exception occurred: Cannot assign value "$event" to template variable "siteUrl". Template variables are read-only.

I am using Angular 13 and copied this segment of code directly from another working Angular 13 application.

A: Because your template variable name is colliding with the property you're binding ngModel to. Change your template variable name to a unique name so ngModel isn't trying to assign to it:

  <input class="form-control" type="text" [(ngModel)]="siteUrl"
    #siteUrlField="ngModel" name="siteUrl" required>

        siteUrl is required

Here's a working stackblitz example.


text:
Q: Javascript variables scope and use in JQuery I have very little knowledge of javascript and jquery, but I was able to put the following code together.
I want to add the result of 'name' to the div "displayName" on an html page when I click the "nameCreationButton" button on the html page.  When I click "nameCreationButton", absolutely nothing happens.
I declared the variable 'name' outside of the function 'generator', so my jquery should be able to access it, right?  I have spent hours looking at this, and I feel silly for not understanding why it will not work.
function generator(){

  var firstName = ["John","Mike","Robert","Patrick"];
  var lastName = ["Smith","Johnson","Williams","Anderson"];

  var randomNumber1 = parseInt(Math.random() * firstName.length);
  var randomNumber2 = parseInt(Math.random() * lastName.length);
  var name = firstName[randomNumber1] + " " + lastName[randomNumber2];
}

var name;

generator();

$(document).ready(function(){
 $(".nameCreationButton").click(function(){
    $(".displayName").append('name');
 });
});

Here is my HTML page if it is any use.
<!DOCTYPE html>

    <link rel='stylesheet' href='style.css'/>

    <button class = "nameCreationButton">Click Here to Generate Name</button>

A: There is absolutely no point in declaring the variable name twice. You do it once inside generator() and once as a global which is not a very good idea.
Instead, what you want is to execute the function generator() once you click on the button. This function needs to return the name.
To rewrite this:
function generator(){
    var firstName = ["John","Mike","Robert","Patrick"],
        lastName = ["Smith","Johnson","Williams","Anderson"],
        randomNumber1 = parseInt(Math.random() * firstName.length, 10),
        randomNumber2 = parseInt(Math.random() * lastName.length, 10);

    return firstName[randomNumber1] + " " + lastName[randomNumber2];
}

$(function(){
    $(".nameCreationButton").click(function(){
        //var name = generator();
        $(".displayName").append(generator());
    });
});

demo

A: You need to remove the single ' quote on append('name').
And also you need to remove the var declaration for the name variable inside the generator function. The var name inside the generator block ({ ...}) makes the variable only visible inside that block. So on your original code, you are having two different variables named name with two different scopes.
Try:
function nameGenerator(){

  var firstName = ["John","Mike","Robert","Patrick"];
  var lastName = ["Smith","Johnson","Williams","Anderson"];

  var randomNumber1 = parseInt(Math.random() * firstName.length);
  var randomNumber2 = parseInt(Math.random() * lastName.length);
  return firstName[randomNumber1] + " " + lastName[randomNumber2];
}

$(document).ready(function(){
 $(".nameCreationButton").click(function(){
    var name = nameGenerator();
    $(".displayName").text(name);
 });
});

A: (*) you had rfered variable with quotes, it will be considered a string
 var name = "aslan";
 console.log(name) //=> aslan
 console.log("name") //=> name

(*) also, variable name is declared inside and out side function.
    variable declared inside function is considered as local variable,
    so var name declared outside function wont get update, which us used append().
    check : http://snook.ca/archives/javascript/global_variable
Change code to:
 function generator(){

   var firstName = ["John","Mike","Robert","Patrick"];
   var lastName = ["Smith","Johnson","Williams","Anderson"];

   var randomNumber1 = parseInt(Math.random() * firstName.length);
   var randomNumber2 = parseInt(Math.random() * lastName.length);
   return  firstName[randomNumber1] + " " + lastName[randomNumber2];
 }

 $(document).ready(function(){
   $(".nameCreationButton").click(function(){
      $(".displayName").append( generator() );
   });
 });


text:
Q: Is it possible to retrieve a value in a child class generated by a decorator defined in a base class? I have a child class method I want to conditionally short circuit. What I'm trying to do is something like this except I want to put the validation logic into the base class.
class BaseClass(object):
    def getvalue(self):
        return True
    def validate(self):
        validated = self.getvalue()
        return validated

class ExtendedClass1(BaseClass):
    def do_some_work(self):
        validated = self.validate()
        if not validated:
            print "Not validated."
            return
        print "Things are validated if the method got this far.", validated

class ExtendedClass2(BaseClass):
    def do_some_work(self):
        validated = self.validate()
        if not validated:
            print "Not validated."
            return
        print "Things are validated if the method got this far.", validated

class ExtendedClass3(BaseClass):
    def do_some_work(self):
        print "This one doesn't require validation."

work1 = ExtendedClass1()
work1.do_some_work()

work2 = ExtendedClass2()
work2.do_some_work()

work3 = ExtendedClass3()
work3.do_some_work()

Following this example I was able to convert some of the repeated code into a decorator pattern.
class BaseClass(object):

    def validate(input_function):
        def wrapper(*args,**kwargs):
            validated = True
            if not validated:
                print "Not validated."
                return
            input_function(*args, **kwargs)
        return wrapper

    validate = staticmethod(validate)

class ExtendedClass1(BaseClass):
    @BaseClass.validate
    def do_some_work(self):
        print "Things are validated if the method got this far."

class ExtendedClass2(BaseClass):
    @BaseClass.validate
    def do_some_work(self):
        print "Things are validated if the method got this far."

class ExtendedClass3(BaseClass):
    def do_some_work(self):
        print "This one doesn't require validation."

work1 = ExtendedClass1()
work1.do_some_work()

work2 = ExtendedClass2()
work2.do_some_work()

work3 = ExtendedClass3()
work3.do_some_work()

However, I need to call a method of the base class in the decorator to do the validation work, and retrieve the value of (validated) in the child class. Following this example here, I modified the decorator in an attempt to let it call self.getvalue(). At this point it doesn't error out, but it doesn't work either because self.getvalue() doesn't return True. This is starting to seem like more trouble than it's worth, but now I'm curious as to whether or not it's possible.
class BaseClass(object):

    def getvalue(self):
        return True

    def validate(self):
        def wrap(input_function):
            def wrapper(*args,**kwargs):
                validated = self.getvalue()
                if not validated:
                    print "Not validated."
                    return
                input_function(*args, **kwargs)
            return wrapper
        return wrap

    validate = staticmethod(validate)

class ExtendedClass1(BaseClass):
    @BaseClass.validate
    def do_some_work(self):
        print "Things are validated if the method got this far."#, validated

class ExtendedClass2(BaseClass):
    @BaseClass.validate
    def do_some_work(self):
        print "Things are validated if the method got this far."#, validated

class ExtendedClass3(BaseClass):
    def do_some_work(self):
        print "This one doesn't require validation."

work1 = ExtendedClass1()
work1.do_some_work()

work2 = ExtendedClass2()
work2.do_some_work()

work3 = ExtendedClass3()
work3.do_some_work()

Is it possible to set an attribute with the decorator and then retrieve it later?
                ...
                self.validated = True
                if not self.validated:
                    print "Not validated."
                    return
                ...
print work1.validated
                ...

AttributeError: 'ExtendedClass1' object has no attribute 'validated'

Essentially, I want to turn this:
class ExtendedClass1(BaseClass):
    def do_some_work(self):
        validated = self.validate()
        if not validated:
            print "Not validated."
            return
        print "Things are validated if the method got this far.", validated

Into this:
class ExtendedClass1(BaseClass):
    @BaseClass.validate
    def do_some_work(self):
        print "Things are validated if the method got this far.", validated

Using the suggestion posted by Zaur Nasibov, this example satisfies my use case. I'm still interested to know if @validate can be implemented as a method instead of a stand alone function, but this gets the job done.
class BaseClass(object):
    def getvalue(self):
        return True

def validate(func):
    def wrapped(self, *args, **kwargs):
        validated = self.getvalue()
        self.validated = validated
        if not validated:
            print "Not validated."
            return
        func(self, *args, **kwargs)
    return wrapped

class ExtendedClass1(BaseClass):
    @validate
    def do_some_work(self,input):
        print "Things are validated if the method got this far.", self.validated, input

class ExtendedClass2(BaseClass):
    @validate
    def do_some_work(self):
        print "Things are validated if the method got this far.", self.validated

class ExtendedClass3(BaseClass):
    def do_some_work(self):
        print "This one doesn't require validation."#, self.validated

work1 = ExtendedClass1()
work1.do_some_work(input="some text")

work2 = ExtendedClass2()
work2.do_some_work()

work3 = ExtendedClass3()
work3.do_some_work()

A: @tponthieux, what you can do is setting the attribute of the called function (method) and then retrieving it:
Simple example (updated):
def validate(func):
    def wrapped(self, *args, **kwargs):
        self.valid = True
        func(self, *args, **kwargs)
    return wrapped

class TestClass(object):
    @validate
    def do_some_work(self):
        print "some work done"

tc = TestClass()
tc.do_some_work()
print tc.valid

A: How about only calling the decorated method if it has been validated? You can pass the return value of the validate method along if you like:
class BaseClass(object):
    def getvalue(self):
        return True

    def validate(input_function):
        def wrapper(self, *args, **kwargs):
            self.validated = self.getvalue()
            if not self.validated:
                print "Not validated."
                return
            input_function(self, validated=self.validated, *args, **kwargs)
        return wrapper

    validate = staticmethod(validate)

class ExtendedClass1(BaseClass):
    @BaseClass.validate
    def do_some_work(self, validated=None):
        print "Things are validated if the method got this far.", validated

class ExtendedClass2(BaseClass):
    @BaseClass.validate
    def do_some_work(self, validated=None):
        print "Things are validated if the method got this far.", validated

class ExtendedClass3(BaseClass):
    def do_some_work(self):
        print "This one doesn't require validation."

work1 = ExtendedClass1()
work1.do_some_work()

work2 = ExtendedClass2()
work2.do_some_work()

work3 = ExtendedClass3()
work3.do_some_work()

The key here is adding self to the wrapper function. What happens is that your decorated functions do not get bound to the instance (and become methods), but the function returned by the decorator (wrapper in the above example) get's bound instead. So this function will get the self (the instance) parameter passed in when called! It's important to remember that what a @decorator does is simply call decorator passing in the function you are decorating, and then replace the function you are decorating with whatever the decorator returned. In your example this is wrapper, and to the class, there is no difference between that and the original function before decorating.
In the above example, I declared self explicitly. If we hadn't, we could also have just taken it from args:
def validate(input_function):
    def wrapper(*args, **kwargs):
        print "args[0] is now the instance (conventionally called 'self')", args[0]
        self = args[0]
        self.validated = self.getvalue()
        if not self.validated:
            print "Not validated."
            return
        input_function(validated=self.validated, *args, **kwargs)

Also note that we pass an extra keyword argument to the wrapped method, named validated. This is entirely optional, you can just drop the validated=self.validated and validated=None parts from the example.


text:
Q: Sequence with a fixed last element Notation I was trying to write a sequence of two different elements (that always appear in order) with a fixed last element, for an example: $A_1, B_1, A_2, B_2, A_3, B_3, A_4$. I'm not sure which would be the best way to explain and represent this situation.
The best that I reached was: $\Gamma = \langle (A_{i},B_{i})_{i=1}^{n},A_{n+1} \rangle$. But I'm not sure if this notation is correct because it is actually a sequence of ordered pairs with a last element (that is not an ordered pair).
So, I'm asking you, is it a valid way to represent what I want? If not, which would be the best way to write that?

A: I think you can safely go with something simple:
$$A_1, B_1, A_2, B_2, \dotsc, A_n, B_n, A_{n+1}.$$


text:
Q: Webpack: How to inject process.env runtime on client(browser) side making build independent of environment SHORT Question
I'm looking some way to tell Webpack that, do not do anything with process variable, just treat as like any other global variable (so it refers to window.process in client bundle). If not possible, then a way to inject variables in process.env of Webpack during runtime on client.
LONG Explaination
At the moment, I use Webpack to pack my React (SSR) application. I have 5 environments like dev1, dev2... staging and production. I want to re-use the same build and keep things configurable like say Google Analytics ID on each environment is different.
Backend Dot ENV module does the job. I can define all constants as KEY=value pair in .env file and load them run time and use as process.env.KEY in the code.
I was trying to replicate same behaviour for the front end side (or shared files). Say I have a baseService.js which makes call to fetch. It can be used from node + client as well. It uses variables like process.env.HOST. Until now I was creating separate build for each environment, therefore had this defined in Webpack using webpack.DefinePlugin plugin to be able to use this on client side bundle.
Now as I want to re-use the builds, I capture all constants in process.env see if any of them is usable on client side by matching them with PUBLIC_(.*) (It would match PUBLIC_KEY), if yes pack then in array and add in main html file as object as shown below:-
window.process = {ENV: { PUBLIC_GA_ID: '1235', PUBLIC_FOO: 'bar' }}

When I bundle my client using webpack and execute process.env.PUBLIC_GA_ID is undefined (although it is there in head html as global window.process variable). It is because webpack still injecting process variable from Node to the front end which has env object as blank {} object. I had it debugged below is the screenshot.

Above is console log of process variable in a baseService.js file. Obviously I cannot use window.process here because then it would fail when file is being used in Node.js
I'm looking some way to tell Webpack that, do not do anything with process variable, just treat as like any other global variable (so it refers to window.process in client bundle). If not possible, then a way to inject variables in process.env of Webpack during runtime on client.

A: I think instead playing with Webpack to do this job, I have settled with for the simplest solution. If anyone has any better answer, please do post.
I created a utility function as follows:-
export const getEnv = key => {
  if (typeof window === 'undefined') {
    // node
    return process.env[key]
  }
  // browser
  return window.process.env[key]
}

Now I call getEnv('PUBLIC_KEY') or getEnv('NODE_ENV') both in node and in browser and works perfectly fine.
Although I'd still prefer the better way Webpack supports option to take process.env run time or inject API for browser

A: I had a similar issue with webpack inlining the contents of process.env.NODE_ENV at compile time.
I was able to switch that off by adding the following to my server webpack config:
  optimization: {
    nodeEnv: 'production'
  }

See the optimization docs for more related info

A: Use "globalThis" in your code in place of "window" and use "globalThis.process" in place of "process".

A: In fact, webpack preset 2 environment to build different app.
Consider this config:
// package.json
"scripts": {
    "build:development": "cross-env NODE_ENV=development webpack",
    "build:production": "cross-env NODE_ENV=production  webpack",
 }

// webpack.config.js
const ENVIRONMENT = process.env.NODE_ENV;
module.exports = {
entry: { // ... },
output: { // ... },

// typeof mode =  "development" | "production" | "none";
mode: ENVIRONMENT

}

$ npm run build:development
After building, open browser, also output that you set current env is: development
good luck

A: What I ended up doing is:

*

*Use webpack to generate the bundle, that will be reused in dev, prod, stage.

*Access the .env file in execution time, with your own code and not using dotenv, neither webpack-dotenv.

*create a function getEnv() that uses  const rawFile = new XMLHttpRequest(); and reads your .env file.

*you don't use dotenv package, neither you require it. You just import { getEnv }  and use it in your code in runtime.

Of course this is not the safest, but either dotenv or webpack-dotenv are since the keys are being injected to the client anyways and accessible.
And you can reuse your bundle, and create the file that your function reads in the docker, or anywhere.


text:
Q: Java - How can I disable a TLS cipher for only some protocols using JVM Config? I've seen lots of examples of disabling TLS ciphers in java using jdk.tls.disabledAlgorithms, for example:
 jdk.tls.disabledAlgorithms=MD2, RSA keySize < 1024, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256

But how can I disable a cipher for only certain protocols, using jdk.tls.disabledAlgorithms or a similar config?
For example, how can I disable TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 for TLSv1.1 only?
It doesn't seem to support the opensssl way of doing this, which is like so:
TLSv1.1:!TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256

It doesnt cause any errors, but the cipher is still allowed.
EDIT: Note that I'm only really interested in JVM config based answers, as I don't control the code that's on lots of these servers, just the JVM and JVM configurations. Some are even 3rd party servers, so more of an ops level thing than anything.
EDIT 2: Note that you can run a java app and supply arguments that change which protocols and ciphers are used, e.g. java -server -Djava.security.properties=./my/custom/java.security -jar myapp.jar will do it - but it wont let you filter ciphers by protocol, only ciphers, or protocols, from what I can see. The file would contain a property entry like jdk.tls.disabledAlgorithms

A: Posting my comment as an answer because why not.
Other answers, and every doc I've found online, seems to agree that what you are asking for is not possible to do within Java, not yet at least. You can enable / disable protocols globally, and you can enable / disable cipher types globally, but you cannot do one based on the other.
However, since you are on the DevOps side, maybe a non-Java solution is possible. You could run separate instances of the app, each one having only TLSv1.1, only TLSv1.2 etc. enabled, and apply the desired cipher filter to each one; and then have nginx (or whatever you use) redirect traffic to the appropriate instance depending on the detected protocol.
So, one instance at NODE1 with:
jdk.tls.client.protocols=TLSv1.1
jdk.tls.disabledAlgorithms=TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256

Another instance at NODE2 with:
jdk.tls.client.protocols=TLSv1.2
jdk.tls.disabledAlgorithms=...

And some nginx rules (use return or rewrite as you see fit):
server {
    [...]
    if ( $ssl_protocol = TLSv1.1 ) {
        return 302 $scheme://NODE1.yourhost.com$request_uri;
    }
    if ( $ssl_protocol = TLSv1.2 ) {
        rewrite ^ $scheme://NODE2.yourhost.com$request_uri;
    }

I'm just a Java dev, my experience with nginx is very limited so you might need to tweak the config a bit. Just trying to help.

A: JSSE docs say that the https.protocols property can store comma separated list of supported protocols in a given SSL context, however this property is used by current JSSE implementation, but could be disregarded by other vendors or future versions, so YMMV.
Programatically you can achieve it like so:
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
socket.setEnabledCipherSuites(new String[] {
    CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName,
    CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName,
});

//allow TLS1.2 only
socket.setEnabledProtocols(new String[] {
    TlsVersion.TLS_1_2.javaName,
});

A: edit lib/security/java.security (could be in a different location based on your JDK) and add the Algorithm to the jdk.tls.disabledAlgorithms
In addition to that keySize could be used to restrict weaker algorithms.
jdk.tls.disabledAlgorithms=MD2, MD4, MD5, EC keySize < 160, RSA keySize < 2048, DSA keySize < 2048
I suppose, you already know all these, and are really looking to have these per version (ideally something like jdk.tls11.disabledAlgorithms)
however, I am not aware of any such fine grained property.
However, protocol version could be restricted as such jdk.tls.client.protocols=TLSv1.1
If you want to support TLSv1.1 and TLSv1.2 a good strategy would be to support only those algorithms (or adjust keySize of algorithms) so that they will be strong in both versions of TLS.
For reference: https://www.java.com/en/configure_crypto.html


text:
Q: paramiko - slow sftp transfer speed compared with system rsync/sftp/scp I have noticed that I can't get the same transfer speed when performing a get or put with paramiko's sftp.
Across our gigabit network from our mac mini server (running Mac os 10.12.6) a file transfer via rsync/sftp/scp/finder sustains around 95-100MB/sec. If I use paramiko's sftp.get I see it reaches a maximum of 25MB/sec.
I was using paramiko 1.17 and updated to 2.3.1 but am seeing pretty much the same speed.
Any ideas what could be causing the limitation?
Thanks!
Adam

A: I ran into the same problem and implemented a few suggestions that others made.  There are three things that can be done:

*

*Increase the buffer size in your transport.
  transport = paramiko.Transport(ftp_host, ftp_port)
  transport.default_window_size = 4294967294 # 2147483647
  transport.packetizer.REKEY_BYTES = pow(2, 40)
  transport.packetizer.REKEY_PACKETS = pow(2, 40)

*Perform a read ahead prior to getting the file.
 ftp_file = ftp_conn.file(file_name, "r")
 ftp_file_size = ftp_file.stat().st_size
 ftp_file.prefetch(ftp_file_size)
 ftp_file.set_pipelined()
 ftp_file_data = ftp_file.read(ftp_file_size)

*The other thing you can do when transferring larger files is implementing "chunks". This splits the files into smaller pieces that are transferred individually. I have only tested this with a transfer to s3.
 chunk_size = 6000000 #6 MB
 chunk_count = int(math.ceil(ftp_file_size / float(chunk_size)))
 multipart_upload = s3_conn.create_multipart_upload(Bucket=bucket_name, Key=s3_key_val)
 parts = []
 for i in range(chunk_count):
     print("Transferring chunk {}...".format(i + 1), "of ", chunk_count)

     start_time = time.time()
     ftp_file.prefetch(chunk_size * (i+1) # This statement is where the magic was to keep speeds high.
     chunk = ftp_file.read(int(chunk_size))
     part = s3_conn.upload_part(
         Bucket=bucket_name,
         Key=s3_file_path,
         PartNumber=part_number,
         UploadId=multipart_upload["UploadId"],
         Body=chunk
     )
     end_time = time.time()
     total_seconds = end_time - start_time
     print("speed is {} kb/s total seconds taken {}".format(math.ceil((int(chunk_size) / 1024) / total_seconds), total_seconds))
     part_output = {"PartNumber": i, "ETag": part["ETag"]}
     parts.append(part)
 print("Chunk {} Transferred Successfully!".format(i + 1))

 part_info = {"Parts": parts}
 s3_conn.complete_multipart_upload(
     Bucket=bucket_name,
     Key=s3_key_val,
     UploadId=multipart_upload["UploadId"],
     MultipartUpload=part_info
 )

The important part while processing the chunck is the  ftp_file.prefetch(chunk_size * (i+1)) which reads ahead incrementally further with each loop.
After implementing all of this, downloads went from 200 kBps to 5 MBps (the max tunnel speed).
In a later iteration of this code I ran into problems with the garbage collection from paramiko. I resolved them by removing the line:
ftp_file.set_pipelined()


text:
Q: vector push_back not working in class object I am making an hierarchy of sorts and am having trouble adding an element to a vector. I simplified the code and still cannot add an element to the vector as expected. The hierarchy looks like:
Pdb > Chain > strings
Pdb and Chain are class names and strings is the name of a vector belonging to Chain. I cannot push_back to add a string to strings. You may get a better idea looking at my code:
Chain Class:
class Chain {
  string chain_id;
  vector<string> strings;

public:
  Chain(string id_) { chain_id = id_; }
  vector<string> GetStrings() { return strings; }
  void AddString(string s) {
    cout << "Size of strings BEFORE push_back in AddString: " << strings.size() << endl;
    strings.push_back(s);
    cout << "Size of strings AFTER push_back in AddString: " << strings.size() << endl;
  }
  string GetChainId() { return chain_id; }
};

Pdb class:
class Pdb {
  string pdb_id;
  vector<Chain> chains;

public:
  Pdb(string id_) { pdb_id = id_; }
  vector<Chain> GetChains() { return chains; }
  void AddChain(Chain c) { chains.push_back(c); }
  string GetPdbId() { return pdb_id; }
};

main:
int main () {

  vector<Pdb> pdbs;
  pdbs.push_back(Pdb("1ubq"));
  cout << "\n\t1. " << pdbs[0].GetPdbId() << endl;
  pdbs[0].AddChain(Chain("A"));
  cout << "\n\t2. " << pdbs[0].GetChains()[0].GetChainId() << endl;
  pdbs[0].GetChains()[0].AddString("Whateva");
  cout << "\n\t3. Size of strings after AddString in main: " << pdbs[0].GetChains()[0].GetStrings().size() << endl;
  return 0;
}

This outputs:
1. 1ubq

2. A
Size of strings BEFORE push_back in AddString: 0
Size of strings AFTER push_back in AddString: 1

3. Size of strings after AddString in main: 0

As you can see the AddString function is adding an element to stings within the AddString function itself but when I GetStrings back in main, after executing AddString, strings is empty. I do not understand why this is happening. Any help would be much appreciated.

A: The problem is that you return a copy of the member, not the member itself:
vector<Chain> GetChains()

should be
vector<Chain>& GetChains()

for this to work.
I must note that you're heavily breaking the single responsibility principle. You're operating on members directly, which can't be a good idea. Consider replacing:
pdbs[0].GetChains()[0].AddString("Whateva");

with something like
pdbs[0].AddStringToChain(0,"Whateva");


text:
Q: Python Selemium- Cannot click on button Hope you´re fine,
Please! Hope you can support me with this topic.
I tried lot of ways to try to click this button by Selenium but I couldn´t. The error is that Selenium cannot locate the object.
ERROR MESSAAGE: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath", "selector":"//*[@id='C47_W166_V167_thtmlb_button_2']"}

Here The python code to make click:
window_before = driver.window_handles[0] #Save Current window
window_after = driver.window_handles[1] #Identify new raised window
driver.switch_to.window(window_after) #To go to new raised window

time.sleep(3)

driver.maximize_window()

driver.switch_to.frame("WorkAreaFrame1popup")
print(driver.title)
time.sleep(3)

ALL_BRANDS_BTN= driver.find_element_by_xpath("//*[@id='C51_W184_V185_thtmlb_button_2']")
ALL_BRANDS_BTN.click()

I made the same for other buttons on the same web tool without any issues, but for this particular button I can´t. Maybe I´m missing something?
I already put extra waiting time but neither worked.
Im attaching an image of the element inspection. Please, hope you can help me,
Thanks in advance

All Brands

All Brands

A: As you have mentioned you have used same kind of code for other buttons So I am assuming you are in correct window and iFrame. If not please insure your button is in correct windoe and frame.
Can you try below code to click your button:
btn = WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH, "//b[text()='All Brands']//ancestor::a"))) #Used Text instea of Id , as not sure if ID is dynamic or not
driver.execute_script("arguments[0].scrollIntoView();", btn ) #Scroll to button
driver.execute_script("arguments[0].click();", btn ) #Click then button


text:
Q: HttpRequest, HttpResponse and HttpConfusion I admit I got kinda confused with Http requests and responses, so I'll begin by presenting my problem.
I made a webpage that takes user input, processes it and uses XMLHttpRequest POST to send the processed data to another page and display said data into said page.
Now, I can form the XMLHttpRequest using POST just fine, as well as successful redirection; but what I want to actually do is have the second page display the POSTed data.
How can I let the second page read and display the data encapsulated in the POST request in a successful redirection from the first page?
Here is my XMLHttpRequest code, in javascript:
var xmlhttp= new XMLHttpRequest()

 xmlhttp.open('POST',"Default2.aspx",false);
  xmlhttp.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
 xmlhttp.setRequestHeader("Connection", "close");

xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            window.location = "Default2.aspx";
            }
}

  xmlhttp.send(""+x);

I want to handle the POSTed data in the second page in javascript or ASP.NET.

A: It sounds like you shouldn't be using AJAX / XMLHttpRequest at all. Just create a form that posts to the second page like normal, ie:
<form action="Default2.aspx">
  <!-- put the form elements here -->
  <input type="submit" value="Submit">
</form>

XMLHttpRequest is for getting server-side data from a different page/script and doing something with that data without leaving the current page. When you want to leave the current page you just use a form, as has been the standard for 15+ years.


text:
Q: ASP.NET How to use WebConfigurationManager to get section from Specific config file? I am trying to get sections from specific .config file such like "my.config".
WebConfigurationManager.OpenWebConfiguration can get the web.config in specific path.
Maybe WebConfigurationManager.OpenMappedWebConfiguration can reach my purpose.
Can anyone share experience?

A: I don't know about using the OpenMappedWebconfig thing, but this is a way to do it using a easy utility class:
http://aspalliance.com/705
If you want to have neater access to the config, then create a custom class that inherits from ConfigurationSection, then you can access the variables using syntax like MyConfig.configkey,  Here's an article that describes how to create the custom class and is good for some further info:
https://web.archive.org/web/20211020133931/https://www.4guysfromrolla.com/articles/032807-1.aspx
This article shows how to do internal custom config sections:
http://www.beansoftware.com/asp.net-tutorials/multiple-config.aspx
HTH,
Lance
EDIT: The aspalliance.com is down, so to tide you over, here are some other helpful links:
Here's a super-simple way to do it - http://www.codeproject.com/KB/files/custom_config_file_reader.aspx
Here's the verbose Microsoft way - http://msdn.microsoft.com/en-us/library/2tw134k3.aspx


text:
Q: JSF Resources - Remove query string recommendation page speed According to page speed my JSF resources would benefit from removing query strings:

Remove query strings from static resources
Enabling public caching in the HTTP headers for static resources
  allows the browser to download resources from a nearby proxy server,
  rather than from a remote origin server.

https://www.medexpress.co.uk/javax.faces.resource/style.css.xhtml?ln=css&v=1_2
It also reports:

Leverage browser caching
Setting an expiry date or a maximum age in the HTTP headers for static
  resources, instructs the browser to load previously downloaded
  resources from local disk, rather than over the network.

How can I make JSF resources conform to page speed suggestions?

A: Use the mod_pagespeed module with Apache.
This takes care of this issue.


text:
Q: Am I using the PHP.js strpbrk function properly? I have the following JS function:
function validatePass()
{
    var oldPass = document.getElementById("oldpass").value;
    var newPass1 = document.getElementById("newpass1").value;
    var newPass2 = document.getElementById("newpass2").value;
    if(strpbrk(newPass1,"abcdefghijklmnopqrstuvwxyz") != false)
    {
        document.getElementById("ContainsAtLeastOneLowercaseLetter").innerHTML = "Met";
    }
    else
    {
        document.getElementById("ContainsAtLeastOneLowercaseLetter").innerHTML = "Not Met";
    }
    if(strpbrk(newPass1,"ABCDEFGHIJKLMNOPQRSTUVWXYZ") != false)
    {
        document.getElementById("ContainsAtLeastOneUppercaseLetter").innerHTML = "Met";
    }
    else
    {
        document.getElementById("ContainsAtLeastOneUppercaseLetter").innerHTML = "Not Met";
    }
    if(strpbrk(newPass1,"1234567890") != false)
    {
        document.getElementById("ContainsAtLeastOneNumber").innerHTML = "Met";
    }
    else
    {
        document.getElementById("ContainsAtLeastOneNumber").innerHTML = "Not Met";
    }
}

That code makes a call to the PHP.js function strpbrk to determine if newPass1 contains acceptable data.  In PHP, strpbrk searches to see if the haystack contains any of the chars in the char_list.  However, in this JS implementation, it searches for all of the chars.  How can I make it behave the way I want to?
TIA.

A: I would suggest using regex instead of strpbrk.
function validatePass()
{
    var oldPass = document.getElementById("oldpass").value;
    var newPass1 = document.getElementById("newpass1").value;
    var newPass2 = document.getElementById("newpass2").value;
    if(/[a-z]/.test(newpass1))
    {
            document.getElementById("ContainsAtLeastOneLowercaseLetter").innerHTML = "Met";
    }
    else
    {
            document.getElementById("ContainsAtLeastOneLowercaseLetter").innerHTML = "Not Met";
    }
    if(/[A-Z]/.test(newpass1))
    {
            document.getElementById("ContainsAtLeastOneUppercaseLetter").innerHTML = "Met";
    }
    else
    {
            document.getElementById("ContainsAtLeastOneUppercaseLetter").innerHTML = "Not Met";
    }
    if(/[0-9]/.test(newpass1))
    {
            document.getElementById("ContainsAtLeastOneNumber").innerHTML = "Met";
    }
    else
    {
            document.getElementById("ContainsAtLeastOneNumber").innerHTML = "Not Met";
    }
}


text:
Q: get content random url dentro de arquivo txt Eu tenho vários arquivos txt dentro de uma pasta
/pasta/1.txt
/pasta/2.txt

Etc...
Dentro desses arquivos contém várias urls
Exemplo:
/pasta/1.txt

conteúdo:
www.site.com/nome/jose.html
www.site.com/nome/joao.html

/pasta/2.txt
conteúdo:
www.site.com/nome/maria.html
www.site.com/nome/juliana.html

Eu preciso de um código que ao acessar a url:
    www.site.com.br/sortear.php
ele acesse a pasta /pasta/ escolhe um dos arquivos (.txt) de forma random e capture uma URL (Ex: www.site.com/nome/jose.html) e acesse essa url.
Alguém consegue me ajudar?

A: Isso é bem simples de ser feito, existem N maneira de fazer isso.
Primeiro precisa obter os arquivos, a lista de arquivos que possui na pasta, neste caso supondo que tudo esteja dentro de /pasta/ e estão em .txt poderia usar o glob para obter o caminhos dos arquivos e depois selecionar um deles usando algum gerador.
$Arquivos = glob('pasta/*.txt');
$ArquivoEscolhido = $Arquivos[random_int(0, count($Arquivos) - 1)];

Pronto, usamos o random_int para selecionar um dos arquivos, o $ArquivosEscolhidos terá o caminho de um dos arquivos, que foi selecionado aleatoriamente.
Agora basta ler os arquivos, neste caso usando o file() e selecionar uma das linhas, poderia fazer:
$Linhas = file($ArquivoEscolhido);
$LinhaEscolhida = $Linhas[random_int(0, count($Linhas) - 1)];

Pronto, agora já selecionou uma linha e pode exibir usando echo $LinhaEscolhida, por exemplo ou se quiser redicionar use o header() veja isto.

O random_int está apenas disponível no PHP 7 e superior. Você também mas poderia usar Mersenne Twister, via mt_rand ou shuffle, ou usar um LFSR/LGC via rand, se usar PHP 7 ou inferior. Também pode usar o scandir com algumas alterações no código.


text:
Q: Why is this UPDATE statement updating every record? I have an UPDATE statement that's intended to update a status field for a limited number of records. Here's the statement:
UPDATE warehouse_box
SET warehouse_box_status_id = wbsv.warehouse_box_status_id
FROM
    warehouse_box_status_vw wbsv INNER JOIN
    pallet_warehouse_box pwb ON wbsv.warehouse_box_id = pwb.warehouse_box_id INNER JOIN
    routing_shipment_pallet rsp ON pwb.pallet_id = rsp.pallet_id
WHERE
    rsp.date_removed IS NULL
    AND pwb.date_unpalletized IS NULL
    AND rsp.routing_shipment_id = 100002

The intended result is for the 6 records that match the WHERE clause to have their statuses updated. What I'm seeing though is that all 200,000+ records are updated. It's as though the WHERE clause is being completely ignored.
Can anyone help shed some light on this for me?

A: You do not have the table warehouse_box included in the FROM clause.  If you add warehouse_box and join it to warehouse_box_status it should solve your problem.

A: You don't appear to be selecting on warehouse_box in the WHERE and INNER JOINs -- only from other tables...

A: What happens when you perform a SELECT with the same FROM and WHERE clauses?

*

*If you get all 200K rows, there are things you can do to track down the problem from there.

*If you get only the 6 records you want to update, it's time to start looking for triggers that might be updating the whole table.
EDIT: Looks like sharper eyes have already found the problem.


text:
Q: which dependency is overriding version of a transitive dependency (Maven) I'm using the below dependency:
<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-identity</artifactId>
  <version>1.4.3</version>
</dependency>

Which requires io.netty » netty-handler version 4.1.72.Final. However, the version is overridden to 4.1.42.Final.
The mvn dependency:tree -X command shows clearly that the version is changed:
[DEBUG]       com.azure:azure-core:jar:1.24.1:compile
[DEBUG]          io.projectreactor:reactor-core:jar:3.3.0.RELEASE:compile (scope managed from compile) (version managed from 3.4.13)
[DEBUG]             org.reactivestreams:reactive-streams:jar:1.0.3:compile (version managed from 1.0.3)
[DEBUG]          io.netty:netty-tcnative-boringssl-static:jar:2.0.26.Final:compile (version managed from 2.0.46.Final)
[DEBUG]       com.azure:azure-core-http-netty:jar:1.11.6:compile
[DEBUG]          io.netty:netty-handler:jar:4.1.42.Final:compile (version managed from 4.1.72.Final)
[DEBUG]             io.netty:netty-common:jar:4.1.42.Final:compile (version managed from 4.1.42.Final)
[DEBUG]             io.netty:netty-transport:jar:4.1.42.Final:compile (version managed from 4.1.42.Final)
[DEBUG]                io.netty:netty-resolver:jar:4.1.42.Final:compile (version managed from 4.1.42.Final)
[DEBUG]             io.netty:netty-codec:jar:4.1.42.Final:compile (version managed from 4.1.42.Final)
[DEBUG]          io.netty:netty-handler-proxy:jar:4.1.42.Final:compile (version managed from 4.1.72.Final)
[DEBUG]             io.netty:netty-codec-socks:jar:4.1.42.Final:compile (version managed from 4.1.42.Final)
[DEBUG]          io.netty:netty-buffer:jar:4.1.42.Final:compile (version managed from 4.1.72.Final)
[DEBUG]          io.netty:netty-codec-http:jar:4.1.42.Final:compile (version managed from 4.1.72.Final)
[DEBUG]          io.netty:netty-codec-http2:jar:4.1.42.Final:compile (version managed from 4.1.72.Final)
[DEBUG]          io.netty:netty-transport-native-unix-common:jar:4.1.42.Final:compile (version managed from 4.1.72.Final)
[DEBUG]          io.netty:netty-transport-native-epoll:jar:linux-x86_64:4.1.42.Final:compile (version managed from 4.1.72.Final)
[DEBUG]          io.netty:netty-transport-native-kqueue:jar:osx-x86_64:4.1.42.Final:compile (version managed from 4.1.72.Final)
[DEBUG]          io.projectreactor.netty:reactor-netty-http:jar:1.0.14:compile
[DEBUG]             io.netty:netty-resolver-dns:jar:4.1.42.Final:compile (version managed from 4.1.72.Final)
[DEBUG]                io.netty:netty-codec-dns:jar:4.1.42.Final:compile (version managed from 4.1.42.Final)
[DEBUG]             io.netty:netty-resolver-dns-native-macos:jar:osx-x86_64:4.1.72.Final:compile
[DEBUG]                io.netty:netty-resolver-dns-classes-macos:jar:4.1.72.Final:compile
[DEBUG]             io.projectreactor.netty:reactor-netty-core:jar:1.0.14:compile

But I could not find other dependencies that uses io.netty » netty-handler with version 4.1.42.Final in the log.
Is there any way to find which dependency actually using io.netty » netty-handler 4.1.42.Final and overriding version 4.1.72.Final?

A: The version comes from <dependencyManagement>, so probably from inside a BOM (an entry with <scope>import</scope>) that is in your POM or your parent POM.


text:
Q: Should we need to consider time dilation effect when travel in a very fast rocket? How long does it take for a rocket to reach a planet 10 light years away if the rocket's speed is just near the light speed?
If the speed is 1 c, the folks will answer it will take 10 year to travel to the planet.
Rocket Speed      Travel Time (without time dilation)
1c                10 years

That is correct for the clock on the earth.
But, due to the time dilation effect, the clock of the rocket will be much slower and the astronauts in the rocket will then take much less time to travel to the planet. Is it correct?
Rocket Speed      Lorentz Contraction       Travel Time
0.9c              0.436                     4.36 years
0.99c             0.141                     1.41 years
0.999c            0.045                     159 days (0.45 years)

The human life is about 100 years. So, does it means we can travel much more than 100 light-year distance if there is a near-light-speed rocket?


text:
Q: Senha com números juntos tem uns novos modelos de digitação de senhas com 5 botões e os números são juntos, alguém sabe com funciona ou se existe alguma biblioteca para isso;
Segue imagem para melhor entendimento.


text:
Q: Prove the following statement: If A is any set, then $A \subseteq A$ I'm doing some practice problems and I'm wondering if I got this right. I think this is a very short proof, but I'm not sure.
Given:
P: A is any set
Q: $A \subseteq A$
We have a $P \rightarrow Q$ statement.
Definition 3.1.2 states that we let A and B be sets. Then A is a subset of B, written $A \subseteq B$, when the statement $(\forall x)[x \in A \rightarrow \in B ]$ is true.
Since A is any set, then by Definition 3.1.2, $(\forall x)[x \in A \rightarrow \in A ]$.
Therefore,  $A \subseteq A$
I still remember the truth table for $P \rightarrow Q$. Both statements of $P$ and $Q$ had to be true for $P \rightarrow Q$ to be true.
So, if A is any subset, then $A \subseteq A$
If $P$ was false and $Q$ was false, the $P \rightarrow Q$ would be true.
If A isn't any subset, then A is not a subset of A.
If A is a subset, then  A is not a subset of A is the only false statement for $P \rightarrow Q$ because $P$ is true, but $Q$ is false.

A: Looks about right, but there's a ton of fluff and stuff and oh man all you need is this:

Definition: $A \subseteq B$ iff $\forall a\in A, a \in B$.
As $\forall a \in A, a \in A$, we have $A \subseteq A$.


text:
Q: Decide whether a non deterministic Büchi automata recognizes deterministic $\omega$ reg. language What it the easiest way to decide whether or not a given non deterministic Büchi automaton is equivalent to some deterministic Büchi automaton? In other words, how can we decide whether a Buchi automaton is "semantically deterministic"?
I am aware that I could solve the problem using the following procedures:

*

*Convert the Buchi automaton into a Muller determistic one (for example using Safra construction) and then checking whether the obtained DMA is closed under superloops.

*Use the condition given in the book Infinite Wors by D. Perrin and J.-E. Pin using $\omega$-semigroups. That is, $\forall f \in S$ such that $f<e$, $(s,f)$ and $(s,e)$ are a linked pair such that $se^{\omega} \in \phi(L)$, check whether or not $sf^{\omega}$ also belong to $\phi(L)$.

However I wonder if there exist others ways to achive the goal.
Thank you in advance.

A: Let $A$ be a finite alphabet. For a regular $\omega$-language $L$ the following are equivalent:
i) $L$ is recognizable by a finite Büchi automaton,
ii) $L = \{ \xi \in A^{\omega} : \xi \mbox{ has infinitely many prefixes in } W \}$ for some regular language $W$,
iii) $L$ is a countable intersection of open sets (i.e. a $G_{\delta}$-set) in the product topology on $A^{\omega}$.
The proofs of these facts could be found in the book you mentioned. Also in the book the following equivalences are proven:
1) $L \subseteq A^{\omega}$ is closed and recognizable,
2) if $L$ is recognized by a finite Büchi automaton, then it is also recognized by the same Büchi automaton, but with the set of non-trap states as final states, where a state is a non-trap state if some final state is reachable.
Using this at least for the closed sets, which in $A^{\omega}$ are also $G_{\delta}$-sets, your problem could be solved for this subclass of deterministically acceptable Büchi languages. Given your (possibly) non-deterministic Büchi automaton, switch the final states as written in condition 2) above, and if both accept the same language then your language is closed, hence deterministically acceptable. Checking if two Büchi-automata accept the same language is simple, just check that the labeling of every accepting loop is also the labeling of some accepting loop in the other automaton (i.e. using that two regular $\omega$-languages are the same if their set of ultimately periodic words coincide).
I do not know any algorithm that starts directly from the non-deterministic Büchi automaton in general without using Muller automata or $\omega$-semigroups. But I try to give you some directions where to look. As written above your question has some topological flavor, and one of the first papers which asked for algorithms computing the topological complexity (i.e. the Borel class) is L.H. Landweber: Decision problems for $\omega$-automata, but here in his algorithms he also starts from a Muller automata. A further refinement of the Borel hierarchy is the so called Wadge-Wagner-hierarchy of regular languages. Here the regular $\omega$-languages are classified up to continuous reducibility (i.e. continuous inverse images) and this refines the Borel hierachy. Hence algorithms for computing the Wagner class solve also your problem. For a given Muller automaton or $\omega$-semigroups the Wagner-class of a given regular $\omega$-language is easy to compute. You can find a description also in the mentioned book. I find the original article on the Wagner hierarchy quite difficult to read (see also my post here), another reference for computing the Wagner classes is:
Computing the Wadge degree, the Lifschitz degree, and the Rabin index of a regular language of infinite words in polynomial time
Thomas Wilke, Haiseung Yoo, TAPSOFT '95, see here.
Hope this helps!