text:
Q: event Action<> vs event EventHandler<> Is there any different between declaring event Action<> and event EventHandler<>.
Assuming it doesn't matter what object actually raised an event.
for example:
public event Action<bool, int, Blah> DiagnosticsEvent;

vs
public event EventHandler<DiagnosticsArgs> DiagnosticsEvent;

class DiagnosticsArgs : EventArgs
{
    public DiagnosticsArgs(bool b, int i, Blah bl)
    {...}
    ...
}

usage would be almost the same in both cases:
obj.DiagnosticsEvent += HandleDiagnosticsEvent;

There are several things that I don't like about event EventHandler<> pattern:

*

*Extra type declaration derived from
EventArgs

*Compulsory passing of object source –
often no one cares

More code means more code to maintain without any clear advantage.
As a result, I prefer event Action<>
However, only if there are too many type arguments in Action<>, then an extra class would be required.

A: The main difference will be that if you use Action<> your event will not follow the design pattern of virtually any other event in the system, which I would consider a drawback.
One upside with the dominating design pattern (apart from the power of sameness) is that you can extend the EventArgs object with new properties without altering the signature of the event. This would still be possible if you used Action<SomeClassWithProperties>, but I don't really see the point with not using the regular approach in that case.

A: If you follow the standard event pattern, then you can add an extension method to make the checking of event firing safer/easier. (i.e. the following code adds an extension method called SafeFire() which does the null check, as well as (obviously) copying the event into a separate variable to be safe from the usual null race-condition that can affect events.)
(Although I am in kind of two minds whether you should be using extension methods on null objects...)
public static class EventFirer
{
    public static void SafeFire<TEventArgs>(this EventHandler<TEventArgs> theEvent, object obj, TEventArgs theEventArgs)
        where TEventArgs : EventArgs
    {
        if (theEvent != null)
            theEvent(obj, theEventArgs);
    }
}

class MyEventArgs : EventArgs
{
    // Blah, blah, blah...
}

class UseSafeEventFirer
{
    event EventHandler<MyEventArgs> MyEvent;

    void DemoSafeFire()
    {
        MyEvent.SafeFire(this, new MyEventArgs());
    }

    static void Main(string[] args)
    {
        var x = new UseSafeEventFirer();

        Console.WriteLine("Null:");
        x.DemoSafeFire();

        Console.WriteLine();

        x.MyEvent += delegate { Console.WriteLine("Hello, World!"); };
        Console.WriteLine("Not null:");
        x.DemoSafeFire();
    }
}

A: Looking at Standard .NET event patterns we find

The standard signature for a .NET event delegate is:
void OnEventRaised(object sender, EventArgs args);
[...]
The argument list contains two arguments: the sender, and the event arguments. The compile time type of sender is System.Object, even though you likely know a more derived type that would always be correct. By convention, use object.

Below on same page we find an example of the typical event definition which is something like
public event EventHandler<EventArgs> EventName;

Had we defined
class MyClass
{
  public event Action<MyClass, EventArgs> EventName;
}

the handler could have been
void OnEventRaised(MyClass sender, EventArgs args);

where sender has the correct (more derived) type.

A: The advantage of a wordier approach comes when your code is inside a 300,000 line project.
Using the action, as you have, there is no way to tell me what bool, int, and Blah are. If your action passed an object that defined the parameters then ok.
Using an EventHandler that wanted an EventArgs and if you would complete your DiagnosticsArgs example with getters for the properties that commented their purpose then you application would be more understandable.  Also, please comment or fully name the arguments in the DiagnosticsArgs constructor.

A: I realize that this question is over 10 years old, but it appears to me that not only has the most obvious answer not been addressed, but that maybe its not really clear from the question a good understanding of what goes on under the covers. In addition, there are other questions about late binding and what that means with regards to delegates and lambdas (more on that later).
First to address the 800 lb elephant/gorilla in the room, when to choose event vs Action<T>/Func<T>:

*

*Use a lambda to execute one statement or method. Use event when you
want more of a pub/sub model with multiple
statements/lambdas/functions that will execute (this is a major
difference right off the bat).

*Use a lambda when you want to compile statements/functions to expression trees. Use delegates/events when you want to participate in more traditional late binding such as used in reflection and COM interop.

As an example of an event, lets wire up a simple and 'standard' set of events using a small console application as follows:
public delegate void FireEvent(int num);

public delegate void FireNiceEvent(object sender, SomeStandardArgs args);

public class SomeStandardArgs : EventArgs
{
    public SomeStandardArgs(string id)
    {
        ID = id;
    }

    public string ID { get; set; }
}

class Program
{
    public static event FireEvent OnFireEvent;

    public static event FireNiceEvent OnFireNiceEvent;

    static void Main(string[] args)
    {
        OnFireEvent += SomeSimpleEvent1;
        OnFireEvent += SomeSimpleEvent2;

        OnFireNiceEvent += SomeStandardEvent1;
        OnFireNiceEvent += SomeStandardEvent2;

        Console.WriteLine("Firing events.....");
        OnFireEvent?.Invoke(3);
        OnFireNiceEvent?.Invoke(null, new SomeStandardArgs("Fred"));

        //Console.WriteLine($"{HeightSensorTypes.Keyence_IL030}:{(int)HeightSensorTypes.Keyence_IL030}");
        Console.ReadLine();
    }

    private static void SomeSimpleEvent1(int num)
    {
        Console.WriteLine($"{nameof(SomeSimpleEvent1)}:{num}");
    }
    private static void SomeSimpleEvent2(int num)
    {
        Console.WriteLine($"{nameof(SomeSimpleEvent2)}:{num}");
    }

    private static void SomeStandardEvent1(object sender, SomeStandardArgs args)
    {

        Console.WriteLine($"{nameof(SomeStandardEvent1)}:{args.ID}");
    }
    private static void SomeStandardEvent2(object sender, SomeStandardArgs args)
    {
        Console.WriteLine($"{nameof(SomeStandardEvent2)}:{args.ID}");
    }
}

The output will look as follows:

If you did the same with Action<int> or Action<object, SomeStandardArgs>, you would only see SomeSimpleEvent2 and SomeStandardEvent2.
So whats going on inside of event?
If we expand out FireNiceEvent, the compiler is actually generating the following (I have omitted some details with respect to thread synchronization that isn't relevant to this discussion):
   private EventHandler<SomeStandardArgs> _OnFireNiceEvent;

    public void add_OnFireNiceEvent(EventHandler<SomeStandardArgs> handler)
    {
        Delegate.Combine(_OnFireNiceEvent, handler);
    }

    public void remove_OnFireNiceEvent(EventHandler<SomeStandardArgs> handler)
    {
        Delegate.Remove(_OnFireNiceEvent, handler);
    }

    public event EventHandler<SomeStandardArgs> OnFireNiceEvent
    {
        add
        {
            add_OnFireNiceEvent(value)
        }
        remove
        {
            remove_OnFireNiceEvent(value)

        }
    }

The compiler generates a private delegate variable which is not visible to the class namespace in which it is generated. That delegate is what is used for subscription management and late binding participation, and the public facing interface is the familiar += and -= operators we have all come to know and love : )
You can customize the code for the add/remove handlers by changing the scope of the FireNiceEvent delegate to protected. This now allows developers to add custom hooks to the hooks, such as logging or security hooks. This really makes for some very powerful features that now allows for customized accessibility to subscription based on user roles, etc. Can you do that with lambdas? (Actually you can by custom compiling expression trees, but that's beyond the scope of this response).
To address a couple of points from some of the responses here:

*

*There really is no difference in the 'brittleness' between changing
the args list in Action<T> and changing the properties in a class
derived from EventArgs. Either will not only require a compile
change, they will both change a public interface and will require
versioning. No difference.

*With respect to which is an industry standard, that depends on where
this is being used and why. Action<T> and such is often used in IoC
and DI, and event is often used in message routing such as GUI and
MQ type frameworks. Note that I said often, not always.

*Delegates have different lifetimes than lambdas. One also has to be
aware of capture... not just with closure, but also with the notion
of 'look what the cat dragged in'. This does affect memory
footprint/lifetime as well as management a.k.a. leaks.
One more thing, something I referenced earlier... the notion of late binding. You will often see this when using framework like LINQ, regarding when a lambda becomes 'live'. That is very different than late binding of a delegate, which can happen more than once (i.e. the lambda is always there, but binding occurs on demand as often as is needed), as opposed to a lambda, which once it occurs, its done -- the magic is gone, and the method(s)/property(ies) will always bind. Something to keep in mind.

A: On the most part, I'd say follow the pattern. I have deviated from it, but very rarely, and for specific reasons. In the case in point, the biggest issue I'd have is that I'd probably still use an Action<SomeObjectType>, allowing me to add extra properties later, and to use the occasional 2-way property (think Handled, or other feedback-events where the subscriber needs to to set a property on the event object). And once you've started down that line, you might as well use EventHandler<T> for some T.

A: Based on some of the previous answers, I'm going to break my answer down into three areas.
First, physical limitations of using Action<T1, T2, T2... > vs using a derived class of EventArgs. There are three: First, if you change the number or types of parameters, every method that subscribes to will have to be changed to conform to the new pattern. If this is a public facing event that 3rd party assemblies will be using, and there is any possiblity that the event args would change, this would be a reason to use a custom class derived from event args for consistencies sake (remember, you COULD still use an Action<MyCustomClass>) Second, using Action<T1, T2, T2... > will prevent you from passing feedback BACK to the calling method unless you have a some kind of object (with a Handled property for instance) that is passed along with the Action. Third, you don't get named parameters, so if you're passing 3 bool's an int, two string's, and a DateTime, you have no idea what the meaning of those values are. As a side note, you can still have a "Fire this event safely method while still using Action<T1, T2, T2... >".
Secondly, consistency implications. If you have a large system you're already working with, it's nearly always better to follow the way the rest of the system is designed unless you have an very good reason not too. If you have publicly facing events that need to be maintained, the ability to substitute derived classes can be important. Keep that in mind.
Thirdly, real life practice, I personally find that I tend to create a lot of one off events for things like property changes that I need to interact with (Particularly when doing MVVM with view models that interact with each other) or where the event has a single parameter. Most of the time these events take on the form of public event Action<[classtype], bool> [PropertyName]Changed; or public event Action SomethingHappened;. In these cases, there are two benefits. First, I get a type for the issuing class. If MyClass declares and is the only class firing the event, I get an explicit instance of MyClass to work with in the event handler. Secondly, for simple events such as property change events, the meaning of the parameters is obvious and stated in the name of the event handler and I don't have to create a myriad of classes for these kinds of events.


text:
Q: Convert IBM Cognos SQL which contains a filter to Microsoft SQL Server Query I'm trying to convert IBM Cognos SQL which contains a filter to Microsoft SQL Server Query.
I tried to apply the filter in the Microsoft SQL Server Query, but it didn't work.
Here the IBM Cognos Query:
IBM Cognos SQL
select
       rank() over ( at client__iacode.ia_code order by XCOUNT(client_document.client_document_id  for client__iacode.ia_code ) desc nulls last)  as  Rank_IA,
       client__iacode.ia_code  as  IA_Code,
       client__iacode.ia_short_descr  as  IA_Short_Descr,
       XCOUNT(client_document.client_document_id  for client__iacode.ia_code,client__iacode.ia_short_descr )  as  Doc_Count,
       XCOUNT(client.client_code  at client__iacode.ia_code,client__iacode.ia_short_descr,client.client_id  for client__iacode.ia_code,client__iacode.ia_short_descr )  as  Client_Count,
       XSUM(XCOUNT(client_document.client_document_id  for client__iacode.ia_code,client__iacode.ia_short_descr )  at client__iacode.ia_code,client__iacode.ia_short_descr )  as  Total_Doc_Count_,
       XSUM(XCOUNT(client.client_code  at client__iacode.ia_code,client__iacode.ia_short_descr,client.client_id  for client__iacode.ia_code,client__iacode.ia_short_descr )  at client__iacode.ia_code,client__iacode.ia_short_descr )  as  Total_Client_Count_
from
       (
           dbo.client client
           join
           dbo.broker client__broker
           on (client.broker_id = client__broker.broker_id)
           join
           dbo.ia_code client__iacode
           on (client.ia_code_id = client__iacode.ia_code_id)
           join
           dbo.client_document client_document
           on (client.client_id = client_document.client_id)
           join
           dbo.client_status client_status
           on (client.client_status_id = client_status.client_status_id)
           join
           dbo.provider client__provider
           on (client__provider.provider_id = client.provider_id)
       )
       left outer join
       dbo.branch client__iacode__branch
       on (client__iacode.branch_id = client__iacode__branch.branch_id)
where
       (client_document.requested_date is not NULL) and
       (client_document.received_date is NULL) and
       (client__iacode__branch.branch_descr = CAST(:PQ1 AS varchar(255))) and
       (client__broker.broker_code = 'CCC') and
       (client_status.client_status_code = 'A') and
       ((client__provider.provider_code <> 'PRS-R') or (client__provider.provider_code is NULL))
group by
       client__iacode.ia_code,
       client__iacode.ia_short_descr
filter
       (rank() over ( at client__iacode.ia_code order by XCOUNT(client.client_code  at client__iacode.ia_code,client.client_id  for client__iacode.ia_code ) desc nulls last) <= 25) and
       (RCOUNT(rank() over ( at client__iacode.ia_code order by XCOUNT(client_document.client_document_id  for client__iacode.ia_code ) desc nulls last)  at client__iacode.ia_code  order by rank() over ( at client__iacode.ia_code order by XCOUNT(client_document.client_document_id  for client__iacode.ia_code ) desc nulls last) asc,client__iacode.ia_code asc,client__iacode.ia_short_descr asc ) <= 25)
order by
       Rank_IA asc,
       IA_Code asc,
       IA_Short_Descr asc

Here the Native SQL Query from the IBM Cognos report studio:
select "client__iacode"."ia_code" AS "C0", "client_documen

    t"."client_document_id" AS "C1", "client__iacode"."ia_short_descr" AS "C2", "client"."client_id" AS "C3", "client"."client_code" AS "C4"

    from ((((("dbo"."client" "client" INNER JOIN "dbo"."broker" "client__broker" on "client"."broker_id" = "client__broker"."broker_id") INNER JOIN "dbo"."ia_code" "client__iacode" on "client"."ia_code_id" = "client__iacode"."ia_code_id") INNER JOIN "dbo"."client_document" "client_document" on "client"."client_id" = "client_document"."client_id") INNER JOIN "dbo"."client_status" "client_status" on "client"."client_status_id" = "client_status"."client_status_id") INNER JOIN "dbo"."provider" "client__provider" on "client__provider"."provider_id" = "client"."provider_id") LEFT OUTER JOIN "dbo"."branch" "client__iacode__branch" on "client__iacode"."branch_id" = "client__iacode__branch"."branch_id"

    where  NOT "client_document"."requested_date" is null and "client_document"."received_date" is null and "client__iacode__branch"."branch_descr" = CAST( @BRANCH AS VARCHAR( 255 ) ) and "client__broker"."broker_code" = 'CCC' and "client_status"."client_status_code" = 'A' and ("client__provider"."provider_code" <> 'PRS-R' or "client__provider"."provider_code" is null)

Here the Microsoft SQL Server Query that I have created so far but it didn't shows me the expected result:
select L1.*
from
(
select        L.Rank_IA,
              L.IA_Code,
              L.IA_Short_Descr,
              L.Doc_Count,
              L.Client_Count,
              L.[Rank],
              (count   (L.Condition) over( order by L.Condition asc, L.IA_Code asc, IA_Short_Descr asc )) as Condition
              from
              (
select
       rank() over (  order by COUNT(client_document.client_document_id    ) desc  )  as  Rank_IA,
       client__iacode.ia_code  as  IA_Code,
       client__iacode.ia_short_descr  as  IA_Short_Descr,
       COUNT( client_document.client_document_id   )  as  Doc_Count,
       COUNT(client.client_code   )  as  Client_Count,
      (rank() over (  order by COUNT( client.client_id   ) desc ) )  as [Rank],
      rank() over (  order by COUNT(  client_document.client_document_id   ) desc ) as Condition
      --XSUM(XCOUNT(client_document.client_document_id  for client__iacode.ia_code,client__iacode.ia_short_descr )  at client__iacode.ia_code,client__iacode.ia_short_descr )  as  Total_Doc_Count_,
      --XSUM(XCOUNT(client.client_code  at client__iacode.ia_code,client__iacode.ia_short_descr,client.client_id  for client__iacode.ia_code,client__iacode.ia_short_descr )  at client__iacode.ia_code,client__iacode.ia_short_descr )  as  Total_Client_Count_
from
       (
           dbo.client client
           join
           dbo.broker client__broker
           on (client.broker_id = client__broker.broker_id)
           join
           dbo.ia_code client__iacode
           on (client.ia_code_id = client__iacode.ia_code_id)
           join
           dbo.client_document client_document
           on (client.client_id = client_document.client_id)
           join
           dbo.client_status client_status
           on (client.client_status_id = client_status.client_status_id)
           join
           dbo.provider client__provider
           on (client__provider.provider_id = client.provider_id)
       )
       left outer join
       dbo.branch client__iacode__branch
       on (client__iacode.branch_id = client__iacode__branch.branch_id)
where
       (client_document.requested_date is not NULL) and
       (client_document.received_date is NULL) and
       (client__iacode__branch.branch_descr = CAST(@BRANCH AS varchar(255))) and
       (client__broker.broker_code = 'CCC') and
       (client_status.client_status_code = 'A') and
       ((client__provider.provider_code <> 'PRS-R') or (client__provider.provider_code is NULL))
group by
       client__iacode.ia_code,
       client__iacode.ia_short_descr)L)L1
--filter
--      (rank() over ( at client__iacode.ia_code order by XCOUNT(client.client_code  at client__iacode.ia_code,client.client_id  for client__iacode.ia_code ) desc nulls last) <= 25) and
--      (RCOUNT(rank() over ( at client__iacode.ia_code order by XCOUNT(client_document.client_document_id  for client__iacode.ia_code ) desc nulls last)  at client__iacode.ia_code  order by rank() over ( at client__iacode.ia_code order by XCOUNT(client_document.client_document_id  for client__iacode.ia_code ) desc nulls last) asc,client__iacode.ia_code asc,client__iacode.ia_short_descr asc ) <= 25)
where L1.[Rank] <=25
and L1.Condition<=25
order by
       Rank_IA asc,
       IA_Code asc,
       IA_Short_Descr asc

Can you please help me to apply that filter in the Microsft SQL Server code.
Thanks in advance for the help.

A: When generating the SQL on a Cognos query it will display both the Cognos SQL and the Native SQL.  The Cognos SQL is what is required for the report and the Native SQL is what is being sent down to the database.  If there is no local processing and the two SQL types are identical within reason,  you should be able to use the SQL from the Native SQL dialog box without any edits.

A: Cognos BI uses "dynamic query mode" by default (starting with 10.2.1). It's basically Cognos' query engine. The engine plans an execution which may include processing data locally after it is received from the data source. You may read all about it in IBM's free redbook here
http://www.redbooks.ibm.com/redbooks/pdfs/sg248121.pdf
Here is a quick overview of the engine
So, that means the native query is not the whole picture. Cognos may do more processing after receiving the data from MS SQL. That being said, if you would like to replicate the same query in MS SQL, you will need to complete the missing logic yourself. If the multi-dimensional model in Cognos is mapped to MS SQL relational database on 1:1, then that should be easy (convert missing parts from Cognos SQL to MS SQL yourself). Lots of the time, it is not that straight forward b/c the model inside Cognos may not be 1:1 mapping to MS SQL tables/columns. In that case, you will need to understand the model inside Cognos when converting Cognos query to MS SQL query b/c that's part of what happens between native query and Cognos query.
I can't be of any help on your model part but for the rest, you can first try changing the query's (or data source's) "Rollup Processing" property to "Database". That should help converting extended aggregate functions (XCOUNT etc) to native SQL. Also check out "Use SQL parameters" property and set it to "Literal" and see if that will helps with the parameters in native SQL.
Screenshot of the properties window
The rank() functions syntax is pretty much the same syntax in MS SQL so you should be able to handle that easily once you took care of extended functions. But I would look at the new native query first.
RCount (running count) can also be easily handled in MS SQL using windowing functions (see link below). But again, first generate the new native query and see if RCount is gone or not.
https://learn.microsoft.com/en-us/sql/t-sql/queries/select-over-clause-transact-sql?view=sql-server-ver15

A: Here where the filters have been created.
The filters is not showed in the Native SQL Query.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prove/Disprove: $A - \lfloor A/B \rfloor - \lceil A/B \rceil \leq \lfloor A/B \rfloor \times (B+1)$ for $A \geq B$ For $A \geq B$, both are strictly positive integers, is the following true?
$$A - \lfloor A/B \rfloor - \lceil A/B \rceil \leq \lfloor A/B \rfloor \times (B+1)$$
I tried the technique used in proving a very similar question:
Prove/Disprove: $A - \lfloor A/B \rfloor - \lceil A/B \rceil \leq (\lfloor A/B \rfloor + 1) \times B$ for $A \geq B$
But it seems like it didn't work in proving this. I also tried empirically generating random A and B's, but also can't find a counterexample.

A: $\newcommand{f}[1]{\left\lfloor #1 \right\rfloor}$
Let $B = 100$ and $A = 199$. Then:
\begin{align*}
LHS &= 199 - 1 - 2 = 196 \\
RHS &= 1(100 + 1) = 101
\end{align*}
So the inequality is false.

EDIT: In response to OP's comment, suppose we restrict further that $\f{A/B} \geq N$ for some $N \in \Bbb{Z}^+$. Let $B = 3N + 3$, and let $A = (N + 1)(3N + 3) - 1$. Clearly $A \geq B$ and $\f{A/B} = N$.
\begin{align*}
LHS &= (N + 1)(3N + 3) - 1 - N - (N + 1) \\
&= (N + 1)(3N + 1) \\
\end{align*}
\begin{align*}
RHS &= N(3N + 4) \\
&= N(3N + 1) + 3N \\
&= (N + 1)(3N + 1) - (3N + 1) + 3N \\
&= (N + 1)(3N + 1) - 1 < LHS
\end{align*}
So the inequality will still fail.


text:
Q: how to add two row value and make one row in my sql given table:
   id price1 price2 type
    1  25      24     A
    2  42      44     B
    3  59      54     C
    4  85      58     D

desire
id price1 price2 type
1   67      68     A
3   59      54     C
4   85      58     D

please suggest me how to implement this because i have tried using Sum function but its not make sense  i am not able to fix it issue please help
basically i have to add two row value and make type A .

A: I don't see any visible logic here, is it just to make type A + B as type A and sum them?
If so use CASE EXPRESSION:
SELECT min(t.id),SUM(t.price1),sum(t.price2),
       CASE WHEN t.type = 'B' THEN 'A' ELSE t.type END as type
FROM YourTable t
GROUP BY CASE WHEN t.type = 'B' THEN 'A' ELSE t.type END

A: Can you try this?
SELECT t1.id,(t1.price1+t2.price1) AS price1,
(t1.price2+t2.price2) AS price2,t1.type
FROM table t1,table t2 WHERE t1.id%2=1 AND t2.id=t1.id+1;

A: This is just a sample result:
select id, sum(price1),SUM(price2),type from
(select id,price1,price2,type from tbl_price ORDER BY id limit 2) as a

union all

select id,price1, price2,type FROM tbl_price where id >2


text:
Q: three.js mesh with many textures I'm currently trying to create a three.js mesh which has a large number of faces (in the thousands) and is using textures. However, my problem is that each face can have its texture changed at runtime, so potentially it's possible that every face has a different texture.
I tried preloading a materials array (for MeshFaceMaterial) with default textures and assigning each face a different materialIndex, but that generated much lag.
A bit of research led to here, which says

If number is large (e.g. each face could be potentially different), consider different solution, using attributes / textures to drive different per-face look.

I'm a bit confused about how shaders work, and in particular I'm not even sure how you would use textures with attributes. I couldn't find any examples of this online, as most texture-shader related examples I found used uniforms instead.
So my question is this: Is there an efficient way for creating a mesh with a large number of textures, changeable at runtime? If not, are there any examples for the aforementioned attributes/textures idea?

A: Indeed, this can be a tricky thing to implement. Now I can't speak much to GLSL (I'm learning) but what I do know is Uniforms are constants and would not change between calls, so you would likely want an attribute for your case, but I welcome being wrong here. However, I do have a far simpler suggestion.
You could use 1 texture that you can "subdivide" into all the tiny textures you need for each face. Then at runtime you can pull out the UV coordinates from the texture and apply it to the faces individually. You'll still deal with computation time, but for a thousand or so faces it should be doable. I tested with a 25k face model and it was quick changing all faces per tick.
Now the trick is navigating the faceVertexUvs 3 dimensional array. But for example a textured cube with 12 faces you could say reset all faces to equal one side like so:
for (var uvCnt = 0; uvCnt < mesh.geometry.faceVertexUvs[0].length; uvCnt+=2 ) {
    mesh.geometry.faceVertexUvs[0][uvCnt][0] = mesh.geometry.faceVertexUvs[0][2][0];
    mesh.geometry.faceVertexUvs[0][uvCnt][1] = mesh.geometry.faceVertexUvs[0][2][1];
    mesh.geometry.faceVertexUvs[0][uvCnt][2] = mesh.geometry.faceVertexUvs[0][2][2];

    mesh.geometry.faceVertexUvs[0][uvCnt+1][0] = mesh.geometry.faceVertexUvs[0][3][0];
    mesh.geometry.faceVertexUvs[0][uvCnt+1][1] = mesh.geometry.faceVertexUvs[0][3][1];
    mesh.geometry.faceVertexUvs[0][uvCnt+1][2] = mesh.geometry.faceVertexUvs[0][3][2];
}

Here I have a cube that has 6 colors (1 per side) and I loop through each faceVertexUv (stepping by 2 as two triangle make a plane) and reset all the Uvs to my second side which is blue. Of course you'll want to map the coordinates into an object of sorts so you can easily query the object to return and reset the cooresponding Uv's but I don't know your use case. For completness, you'll want to run mesh.geometry.uvsNeedUpdate = true; at runtime to see the updates. I hope that helps.


text:
Q: Web Application - Dynamic Image Rendering I am an absolute noob when it comes to Web Application. I am building a network visualization toolkit based on Google App Engine. I have implemented the Spanning Tree Protocol as a sample. This is what it does:

*

*Take the network topology from the client as input

*Generate a network graph based on 1, and render that image to the client

*Generate the spanning tree using the MST protocol

*Render the image of the spanning tree to the user

You can go to http://www.varun-c.appspot.com to see a demo. I have been instructed by my professor to stay away from javascript. If you notice, the application runs properly.
Here is the problem:

*

*The MST protocol is a step by step algorithm. What my application currently does it runs the entire algorithm in the backend and renders the final result.

*What my prof. wants me to do is to add a button 'Step by Step'. When the user clicks on that button, the entire MST protocol is run one step at a time so the user can visualize the actual simulation of how MST works.

I have absolutely no clue of how to do that. AS I said, web development is not really my forte. If my explanation of the problem isn't clear enough, kindly let me know. I shall try my best to explain it properly. And do visit the website once. It will give you an idea of what the application does.
EDIT 1: I got it working. For those who are wondering, I create a hidden variable 'iterator'  which I keep on exchanging between HTML and Python backend to keep track of the step number at every click of the 'Step by Step' button. At the server side, I create a simple data structure to store all the instances generated by my algorithm. Combining this with the iterator, the image is rendered. The link posted above now reflects those changes.

A: Generate a series of images for every step. Then create a GUI that facilitates changing the image displayed by clicking previous/next button. It is possible to do this without any javascript, just using HTML+CSS.

A: I don't understand the topic fully since this is definitely not my field of expertise. So I try to rephrase the problem like this:
You have to show sequential pictures to the user that are generated by your algorithm. For me this is a perfect example of a task which should be done on the client side, using Javascript and the canvas element. There are a lot of libraries for this. But since your professor precluded this way you could generate the pictures for the single steps on the server.
Not sure if these thoughts are of any help.


text:
Q: Why are event.target.checked and MouseEvent target.checked not the same for a radio input? I'm having an issue with radio inputs and controlling them through JavaScript.
The problem I have is with evaluating whether an input is checked when the click event fires.

const radio = document.querySelector('input[type="radio"]');

radio.addEventListener('click', (e) => {
  console.log(e.target.checked);
  console.log(e)
  if(e.target.checked){
    e.target.checked = false;
  }
});
Click me to trigger event<input type="radio" id="radio" name="radio">
Click me to switch back<input type="radio" id="radio2" name="radio">

This shows how if you trigger the event, there is a mismatch between the e.target.checked value and if you inspect the MouseEvent object in the browser console (navigate to the target and the checked property). When you compare the two, the former always appear to be true (even when visually you can see the input is not checked) and the latter is false.
Why are the two properties not the same? Any help will be appreciated.


text:
Q: Enforcing contracts for struct fields with auto values, measuring time complexity I'm a newbie trying to make basic sense of structures and contracts by making a structure to use as a tool to count procedure calls (in my class we're just getting into time complexity) Basically, I'm wondering if you can enforce contracts on structure fields with auto-values.
Here is the code I'm working with:
#lang racket
(struct counter (name [count #:mutable #:auto])
  #:auto-value 0
  #:property prop:procedure
  (lambda(c-id)
    (set-counter-count! c-id (add1 (counter-count c-id)))))

(define (counter-print! counter)
  (printf "~a: ~a\n" (counter-name counter) (counter-count counter)))

(define (counter-reset! counter)
  (set-counter-count! counter 0))

(provide (contract-out (struct counter ([name string?]
                                        [count integer?])))
         counter-print! counter-reset!)

I'd use the structure by defining counters out in front of a procedure of interest, inserting calls to the counter where I want to count internal procedure calls, and then repeatedly running the procedure with varying input sizes and printing/reseting the counters (You can let me know if this is a boneheaded way to gather data about complexity too).
Now I know my code doesn't work because the contract seems to enforce that counter takes 2 parameters, but the structure definition has it that counter takes 1. A simple fix would be to remove the auto keywords, but I'm wondering if there is a way to have count automatically set to 0 yet still enforce, in order to make the data-type more secure, that set-counter-count! fails when called on a non-integer value. Any suggestions?

A: I never seem to use #:auto because it never seems to work quite the way I hope.
In this case I think I'd simply provide contracts for the individual struct constructor and accessor functions:
(provide (contract-out [counter (-> string? counter?)]
                       [counter-count (-> counter? integer?)]
                       [counter-name (-> counter? string?)])
         counter-print! counter-reset!)

And use like so:
#lang racket

(require "counter.rkt")

(define c (counter "a"))
(counter-name c)  ;=> "a"
(counter-count c) ;=> 0
(c) ;increment
(counter-count c) ;=> 1

Having said all that, for what you're describing I think I'd probably just use a mutable hash-table. Also, I'd probably make the hash-table keys be procedure? not string?. For instance:
(define ht (make-hash)) ;(hash/c procedure? integer?)

(define (increment-counter proc)
  (hash-update! ht
                proc
                (λ (v) (add1 v))
                0))

(define (get-counter proc)
  (hash-ref ht proc #f))

(increment-counter display)
(get-counter display) ;=> 1
(increment-counter display)
(get-counter display) ;=> 2

(increment-counter displayln)
(get-counter displayln) ;=> 1

ht ;=> '#hash((#<procedure:displayln> . 1) (#<procedure:display> . 2))


text:
Q: Can I start a program from the terminal and make it launch visually in the background? If I open a program, like Firefox, from the terminal then that program will get the focus of the GUI. Can I somehow open it so that it will run in the visual background and not pop up, blocking any current program I am working with?
My problem is that I use karma test runner which is run every time I edit my code. Whenever that is done karma launches a browser which pops up in front of everything else on the screen which can be quite annoying.
I am using Ubuntu 13.04.

A: To do this, you will need xdotool. To install it, run the following command in terminal:
sudo apt-get install xdotool

Now, I will explain how you can do it for Firefox using a script:

*

*In a terminal run:
mkdir -p bin

This command will make a bin directory in your home folder if you don't already have it.

*After run:
gedit ~/bin/firefox.sh

This will create the new file change_sources.sh in gedit.

*Copy and paste the following script in the new created file:

#!/bin/bash

delay=2
windowId=$(xdotool getwindowfocus)

firefox &
sleep $delay

xdotool windowactivate $windowId

*

*Save the file and close it.

*Go back into terminal and run:
chmod +x ~/bin/firefox.sh

to grant execute access for the script.

*Run the script with:
firefox.sh

In the same manner you can open any other application from terminal in the background.


text:
Q: Inorder tree walk not working I am trying to practice BST tree implementation with python, following is my code,
import pdb

class Node():
    def __init__(self, parent=None, key=None):
        self.parent = parent if parent != None else None
        self.left = None
        self.right = None
        self.key = key if key != None else None

class BST():
    def __init__(self):
        self.root = Node()

    def insertKey (self, key):
        #pdb.set_trace()
        # transverse till we find empty position
        if (self.root.key == None):
            self.root.key = key
        else:
            node = self.root
            while (node.left != None and node.right != None):
                if node.key < key:
                    node = node.right
                else:
                    node = node.left
            #we have node either left or right is empty
            if node.key < key:
                node.right = Node (node, key)
            else:
                node.left = Node (node, key)

    def inOrder (self, node):
        #pdb.set_trace()
        if node != None:
            self.inOrder (node.left)
            print node.key
            self.inOrder (node.right)

    def printLeft (self, node):
        if node != None:
            self.printLeft (node)
            print node.key

    def debugAll (self):
        self.inOrder (self.root)
        #self.printLeft (self.root)

    def fromArray (self, numbers):
        srt = sorted(numbers)
        print srt
        length = len(srt)
        mid = length/2
        rootEle = srt[mid]
        self.insertKey (rootEle)
        for i in range (1, mid+1):
            try:
                #pdb.set_trace()
                self.insertKey (srt[mid-i])
                self.insertKey (srt[mid+i])
            except IndexError:
                pass

bst = BST()
bst.fromArray ([1,2,4,3,6,5,10,8,9])
bst.debugAll ()

However the result of the inOrder tree walk is unexpected
1
4
5
6
10

I tried to debug through the pdb while inserting the keys, the keys are properly inserted, but when transversing the tree, some Node are skipped because they're marked as 'NoneType'. May be I am missing out on some language specifics here.

A: For a start, the code you have below isn't right:
        while (node.left != None and node.right != None):
            if node.key < key:
                node = node.right
            else:
                node = node.left

It will stop descending if either the left or the right node doesn't exist.
EDIT:  If you modify the loop like this, it works.  Could be better optimized, but it's a start...
class Node():
    def __init__(self, parent=None, key=None):
        self.parent = parent if parent != None else None
        self.left = None
        self.right = None
        self.key = key if key != None else None

class BST():
    def __init__(self):
        self.root = Node()

    def insertKey (self, key):
        #pdb.set_trace()
        # transverse till we find empty position
        if (self.root.key == None):
            self.root.key = key
        else:
            node = self.root
            while 1:
                if node.key < key:
                    if node.right is None:
                        node.right = Node(node, key)
                        break
                    else:
                        node = node.right
                else:
                    if node.left is None:
                        node.left = Node(node, key)
                        break
                    else:
                        node = node.left

    def inOrder (self, node):
        #pdb.set_trace()
        if node != None:
            self.inOrder (node.left)
            print node.key
            self.inOrder (node.right)

    def printLeft (self, node):
        if node != None:
            self.printLeft (node)
            print node.key

    def debugAll (self):
        self.inOrder (self.root)
        #self.printLeft (self.root)

    def fromArray (self, numbers):
        srt = sorted(numbers)
        print srt
        length = len(srt)
        mid = length/2
        rootEle = srt[mid]
        self.insertKey (rootEle)
        for i in range (1, mid+1):
            try:
                #pdb.set_trace()
                self.insertKey (srt[mid-i])
                self.insertKey (srt[mid+i])
            except IndexError:
                pass

bst = BST()
bst.fromArray ([1,2,4,3,6,5,10,8,9])
bst.debugAll ()


text:
Q: What screwdriver do I need to remove the fans inside an Acer Nitro 5 AN515-42-R5ED laptop? I'm not really tech savy, but I need a screwdriver to unscrew my fans and hard drive and I am not too sure what screwdriver I need.
This is something I want to unscrew to re-apply the thermal flash and blah blah. This is prob a dumb question but I just need the screwdriver to unscrew it.

A: Those screws in the picture are Philips screws. They are either number 1 or number 0.
You can get good, high quality, Philips drivers at Home Depot, Lowes in the US, North America, or at a good hardware store where you live.
Buy top quality screwdrivers so as not to damage the screw head. This is easily done with a poor quality driver, or a driver that does not fit properly, so you will want to take care.
I have these tools and have removed / replaced screws like this.


text:
Q: How does the indexOf method is returning the falsely value? function bouncer(arr) {
  var array = [false, null, 0, NaN, undefined, ""];
  var result = [];
  for (var i = 0; i < arr.length; i++) {
      if (array.indexOf(arr[i]) === -1) {
          result.push(arr[i]);
      }
  }
  return result;
}
ex : bouncer([7, "ate", "", false, 9]) should return [7, "ate", 9].

Hello Everyone,
I am trying to delete all the falsely values that are in the array input, but for somehow when I run bouncer([false,null, 0, NaN, undefined, ""]); I get [NaN] as a return value while I am expecting an empty array. Does anyone know why the function is returning the falsely values ?

A: It's because NaN is really a concept rather than a concrete number.
Consider the two "numbers" 0 / 0 and sqrt(-1). Neither of these are defined in the real number space so both give NaN, but they are clearly different values.
Because NaN basically indicates an unknown value that couldn't be represented in IEEE-754, it is never considered equal to another NaN, even itself.
This is the right thing to do because, given the infinitude (literally) of numbers that have no real representation in IEEE-754, the chances of two of them being the same number are infinitesimally small :-)
In fact, many implementations of isNaN() depend on this feature, to wit (pseudo-code):
define isNaN(n):
    return n != n

To actually solve this problem, one way is to remove the NaN from the checking array and slightly modify the conditional:
var array = [false, null, 0, undefined, ""];
:
if ((array.indexOf(arr[i]) === -1) && (! isNaN(arr[i])) {

A: There is already an answer that explains why NaN is included in your result. As to a solution to your problem, the following should suffice:
function bouncer(arr) {
  return Array.isArray(arr) ? arr.filter(v => v) : undefined;
}

The idea here is we filter out the values which coerce to true in a boolean context. Thus, the function we use to filter just returns the value itself!

A: As already mentioned - NaN is (by design) not equal to anything (not even itself).
To solve your problem you can add the arr[i] === arr[i] to your if(...):

function bouncer(arr) {
  var array = [false, null, 0, undefined, ""];
  var result = [];
  for (var i = 0; i < arr.length; i++) {
      if (array.indexOf(arr[i]) === -1 && (arr[i] === arr[i])) {
          result.push(arr[i]);
      }
  }
  return result;
}
console.log(bouncer([7, "ate", "", false, 9]));
console.log(bouncer([false,null, 0, NaN, undefined, ""]));


text:
Q: How to show posts in a WordPress theme using HTML 5? I am pretty new in HTML 5 and I am developing a WordPress theme using HTML 5 and I have the following doubt:
I have to put this WordPress code that show all the posts in my page theme

<?php if (have_posts()) : ?>

        <?php while (have_posts()) : the_post(); ?>

                <h2 id="post-<?php the_ID(); ?>"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?>

                <?php the_time('F jS, Y') ?>

                    <?php the_content('Read the rest of this entry »'); ?>

Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit','','|'); ?>  <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?>

        <?php endwhile; ?>

<?php posts_nav_link('','','« Previous Entries') ?>

<?php posts_nav_link('','Next Entries »','') ?>

    <?php else : ?>

Not Found

<?php _e("Sorry, but you are looking for something that isn't here."); ?>

        <?php include (TEMPLATEPATH . "/searchform.php"); ?>

    <?php endif; ?>

Now in the previous code this php code is wrapped inside a classic XHTML ... block. Now I want to optimize the previous code using HTML 5.
So is it a good choice replace the external ...  with a ... ?
Or are there a better solution?
After do this operation is it a good choice wrap every post using the HTML 5 ... tag?
I mean that I replace this code:

    ..................
    ..................
    ..................

with something like:

   ..................
   ..................
   ..................

Is it a good idea?
Tnx
Andrea

A: A great reference to check is the underscores (_s) theme. It's an HTML5 blank theme maintained by Automattic (the company who owns WP). Here's the template they use:

…

…

…

  …

A: WordPress doesn't care which html its templates output, WordPress just echo's the content that's all. Your theme however could depend on the .post class but I guess you're making your own theme


text:
Q: How to handle domain model updates and immutability of stored events? I understand that events in event sourcing should never be allowed to change. But what about the in-memory state? If the domain model needs to be updated in some way, shouldn't old event still be replayed to old models? I mean shouldn't it be possible to always replay events and get the exact same state as before or is it acceptable if this state evolves too as long as the stored events remains the same? Ideally I think I'd like to be able to get a state as it was with it's old models, rules and what not. But other than that I of course also want to replay old events into new models. What does the theory say about this?

A: Anticipate event structure changes
You should always try to reflect the fact that an event had a different structure in your event application mechanism (i.e. where you read events and apply them to the model). After all, the earlier structure of an event was a valid structure at that time.
This means that you need to be prepared for this situation. Design the event application mechanism flexible enough so that you can support this case.
Migrating stored events
Only as a very last resort should you migrate the stored events. If you do it, make sure you understand the consequences:

*

*Which other systems consumed the legacy events?

*Do we have a problem with them if we change a stored event?

*Does the migration work for our system (verify in a QA environment with a full data set)?


text:
Q: AjaxBehavior added at runtime but AjaxBehaviorListener is not invoked I am trying to add some ajax behaviour in a <h:inputText> component at runtime.
I spent a day to figure out what is going wrong with the next code with no success.
After invoking the initUIComponent method, the component indeed triggers ajax requests, a normal ajax response is also returned. However the AjaxBehaviorListener is never invoked. What have I missed? I use glassfish 3.1.2.2 with the default mojarra implementation.
public void initUIComponent(HtmlInputText c) {
    FacesContext fc = FacesContext.getCurrentInstance();

    AjaxBehavior ajaxBeh = (AjaxBehavior) fc.getApplication() .createBehavior(AjaxBehavior.BEHAVIOR_ID);
    ajaxBeh.setRender(Collections.singletonList("elId1"));
    ajaxBeh.setExecute(Collections.singletonList("@this"));
    ajaxBeh.addAjaxBehaviorListener(new AjaxBehaviorListener() {
        @Override
        public void processAjaxBehavior(AjaxBehaviorEvent e)
                throws AbortProcessingException {
            System.out.println("Something is happening!");

        }
    });
    c.addClientBehavior("keyup", ajaxBeh);

}

A: Finally it seems that this is a Mojarra bug. The code works smoothly with MyFaces. Here is the related Jira issue (JAVASERVERFACES-2674).


text:
Q: Angular 2 binding an event to a component at its selector level I have the following Angular 2 component:
import { Component, ElementRef, Renderer } from '@angular/core';;

@Component({
  selector: 'my-button',
  templateUrl: 'button.html'
})
export class ButtonComponent {
  private text: string;
  constructor(
    private elementRef: ElementRef,
    private renderer: Renderer
  ) {
    this.text = 'test';
  }

  touchmove(event) {
    console.log(this)
  }

}

I have the button's html
{{button}}

I have the component where its used in another page:

What I want to do is to bind the <my-button (touchmove)="touchmove()">. I can't do this though because the logic for this has to happen inside the component not outside it.
I don't really want to make a sub-element inside the button template. I've tried binding to the element using:
this.renderer.listen(this.elementRef.nativeElement, 'touchmove', this.touchmove);

The problem with the above strategy is though, when touchmove is fired, this is null. If I use this.renderer.listen(this.elementRef.nativeElement, 'touchmove', this.touchmove.bind(this)) also acts a odd because the event argument is weird, sometimes it has no touches in it (which doesn't happen when I use a (touchmove)="touchmove()" style binding on the component parent's page.
Is there a correct way to bind the events without using a sub element in my button template, or getting the weird binding issues i'm having?
Edit:
By inside my component, I mean if I did this with my html instead of {{button}}
<div (touchmove)="touchmove()">{{text}}</div>

It solves my issue, but I can't bind to this  i want to bind to the element that contains this div, the component selector itself: my-button

A: If you use arrow function then this will work
this.renderer.listen(this.elementRef.nativeElement, 'touchmove', (e) => this.touchmove(e));


text:
Q: JPA table to entity incorrect conversion What I am trying to achieve here is fire an sql query using spring JPA and get entites in return, then transform the objects in ay structure.
The problem is when two tables and entites have the same column, JPA is unable to diffentiate between the vales of those properties and maps wrong values to entities, here is my code:
DAO
public class EMIDao implements IEMIDao {

    @Autowired
    private EntityManager entityManager;

    @Override
    public List<EMI> fetch(Integer month) {
        Query query = entityManager.createNativeQuery(
                "SELECT DISTINCT e.*, p.*, l.*, i.* FROM emi e JOIN loan l ON l.loan_id = e.loan_id LEFT JOIN product p ON p.product_id = l.product_id LEFT JOIN item i ON i.product_id = p.product_id LEFT JOIN item_return ir ON ir.item_id = i.item_id WHERE e.date = ?1 AND ir.item_return_id IS NULL",
                "EMIProductDTO");
        query.setParameter(1, "2020-" + month + "-16");
        List<Object[]> objects = query.getResultList();

        return EMITransformer.transform(objects);
    }

}

Transformer
public class EMITransformer {

    public static List<EMI> transform(List<Object[]> objects) {
        Map<Integer, EMI> emiMap = new HashMap<>();
        Map<Integer, Product> productMap = new HashMap<>();
        Map<Integer, Loan> loanMap = new HashMap<>();
        Map<Integer, Item> itemMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(objects))
            for (Object[] objectArray : objects) {
                if (ArrayUtils.isNotEmpty(objectArray)) {
                    EMI emi = (EMI) objectArray[0];
                    if (!emiMap.containsKey(emi.getId()))
                        emiMap.put(emi.getId(), emi);

                    Product product = (Product) objectArray[1];
                    if (product != null && !productMap.containsKey(product.getId())) {
                        product.setItems(new HashSet<>(0));
                        productMap.put(product.getId(), product);
                    }

                    Loan loan = (Loan) objectArray[2];
                    if (loan != null && !loanMap.containsKey(loan.getId()))
                        loanMap.put(loan.getId(), loan);

                    Item item = (Item) objectArray[3];
                    if (item != null && !itemMap.containsKey(item.getId()))
                        itemMap.put(item.getId(), item);
                }
            }
        itemMap.forEach((id, item) -> {
            productMap.get(item.getProductId()).getItems().add(item);
        });
        loanMap.forEach((id, loan) -> {
            loan.setProduct(productMap.get(loan.getProductId()));
        });
        emiMap.forEach((id, emi) -> {
            emi.setLoan(loanMap.get(emi.getLoanId()));
        });
        return new ArrayList<>(emiMap.values());
    }
}

This is the data I have in my mysql db

This is the output I get after the db call

Its basically confusing price of product with price of item
EMI entity:
@Entity
@Table(name = "emi")
@SqlResultSetMapping(name = "EMIProductDTO", entities = {
        @EntityResult(entityClass = EMI.class),
        @EntityResult(entityClass = Product.class),
        @EntityResult(entityClass = Loan.class),
        @EntityResult(entityClass = Item.class)
})
public class EMI {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "emi_id")
    private Integer id;
    @Column(name = "loan_id")
    private Integer loanId;
    @Column(name = "principal")
    private Integer principal;
    @Column(name = "interest")
    private Integer interest;
    @Column(name = "date")
    private Date date;
    @Column(name = "created_on")
    private Timestamp createdOn;
    @Transient
    private Integer emi;
    @Transient
    private Loan loan;

Product Entity
@Entity
@Table(name = "product")
@SqlResultSetMapping(name = "ProductItemDTO", entities = { @EntityResult(entityClass = Product.class),
        @EntityResult(entityClass = Item.class) })
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "product_id")
    private Integer id;
    @Column(name = "order_number")
    private String orderNumber;
    @Column(name = "product_type")
    private String type;
    @Column(name = "price")
    private Integer price;
    @Column(name = "created_on")
    private Timestamp createdOn;

Item Entity
@Entity
@Table(name = "item")
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "item_id")
    private Integer id;
    @Column(name = "type")
    private String type;
    @Column(name = "brand")
    private String brand;
    @Column(name = "price")
    private Integer price;
    @Column(name = "product_id")
    private Integer productId;
    @Column(name = "created_on")
    private Timestamp createdOn;

Every thing is working as expected, I cannot change the approach to using the onetoonemapping annotations , just want jpa to map the price fields properly any help is highly appreciated. thanks in advance.


text:
Q: What happens if I start up my DSL-Modem As far as I know the dsl modem tries to authenticate at the ISP via CHAP in a PPPoE-frame which is in an Ethernet-frame. But in a "normal" Ethernet frame needs a destination MAC address. How does my DSL-modem get the destination-address of the ISP-device on the other end?

A: PPPoE clients use PPPoE Active Discovery to discover PPPoE Access Concentrators (servers) on the network. The first packet the client transmits is a PPPoE Active Discovery Initiation (PADI) which is sent to the Ethernet broadcast address (all ones in binary, all f's in hex: ff:ff:ff:ff:ff:ff). And PPPoE ACs on the network respond with PADO's (Offers). The client notes the source MAC address of the PPPoE AC that sent the PADO the client is interested in, and replies to that MAC address with a PADR (Request). If the AC accepts the request, it responds with a PADS (Session-confirmation).
PPPoE Active Discovery uses EtherType 0x8863.
After Active Discovery completes, the PPPoE client and AC start sending frames using the PPPoE Session EtherType 0x8864. These frames contain PPP messages, including LCP, authentication, and IPCP negotiation, and eventually IP datagrams in PPP.
So the CHAP frames are sent to the unicast MAC address of the PPPoE Access Concentrator, which was discovered via PPPoE Active Discovery.

A: It sends to ff:ff:ff:ff::ff:ff which is the "broadcast" mac address.  If you receive a frame with this destination don't drop it.  It's for you!


text:
Q: Write-Host with a color depending on the value of the message I would like to print a number in green if it's 100 or red if less, but this is not working

Write-Host -ForegroundColor { (if ($number -eq 100) {Green} else
  {Red}) } "$number"

How can I do this without having

if (...) {Write-Host ...} else {Write-Host ...}

A: Try it like this:
Write-Host $number -ForegroundColor $(if ($number -eq 100) {'Green'} else {'Red'})

You don't want to use {} in this case.  ForegroundColor does not accept a scriptblock and it is not pipeline bound.  Besides you're not piping anything into Write-Host.  A subexpression $() allows you to evaluate statements like if, foreach, etc.


text:
Q: Is this limit valid/defined and if so, what is the value of it? I was wondering if the following limit is even defined/valid; if it makes any sense. If so, what is the value of it? If not, why is it not defined/valid?
Define $n$:
$$ab=n$$ for $ a\rightarrow \infty$ and $ b\rightarrow 0$
Sure, this might be a weird question due to its perhaps philosophical nature. Please keep in mind that I am not yet that good at maths, so I would greatly appreciate an "understandable" answer.
Edit: I have read some of your answers. Does the following clarification change anything?
Let $a,b\in$ R
There is no "relation" between the two variables, one cannot be expressed using the other (such as $a=1/b$)
To rephrase the question: If two variables approach infinity and zero respectively, what would their product be (if it can be determined)?

A: There are many limits we run across that are of the form $0 \cdot \infty$.  This is known as an indeterminate form and needs closer study, which requires a clearer definition than you have supplied.  Each of $a$ and $b$ normally comes with a formula.  Often those depend on a parameter that is common to them.  For example, we might have $\lim_{c \to \infty} c^2(\frac 1c)$.  In that case $a=c^2 \to \infty$ and $b=\frac 1c \to 0$  The product goes to infinity.  Alternately, you could have $\lim_{c \to \infty} c(\frac 1{c^2})$ with the opposite behavior.
With the update, you cannot sensibly define a limit of the product.  The limit would depend on how fast $a$ goes to $\infty$ compared to how fast $b$ goes to zero.  As you have not specified how the limits are taken, the product is only defined if $a$ and $b$ have separate limits that do not result in an inderminate form.

A: Rather than "predefining n", I would approach it like this: Because a and b are two separate variables, their limits can be taken separately.
\begin{align*}
\lim_{a\rightarrow\infty}\lim_{b\rightarrow0}ab = \lim_{a\rightarrow\infty}(\lim_{b\rightarrow0}ab) = \lim_{a\rightarrow\infty}(a\times0) = \lim_{a\rightarrow\infty}0 = 0
\end{align*}
On the other hand, if you flip the limit-order,
\begin{align*}
\lim_{b\rightarrow0}\lim_{a\rightarrow\infty}ab = \lim_{b\rightarrow0}(\lim_{a\rightarrow\infty}ab) = \lim_{b\rightarrow0}(\infty\times b) = \lim_{b\rightarrow 0}\infty = \infty
\end{align*}
When you change the order of the limits, they evaluate to different things. If there was such a thing as $\lim_{a,b \rightarrow \infty, 0}ab$ then its value should be constant, which shows that the limit cannot exist (in the sense that it's undefined).

A: The limit is undefined because it isn't specified at what rate $a$ and $b$ are approaching $\infty$ and $0$ relative to each other.
For example, if you would define $b$ as $1\over a$,then as $a \rightarrow \infty$ and $b \rightarrow 0$, $n \rightarrow 1$
However, if you would define $b$ as $1\over a^2$, then as $a \rightarrow \infty$ and $b \rightarrow 0$, $n \rightarrow 0$
Since the relation between $a$ and $b$ is not given, the limit remains undefined.
If as you mention in the edit there is no relation between $a$ and $b$, then there would be no limit for $n$. If $a$ would grow faster proportionally to $b$ getting smaller, $n$ would get larger, and if $b$ would shrink faster, then $n$ would get smaller. Since $n$ is not closing in on a certain number (or $\pm \infty$), $n$ does not have a limit.

A: This is known as an indeterminate form. In short, whether it's defined or not, and in case it is what value it is, depends on how quickly $a$ grows and how quickly $b$ shrinks.
Example. Let $a = k$ and $b = c/k$ where $c$ is a constant. Then
$$ab = k(c/k) = c$$
for all $k$. Hence the limit as $k\to \infty$ is simply $c$. What this means is that the limit can equal any constant depending on the value of $c$.


text:
Q: Should Commit button always be used together with Submit button in ADF JDeveloper? I am developing an ADF Fusion Web Application and I want to be able to update and save the changes about entities into my database. Do I always have to drag and drop both Submit and Commit buttons together? I can not unserstand their difference implicitly.

A: The submit button actually does nothing special, it just does a submit of your form (like in normal HTML). It's the same functionality as every other button (except if you start using the immediate attribute, but not considering this here). The data from your form (or input components) will then be 'saved' in your model (so your entities). But not in the database of course.
When using the commit button, a submit happens (so everything for above happens) and then your data will get committed (saved in your db).

A: User404 is correct. Lets go one step further. A lot of people do not want separate submit and commit buttons. This may give an example of calling the commit programmatically from the ActionListener event handler of a button.


text:
Q: How does a NIC work from a kernel's perspective? Couldn't phrase my question properly so a Google search didn't help me. Can someone explain how a NIC works from a the kernel's perspective. In order for the kernel to talk to the device, you'll need either a driver/kernel module. My questions:

*

*I understand that devices are represented as files in Linux. If the driver/module provides user-space APIs to talk to the device, does that mean system-calls such as read/write to the device's file is redundant? I'm not saying one should actually use a system-call to read/write to a device's file, but just for a sake of argument.

*How does device names such as eth0 fit into all this?

*Where exactly does tcpdump get it's data? If I run something like:
tcpdump -vv -i eth0
does tcpdump read from a device file somewhere? It will be too complicated to actually probe the NIC's tx/rx port for the bits that goes in/out of it, so how does tcpdump get it's information?
Any information provided is greatly appreciated. Feel free to provides links to website or books where I can learn more about this.

A: "If the driver/module provides user-space APIs to talk to the device, does that mean system-calls such as read/write to the device's file is redundant?"
What you are stating here is very similar to the Poll Mode driver provided by the DPDK library.
https://doc.dpdk.org/guides/prog_guide/poll_mode_drv.html
If the driver provides user-space APIs then the read/write, send/recv system calls will become redundant. You must use the APIs provided by the driver to read and write to the NIC devices.
However if you still want to use the linux system calls such as read/write or send/recv, you could design your application such that after reading the raw data from the driver API, you 'inject' the raw data into the linux kernel, You can achieve this by writing the raw data into a tun/tap device and have your application read the data using linux system calls from the tun/tap device.
"Where exactly does tcpdump get it's data?"
Most packet sniffing applications sniff packets with the help of raw sockets opened at the l2 layer.
https://www.unix.com/programming/229235-raw-socket-programming-efficient-packet-sniffer.html
Found a post related to tcpdump that gives a more detailed explaination:
https://unix.stackexchange.com/questions/23060/what-level-of-the-network-stack-does-tcpdump-get-its-info-from


text:
Q: IpTables -j REJECT to instantly block the loading on user browser I have been searching for a solution to notify the browser on user that the request is Rejected so stop loading it. Because I have blocked facebook and every page that have a facebook plugin is stacked at loading for 1 min, leading in confusion.
When I use this rule:
iptables -A FORWARD -p tcp -m iprange --src-range192.168.1.50-192.168.1.100 --dport 443 -j REJECT.
I have to add this code --reject-with tcp-resetto do the request below, so the browser was noticed instantly for the rejection and didn't wait in loading any more.
Now my question is how can I do the same with this new rule I have added recently that block facebook using L7 information?
iptables -A FORWARD -m string --string "facebook.com" --algo bm --from 1 --to 600 -j REJECT
The blocking part work very well but the problem is that the hole pages that contains any facebook plugin or part stay in loading for +5 sec without interrupting any work on main page, only that the load symbol on browser tab lead to misunderstanding on user experience


text:
Q: What was the SquashFS compression method? I've got some SquashFS files, and I'd like to know how they were compressed so that I can have a rough idea of how they would perform when mounted.
The only binaries  provided by the squashfs-tools package are mksquashfs and unsquashfs, which are for creating/appending SquashFS files and extracting SquashFS files, respectively.
How can I determine what compression method was used to make a specific SquashFS file?

A: unsquashfs -s did not have the capability of displaying the compression type used until this commit on 07 August 2009.  This means that if you are running squashfs-tools 4.0 or older, you wouldn't be able to see the compression method used.
From this information, I derived a way to read the SquashFS 4.0 superblock to determine the compression method used (where $SQUASHFS is the path to your SquashFS file):
dd if=$SQUASHFS bs=1 count=2 skip=20 2>/dev/zero | od -An -tdI | xargs

Alternatively, here's a function for those who would like to type in the filename at the end of the line:
sqsh_comp_method(){ dd if="$1" bs=1 count=2 skip=20 2>/dev/zero|od -An -tdI | xargs;};sqsh_comp_method

You will get a number (between 1 and 6 as of SquashFS 4.4).  You can match that number to the following table to see what compression method was used:
╔═══╦════════════════════╦════════════════════╗
║ # ║ Compression Method ║ Compatible Version ║
╠═══╬════════════════════╬════════════════════╣
║ 1 ║ gzip               ║ 1.0 and newer      ║
║ 2 ║ lzma               ║ 4.1 and newer      ║
║ 3 ║ lzo                ║ 4.1 and newer      ║
║ 4 ║ xz                 ║ 4.2 and newer      ║
║ 5 ║ lz4                ║ 4.3 and newer      ║
║ 6 ║ zstd               ║ 4.4 and newer      ║
╚═══╩════════════════════╩════════════════════╝

(Source)
Note that the above dd command will only provide a reliable output if the file you specified had a SquashFS 4.0 superblock.  The following command will output "Not SquashFS 4.0" if the file $SQUASHFS does not have the SquashFS 4.0 magic number:
if [[ "$(dd if="$SQUASHFS" bs=1 count=4 skip=28 2>/dev/zero | xxd -p)" != "04000000" ]] ; then echo -n "Not " ; fi ; echo "SquashFS 4.0"

Explanation
In SquashFS 4.0 filesystems, the compression method is stored on the 21st and 22nd bytes of the superblock as a data type short.  dd bs=1 count=2 skip=20 will retrieve the short, od -An -tdI will turn the short into a human-readable number, and xargs is just to get rid of the leading spaces.
Before SquashFS 4.0, there was only the gzip method.

Old answer
unsquashfs has the -s flag for displaying SquashFS filesystem information.
Example usage:
deltik@node51 [/tmp]# unsquashfs -s template.squashfs
Found a valid SQUASHFS 4:0 superblock on template.squashfs.
Creation or last append time Thu Apr 30 23:07:23 2015
Filesystem size 47225242.44 Kbytes (46118.40 Mbytes)
Compression gzip
Block size 131072
Filesystem is exportable via NFS
Inodes are compressed
Data is compressed
Fragments are compressed
Always_use_fragments option is not specified
Xattrs are compressed
Duplicates are removed
Number of fragments 23629
Number of inodes 437076
Number of ids 1

If you just want the compression type identified, you could pipe the output through awk '/^Compression/{print $2}'.  Example:
deltik@node51 [/tmp]# unsquashfs -s template.squashfs | awk '/^Compression/{print $2}'
gzip

A: The file utility at version 5.39 and above support displaying the squashfs compression. If giving file a block device, one needs to tell it not to care that it's a special file and look inside as if it was a file.
file --special-files /dev/mmcblk0p1
/dev/mmcblk0p1: Squashfs filesystem, little endian, version 4.0, zlib compressed, 817826784 bytes, 27633 inodes, blocksize: 131072 bytes, created: Mon Nov 29 20:51:12 2021

A: Also looking for a better answer. I'm assuming you want to know because your OS doesn't seem to support the compression used in providing you with the squashedfs in question. Or perhaps like the unsquashfs on CentOS6, yours doesn't report the Compression type.
So I  strings | head on the compressed file. The first line will be hsqs and the second line should  indicate the compression method used.  I believe I used this method to determine that 7zXZ indicating that 7zip was in fact the method. However, with gzip, no such luck. I have to use od -b on the file to get the octal dump and to try to match the file signature with those associated with the file program. Again, however, no such luck (the string I expected to find is 037 213 but I see only 037 221.


text:
Q: Proof of the chainrule: is this proof correct and did I use the right notation? I created this proof of the chainrule. Being a (relative) beginner at math I have a few questions.

*

*Is the proof below correct? I was especially in doubt about the use of $h$ on both sides.

*Is the (Langrange?) notation correct this way?

*How to write the same proof using Leibniz's notation? I wrestled writing this proof in Leibniz notation, because what would in that case be the meaning of $dg$? Is it $g(x+h)-g(x)$ or $k$ or $h$?

To be proved:
If $f(u)$ is differentiable at $u=g(x)$, and $g(x)$ is differentiable at $x$ then:
$$f(g(x))'\stackrel{?}{=}f'(g(x))g'(x)$$
Or similarly
$$\lim \limits_{h \to 0}\frac{f(g(x+h))-f(g(x))}{h}\stackrel{?}{=}\lim \limits_{k \to 0}\frac{f(g(x)+k)-f(g(x))}{k}\lim \limits_{h \to 0}\frac{g(x+h)-g(x)}{h}$$
Case 1: if $h$ has a value such that $g(x+h)=g(x)$ then:
$$\lim \limits_{h \to 0}\frac{f(g(x+h))-f(g(x))}{h}=0$$
And
$$\lim \limits_{k \to 0}\frac{f(g(x)+k)-f(g(x))}{k}\lim \limits_{h \to 0}\frac{g(x+h)-g(x)}{h}=0$$
Both sides of the equation to prove equal zero, therefore the equation holds in this case.
Case 2: if $h$ has a value such that $g(x+h)\ne g(x)$ then:
We multiply the lefthandside by $\frac{g(x+h)-g(x)}{g(x+h)-g(x)}$
$$\lim \limits_{h \to 0}\frac{f(g(x+h))-f(g(x))}{h}=\lim \limits_{h \to 0}\frac{f(g(x+h))-f(g(x))}{g(x+h)-g(x)}\lim \limits_{h \to 0}\frac{g(x+h)-g(x)}{h}$$
Taking
$$u=g(x)$$
$$k=g(x+h)-g(x)$$
We get
$$\lim \limits_{h \to 0}\frac{f(g(x+h))-f(g(x))}{h}=\lim \limits_{h \to 0}\frac{f(u+k)-f(u)}{k}\lim \limits_{h \to 0}\frac{g(x+h)-g(x)}{h}$$
And as $h\to 0, k\to 0$, therefore
$$\lim \limits_{h \to 0}\frac{f(g(x+h))-f(g(x))}{h}=\lim \limits_{k \to 0}\frac{f(u+k)-f(u)}{k}\lim \limits_{h \to 0}\frac{g(x+h)-g(x)}{h}$$
Thus
$$f(g(x))'=f'(u)g'(x)=f'(g(x))g'(x) \tag*{$\blacksquare$}$$

A: Your case 1 is irreparably flawed.$
\def\lfrac#1#2{{\large\frac{#1}{#2}}}
$
In that case you claimed that if $g(x+h)=g(x)$ for some $h$ then $\lim_{h\to0} \lfrac{f(g(x+h))−f(g(x))}{h} = 0$. That is false. For example let $f$ be the identity function, and $g = \sin$ and $x = 0$ and $h = π$. Then $g(x+h) = g(x)$ but $\lim_{h\to0} \lfrac{f(g(x+h))−f(g(x))}{h}$ $= \lim_{h\to0} \lfrac{\sin(h)-\sin(0)}{h} = 1$, contradicting your claim.
Your case 2 is also completely broken for the same logical reason, because even if $g(x+h) \ne g(x)$ for some $h$ it does not mean that $\lim_{h\to0} \lfrac{f(g(x+h))−f(g(x))}{g(x+h)-g(x)}$ exists, so your first line in that case is already wrong. For example let $f$ be the identity function again, and $g(t) = |t-1|+|t+1|$ for every real $t$, and $x = 0$. Then $g(2) \ne g(0)$ but $\lim_{h\to0} \lfrac{f(g(x+h))−f(g(x))}{g(x+h)-g(x)}$ does not exist because $g(x+h)-g(x) = 0$ for every $h \in [-1,1]$. Note that $g'(0) = 0$ and $f'(2) = 1$, and the chain-rule still holds, but the limit you wrote down does not exist.

A: This answer will attempt to elaborate further on the problem that Medo pointed out in the comments:
Fix some value of $x$ and consider the sets
$$
H=\{h\mid\ g(x+h)= g(x)\} \\
H^c=\{h\mid\ g(x+h)\neq g(x)\}
$$
Here $H$ corresponds to your case 1, and $H^c$ corresponds to your case 2.

*

*Either set may be infinite (countable or uncountable) or empty and $H$ may also be finite.

*So first of all, there is no guarantee that $h=0$ is a limit point of both sets meaning $h\to 0$ may not even make sense within both sets. In that case one can simply argue using the set in which $h=0$ is in fact a limit point, and everything should be fine.

*Second of all, if $h=0$ is a limit point of both $H$ and $H^c$ so that $h\to 0$ makes senses for both, we need an extra argument to make sure that the two limits are equal. This is where some work remains to be done.

The way I have developed for dealing with the problem uses a more Leibnizian approach, namely define:
$$
\frac{\Delta f(g)}{\Delta x} =
\begin{cases}
0 & \text{for }\Delta g=0 \\
\quad\\
\frac{\Delta f}{\Delta g}\cdot\frac{\Delta g}{\Delta x} & \text{for }\Delta g\neq 0
\end{cases}
$$
where $\Delta g$ and $\Delta f$ denote the corrsponding changes of $g(x)$ and $f(g(x))$ when $x$ is changed by $\Delta x$.
This can be shown to be continuous and always equal to
$$
\frac{f(g+\Delta g)-f(g)}{\Delta x}
$$
and so it provides a continuous alternative to the problematic fatorization by "filling in" the missing values when $\Delta g=0$.

A: The main reason that this is not written well is that you are manipulating limits. This is very hard to read because there is a non-trivial claim built into each use of "$\lim$".
Unless you have separately verified it, the fact that the function $f \circ g$ is differentiable at $x$ is really part of the conclusion, so if you start with this limit on the left-hand side and then manipulate that expression, in my book you have committed an unforgivable analysis sin immediately.
If you are just doing algebra, then just write the algebra without $\lim$ in front of everything.
If you are taking a limit, justify it exists first, and then take the limit.

A: (Note: the proof has been edited so the comment below no longer applies.)
In case 1, you are assuming that $g(x+h) = g(x)$ for all real numbers $h$. In case 2, you are assuming that $g(x+h) \neq g(x)$ for all nonzero real numbers $h$. However, there is a third case that you have not covered, which is the case where $g(x+h)=g(x)$ for some but not all nonzero real numbers $h$.
By the way, the assumptions you made in each case could have been stated more clearly by inserting phrases such as "for all real numbers $h$". You could also use phrasing like, "if $h$ is a nonzero real number then $g(x+h) \neq g(x)$."

Follow-up comment: The proof has been revised to say:

if $h$ has a value such that $g(x+h)=g(x)$ then: $$\tag{1}\lim \limits_{h
 \to 0}\frac{f(g(x+h))-f(g(x))}{h}=0$$

But, how does equation (1) follow from the fact that there is a value of $h$ such that $g(x + h) = g(x)$? That is a non-sequitur.
Equation (1) would be obviously true if $g(x + h) = g(x)$ for all real numbers $h$. But case 1 (as written currently) only assumes that there exists a value of $h$ such that $g(x + h) = g(x)$.

A: One thing that's worth learning is the notation for the composition of $f$ and $g.$ We use $f\circ g$ to denote this function. I.e., $(f\circ g)(x) = f(g(x)).$
In your To be proved, we can use this notation. You wrote $f(g(x))' = f'(g(x))g'(x).$ The problem with this is that on the left you have $'$ followed by blank space, whereas on the right the $'$ symbols are followed by further notation. It's an inconsistency that can be corrected by writing
$$(f\circ g)'(x)=f'(g(x))g'(x).$$
On your paragraph that starts "Or similarly": You have
$$\lim \limits_{h \to 0}\frac{f(g(x+h))-f(g(x))}{h}$$ $$=\lim \limits_{k \to 0}\frac{f(g(x)+k)-f(g(x))}{k}\cdot\lim \limits_{h \to 0}\frac{g(x+h)-g(x)}{h}.$$
That is fine. You asked about having $h$ on both sides, but that is no problem whatsoever. In fact you could replace $k$ by $h$ on the right. The variable $h$ is called a "dummy variable", meaning any symbol could be used there (except for the symbols that already have meaning, like $x.$)
That's the small stuff. Others have pointed out the big mistakes, where you divide the proof into two cases: i) There is an $h\ne 0$ such that $g(x+h)-g(x) =0,$ and ii) There is an $h\ne 0$ such that $g(x+h)-g(x) \ne 0.$ Huge problem here: a few values of $h$ cannot tell you anything about about a limiting process, where we are letting $h\to 0$ through infinitely many values.
A better division into cases is this: case i) $g'(x)=0;$ case ii) $g'(x)\ne 0.$ How would the proofs go in these cases?
Proof for case i): Observe the following: There is a constant $C$ such that
$$|f(y)-f(g(x))|\le C|y-g(x)|$$
for all $y$ sufficiently close to $g(x).$ This follows from the existence of $f'(g(x)).$ Thus for small $h\ne 0,$
$$\left |\frac{f(g(x+h))-f(g(x))}{h} \right | \le C\frac{|g(x+h))-g(x)|}{|h|} \to C\cdot |g'(x)|=0.$$
Thus $(f\circ g)'(x) = 0,$ which is exactly what we want in this case.
Proof for case ii): This is the easy case. We need only observe that $g'(x)\ne 0$ implies $g(x+h)-g(x)\ne 0$ for all small nonzero $h.$ For such $h$ we can do what all beginners crave to do:
$$\frac{f(g(x+h))-f(g(x))}{h} = \frac{f(g(x+h))-f(g(x))}{g(x+h)-g(x)}\frac{g(x+h)-g(x)}{h} \to f'(g(x))g'(x).$$
I've been brief in these proofs. Please ask if you have questions.

A: An easy way to avoid the problem with the case $g'(p)=0$ is to perturb $g$ by a linear function: we can evaluate the derivative
$$
\frac{d}{dx}f(g(x)+\epsilon x)\Big|_{x=p}
$$
using the "Leibniz way" since $g'(p)+\epsilon\neq 0$.  Hence,
$$
\frac{d}{dx}f(g(x)+\epsilon x)\Big|_{x=p}=f'(g(p)+\epsilon p)(0+\epsilon).
$$
The left hand side depends continuously on $\epsilon$, so letting $\epsilon\to 0$ gives
$$
\frac{d}{dx}f(g(x))\Big|_{x=p}=0=f'(g(p))g'(p).
$$


text:
Q: Web Scraping. Need Help for this type of the Dynamic Web pages I wanted to develop a logic board that will keep the Wi-Fi Dongle charging based on the battery percentage. for this, I am scraping the home UI of the dongle as shown in the attached images. below is the basic code that I used to scrape the full website.
While Scarping I found that the website received is different from what appears in the web browser this was also confirmed with the website inspect tool and using the View Page Source method. I also tried Selenium, but no result was achieved. can anyone point me in the right direction?

import requests

url = "http://192.168.8.1/index.m.htm"
response = requests.get(url)
print(response)
print(response.status_code)
print(response.text)


text:
Q: Objective C NSMutableArray work with nil I want to create a NSMutableArray to represent a game board that holds grid element (assume I have a chess class). In this case, I already know the size of the board so I want to create an array by initWithCapacity:[size] and then initialize them as nil. During the game, I may insert or remove chess object into/from this array based on game. I need to check if some cell is nil sometimes.
Clearly initWithCapacity only allocate memory, but gives an empty array whose element is not assessable. I think insert [NSNull null] one by one is inefficient (I can turn to use 0 to represent nil but still not what I want).
Is there any type/structure in Objective C like a C/C++ array for my purpose? Or is it wise to use C/C++ array here? (e.g. Chess myArray[size])

A: It is by design that NSMutableArrays and other collections do not permit nil and [NSNull null] is used as a placeholder for the concept of "nothing" instead.

I think insert [NSNull null] one by one is inefficient

[NSNull null] is a singleton, so won't allocate lots of memory unnecessarily and is not inefficient.
This answer has more information.

Anther efficiency I'm concerning about [NSNull null] is when I first create the array, if this array is kind of large (say 100 entries)

100 elements isn't a problem. Your device will be able to iterate 100 elements very quickly. Time it if you like.

is enumeration the only way I can assign a nil to each of these 100 entries? (e.g. for (i=0;i<size;i++) {[myArray addObject:[NSNull null]];}

It's the first way I would think of doing it.

"Premature optimisation is the root of all evil"
Donald Knuth
You seem to be concentrating on optimisation too early. You should favour readability over efficiency at this point.
When your app seems to slow down, or near the end of a release, profile the application and find out what, if any problems exist. Otherwise you may find yourself spending a day "optimising" a for loop to find that you've saved 0.000001s per update.
Moreover, readable code is easier to:

*

*debug

*update

*maintain

*share

Micro-optimised code takes longer to produce, is prone to bugs, difficult to debug and maintain and often impossible to share as another developer may not know how to interpret your optimisations.
That's not to say "don't optimise", rather concentrate on optimising the biggest problems.

A: You can use something like this:
NSMutableArray *array = [NSMutableArray arrayWithArray:@[@"First", @"Second", @"Third"]];
[array addObject:[NSNull null]];

[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if (![obj isKindOfClass:[NSNull class]]) {
        // Do something
    }
}];


text:
Q: Add label to image NodeJS ImageMagick Apologies if this has been asked but I am struggling to find the answer.
I am using the Node GM package with ImageMagick. As I am under the impression the label only works there.
I want to take an image and add a label over the top of it.
I was originally using drawText() to acheive this, however I need to take advantage of the auto sizing of the label in IM. What I have is:
im(path.join(__dirname, '../public/images/imgen/backgrounds/', color + '_' + type + '.png'))
    .gravity('West')
    .fill('#FFFFFF')
    .font(path.join(__dirname, '../public/fonts/Lato/Lato-Bold.ttf'))
    .out('label: ' + text)
    .write(
      path.join(__dirname, '../public/images/imgen/generated/', fileName), function(err) {
        if (!err) {
          // If the write was successful then redirect to the new image
          res.redirect('/images/imgen/generated/' + fileName);
        } else {
          console.error(err);
          res.status(500).end();
        }
    });

The above generates two images instead of one. I'm guessing I need to create an empty image and insert the image as a background. Yet I can not work out how to do this.
im(1080, 1080)
    .gravity('West')
    .fill('#FFFFFF')
    .font(path.join(__dirname, '../public/fonts/Lato/Lato-Bold.ttf'))
    // Add the image as a background here
    .out('label: ' + text)
    .write(
      path.join(__dirname, '../public/generated/', fileName), function(err) {
        if (!err) {
          // If the write was successful then redirect to the new image
          res.redirect('/images/imgen/generated/' + fileName);
        } else {
          console.error(err);
          res.status(500).end();
        }
    });

Where it says Add the image as a background here, I don't know what to do to add an image. I can't find it anywhere in the gm docs to insert an image.
I have tried .out('texture: ...') and .out('background: ...') but no look. I get the following error from IM convert: no decode delegate for this image formatTEXTURE' @ error/constitute.c/ReadImage/501.`
I'm probably not understanding correctly the out() method. But digging through Github issues and search results hasn't yielded the answer.
Thanks in advance for any help you can give.

A: I have a real mental block with all those parentheses in node.js but you said any help is welcome, so maybe we can get you sorted out by working a bit towards each other. I'll start at the command-line with ImageMagick and then you will maybe understand what is going on behind the scenes and be able to translate that to node.js.
The first thing is that ImageMagick operators without a dash before them and with a colon after them generate their own canvas - that means they don't don't need some pre-existing thing to write or draw on. Examples are canvas:, xc:, gradient:, label::
convert -size 100x80 canvas:red a.jpg               # "canvas: is same as "xc:"

convert -size 100x80 gradient:cyan-magenta a.jpg    # "gradient:" has a colon

convert -size 400x60 -undercolor yellow label:"This will be autosized to fit" -trim c.jpg

convert -size 400x60 -undercolor yellow label:"... so will this" -trim c.jpg

Hopefully you can see ImageMagick chose a bigger font for the shorter message.
All that is fine, but if you want to use -annotate (which you will notice is preceded by a dash and does not have a colon after it), you need to create a canvas first and then annotate it afterwards like this:
convert -size 400x120 xc:blue -fill yellow -annotate +40+80  "Annotation" c.jpg

What I am getting to, is that if you create a canvas AND a label (which creates its own canvas, remember), you will effectively have two canvases and get two output images. So, you have two options on how to get around that. You either:

*

*use a canvas and annotate it, or

*you create a label and background image and then composite the label over the canvas.
I just showed you the first option already, so let's look at the second. You can create a label of the correct size and then position it over a background wherever you like and then composite it onto the background as you wish:
convert -size 150x40 -undercolor yellow label:"Some funky text" -trim \
  -size 300x200 -gravity center xc:red +swap -composite result.jpg

So, what that does is create a label that is 150x40 and puts the text on it. The second line then creates another canvas in red of 300x200 and puts it behind the text label (using +swap) and composites it into the middle. You see, because I composited the label onto the canvas, they have become a single composite image rather than remaining two independent images.
Here is another example where we have an image of the White House and want to create a label and overlay it. First we create the label, all the correct size and colour, then we load the White House image and swap it to the back before compositing the label on top:
magick -size 300x200 -background none -fill magenta label:"Some funky label" -trim whitehouse.jpg +swap -gravity southeast -composite result.png

Hopefully you can see how to put all the beloved parentheses around that to make it into node.js....


text:
Q: Setup repository privilege in svn I have a subversion at this folder : http://202.45.139.85/svn/UAP_4.0/4.0.1
Now I'm creating a new folder for 4.0.2.
I already add in my username at file authz in folder /var/www/svn/uap/repo/conf
[aliases]
anirzam

[groups]
test = anirzam

[repository:/erynn]
@test = r

But, I still manage to check in file in this folder.
I have a list of username in file :
/etc/apache2/mods-enabled# vim dav_svn.passwd
anirzam:$apr1$vk/00Pnk$57Ss.H0pkoT7gKKoDNWCu/

My question:
Is it the correct way to control access for repository in svn?
And do I have to restart the svn once I edit the authz file then only it can get reflect?
FYI, I'm referring to this link How to setup access control in SVN?.
Thank You.