text:
Q: Shell: Does "a -lt b" not mean true if a is less than b?   I'm not trained in Linux, but I can muddle through with some doc lookups, but I'm stumped.
I found a script that helps set the date on my dd wrt router when it starts up, but only if the current date is less than the stored date.  I can share the whole script if you want, but it boils down to this statement not evaluating to true when I expect it to.  I'm putting the literals in, rather than the variables, and it still does not return true, it executes the "else" statement:
 if [ 021715402012 -lt 021815402012 ]
  then
     echo "the first seems less than the second"
  else
     echo "the first does not seem less than the second for some reason"
  fi

I would expect "the first seems less than the second" but this is not the case...
Is it an overflow problem?  I tried to make it a string compare like this:
if [ x021715402012 -lt x021815402012 ]

and tried putting it in quotes:
if [ "x021715402012" -lt "x021815402012" ]

it always executes the else.  Does "a -lt b" not mean true if a is less than b?
Any insight into this would be appreciated, I'm stumped!

A: The mnemonics such as -lt might be said to come from the original Fortran comparators such as .LT. from the late 1950s.
Yes, in the shell, -lt does a 'less than' numeric comparison.  (Be aware, though, that in Perl, the numeric comparisons are < etc, and the string comparisons are denoted by the alphabetic operators such as -lt!)
However, in some, perhaps many, shells the conversion and comparison may well be done in the local long integer format.  If you're on a 32-bit machine, the values you quote exceed the 32-bit (signed) range by a factor of 10 or so. On a 64-bit machine, or with a shell that uses long long, you'd be OK.
The hex equivalents of the decimal numbers are 021715402012 = 0x50E56BD1C and 021815402012 = 0x5144C9E1C; they can't be octal because of the 8.  (However, if the shell does interpret the leading zero as 'octal', then the second number is just 021 or 17 decimal because the 8 ends the octal number.  However, the 64-bit shells I tested on (Mac OS X 10.7.3 and RHEL 5) both seemed to treat them as decimal, not octal.)
The example code below, compiled under 64-bit gives the following output:
021715402012 =  240565532 = 0x050E56BD1C
021815402012 =  340565532 = 0x05144C9E1C

Compiled under 32-bit, it gives the following output:
021715402012 = 2147483647 = 0x007FFFFFFF
021815402012 = 2147483647 = 0x007FFFFFFF

If this was what happened in your shell, then the resulting behaviour of -lt would be explained.  You could confirm it by testing whether the two values are -eq; counter-intuitively, this would probably evaluate to true under the hypothesis that you are using a 32-bit shell that limits its arithmetic to long (32-bit) signed integers.
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *array[] = { "021715402012", "021815402012" };
    for (int i = 0; i < 2; i++)
    {
        int j = atoi(array[i]);
        long k = strtol(array[i], 0, 10);
        printf("%-10s = %10d = 0x%.10lX\n", array[i], j, k);
    }
    return 0;
}

A: What shell and version are you using? Any chance of an embedded control character somewhere?  (Try deleting re-typing the code.)  On openSUSE 11.2 (x86_64):
$if [ 021715402012 -lt 021815402012 ]; then echo yes; else echo no; fi
yes

Interestingly, though,
$if [ 012 -lt 11 ]; then echo yes; else echo no; fi
no

This surprises me because man bash says that -lt performs an arithmetic comparison, and a constant with a leading 0 is interpreted as octal.  So I'd expect this to test whether ten is less than eleven, because 012 base 8 = 8 + 2.
Can someone set us straight?

A: A few things are happening...
Your shell seems to be using 32-bit arithmetic and your numbers are overflowing the format.
Also, all command parameters in shell scripts are strings, so the quotes will have no effect at all unless characters in a parameter are significant to the shell parser.
The shell if statement is actually running the test(1) command which is linked to [ as a shorthand. (And then it ignores a final ].) Although the command could have used the same operator for numeric and string comparisons, as it happens the command is designed in such a way that the operators assume a certain type, and -lt assumes numeric.
On bash and ash (dash) I get an error message on your x... example.

A: I'm not sure if your particular shell is using this interpretation, but here's what I think is happening:
021715402012 is an 11-digit octal number.  021815402012 is a two-digit octal number terminated by a non-octal digit (the 8).
Of 021715402012 and 021, clearly the second is smaller.
Regarding your other attempts, the documentation for the test and [ commands indicates that -lt is only valid for numeric arguments, not strings.


text:
Q: Vertex Shader Compile Error while trying to pass the info from V.Shader->G.Shader->F.Shader using Interface block I want to pass the info per face which includes the material and face index. I created an interface block in the vertex shader and assigned the values to it which I pass to Geometry Shader and than Fragment shader.
I get the vertex shader compile error for which I have no idea why its happening. I have attached my Shaders and settings code here.I am unable to figure out the error
//  Configuration setting for geometry shader

    glProgramParameteriEXT(g_programObj, GL_GEOMETRY_INPUT_TYPE_EXT, InPrimType);
    glProgramParameteriEXT(g_programObj, GL_GEOMETRY_OUTPUT_TYPE_EXT, OutPrimType);
    glProgramParameteriEXT(g_programObj, GL_GEOMETRY_VERTICES_OUT_EXT, OutVertexNum);
    glLinkProgramARB( g_programObj);
    glGetObjectParameterivARB( g_programObj, GL_OBJECT_LINK_STATUS_ARB, &bLinked );
    if( bLinked == false ) {
        glGetInfoLogARB( g_programObj, sizeof(str), NULL, str );
        printf("Linking Fail: %s\n",str);   return false;
    }

// GL List here

glBegin(GL_POINTS);
        for (i = 0; i < faceNum; i++) {
            mesh->GetFaceNodes(i + 1, ver[0], ver[1], ver[2], ver[3]);
            glColor3f(1.50, 2.50, 3.50);
            glVertex4i(ver[0] - 1, ver[1] - 1, ver[2] - 1, i+1);
        }
        glEnd();
        glEndList();

Vertex Shader:
uniform samplerRect vertexTexture;
uniform int sizeNx;
uniform vec3 Cent;

varying out info
{
    vec3 material;
} outInfo;

void main( void )
{
    int ix,iy;

    //I guess I am doing something wrong here
    outinfo.material.x = gl_Vertex.w;
    outinfo.material.y = gl_Color.y;
    outinfo.material.z = gl_Color.z;

    iy=gl_Vertex.x/sizeNx;      ix=gl_Vertex.x-iy*sizeNx;
    gl_Position.xyz = texture2DRect(vertexTexture,vec2(ix,iy)).rgb-Cent;
    gl_Position.w =1.0;

    iy=gl_Vertex.y/sizeNx;      ix=gl_Vertex.y-iy*sizeNx;
    gl_FrontColor.xyz = texture2DRect(vertexTexture,vec2(ix,iy)).rgb-Cent;
    gl_FrontColor.w = 1.0;

    iy=gl_Vertex.z/sizeNx;      ix=gl_Vertex.z-iy*sizeNx;
    gl_BackColor.xyz = texture2DRect(vertexTexture,vec2(ix,iy)).rgb-Cent;
    gl_BackColor.w  = 1.0;

    gl_PointSize=1.0;

}

Geometry Shader:
    #version 120
    #extension GL_EXT_geometry_shader4: enable

    varying out vec4 color;

    varying in info
    {
        vec3 material;

    } inInfo[];

    varying out info
    {
        vec3 material;

    } outInfo;
// Doing calculations in geometry shader,so cant directly send the info from v.shader to f.shader.

Fragment Shader:
varying in info
{
    vec3 material;
    } inInfo;

void main( void )
{
    if (color.z<0.0)
        gl_FragData[0] = vec4(inInfo.material.x ,inInfo.material.y, -(gl_FragCoord.z), inInfo.material.z);
    else
        gl_FragData[0] = vec4(inInfo.material.x ,inInfo.material.y, gl_FragCoord.z, inInfo.material.z);
}

This is all and this gives me error of Vertex shader compile error by this condition
glGetObjectParameterivARB(g_vertexShader, GL_OBJECT_COMPILE_STATUS_ARB, &bCompiled);
    if (bCompiled == false) {
        glGetInfoLogARB(g_vertexShader, sizeof(str), NULL, str);
        printf("Warning: Vertex Shader Compile Error\n\n"); return false;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как составить и использовать функцию, которая будет возвращать два значения Составить функцию поиска суммы и произведения трех целых чисел. Найти с ее помощью сумму и произведение шести данных чисел.

A: struct sum_prod {
    int sum;
    int prod;
};

// function can returns structures
struct sum_prod
sum_and_prod (int a, int b, int c)
{
    struct sum_prod result;
    result.sum = a + b + c;
    result.prod = a * b * c;

    return result;
}

A: как вариант
void sum_and_mult(int a, int b, int c, int &sum, int &mult) {
  sum = 0;
  mult = 1;
  sum = a + b + c;
  mult = a * b*c;
}

A: Судя по вопросу (который на мой взгляд составлен криво), суть задания была в функций с переменным числом параметров.
#define UNUSED(x) (void)(x)

#include <iostream>
#include <vector>
#include <numeric>

template<typename... T2>
int s_and_c(auto f, const T2&... args) {
    auto il = std::initializer_list<int>{args...};
    std::vector<int> v(il);

    return f(v);
}

int main(int argc, char *argv[]) {
    UNUSED(argc);
    UNUSED(argv);

    auto f_sum{[](std::vector<int>& v){return std::accumulate(std::begin(v), std::end(v), 0, [](int a, int b){return a + b;});}};
    auto f_c{[](std::vector<int>& v){return std::accumulate(std::begin(v), std::end(v), 1, [](int a, int b){return a * b;});}};

    auto s1 = s_and_c(f_sum, 1);
    std::cout << "res : " << s1 << std::endl;
    auto s1_c = s_and_c(f_c, 1);
    std::cout << "res : " << s1_c << std::endl;

    auto s2 = s_and_c(f_sum, 1, 2, 3, 4, 5, 6);
    std::cout << "res : " << s2 << std::endl;
    auto s2_c = s_and_c(f_c, 1, 2, 3, 4, 5, 6);
    std::cout << "res : " << s2_c << std::endl;

    auto s3 = s_and_c(f_sum, 1, 2, 3);
    std::cout << "res : " << s3 << std::endl;
    auto s3_c = s_and_c(f_c, 1, 2, 3);
    std::cout << "res : " << s3_c << std::endl;

    return 0;
}


text:
Q: Does Kicad (pcbnew) allow dragging nodes — i.e. junctions between track segments? I am starting to use Kicad and am used to gEDA suite. The latter allows dragging anything in pcb: tracks, track segment ends, footprints, selected objects... For instance, you can drag the end of a track segment in gEDA pcb by clicking one end with a left click and drag it so only that very end is dragged while the other stays in place.
I just couldn't figure out how to do that in Kicad; all I could do was drag the clicked/selected segment. On the other end I tried myself at grab-and-drag a whole track while conforming to the DRC rules, keeping the net connected, which feature gEDA doesn't have. That said I find this feature very convenient.
So is it possible to drag track segment ends in Kicad or do I have to change paradigm? I didn't find any info on that very topic so either it's too trivial to be mentioned (you can all me dumb) or it's not implemented because something more useful is in place...

A: Well, I finally found the answer on my own so I'm posting it here in case someone, just like me, happens to wonder. Put Kicad in OpenGL view mode and drag vias, tracks, track corners or whatever you want — provided you set DRC and routing constraints, of course. It is explained in this video on Youtube.
To drag items while in OpenGL view mode, select Add single track on the rightmost toolbar and then press D over the track/node you want to drag (no click required). The router will shove tracks or move the one you're dragging around according to the routing preferences you previously set. Press E while adding a (single) track to set routing preferences.


text:
Q: Android bulkTransfer return -1 when read data but there is really some data in the buffer I write a app in galaxy tab p7300 to communicate with a key (scsi device) via otg cable. I can  read data first time with bulkTransfer(),but can not the next time . Then I use Ellisys Visual USB to sniff data and I find that the key really return 13 bytes data. But in the android client (GT-P7300) I receive -1 that bulkTransfer return. I have run out my idea. Thanks for anybody that can give me  a piece of clues.

A: When using the USB Bulk transfer, here is a list of things to check when transaction fails
a) Verify the direction of the endpoint you have passed the bulkTransfer function
b) ensure that the buffer has sufficient length to store incoming data
c) The length field is perhaps the most important. If you know the exact size of the response, use it.
d) The Timeout parameter. If you send a query to the device and do not provide enough timeout when listening to the response, the bulkTransfer can return -1.
It looks like the timeout is affecting behavior in your Case. My suggestion is to use the exact number of bytes in the length fields for each response, and use a longer timeout (like 1000) so you give enough time for the bulk request to complete.

A: Its too late to post a solution , but in case in future someone needs help about it can get an answer from here.
I faced the same issue. I was using Android (Samsung galaxy s3) as usb host device. I figured out about the read endpoint and write endpoint not trasferring data using USB BulkTransfer. I tried to switch the endpoints for host mode case, it recognized and successfully write/read the data.
 mReadEndpoint = mDataInterface.getEndpoint(0);// tweaking endpoints // 1 was for read and 0 was for write
 mWriteEndpoint = mDataInterface.getEndpoint(1);

P.S there is an application available for android named "USB device info". It helped me a lot in understanding interfaces and endpoints of my usb device.


text:
Q: Is it possible to declare a scanner variable inside a method in Java to read keyboard input? final int MAX_ROUNDS = 5;
String name1,name1;

Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter player1 name: ");
name1 = keyboard.nextLine();
System.out.println("Please enter player2 name: ");
name2 = keyboard.nextLine();
Player player1 = new Player(name1);
Player player2 = new Player(name2);

Dealer dealer = new Dealer();

    for(int count = 1; count <=MAX_ROUNDS; count++)
    {
        System.out.println("------------------");
        System.out.ptintf("Round : %d",count);
        dealer.rollDice();
        player1.makeGuess();
        player2.makeGuess();
        roundResults();

excerpt from the makeGuess method which belongs to the  Player class.
public void makeGuess()
{
Scanner keyboard = new Scanner(System.in)

System.out.printf("Please guess 'even' or 'odd' "+
        "%s.", name);
String answer = keyboard.nextLine();

        if(answer.equalsIgnoreCase("even")
            guess = "Cho (even)";
        else
            guess = "Han (odd);
  }

I am not being prompted anything when the method executes I cannot understand why I did not include everything for the program. was just wondering if anyone eye balling this code could see something obvious otherwise, i will just take out the guess submission.

A: While I cannot find anything wrong with your code, If I had to take an educated guess, the dealer.dice() method probably has an infinite loop, which is causing your whole program to malfunction

A: Have you tried to print out name1, name2, etc. variables that get their values from the scanner to see if it is working? Try doing that immediately after setting their value to be keyboard.nextLine(). This should then give you a better idea of where the problem lies.


text:
Q: Конкатенация строковых литералов разных типов Легально ли соединять многострочные литералы, если они имеют разный тип?
Например, обычную строку и f-строку:
x = ('simple'
     f'f-string {42}')

A: Да, это описано в PEP 498 – Literal String Interpolation:

Adjacent f-strings and regular strings are concatenated. Regular strings are concatenated at compile time, and f-strings are concatenated at run time. For example, the expression:
>>> x = 10
>>> y = 'hi'
>>> 'a' 'b' f'{x}' '{c}' f'str<{y:^4}>' 'd' 'e'

yields the value:
'ab10{c}str< hi >de'


text:
Q: Probability Review Math Question I am currently stuck on the following probability problem:
"If 7 boys and 4 girls line up in the cafeteria in a random order, find the probability that the people at the beginning and at the end of the line are the same sex?"
In the textbook, it states that the answer is 27/55 but I am unsure how to reach that answer.

A: There are $11!$ of all possibilities how to line them all up. Then there are $2\binom{7}{2}$ ways to choose two boys at the beginning and end of the line (order matters, so times $2$), and rest can be permuted in $9!$ ways. Similarly there are $2\binom{4}{2}$ ways to choose two girls at the beginning and end of the line, and rest is again $9!$ permutations. So overall
$$
\frac{2\binom{7}{2}9!+2\binom{4}{2}9!}{11!}=\frac{27}{55}.
$$

A: The event that the front and last are the same gender is equivalent to the front and last both being boys or the front and last both being girls.
The first being a boy occurs with probability $\frac{7}{11}$ and the last being a boy given that the first is a boy will be $\frac{6}{10}$.  The probability then that both of these occur, the first and last both being boys will be the product of these, $\frac{7}{11}\times\frac{6}{10}$.
Similarly, the first being a girl occurs with probability $\frac{4}{11}$ and the last a girl given that the first is a girl will be $\frac{3}{10}$
The probability of either will then be:
$$\frac{7}{11}\times\frac{6}{10}+\frac{4}{11}\times\frac{3}{10} = \frac{27}{55}$$

A: Since you are only interested in outcome of 2 places you can take probailities of just them. So probability of first and last person both being boys is 7/11 * 6/10= 42/110, and probability of both of them being girls are 4/11 * 3/10= 12/110
Adding these up we get 54/110 or 27/55


text:
Q: Is there a way to check if a database exists in Mongo from the Node.js driver? I'm finding it surprisingly difficult to see find a way to see if a database exists or not in MongoDB from the Node.js driver. There seems to be no method in the Node.js driver to check if a database exists.
For example, the following doesn't throw an error:
var mongo = require('mongodb').MongoClient;

mongo.connect({ 'mongodb://localhost:27017/databaseThatDoesntExists }, function (err, db) {
   // There is no error
   if (err) console.log(err);
   // Let's get some stats on a database that doesn't exist
   db.statsAsync(function (err, result) {
      console.log(result);
   });
});

Results will be an object like this:
{ db: 'databaseThatDoesntExist',
  collections: 0,
  objects: 0,
  avgObjSize: 0,
  dataSize: 0,
  storageSize: 0,
  numExtents: 0,
  indexes: 0,
  indexSize: 0,
  fileSize: 0,
  ok: 1 }

Can you check to see if a database exists in MongoDB form the Node.js driver?  Is there even a concept of a database existing in MongoDB? Is referencing a database that doesn't exist just referencing a database with no collections?
Mongo, why can't you just throw an error! I like when my code throws errors!

A: Check if db.admin().listDatabases contains the database name.
If the server has authorization enabled, you will need the appropriate permissions.

A: The easiest way to tell whether a database exists would be from the mongo she'll. To list all databases available, enter the following into your Mongo shell.
show dbs

To list the database you're currently using, enter:
db

To explicitly select a database, enter:
use <database>


text:
Q: twitter bootstarp 3 modal faded with the background and won't work I have created the model using bootstrap 3 but my model fades with the background and does not work.
Here is the screenshot and code!

*Upload

Upload Image

select an image

                <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>

A: Here is a working sample. http://jsbin.com/togozico/1/edit. Is your problem with z-index?


text:
Q: Apply different KDE Window Rules if external monitor is present How can I have Window Rules (as seen in System Settings > Workspace > Window Management > Window Rules), that are conditional on my laptop using an external monitor?
When I'm connected to an external monitor, I'd like several windows to be launched on the laptop's monitor and pinned (visible on all desktops). When I'm only using the laptop's monitor, the windows should get default behavior. Is there a way to specify this?
I don't need anything to happen when I unplug or plug in the monitor; it's fine for existing windows to keep their last behavior.
I'm open to solutions that may involve "you'll need to write a shell script or program", but I have no idea where I might hook such a thing in, or if it's even possible. (While "modify KWin" is something I could do, that seems overkill.)
I think I could solve the problem with polling, but that would be very inefficient, and unless I polled very frequently, would cause the window's behavior to change while I was trying to work with it.
My current solution is to just apply the "all desktops" rule all of the time, and just unpin the windows when I'm on my laptop. I don't try to position it, as the position with an external monitor is likely to be off screen without an external monitor.
I'm using KDE 5.24.6 (at least that's what plasmashell --version and kwin --version report) on Kubuntu 22.04.1.

A: This is not possible with window rules. You can use KWin scripting instead. Relevant functions in the API are:

*

*workspace.numScreens (get the current number of screens)

*workspace.numberScreensChanged (do something when the number of screens changes)

*workspace.clientAdded (do something when a new window opens)

*workspace.clientList() (to iterate all windows)

*client.windowType, client.caption, client.resourceClass (to identify the window by type, title and application)

*workspace.sendClientToScreen(window, screen) (set screen assignment)

*client.onAllDesktops (set pinned status)

Example: On startup, when the screen setup changes and when a new window opens, set all normal windows of application "dolphin" and title "potato" to screen 1 and pinned when two monitors are connected, and screen 0 and unpinned with one monitor:
function arrangeWindow(window) {
    if (window.normalWindow && window.resourceClass == "dolphin" && window.caption == "potato") {
        if (workspace.numScreens == 2) {
            workspace.sendClientToScreen(window, 1);
            window.onAllDesktops = true;
        } else if (workspace.numScreens == 1) {
            workspace.sendClientToScreen(window, 0);
            window.onAllDesktops= false;
        }
    }
}

function arrangeAllWindows() {
    workspace.clientList().forEach(arrangeWindow);
}

arrangeAllWindows();
workspace.numScreensChanged.connect(arrangeAllWindows);
workspace.clientAddded.connect(arrangeWindow);


text:
Q: Code with const keyword won't compile I don't understand  why this piece of code won't compile.
I get following error in line return source->GetA();

cannot convert 'this' pointer from 'const class FooStruct' to 'class
  FooStruct &'

If I remove the const keyword it compiles fine.
class FooStruct
{
  int a;
public:
  int GetA() {return a;};

  int Bar(const FooStruct *source);
};

int FooStruct::Bar(const FooStruct *source)
{
  return source->GetA();
}

The code itself doesn't make sense. It has been stripped down from some real code and its only purpose is to illustrate the problem.

A: It is because of this line:
return source->GetA();

Here you are trying to execute GetA function on the pointer that you got. If the pointed object is const, the function must also be const, because:

*

*Both const and non-const functions can be executed on non-const objects

*Only const functions can be executed on const objects.

It is a good idea to mark all the functions that do not modify the state of the object as const, so they can be used on const objects (e.g. in functions that accept const T & as a parameter).
So in your case, the class should look like:
class FooStruct
{
public:
  int GetA() const {return a;}
};

A: The function GetA itself needs to be marked const:
int GetA() const {
    return a;
}

This then allows a const source* pointer to call that function.


text:
Q: Table row fills remaining height Chrome vs. Firefox I have a code that acts differently on Firefox and Chrome.
The behaviour I want is the one on Firefox. I want to reproduce it on Chrome without success.
In the following code, the idea is that the tr class="spacer" fills the remaining height below the the tr class="family" rows so they would be displayed at the top of the tr class="category" row.
On Chrome this is completely inconsistent...

.category th {
  height: 200px;
  background: red;
}

.family {
  height: 70px;
  background: blue;
}

      Category
      Family
      Info

      Category 1

      Family 1
      Many different things

      Category 2

      Family 2
      Other things

      Family 3
      Way more things

A: According to this example https://www.w3schools.com/tags/att_td_rowspan.asp, I rewrite your code like this. Hope this help you.

        Category
        Family
        Info

        Category 1
        Family 1
        Many different things

        Category 2
        Family 2
        Other things

        Family 3
        Way more things

A: I think the problem is how you structure your table but I have no solution using html tables.
I would rather use the css grid property. It needs a little bit more code but it provides in my Opinion more options a better responsiveness and so on.
I wrote down some code to display the same as you want with the tables. Of course you can modify the code to make it work more like you planned but it's a basic structure.
Html:

Category

Family

Info

Category 1

Family 1

Many different things

Category 2

Family 2

Many different things

Family 3

Many different things

Css:
.grid-category {
  min-height: 200px;
  background: red;
}

.family {
  height: 70px;
  background: blue;
}

.grid {
  display: inline-grid;
  grid-gap: 4px;
  grid-template-columns: auto auto auto;
  grid-template-rows: 16px auto auto;
}

.first,
.second {
  display: grid;
  grid-column: 1 / 4;
  grid-template-columns: auto auto auto;
  grid-template-rows: auto auto auto;
}

.grid-category {
  grid-row: 1 / 4;
}


text:
Q: how to restrict copy paste in a Textbox, in MFC? I am developing a small application in MFC... there is a little problem..hope you guys would help me regarding this...Here we go..the problem is...I have 6 little edit control(Text box) in which I will allow the user to enter some numbers..I have limited the number of chars/textbox as 4 but its allowing the user to copy and paste n numbers....How do I restrict the copy paste option in an Edit control....Please help me...

A: I found 2 ways of solving the problem....please check the below...
1st method:
class CNoPasteEdit: public CEdit
{
public:
CNoPasteEdit();
~CNoPasteEdit();
protected:
// This line will need to be added by hand because WM_PASTE is not available in
// class wizard
afx_msg void OnPaste(WPARAM wParam, LPARAM lParam);
afx_msg void OnContextMenu(CWnd* pWnd, CPoint point);
DECLARE_MESSAGE_MAP()
};

Then you will need to edit the .cpp file for this class like so
CNoPasteEdit::CNoPasteEdit(){
// Put any construction code here
}

CNoPasteEdit:~:CNoPasteEdit(){
// Put any destruction code here
}

BEGIN_MESSAGE_MAP(CNoPasteEdit, CEdit)
// This line is needed because there is no default macro for WM_PASTE messages
// This line will also need to be added by hand
ON_MESSAGE(WM_PASTE, OnPaste)
ON_WM_CONTEXTMENU()
END_MESSAGE_MAP()

void CNoPasteEdit::OnPaste(WPARAM wParam, LPARAM lParam){
// Put any code here you want to execute when the user right clicks on the edit
// control. Just leave it blank to disable the menu
}

void CNoPasteEdit::OnContextMenu(CWnd* pWnd, CPoint point){
// Put any code here you want to execute when the user tries to paste into the edit
// conrtol. Just leave it blank to prevent pasting.
}

2nd method:
Handle the ON_EN_CHANGE event and capture the text in the CString and check if its more than the limited character..if its..you can clear the text box with a warning message...


text:
Q: is there some way to tell the window manager to block all input to any new window, or any kind of popup dialog for a few seconds? (This is not about web browsing), this is about:

*

*system popups (I know only the one about: application not responding).

*Windows focus and input grabbing behavior.

what is the worst thing we all (???) ever faced about popups?
We click on their button by mistake, the window vanishes and we dont know what it was about, there is no log, there is no recording to review, my visual memory (on my brain) wont give enough hints about the mess I did, we end up with nothing!!
And it is rare to happen to me, but frequently relatives, not used to technology, have problems with it, they just impatiently keep clicking and the sudden popup/window makes them create unnecessary problems.
not only on ubuntu, anywhere: windows, android (mac too? never saw one, neither iphone).
so, i wonder if there is some config on gnome (that I use) or any other WM on linux, that we could force the new window, or popup (*1) to be blocked from all input for a few seconds, so we have a time to see and understand what it is about.
(*1) like the system popup saying the application is not responding and if we want to missRageClick on force close or missHappyClick on wait, as I also dont really need it because I could just run xkill thru xbindkeys, but another popup could still come above and make me xkill it!!!! not if we could block all input for a few seconds...
So, my concern is about any new windows too, of other applications, that open above other ones we are reading or interacting with. And then that new window grabs the keyboard input, or receives mouse clicks and makes things complicated.
Changing the focus behavior, if the WM allows it, is not a good option (like make windows open below others), as it makes it much more difficult the use it.
What I want is any new window or popup to continue behaving that way, opening above other windows, but do not promptly receive any input! For ex. they could be opened with SIGSTOP for 2s, I think it could work.
ubuntu 20.04 here
PS.: I use machines of about 10+ years old, so applications dont open instantly, or I may have started a heavy application like 10 minutes ago (like UE4Editor) and that app suddenly opens receiving mouse clicks, and the application may receive keyboard input too.


text:
Q: Excel data load into Azure SQL using SQL query Wants to load Excel data into Azure SQL using SQL query.
As openrowset is not allowed in Azure, Please help me to write query to insert excel data into Azure DB.

A: Quick steps:

*

*Import your excel or csv into Local sql server using import task

*Using the import table, create a Sql script with insert data statement.

*Run this script on your Azure Database
The queries are given clearly in MS site:
https://learn.microsoft.com/en-us/sql/relational-databases/import-export/import-data-from-excel-to-sql
I recommend you to refer topics in these links:
https://azure.microsoft.com/en-us/documentation/articles/sql-data-warehouse-load-with-bcp/
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connect-excel

A: Before you can run a distributed query, you have to enable the ad hoc distributed queries server configuration option
sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

example with OPENDATASOURCE
USE ImportFromExcel;
GO
SELECT * INTO Data_dq
FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0',
'Data Source=D:\Desktop\Data.xlsx;Extended Properties=Excel 12.0')...[Data$];
GO

You can create a linked server from SQL Server Management Studio, or by running the system stored procedure sp_addlinkedserver
DECLARE @RC int

DECLARE @server     nvarchar(128)
DECLARE @srvproduct nvarchar(128)
DECLARE @provider   nvarchar(128)
DECLARE @datasrc    nvarchar(4000)
DECLARE @location   nvarchar(4000)
DECLARE @provstr    nvarchar(4000)
DECLARE @catalog    nvarchar(128)

-- Set parameter values
SET @server =     'EXCELLINK'
SET @srvproduct = 'Excel'
SET @provider =   'Microsoft.ACE.OLEDB.12.0'
SET @datasrc =    'D:\Desktop\Data.xlsx'
SET @provstr =    'Excel 12.0'

EXEC @RC = [master].[dbo].[sp_addlinkedserver] @server, @srvproduct,
@provider,
@datasrc, @location, @provstr, @catalog

Reference: https://learn.microsoft.com/en-us/sql/relational-databases/import-export/import-data-from-excel-to-sql

A: You can use OPENROWSET:
SELECT * INTO EXCEL_IMPORT
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0; Database=C:\Excel\Spreadsheet.xls; HDR=YES; IMEX=1',
'SELECT * FROM [Sheet1$]');


text:
Q: NLog: How do I control the format of a message from a LogEventInfo object? I'm new to NLog, and I've been playing with LogEventInfo objects, since I think I'll need them in my application.  I created a LogEventInfo object with a plain text string, and then I called Logger.Debug(myEventInfoObject), using a FileAppender set up to write ${message}.  Where I expected to see my text string, I saw instead the logger name, the message level, the message, and the sequence ID.  I found that that expanded string is what I get when I call myEventInfoObject.ToString().  How can I control what appears when ${message} comes from a LogEventInfo object?
Here's my config file:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      throwExceptions="true">
  <targets>
    <target name="file" xsi:type="File" layout="${longdate}  ${logger}  ${message}" fileName="${basedir}/nlog_sample_file.txt" />
  </targets>

  <rules>
    <logger name="*" minlevel="Debug" writeTo="file" />
  </rules>
</nlog>

Here's my code generating the log:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NLog;

namespace NLogSample
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, "", "This message from the LogInfoEvent will not be used.");
                theEvent.Properties["Message"] = "This message from the LogInfoEvent Message property will be used.";

                logger.Debug(theEvent);
                logger.Debug("Does the sequence ID show up in this message?");

                string formattedMessage = theEvent.FormattedMessage;
                string eventString = theEvent.ToString();
            }
            catch (Exception ex)
            {
                int a = 1;
            }
        }
    }
}

Finally, here is a sample of the message:
2014-10-08 10:14:13.5525  NLogSample.Program  Log Event: Logger='' Level=Debug Message='This message from the LogInfoEvent will not be used.' SequenceID=2
I am working in Visual Studio 2012 on a Win7 Pro machine.
Thanks very much!
RobR

A: I had to do this
    class MyLogEventInfo : LogEventInfo {
        public override string ToString() {
            return base.FormattedMessage;
        }
    }

...
    var theEvent = new MyLogEventInfo();
    theEvent.Message = "This message from the LogInfoEvent will not be used.";
    logger.Debug(theEvent);

A: If you want to create LogEventInfo objects and fill them with your own information, you should use one of the Logger.Log method signatures, not the Logger.Info/Logger.Debug/etc method signatures.
The behavior you are seeing right now is probably because the Logger.Debug method is receiving an object (which happens to be a LogEventInfo object) and is calling ToString on it before logging it.

A: @wageoghe is right.  Here is how I use it:
// Create the logger
Logger logger = LogManager.GetCurrentClassLogger();

// Create the LogEventInfo object
LogEventInfo logEvent = new LogEventInfo();

// Now add the event characteristics
logEvent.Properties["EventCode"] = eventId;
logEvent.Level = level;
logEvent.Message = message;
logEvent.Exception = ex;

// Actually write the log entry.
logger.Log(logEvent);

No need to use the wrapper log objects, just define your LogLevel using the Level property in LogEventInfo() and then pass that object to Log().


text:
Q: Django Rest Framework allow not authenticated access to a view in certain cases I have a ViewSet which permission_classes is set to (permissions.IsAuthenticated,), but I want this view to allow not authenticated access when the method is retrieve().
This is my ViewSet:
class AlbumViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.IsAuthenticated,)
    queryset = proxies.AlbumProxy.objects.all()
    serializer_class = serializers.AlbumSerializer
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,)
    search_fields = ('name', 'description', 'company__name')
    filter_fields = ('code', 'company')

    def retrieve(self, request, pk):
        password = request.query_params.get('password', None)

        instance = proxies.AlbumProxy.objects.get(code=pk)

        if instance.access_code != password and password != settings.MASTER_KEY:
            raise Exception(_("Invalid password for album {}".format(instance.code)))

        instance_to_return = serializers.AlbumSerializer(instance=instance, context={'request': request}).data
        instance_to_return.pop('access_code')

        return Response(instance_to_return)

Is there a way I can disable permission_classes when the method retrieve() is on, but to leave it working in any other case?

A: You can override get_permissions like so:
def get_permissions(self):
    if self.action == 'retrieve':
        return []  # This method should return iterable of permissions
    return super().get_permissions()

A: Django Rest Framework gives what you need out of the box. See IsAuthenticatedOrReadOnly permission.


text:
Q: Methods of modern web development Have just finished my first web based application using Ruby on Rails. It was fine and I feel like i have a good general understanding of RoR now.
I want to try a different method of web design next but don't want to start learning outdated methods, I want to stay current.
I understand that different technologies are used to achieve different things, but just want make sure I'm investing my time in something useful.
What are the latest wave of developers using to create their applications? Java? PHP?

A: Take a look @ node.js.  It allows you to code JavaScript on the browser and the server.  JavaScript is becoming the defacto web language so it allows you to extend your skills their and share code (very powerful for the browser form and server REST service to share validation and other logic).
Also, many cloud services (Azure, CloudFoundry, Joyent etc...) are hosting it.  Alot of folks are onto this web technology (including Microsoft https://github.com/tjanczuk/iisnode - disclaimer: I work for them).
Besides it being new, it also encourages an async non-blocking I/O method of creating network servers which is a good pattern to get your head around.
Some videos to watch:
http://www.youtube.com/watch?v=jo_B4LTHi3I
http://www.youtube.com/watch?v=F6k8lTrAE2g
http://www.youtube.com/watch?v=SAc0vQCC6UQ
Start @ nodebeginner.org then look @
http://expressjs.com and
http://socket.io
Edit: Recently created this full sample pulling together modern concepts: https://github.com/bryanmacfarlane/quotes-feed

A: Try Django. It's a web framework built completely in Python (a language similar to Ruby) and has great documentation, if you're willing to learn Python, which is relatively easy.
There's a great and free tutorial on it here.


text:
Q: Undefined reference to while linking dll library I am trying to compile one of the metatrader 4 c++ api libraries in code::blocks.
Here is the main program
`#include "stdio.h"
 #include "MT4APITest.h"
 int main(void)
 {
  char err[255];
  SunkTCPClient* pCl = MT4_TC_StartClient("127.0.0.1", 4567, err);
  MT4APITest test;
  test.Run(pCl);
  return 0;
 }`

In build options -> liker settings, I have included relative path "bin/Debug/MT4_API.lib"
In build options -> Search Directories -> Compiler - >, I have included "C:\home\mt4\". This is the folder where I have kept my mt4_API.dll library. In the same folder, I've placed below files.
`main.cpp
MT4_API.h
MT4_APITest.cpp
MT4_APITest.h
mt43.cbp (for code blocks).`

When I compile this, the compilation command turns out to be
mingw32-g++.exe  -o bin\Debug\mt43.exe obj\Debug\main.o obj\Debug\MT4APITest.o    bin\Debug\MT4_API.lib
and getting the error
C:/cygwin/home/LENOVO/mt4/mt43/main.cpp:10: undefined reference to MT4_TC_StartClient(char const*, int, char*, wchar_t const*)@16'
obj\Debug\MT4APITest.o: In function ZN10MT4APITest15TestAccountInfoEv':
C:/cygwin/home/LENOVO/mt4/mt43/MT4APITest.cpp:48: undefined reference to MT4_TC_GetAccountInfo(SunkTCPClient*, MT4AccountInfo*)@8'
C:/cygwin/home/LENOVO/mt4/mt43/MT4APITest.cpp:48: undefined reference to MT4_TC_GetErrorDescription(MT4_RET_CODE)@4'
obj\Debug\MT4APITest.o: In function ZN10MT4APITest14TestSymbolInfoEv':
C:/cygwin/home/LENOVO/mt4/mt43/MT4APITest.cpp:57: undefined reference to MT4_TC_GetSymbolListCount(SunkTCPClient*, int*)@8
and the list continues. May I know what I am missing here.


text:
Q: Numerical Minimization not working as it should Thanks for the help in advance!
I have setup a module intending it to work as a function for minimization. The module works flawlessly for things such as plotting, but when I try to use a minimization algorythm on it i get errors from the Eigenvalues function used in the module (Which again, works good for plots). Any idea on what might be happening?
NSolve[{SigmasWithQR[10, 2, 0.7, x, 0.4, y, 30][[1]] =
SigmasWithQR[10, 2, 0.7, x, 0.4, y, 30][[2]] &&
SigmasWithQR[10, 2, 0.7, x, 0.4, y, 30][[2]] =
SigmasWithQR[10, 2, 0.7, x, 0.4, y, 30][[3]]}, {x, y}]

Using minimize on another module defined as the difference between the three quantities i am trying to equate results in the exact same output.
(I am sorry, i am new here and dont really know how to format the error. I know I am not providing a minimal functioning example, but since I dont know what might be malfunctioning, I have no idea on how to narrow it down.)
Error:
"Unable to find all roots of the characteristic polynomial"


text:
Q: shim: transport is closing error Exact same error as mentioned in jira ticket https://jira.hyperledger.org/browse/FAB-246 .
Although one of the comment says to take everything latest but that didn't helped me.
My fabric env: running within docker toolbox for mac with docker-compose.yaml as mentioned below.
membersrvc:
  image: hyperledger/fabric-membersrvc
  command: membersrvc
vp0:
  image: hyperledger/fabric-peer
  environment:
    - CORE_PEER_ADDRESSAUTODETECT=true
    - CORE_VM_ENDPOINT=http://172.17.0.1:2375
    - CORE_LOGGING_LEVEL=DEBUG
    - CORE_PEER_ID=vp0
    - CORE_PEER_PKI_ECA_PADDR=membersrvc:7054
    - CORE_PEER_PKI_TCA_PADDR=membersrvc:7054
    - CORE_PEER_PKI_TLSCA_PADDR=membersrvc:7054
    - CORE_SECURITY_ENABLED=true
    - CORE_SECURITY_ENROLLID=test_vp0
    - CORE_SECURITY_ENROLLSECRET=MwYpmSRjupbT
  links:
    - membersrvc
  command: sh -c "sleep 5; peer node start --peer-chaincodedev"

And I was registering my chaincode by using below command.
CORE_CHAINCODE_ID_NAME=mycc CORE_PEER_ADDRESS=0.0.0.0:50250 ./chaincode_example02

I got the peer port as 50250 by running below command.
netstat -atp tcp | grep -i "listen"


text:
Q: Same affiliation for multiple authors using achemso I would like to assign the same affiliation for multiple authors using the achemso document class. I tried the following, but it does not work:
\documentclass{achemso}
\usepackage[utf8]{inputenc}
\usepackage{authblk}

\title{Notitle}

\author[1]{Noname1}
\author[1]{Noname2}
\author[2]{Noname3}
\author[1,2,3]{Noname4}

\affil[1]{Nowhere1}
\affil[2]{Nowhere2}
\affil[3]{Nowhere3}

\begin{document}

\maketitle

\end{document}

Could you please help to make this code correct?


text:
Q: Linux xsetwacom setting equivalent to Windows wacom driver mapping In the Windows drivers for Wacom tablets, you have the option of mapping (a) the hole monitor to a specific area of the tablet, something like this:

I can't find an option in the xsetwacom command to emulate this behavior. Is this posible?

A: For using xsetwacom to do it, look here:
http://linuxwacom.sourceforge.net/wiki/index.php/Dual_and_Multi-Monitor_Set_Up#Coordinate_Transformation_Matrix
You basically have to do it by hand, calculating the proportions of your monitor and translating them to tablet size. The instruction in the link explain how to map the whole tablet to the screen, with distortion. It should be easy (if you get the math behind it) to adapt it to not distort.
BUT there are GUI apps too:
http://linuxwacom.sourceforge.net/wiki/index.php/External_applications#Utilities
If you're on KDE you maybe want to take a look at the "Wacom tablet" settings module. It's not yet where the windows driver is, but it lets you do what you want, set different profiles and more. I must say that it's not working well for me on Debian Jessy, but the version on the repos is an pretty old. (You don't say what distro are you using, usually relevant in a linux question)
There's also a GNOME applet, never tried it, but seems good (even better?).


text:
Q: Few problems with my animations c# I was working on a winforms app that is animation-heavy, I made all the animations my self.
I use an enum, that contains all animations which is used to call a new thread that runs the appropriate animation for the appropriate control. Here's one example:
    private void animateBackColor(Control control)
    {
        int i = 0;
        while (i <= 255)
        {
            control.BackColor = Color.FromArgb(i, control.BackColor);
            i += 15;
            Thread.Sleep(15);
        }
    }

The problems are the following:
+Sometimes, the animations get too stuttery and laggy and they become horrible.
+The controls that are overlapped by the moving ones take too long to repaint which looks ugly.
+I get this bug very rarely "collection was modified after the enumerator was instantiated" in the portion that changes a property about the control.
There's also a problem about this animation that fades in an image:
    private void animateFadeOut(Control control)
    {
        int i = 255;
        while (i > 15)
        {
            control.BackColor = Color.FromArgb(i, control.BackColor);
            i -= 30;
            Thread.Sleep(5);
        }
        PNL_runningDownloads.Controls.Remove(control);
    }

    public static Bitmap ChangeOpacity(Image img, float opacityvalue)
    {
            Bitmap bmp = new Bitmap(img.Width, img.Height); // Determining Width and Height of Source Image
            Graphics graphics = Graphics.FromImage(bmp);
            ColorMatrix colormatrix = new ColorMatrix {Matrix33 = opacityvalue};
            ImageAttributes imgAttribute = new ImageAttributes();
            imgAttribute.SetColorMatrix(colormatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            graphics.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, img.Width, img.Height,
            GraphicsUnit.Pixel, imgAttribute);
        graphics.Dispose(); // Releasing all resource used by graphics
        return bmp;
    }

+It says that the control is currently in use elsewhere
Thank you very much :)

A: I managed to find the program where I make use of heavy animations. Here's how main loop looks like:
static void Main() {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    Form1 form = new Form1();
    Clock clk = new Clock();
    FPSCounter counter = new FPSCounter();

    form.Show();
    clk.Reset();
    counter.Frequency = clk.Frequency;
    counter.RefreshRate = clk.Frequency / 2;

    double delta, time = 0f;
    long tick;

    while (form.Created) {
        tick = clk.TicksDelta();
        delta = (double)tick / clk.Frequency;
        time += delta;

        form.Update(delta, time);
        Application.DoEvents();

        counter.tick(tick);
        form.Text = counter.ToString();
    }
}

Clock class implementation:
public class Clock {
    [DllImport("kernel32.dll"), SuppressUnmanagedCodeSecurity]
    private static extern bool QueryPerformanceCounter(out long ticks);
    [DllImport("kernel32.dll"), SuppressUnmanagedCodeSecurity]
    private static extern bool QueryPerformanceFrequency(out long freq);

    private long myTmpFreq;
    private long myTmpCtr;
    private long myDeltaCtr;
    private long myDelta;

    public long Frequency {
        get {
            return myTmpFreq;
        }
    }
    public long Counter {
        get {
            QueryPerformanceCounter(out myTmpCtr);
            return myTmpCtr;
        }
    }

    public void Reset() {
        myDeltaCtr = Counter;
    }
    public long TicksDelta() {
        QueryPerformanceCounter(out myTmpCtr);
        myDelta = myTmpCtr - myDeltaCtr;
        myDeltaCtr = myTmpCtr;
        return myDelta;
    }
    public double Delta() {
        return (double)TicksDelta() / myTmpFreq;
    }

    public Clock() {
        QueryPerformanceFrequency(out myTmpFreq);
    }
}

If you make your WinForms application othis way you'll be able to run "real-time" animations and use UI thread as well. Everything will work smooth and nice.
Hope this helps. If you have further questions, please let me know.
EDIT: FPS Counter implementation
public class FPSCounter {
    private const int BUFFER_SIZE = 25;
    private long[] myTicks = new long[BUFFER_SIZE];
    private int myIdx;

    private decimal myFPS;
    public decimal FPS {
        get {
            return myFPS;
        }
    }

    private long myRefreshRate;
    public long RefreshRate {
        get {
            return myRefreshRate;
        }
        set {
            myRefreshRate = value;
        }
    }

    private long myFreq;

    public long Frequency {
        get { return myFreq; }
        set { myFreq = value; }
    }

    private long myTick;
    public void tick(long tick) {
        myTicks[myIdx++] = tick;
        if (myIdx >= BUFFER_SIZE)
            myIdx = 0;

        myTick += tick;
        if (myTick > myRefreshRate) {
            myTick = 0;
            myFPS = count();
        }
    }

    private decimal count() {
        long sum = 0;
        foreach (long i in myTicks)
            sum += i;

        if (sum == 0)
            return 0;

        return myFreq / (sum / myTicks.Length);
    }

    public override string ToString() {
        return String.Format("FPS: {0}", FPS);
    }

}


text:
Q: ArCore success floor find Is there a method, which is performed after a floor is found in ArCore? I tried to look for a solution, but I did not have success. I am looking for something like .
I need to diplay fbx, exactly when surface is detected .
edit: i will be thankful also for condition, which i can checkt that with.

onSurfaceDetection()

A: There is a sample of that in Solar System ARCore Sample from Google.
arSceneView
    .getScene()
    .addOnUpdateListener(
        frameTime -> {
          for (Plane plane : frame.getUpdatedTrackables(Plane.class)) {
            if (plane.getTrackingState() == TrackingState.TRACKING) {
              // Plane detected
            }
          }
        });


text:
Q: set up one storeview for multiple domains Is there a way to create a Magento 2.4 instance, that has one website => one storeview
and this one storeview is divided depending en each functionality to multiple domains for exemple:
myacountabc.test => customer pages
mycatalogabc.test => for catalog and search pages
mycartabc.test => for checkout page and cart pages
ect
all these domains redirect to same storeview
thanks all

A: Yes, it is possible to create a Magento 2.4 instance with one website and one store view that is divided into multiple domains for different functionalities. To achieve this, you can follow the steps below:

*

*Set up your Magento 2.4 instance with one website and one store view.

*Create the additional domains that you want to use for each functionality (e.g., myacountabc.test, mycatalogabc.test, mycartabc.test).

*Set up your web server (e.g., Apache, Nginx) to redirect each domain to the same store view in Magento 2.4.

*In Magento 2.4, go to Stores > Configuration > General > Web.

*Under the Base URLs section, enter the base URL for each of your domains.

*Under the Store View section, select your store view and set the Secure Base URL and Unsecure Base URL for each of your domains.

*Save your changes and test each of your domains to ensure they are redirecting to the correct store view in Magento 2.4.
Note: You may also need to configure your DNS settings to point each domain to the IP address of your web server.


text:
Q: How can i add a data object of a class array to a drop down list? I have an array for type Person
Person[] Traders = GetTraders();

Person class contains data objects such as first name, last name etc.
I want to add all first names to a dropdownlist. How can i do that? I tried doing it like this, but it won't get the first names:
ddl_traders.DataSource = traders;

EDIT
Person has the following string fields: FirstName, LastName, login.
I want the dropdownlist to display FirstName, but the value has to be the logins. I'm fairly certain that is possible, although I have no idea how it can be done. Any suggestions?

A: One way:
ddl_traders.DataSource = GetTraders().OfType<Person>().Select<Person, string>(p => p.FirstName).ToList<string>();

This depends on Person having a string field called FirstName.

A: This may not be the best way, but you can just specify the field to be diplayed like:
    ddl_traders.DateSource = traders;
    ddl_traders.DataTextField = "FirstName";
    ddl_traders.DateValueField= "login";
    ddl_traders.DataBind();

This allows you to bind the full Person Object, but only display the name, and keep the login as the value.


text:
Q: Counting duplicate records within duplicate records using SQL select statement I have a table with duplicate tag_id, and  serial numbers.  How could I display a list of  distinct tag_id and the number of serial numbers related to it.   In other words, I need to know how many serial numbers each distinct tag_id has.

A: Try this query..
 SELECT YourColumn, COUNT(*) TotalCount
    FROM YourTable
    GROUP BY YourColumn
    HAVING COUNT(*) > 1
    ORDER BY COUNT(*) DESC

A: Similar to what Dyrandz had, but counting the number of serial numbers per tag id as you requested.
DECLARE @YourTable AS TABLE (
    tag_id     INT,
    serial_no  VARCHAR(100)
)

INSERT INTO @YourTable (tag_id, serial_no)
VALUES (1, 'abc'), (2, 'cde'), (3, 'def'), (1, 'xyz'), (3, 'lmn')

SELECT tag_id, COUNT(serial_no) AS TotalSerialNumbers
FROM @YourTable
GROUP BY tag_id
ORDER BY 2 DESC


text:
Q: When i run a program on eclipse, the console shows nothing until I type in something, then takes that as the first input (for scanf for example) So I just installed eclipse on windows after having too many problems with my old installation on a vm running Ubuntu.
All problems gone except for what I wrote in the title. Scanf text never comes up first, no matter which program I'm running. It shows text when I have entered all that I can enter. Let me give you an example:
#include <stdio.h>
#include <stdlib.h>

int main() {

    int number1;
    int number2;

    printf ("Type in a number \n");
    scanf ("%d", &number1);

    printf ("Type in a number \n");
    scanf ("%d", &number2);

    int number3 = number1 * number2;

    printf ("%d", number3);

    return 0;
}

Console looks like this:
2
3
Type in a number
Type in a number
6

2 and 3 I had to type in first, then the last three lines showed up. That's not how it's supposed to be is it?
Thanks for any help!

A: What seems to work is writing
setbuf(stdout, NULL);

into every main of every program. It does fix the problem, yet there's maybe another fix that's not so annoying as doing that everytime. It's not bad, but I don't get why it simply worked on another instance of eclipse but here not.


text:
Q: Initializing an object with the address of itself Is this defined in C99 and C11?
struct A
{
    struct A* first;
    int value;
};

{    // inside a function
    struct A a = { &a };
    a.first->value = 123;
}

And using specifier static:
{    // inside a function
    static struct A a = { &a };
    a.first->value = 123;
}

A: This is well-defined behavior.
According to the C Standard §6.2.4 (emphasis mine):

An object exists, has a constant address, and retains its last-stored value throughout its lifetime.

The lifetime of the non-static struct begins with the entry into the block in which it is declared (known as automatic storage duration):

For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way.

And if, in the block with which the declaration is associated, you specify an initialization:

[the initialization] is performed each time the declaration is reached in the execution of the block; otherwise, the value becomes indeterminate each time the declaration is reached.

So upon entering the block, the struct has guaranteed storage and a constant address that you are free to use in an initialization for that struct, since the initialization is guaranteed to happen after the lifetime of the struct has started.
For the static struct,

Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

So the struct has guaranteed storage and a constant address as soon as program execution starts, and its stored value is initialized during that lifetime but prior to the standard execution protocol (calling main(), etc).
Source: C99 draft. The C11 literature for these references is identical.
Here's a demo. This compiles without warnings under -std=c99 -pedantic and -std=c11 -pedantic.


text:
Q: The size of picturebox is different than what was initialized as Just for testing I have created a new windows forms project with a picturebox on the form and changed the size of it to 100x100. This is the InitializeComponents function:
private void InitializeComponent()
{
    this.pictureBox1 = new System.Windows.Forms.PictureBox();
    ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
    this.SuspendLayout();
    //
    // pictureBox1
    //
    this.pictureBox1.Location = new System.Drawing.Point(13, 13);
    this.pictureBox1.Name = "pictureBox1";
    this.pictureBox1.Size = new System.Drawing.Size(100, 100);
    this.pictureBox1.TabIndex = 0;
    this.pictureBox1.TabStop = false;
    //
    // Form1
    //
    this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.ClientSize = new System.Drawing.Size(800, 450);
    this.Controls.Add(this.pictureBox1);
    this.Name = "Form1";
    this.Text = "Form1";
    this.Load += new System.EventHandler(this.Form1_Load);
    ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
    this.ResumeLayout(false);

}

This is my From1_Load function:
private void Form1_Load(object sender, EventArgs e)
{
    MessageBox.Show(pictureBox1.Size.ToString());
}

And this is what I get when I run the app:

Why do I get width=67 height= 65 when it is clear in init that it was meant to be 100x100?
My monitor res is 3840x2160 with change of size of text as 125% Tweaking these settings do not change the result.

A: Add an image reference.
pictureBox1.Image = Properties.Resources.myImage;

See what happens then, I just need more information to help...


text:
Q: Memcached - Connection refused I tried a simple test with memcached from jelastic and always getting the exception "COnnection refused"... But the URL ist correct. Is some add
    MemcachedClient c = new MemcachedClient(
            new InetSocketAddress("memcached-myexample.jelastic.dogado.eu", 11211));

    c.set("someKey", 3600, user);

    User cachedUser = (User) c.get("someKey");

Here is the exception:
2014-01-02 00:07:41.820 INFO net.spy.memcached.MemcachedConnection:  Added {QA sa=memcached-myexample.jelastic.dogado.eu/92.51.168.106:11211, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue
2014-01-02 00:07:41.833 WARN net.spy.memcached.MemcachedConnection:  Could not redistribute to another node, retrying primary node for someKey.
2014-01-02 00:07:41.835 WARN net.spy.memcached.MemcachedConnection:  Could not redistribute to another node, retrying primary node for someKey.
2014-01-02 00:07:41.858 INFO net.spy.memcached.MemcachedConnection:  Connection state changed for sun.nio.ch.SelectionKeyImpl@2dc1482f
2014-01-02 00:07:41.859 INFO net.spy.memcached.MemcachedConnection:  Reconnecting due to failure to connect to {QA sa=memcached-myexample.jelastic.dogado.eu/92.51.168.106:11211, #Rops=0, #Wops=2, #iq=0, topRop=null, topWop=Cmd: set Key: someKey Flags: 1 Exp: 3600 Data Length: 149, toWrite=0, interested=0}
java.net.ConnectException: Connection refused
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:735)
    at net.spy.memcached.MemcachedConnection.handleIO(MemcachedConnection.java:629)
    at net.spy.memcached.MemcachedConnection.handleIO(MemcachedConnection.java:409)
    at net.spy.memcached.MemcachedConnection.run(MemcachedConnection.java:1334)

A: I would try to telnet to your memcached cluster in order to rule out a firewall issue. You can do that with the following command.
telnet memcached-myexample.jelastic.dogado.eu 11211

If that doesn't work then you have network issues. If this is the case I would first check to see if you have a firewall up.

A: Add int portNum = 11211; at the first, and try again.
int portNum = 11211;
MemcachedClient c = new MemcachedClient(
new InetSocketAddress("memcached-myexample.jelastic.dogado.eu", portNum));

// Store a value (async) for one hour
c.set("someKey", 3600, someObject);
// Retrieve a value (synchronously).
Object myObject=c.get("someKey");

A: Thanks but the error was on a firewall rule from the provider. So not my failure.

A: Check /etc/memcached.conf file and update the server IP address from which you want to access the cache.


text:
Q: Rendering of pop up window is different in IE8 and IE9 using ExtJS I had a issue of a Pop Up box not showing completely when the main browser root element is reduced in size i.e. so the pop up window is not completely visible, because of the small window. If you go to maximize the main browser window, the pop up expands with the screen and remains as if the window were still shrunken, but only larger.
I therefore modified the code to center the pop up window. Though this approach works in IE8, it does not work in IE9, and newly installed Chrome. Though repair fix in Chrome works, and it works perfectly in Firefox. Anyway to fix this issue in IE9 and Chrome.
Below is the code refernce:
openPopUp: function (width, height, title, actionName, popupClass, popupClosable) {
    var parentIsPopup = DCT.Util.getSafeElement('_popUp').value;
    DCT.Util.getSafeElement('_popUp').value = '1';
    var interviewPopup = new DCT.PopupWindow({
        width: width,
        height: height,
        modal: true,
        title: title,
        cls: (Ext.isEmpty(popupClass)) ? null : popupClass,
        closable: popupClosable,
        dctAssignFocus: true,
        dctInterview: true,
        dctItemClass: DCT.InterviewPanel,
        dctParentIsPopup: parentIsPopup,
        dctPanelConfig: {
            dctParentIsPopup: parentIsPopup,
            dctActionName: actionName
        }
    });
    interviewPopup.show();
    Ext.getCmp('dctPopupWindow').center(); // this was the line added by me
},

Thanks In Advance.


text:
Q: How often do you use pseudocode in the real world? Back in college, only the use of pseudo code was evangelized more than OOP in my curriculum. Just like commenting (and other preached 'best practices'), I found that in crunch time psuedocode was often neglected. So my question is...who actually uses it a lot of the time? Or do you only use it when an algorithm is really hard to conceptualize entirely in your head? I'm interested in responses from everyone: wet-behind-the-ears junior developers to grizzled vets who were around back in the punch card days.
As for me personally, I mostly only use it for the difficult stuff.

A: I use pseudocode when away from a computer and only have paper and pen. It doesn't make much sense to worry about syntax for code that won't compile (can't compile paper).

A: I almost always use it nowadays when creating any non-trivial routines.  I create the pseudo code as comments, and continue to expand it until I get to the point that I can just write the equivalent code below it.  I have found this significantly speeds up development, reduces the "just write code" syndrome that often requires rewrites for things that weren't originally considered as it forces you to think through the entire process before writing actual code, and serves as good base for code documentation after it is written.

A: I and the other developers on my team use it all the time. In emails, whiteboard, or just in confersation. Psuedocode is tought to help you think the way you need to, to be able to program. If you really unstand psuedocode you can catch on to almost any programming language because the main difference between them all is syntax.

A: If I'm working out something complex, I use it a lot, but I use it as comments.  For instance, I'll stub out the procedure, and put in each step I think I need to do.  As I then write the code, I'll leave the comments: it says what I was trying to do.
procedure GetTextFromValidIndex (input int indexValue, output string textValue)
// initialize
// check to see if indexValue is within the acceptable range
//    get min, max from db
//    if indexValuenot between min and max
//       then return with an error
// find corresponding text in db based on indexValue
// return textValue
   return "Not Written";
end procedure;

A: I've never, not even once, needed to write the pseudocode of a program before writing it.
However, occasionally I've had to write pseudocode after writing code, which usually happens when I'm trying to describe the high-level implementation of a program to get someone up to speed with new code in a short amount of time. And by "high-level implementation", I mean one line of pseudocode describes 50 or so lines of C#, for example:

Core dumps a bunch of XML files to a folder and runs the process.exe
  executable with a few commandline parameters.

The process.exe reads each file
    Each file is read line by line
    Unique words are pulled out of the file stored in a database
    File is deleted when its finished processing

That kind of pseudocode is good enough to describe roughly 1000 lines of code, and good enough to accurately inform a newbie what the program is actually doing.
On many occasions when I don't know how to solve a problem, I actually find myself drawing my modules on a whiteboard in very high level terms to get a clear picture of how their interacting, drawing a prototype of a database schema, drawing a datastructure (especially trees, graphs, arrays, etc) to get a good handle on how to traverse and process it, etc.

A: I use it when explaining concepts.  It helps to trim out the unnecessary bits of language so that examples only have the details pertinent to the question being asked.
I use it a fair amount on StackOverflow.

A: I don't use pseudocode as it is taught in school, and haven't in a very long time.
I do use english descriptions of algorithms when the logic is complex enough to warrant it; they're called "comments". ;-)
when explaining things to others, or working things out on paper, i use diagrams as much as possible - the simpler the better

A: Steve McConnel's Code Complete, in its chapter 9, "The Pseudocode Programming Process" proposes an interesting approach: when writing a function longer than a few lines, use simple pseudocode (in the form of comments) to outline what the function/procedure needs to do before writing the actual code that does it. The pseudocode comments can then become actual comments in the body of the function.
I tend to use this for any function that does more than what can be quickly understood by looking at a screenful (max) of code. It works specially well if you are already used to separate your function body in code "paragraphs" - units of semantically related code separated by a blank line. Then the "pseudocode comments" work like "headers" to these paragraphs.
PS: Some people may argue that "you shouldn't comment what, but why, and only when it's not trivial to understand for a reader who knows the language in question better then you". I generally agree with this, but I do make an exception for the PPP. The criteria for the presence and form of a comment shouldn't be set in stone, but ultimately governed by wise, well-thought application of common sense anyway. If you find yourself refusing to try out a slight bent to a subjective "rule" just for the sake of it, you might need to step back and realize if you're not facing it critically enough.

A: I use it all the time. Any time I have to explain a design decision, I'll use it. Talking to non-technical staff, I'll use it. It has application not only for programming, but for explaining how anything is done.
Working with a team on multiple platforms (Java front-end with a COBOL backend, in this case) it's much easier to explain how a bit of code works using pseudocode than it is to show real code.
During design stage, pseudocode is especially useful because it helps you see the solution and whether or not it's feasible. I've seen some designs that looked very elegant, only to try to implement them and realize I couldn't even generate pseudocode. Turned out, the designer had never tried thinking about a theoretical implementation. Had he tried to write up some pseudocode representing his solution, I never would have had to waste 2 weeks trying to figure out why I couldn't get it to work.

A: Mostly use it for nutting out really complex code, or when explaining code to either other developers or non developers who understand the system.
I also flow diagrams or uml type diagrams when trying to do above also...

A: I generally use it when developing multiple if else statements that are nested which can be confusing.
This way I don't need to go back and document it since its already been done.

A: Fairly rarely, although I often document a method before writing the body of it.
However, If I'm helping another developer with how to approach a problem, I'll often write an email with a pseudocode solution.

A: I don't use pseudocode at all.
I'm more comfortable with the syntax of C style languages than I am with Pseudocode.
What I do do quite frequently for design purposes is essentially a functional decomposition style of coding.
public void doBigJob( params )
{
    doTask1( params);
    doTask2( params);
    doTask3( params);
}
private void doTask1( params)
{
    doSubTask1_1(params);
    ...
}

Which, in an ideal world, would eventually turn into working code as methods become more and more trivial.  However, in real life, there is a heck of a lot of refactoring and rethinking of design.
We find this works well enough, as rarely do we come across an algorithm that is both: Incredibly complex and hard to code and not better solved using UML or other modelling technique.

A: I never use or used it.
I always try to prototype in a real language when I need to do something complex, usually writting unit tests first to figure out what the code needs to do.


text:
Q: Code Chunk Runs, But Will Not Knit: Error "Object Not Found" I know this is a common problem for newbs, and I've looked around, but can't seem to find the solution.
This is the code that runs fine by itself, but will not knit:
lifters100 <- x1998short %>%
  sample_n(100)

Here's the error message I'm getting:

I also know that a knit pulls from a new environment, so I tried creating the object within itself with this:
x1998short <- x1998short

But that genius plan didn't work either.
Thank you in advance.


text:
Q: How to configure Spring Cloud logging? I have a Spring Boot application with Spring Cloud components, namely org.springframework.cloud:spring-cloud-starter-aws-parameter-store-config.
The component produces logs at WARN level when the application starts which I want to suppress.
Setting a log level in the application.yml like
logging:
  level:
    org.springframework.cloud.aws.paramstore.AwsParamStorePropertySourceLocator: ERROR

did not work. Apparently its because this cloud component works at bootstrap time before the Spring Boot context starts and the application.yml is read.
How can I suppress this component logs in the best way?


text:
Q: How can I troubleshoot Sharepoint workflows? I'm a bit lost here and I can't find much documentation.

A: .NET workflows or ones created using SharePoint designer?
I've only got latter experience and they aren't really easy to debug, you really just have to do them 1 step at a time and test up to each step.
You can view the workflow state as well in SharePoint when you go to the List Settings (sorry I don't have a WSS machine to look at currently).

A: Agree with @Slace.  Make sure you create your workflows in SP Designer to be executable from the browser, even if eventually they'll only be kicked off by status changes.  That will in itself make troubleshooting easier.

A: Assuming you are talking about SharePoint Designer workflows? You can convert them into .NET workflows following these steps.
From there, you can debug them. I haven't tried it myself (yet).

A: As stated, your only real choice for debugging SharePoint Designer workflows is by either going through the painful process of converting them into .NET worklows, or doing things like writing out the History List after every single step so you can see what is failing.
However, even .NET workflows are very difficult to debug in VS2005.  In VS2008, they added the ability to more easily debug workflows developed using that environment.

A: I guess you've already seen this :-)
Troubleshoot workflow errors

A: This article has some great debugging tips for SharePoint.  It gives a good general approach to development/debugging.  Here are a few of the tools that are referenced:

*

*Reflector

*Fiddler

*DebugView (in fact all of the SysInternals tools)

*IE Dev Toolbar

*XsltMajic

*WinDbg

A: No one mentioned the obvious resource for SharePoint Debugging -- the ULS logs.  A ULS viewer filtered on a level of "unexpected" will usually show you the logged cause for the failure.


text:
Q: Facebook App canvas Page not loading I keep getting this error when I try to use my app I created for Facebook. When I go the the url for the app it take me to the login page, but when I log in I get a pop up box with the error.

App Not Setup: The developers of this app have not set up this app
  properly for Facebook Login.

Every time I click ok it just reloads the popup again.
I have already changes the satatus to Live under status and review in my dashboard.
When I log into my account on facebook, it works fine, but I suppose this is because I am set as an admin for the app on the dashboard.
But other users get the problem above.
The code used:
require_once('facebook-php-sdk/src/facebook.php');

        $facebook= new Facebook(array(
          'appId' => $this->config->item('app_id'),
              'secret' => $this->config->item('app_secret'),
              'allowSignedRequest' => true,
        ));

        $_REQUEST += $_GET;
        $user = $facebook->getUser();

        if ($user) {
          try {

            $user_profile = $facebook->api('/me?fields=picture.width(100).height(100),first_name,last_name,username,email');

          } catch (FacebookApiException $e) {
            $user = null;
          }
        } else {
           $login_url = $facebook->getLoginUrl(array(
                'scope' => 'email'
            ));

           redirect($login_url, 'refresh');
        }

This code is in my controller of my codeigniter application which I built the app.
How do I fix this?
UPDATE:
After I added the app as a canvas app this error seemed to go away, however there is still a problem.
I added the Facebook app platform and entered the canvas url, secure canvas url etc.
When I go to the app at the canvas page https://apps.facebook.com/MyApp/ - it work fine as I am a app administrator I guess.
However when an external user goes to the canvas page it just remain blank, but if a user goes to the canvas url http://apps.mydomain.com/MyAPP the app asks for their permissions and works fine as a website.
It just remains blank to users on the canvas page. Why doesn't the canvas page ask for permission?
Help Please.
EDIT:
require_once('facebook-php-sdk/src/facebook.php');

        $facebook= new Facebook(array(
          'appId' => $this->config->item('app_id'),
              'secret' => $this->config->item('app_secret'),
              'allowSignedRequest' => true,
        ));

        $_REQUEST += $_GET;
        $user = $facebook->getUser();

        if ($user) {
          try {

            $user_profile = $facebook->api('/me?fields=picture.width(100).height(100),first_name,last_name,username,email');

          } catch (FacebookApiException $e) {
            $user = null;
          }
        } else {
           $login_url = $facebook->getLoginUrl(array(
                'scope' => 'email'
            ));

           require_once('facebook-php-sdk/src/facebook.php');

    $facebook= new Facebook(array(
      'appId' => $this->config->item('app_id'),
          'secret' => $this->config->item('app_secret'),
          'allowSignedRequest' => true,
    ));

    $_REQUEST += $_GET;
    $user = $facebook->getUser();

    if ($user) {
      try {

        $user_profile = $facebook->api('/me?fields=picture.width(100).height(100),first_name,last_name,username,email');

      } catch (FacebookApiException $e) {
        $user = null;
      }
    } else {
       $login_url = $facebook->getLoginUrl(array(
            'scope' => 'email'
        ));

        echo("<script> top.location.href='" . $login_url . "'</script>");
        }

A:
Why doesn't the canvas page ask for permission?

Because you are redirecting inside of the iframe, but the FB login dialog does not want to be displayed in (i(frames) – for the obvious reason, that that would lead to a lot of phishing, since users are supposed to see that the page they are entering their login credentials too is actually the real FB site.
So you have to redirect within the top window instance, via JavaScript:
top.location.href = '…';


text:
Q: Possible to use a different set of hooks for a user or group in Mercurial? I am not sure if this is possible currently but is it possible to specify a separate set of hooks for a user or group (groups from the ACL extension).
I know you can specify the hooks on each user's machine individually but I would like to also place the hooks on the central repo (so that those hooks are ran when they push).
For example
say I have hooks for group A
[hooks]
pretxngroupchange.A=python:Group-A-hook.py:hook

for all of group A
and
[hooks]
pretxngroupchange.B=python:Group-B-hook.py:hook

If someone from group A pushes, I don't want the hooks for group B to be triggered
Is this possible?  Even if I can't do it by groups (which I think Mercurial should pick up Os-level groups), is it possible for Hg to run it per user?

A: You could use a single script which looks up users by name and performs a different activity based on the user. In order to avoid having to update the script for new users, you could revision a user list in an Hg repo and read the latest version of the repo inside this hook.
I'm not sure that this qualifies as a "good idea", but it might work if you can't find another solution.


text:
Q: Using getopt in C for command line arguments I am working on trying to take in command line arguments. If I want to have multiple optional command line arguments how would I go about doing that? For example you can run the program in the following ways:
(a is required every instance but -b -c -d can be given optionally and in any order)
./myprogram -a
./myprogram -a -c -d
./myprogram -a -d -b

I know that getopt()'s third argument is options. I can set these options to be "abc" but will the way I have my switch case set up causes the loop to break at each option.

A: The order doesn't matter so far as getopt() is concerned. All that matters is your third argument to getopt() (ie: it's format string) is correct:
The follow format strings are all equivalent:
"c:ba"
"c:ab"
"ac:b"
"abc:"

In your particular case, the format string just needs to be something like "abcd", and the switch() statement is properly populated.
The following minimal example¹ will help.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main (int argc, char **argv)
{
  int aflag = 0;
  int bflag = 0;
  char *cvalue = NULL;
  int index;
  int c;

  opterr = 0;

  while ((c = getopt (argc, argv, "abc:")) != -1)
  {
    switch (c)
      {
      case 'a':
        aflag = 1;
        break;
      case 'b':
        bflag = 1;
        break;
      case 'c':
        cvalue = optarg;
        break;
      case '?':
        if (optopt == 'c')
          fprintf (stderr, "Option -%c requires an argument.\n", optopt);
        else if (isprint (optopt))
          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
        else
          fprintf (stderr,
                   "Unknown option character `\\x%x'.\n",
                   optopt);
        return 1;
      default:
        abort ();
      }
  }

  printf ("aflag = %d, bflag = %d, cvalue = %s\n",
          aflag, bflag, cvalue);

  for (index = optind; index < argc; index++)
    printf ("Non-option argument %s\n", argv[index]);
  return 0;
}

¹Example taken from the GNU manual


text:
Q: NGINX restrict admin area on wordpress but allow wp-admin/admin-ajax.php? I have a few websites which use the following code to restrict the admin area. So far have not found a better solution than this.
##> COMMENT - WordPress Admin Area Passwords
location ^~ /wp-admin/ {
auth_basic "Restricted Access";
auth_basic_user_file /home/bea/panel/security/.htpasswd;

location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.3-fpm-website123.com.sock;
}
}

We are using a plug-in that allows users to see and under construction page but provides a login to allow website owner to view their website while it is being built. Have a look at the image below.
As you can see below the user is prompted to fill in a password to access the website but also they are prompted to fill in the username and password to access the admin area. this pop-up only comes up when the user has put in a password to access the website and clicks on "Access the site".

After contacting the plug-in creator, they suggested to exclude wp-admin/admin-ajax.php?
Or is there a better practice to follow. I have noticed from time to time that some plug-ins require access to the admin area to function correctly.
I may have found a solution:
##> COMMENT - WordPress Admin Area Password, usally for LIVE sites
location /wp-admin {
        location ~ /wp-admin/admin-ajax.php$
        {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.3-fpm-WEBSITE.tv.com.sock;
        }

        location ^~ /wp-admin/ {
        auth_basic "Restricted Access";
        auth_basic_user_file /home/user/panel/security/._htpasswd;
        }
        location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.3-fpm-WEBSITE.tv.sock;
        }
}

I just want somebody to validate the code above and check that it is secure? I'm still willing to offer a bounty to validate its level of security.

A: After playing around for many hours I have found a working solution but I am not quite sure if it is secure?
location /wp-admin {
        location ~ /wp-admin/admin-ajax.php$
        {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.3-fpm-WEBSITE.tv.com.sock;
        }

        location ^~ /wp-admin/ {
        auth_basic "Restricted Access";
        auth_basic_user_file /home/user/panel/security/._htpasswd;
        }
        location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.3-fpm-WEBSITE.tv.sock;
        }
}

But it is a working solution

A: I think something like below should do the job for you
location ^~ /wp-admin/ {
   auth_basic "Restricted Access";
   auth_basic_user_file /home/bea/panel/security/.htpasswd;

   location ~ \.php$ {
      include snippets/fastcgi-php.conf;
      fastcgi_pass unix:/var/run/php/php7.3-fpm-website123.com.sock;
   }
}

location = /wp-admin/admin-ajax.php {
   include snippets/fastcgi-php.conf;
   fastcgi_pass unix:/var/run/php/php7.3-fpm-website123.com.sock;
}


text:
Q: Reanimated crashed the App while using useAnimatedStyle I'm trying to animate a card's border radius and shadow opacity but instantly closes on IOS. I'm not sure if I'm using reanimated correctly though. I feel like there is crucial mistake I'm making. Here is the code.

   const anim = loop({
      autoStart: true,
      duration: 1750,
      easing: EasingNode.inOut(EasingNode.ease),
    });

  const riskCardStyle = useAnimatedStyle(() => {
    const borderRadius = Animated.interpolateNode(anim, {
      inputRange: [-1, 0, 1],
      outputRange: [30, 0, 30],
      extrapolate: Extrapolate.CLAMP,
    });
    const shadowOpacity = Animated.interpolateNode(anim, {
      inputRange: [-100, 0, 100],
      outputRange: [1, 0, 1],
      extrapolate: Extrapolate.CLAMP,
    });
    return {
      backgroundColor: Colors.white,
      flex: 1,
      position: 'relative',
      borderTopLeftRadius: borderRadius,
      borderTopRightRadius: borderRadius,
      shadowColor: 'rgba(168, 179, 255, 0.4)',
      shadowOffset: {
        width: 0,
        height: -3,
      },
      shadowRadius: 20,
      shadowOpacity,
    };
  });

thanks in advance


text:
Q: How to connect to wifi using nmcli with a static IP address and password? There is info on how to connect to ethernet(eth0) with nmcli using a static IP, but nothing on how to connect to wifi (wlan0)?
This sets up a connection profile but how to add the password and actually bring up the connection?
nmcli con add con-name "mySSID" ifname wlan0 type wifi ssid "mySSID" ip4 192.168.100.101

A: NOTE: The following is only guaranteed to work with nmcli v1.22 (because that's what version I have), the latest is probably very similar but, in my case there's a random -- required; it is in the documentation specified for that command. Check your version with nmcli -v then check the specific documentation here >>Network Manager (after you click your version click the nmcli link)
I.e., for Version 1.2
nmcli con add con-name "&%TEST%&" type wifi ifname mlan0 ssid "&%SSIDNAME%&" -- wifi-sec.key-mgmt wpa-psk wifi-sec.psk "&%PASSPHRASE%&" ipv4.method manual ipv4.address 192.168.1.51/16 ipv4.dns 8.8.8.8,8.8.8.4 ipv4.gateway 192.168.1.1
Then
nmcli con up "&%TEST%&"
However, it may be more wise to ignore the con-name because you can have multiple connections with the same name.  (Luckily nmcli con delete "&%TEST%& deletes all of those at once!)
You could use the uuid instead.
find it by nmcli con show
then connect using
nmcli con up uuid 1c86c960-8533-11e7-bb31-be2e44b06b34
(*your uuid will not be the same...)


text:
Q: ¿Cómo asigno un nombre al exportar una tabla a Excel desde C# devexpress? Quiero que al exportar un Excel, también pueda asignar un nombre a la tabla que envío.
try
     {
       ClassResultPV cr;
         {
                    CtrTareo ctr = new CtrTareo();
                    cr = ctr.Pln_CargarDiasConceptuales(new DtoTareo()
                    {
                        RucE = Globales.RucEmp,
                        Ejer = Globales.EjeEmp,
                        Prdo = Globales.Prdo,
                        TipPlan = Globales.TipoPlanilla == TipPlanilla.Empleados ? "E" : "O",
                        Sem = Globales.TipoPlanilla == TipPlanilla.Empleados ? null : Globales.Semana,
                        Usu = Globales.UsuActual,
                        Cd_ModContrato = chkModContrato.Visible == true ? HelpPV.ObtenerCodidoStr_CheckedComboBoxEdit(chkModContrato, ',') : null
                    });
                    dtdc = cr.DT;
                    gcDiasConcep.DataSource=dtdc;
                }
                try
                {
                    Utiles.ExportarGridDevExpress(gvDiasConcep, "Formato de Importación Días Conceptuales", ExportXtraGrid.Export,true);
                    //List<GridControl> ogrid = new List<GridControl>();
                    //ogrid.Add(gcDiasConcep);
                    //List<String> otits = new List<String>();
                    //otits.Add("Formato de Importación Días Conceptuales");
                    //List<StringAlignment> lSA = new List<StringAlignment>();
                    //lSA.Add(StringAlignment.Near);

                    //Utiles.ExportarGridExcel(ogrid.ToArray(), otits.ToArray(), lSA.ToArray(), "Formato de Importación Días Conceptuales", false);

                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {

            }

A: Al parecer el codigo que exporta a excel, lo tienes dentro del método "Utiles.ExportarGridDevExpress".
Necesitarías poner el código de ese método, para ver como exportas el excel.


text:
Q: Why I can't use let in protocol in Swift? I have a doubt about protocols in Swift about the use of var and the keywords { get set }.
From Apple documentation:

If a protocol requires a property to be gettable and settable, that
  property requirement cannot be fulfilled by a constant stored property
  or a read-only computed property. If the protocol only requires a
  property to be gettable, the requirement can be satisfied by any kind
  of property, and it is valid for the property to be also settable if
  this is useful for your own code.
Property requirements are always declared as variable properties,
  prefixed with the var keyword. Gettable and settable properties are
  indicated by writing { get set } after their type declaration, and
  gettable properties are indicated by writing { get }.

I can't understand why I can't use let. A var in a protocol with only get isn't just a let?
Something like this:
protocol someProtocol
{
   var someProperty: String { get }
}

it would not be just:
protocol someProtocol
{
   let someProperty: String
}

I'm missing something?

A: "A var in a protocol with only get isn't just a let?" No. A let indicates a constant. But that is not the case here. Consider the following:
protocol SomeProtocol {
    var someProperty: String { get }
}

class SomeClass : SomeProtocol {

    var someProperty: String = ""

    func cla () {
        someProperty = "asd"
    }
}

let someInstance = SomeClass()

print(someInstance.someProperty) // outputs ""
someInstance.cla()
print(someInstance.someProperty) // outputs "asd"

The protocol specifies what the conforming class shows to the outside - some property of type String named someProperty which you can at least get.
If the protocol specifies { get } your class can choose to conform via let someProperty: String = "" but it can similarly choose to conform via the above code. If on the other hand the protocol specifies { get set } you cannot use let in the implementation but have to make it set-able as well.
A protocol simply cannot define that a value has to be constant - neither should it, that is an implementation detail that has to be taken care (or decided about) by the class / struct that implements it.

A: The difference is between
protocol MyProtocol {
    let someProperty: String
}

which makes no sense — a protocol isn't supposed to dictate how someProperty is defined/stored, only that it's available as a property. It could be either a computed or stored property, but that's for the implementer to decide, not the protocol itself.
and
protocol MyProtocol {
    var someProperty: String { get }  // abstract interface
}

struct MyStruct: MyProtocol {
    let someProperty: String  // concrete implementation: stored property
}

struct OtherStruct: MyProtocol {
    let i: Int
    var someProperty: String { return "\(i)" }  // concrete implementation: computed property
}

which is perfectly allowed!

A: I think a protocol can require that a structure has something, but it can't restrict functionality of struct or object. That shouldn't prevent you from doing what you'd probably like to do in code, for example using a var in the protocol and a let for the implementation is acceptable.
protocol MyProtocol {
    var trythis: Int { get }
}

struct MyStructure: MyProtocol {
    let trythis: Int
}

A: A property declared with let is considered read-only under the hood. For this reason, a protocol can require that a property be a constant by setting it read-only. This deduction can be verified using some of the Objc runtime functions  property_getAttributes.
protocol SomeProtocol {
    var someTypeProperty: Int { get }
}

struct Foo: SomeProtocol {
    let someTypeProperty: Int
}


text:
Q: Symfony default locale without specifying in URL I would like to configure the Symfony locale options so that I can successfully access the following routes:
/route
/{locale}/route

Currently, I can access /{locale}/route and I get my view, however, /route returns a No route found for "GET /route".  My configuration is as follows:
#app/config/parameters.yml
parameters:
    locale: en

#app/config/config.yml
parameters:
    app_locales: en|fr
framework:
    translator: { fallback: "%locale%" }
    default_locale: "%locale%"

#app/config/routing.yml
app:
    resource: '@AppBundle/Controller/'
    type: annotation

My Controller has the following annotations:
#src/AppBundle/Controller/Admin/MyController.php
/**
 *
 * @Route(
 *     "/{_locale}/admin/my",
 *     defaults={"_locale":"%locale%"},
 *     requirements={"_locale":"%app_locales%"}
 *     )
 */
class MyController extends Controller
{
    /**
     * @Route("/", name="admin_my_list")
     * @Method("GET")
     */
    public function listAction()
    {
        ...
    }
}

If I specifically include the locale, it all works.  If I exclude the locale, I get the No route found error.

A: You have to define another route to cover the scenario without the provided locale, try changing your route definition to:
#src/AppBundle/Controller/Admin/MyController.php

class MyController extends Controller
{
    /**
     * @Route(
     *     "/admin/my",
     *     defaults={"_locale":"%locale%"},
     *     )
     * @Route(
     *     "/{_locale}/admin/my",
     *     requirements={"_locale":"%app_locales%"}
     *     )
     * @Method("GET")
     */
    public function listAction()
    {
        ...
    }
}

A: I agree with what Boris commented up there.
An alternative solution about making a RouteMatcher is to use EventListener and redirect user into same route with the default Locale (Check the answer that has more upvotes)
In my opinion doing this with EventListeners like Athlan explained there is the way to go. I would not mess with making your own RouteMatcher.
Just see what lordrhodos wrote, never tried to put two routes like this in a Controller annotations, but I think if you have only one Controller is the way to go. If they are going to be a lot might be a lot cleaner to do this with EventListeners in only one place.


text:
Q: How to handle GitHub search API rate limits I'm building an automated script to do some recurring search using GH search API. However I hit the "Secondary" rate limit sometimes. For referece I'm using github3.py library.
So my workaround so far is to check the rate limit before each search request like this:
for term in SEARCH_TERMS:
    self.check_rate_limit()
    result = gh.search_code(term)

    while True:
        try:
            self.check_rate_limit()  # it checks gh.rate_limit() if ["resources"]["search"]["remaining"] is lower (but it seems it's not being hit)
            item = next(result)

            # process...

            time.sleep(2)  # This helps a bit but I still hit the secondary rate limit
        except ForbiddenError:
            logging.error("(Secondary) Rate limit reached.")
            time.sleep(120)  # sleep 2 minutes but it continues to next iteration
        except StopIteration:
            break

But it never reaches the sleep condition. Instead, after the search query and while iterating the generator results, sometimes I get a github3.exceptions.ForbiddenError because of the secondary rate limit. The probability of raising that error decreases when I force a time.sleep(2) on each result iteration, but that doesn't seem right to me. I tried to understand more about the secondary rate limit but I couldn't find a clear explanation in the documentation. Am I missing something?

A: In GitHub docs it is defined as "Rate Limit" and is stated there:
"The Search API has a custom rate limit. For requests using Basic Authentication, OAuth, or client ID and secret, you can make up to 30 requests per minute. For unauthenticated requests, the rate limit allows you to make up to 10 requests per minute." (https://docs.github.com/en/rest/search)
So having some sleep time between the searches does seem reasonable here.