text:
Q: Exchange Web Services Schema Validation Error I'm sending a SOAP request to Exchange Web Services but I'm getting an error response back from the server. It seems to point to a schema validation issue, something wrong in my request. However, this request works fine in Exchange 2016 but doesn't seem to work in Exchange 2007.
This is my request to .../EWS/Exchange.asmx:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:ns2="http://schemas.microsoft.com/exchange/services/2006/messages">
  <SOAP-ENV:Header>
    <ns1:RequestServerVersion Version="Exchange2007_SP1" />
  </SOAP-ENV:Header>
  <SOAP-ENV:Body>
    <ns2:FindItem Traversal="Shallow">
      <ns2:ItemShape>
        <ns1:BaseShape>AllProperties</ns1:BaseShape>
        <ns1:AdditionalProperties>
          <ns1:ExtendedFieldURI PropertySetId="c2dd7db7-7f7f-42cf-bbf7-7384836b0c89" PropertyName="CRMID" PropertyType="Integer" />
        </ns1:AdditionalProperties>
      </ns2:ItemShape>
      <ns2:Restriction>
        <ns1:Or>
          <ns1:IsEqualTo>
            <ns1:ExtendedFieldURI PropertySetId="c2dd7db7-7f7f-42cf-bbf7-7384836b0c89" PropertyName="CRMID" PropertyType="Integer" />
            <ns1:FieldURIOrConstant>
              <ns1:Constant Value="11290" />
            </ns1:FieldURIOrConstant>
          </ns1:IsEqualTo>
        </ns1:Or>
      </ns2:Restriction>
      <ns2:ParentFolderIds>
        <ns1:DistinguishedFolderId Id="calendar" />
      </ns2:ParentFolderIds>
    </ns2:FindItem>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

This is the response I'm getting:
<?xml version="1.0"?>
<soap11:Envelope xmlns:soap11="http://schemas.xmlsoap.org/soap/envelope/">
    <soap11:Header>
        <t:ServerVersionInfo MajorVersion="8" MinorVersion="1" MajorBuildNumber="436" MinorBuildNumber="0" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" />
    </soap11:Header>
    <soap11:Body>
        <soap11:Fault>
            <faultcode>soap11:Client</faultcode>
            <faultstring>The request failed schema validation: The element 'Or' in namespace 'http://schemas.microsoft.com/exchange/services/2006/types' has incomplete content. List of possible elements expected: 'SearchExpression' in namespace 'http://schemas.microsoft.com/exchange/services/2006/types'.</faultstring>
            <detail>
                <e:ResponseCode xmlns:e="http://schemas.microsoft.com/exchange/services/2006/errors">ErrorSchemaValidation</e:ResponseCode>
                <e:Message xmlns:e="http://schemas.microsoft.com/exchange/services/2006/errors">The element 'Or' in namespace 'http://schemas.microsoft.com/exchange/services/2006/types' has incomplete content. List of possible elements expected: 'SearchExpression' in namespace 'http://schemas.microsoft.com/exchange/services/2006/types'.</e:Message>
                <e:Line xmlns:e="http://schemas.microsoft.com/exchange/services/2006/errors">22</e:Line>
                <e:Position xmlns:e="http://schemas.microsoft.com/exchange/services/2006/errors">11</e:Position>
            </detail>
        </soap11:Fault>
    </soap11:Body>
</soap11:Envelope>

I'm having trouble finding any information about the http://schemas.microsoft.com/exchange/services/2006/types namespace and I don't know what to change in my request for it to work correctly.
Does anyone know how I can change my request to resolve the error?


text:
Q: powershell - Grab specific info from array issue I have a small script that will help users in our environment shadow the sessions from other users in the facilities (I work at the corporate office, corporate users need the ability to shadow other user's sessions along different sites)
So I've got this:
$servers = "server1, server2, server3, server4, server5"

#search for user in servers farm
foreach ($server in $servers) {

$results = & qwinsta.exe $userid /server:$server

    if ($results -ne $null) {

        write-host "User found in $server"

        $serverfound = $server

        write-host $results[1]

        $sessionid = $results[1] | Where-Object { $_ -is 0..99}

        write-host "Session ID is: $sessionid"
    }
}

However, I can't get it to grab the session id from the result, this is the output of the script:

Please wait while we search for x2adm on the RDSfarm Servers
User found in server5
rdp-tcp#0         x2adm                2  Active
Session ID is:

I am trying to simply grab the number in the output and assign it to $sessionid so that I can fully automate the shadowing process.
Any help will be appreciated. Thanks in advance.

A: I would recommend you use ConvertFrom-String instead.  It's awesome for parsing data like this.
ConvertFrom-String $results[1]

P1 :
P2 : console
P3 : Stephen
P4 : 1
P5 : Active
P6 :

So our $SessionID value would be found in p4 (P# is just an arbitrary name that this cmdlet gives to the strings it finds).
The full command would be
$sessionID = convertfrom-string $results[1] | select -expand P4

This will work with your current code with no further modifications.

A: Check the data type of $servers and you will see that it is a string and not a string array which is how you are treating it.
PS C:\Users\matt> $servers = "server1, server2, server3, server4, server5"
PS C:\Users\matt> $servers.GetType().FullName

System.String

You can read more about the basic concepts of arrays from about_arrays You need to define it like this.
$servers = "server1", "server2", "server3", "server4", "server5"

As far as dealing with output from qwinsta I have an answer that converts data from that into a PowerShell object. Might not need to be that extreme since you are not using the exact same command that the Op of the linked question was. Point being is that ConvertFrom-StringData is a powerful cmdlet.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding Event Listener to an array Im trying to do homework assignment and confused why I'm getting error message(undefined is not an object (evaluating 'buttons[i].style'))
any help appreciated Ive been trying to loop through the buttons array and add an Event Listener to each item in the list
var buttons = document.getElementsByClassName("quality");
for(var i = 0; i < buttons.length; i += 1){
buttons[i].addEventListener('click', function (i) {
    buttons[i].style.background = "red";
});
}

<!doctype html>

 <title>L.A. Hiking</title>
 <link rel="stylesheet" href="css/hiking.css">

Home

Contact

About

Pick one:

Hard

Medium

Easy

Pick one:

Hard

Medium

Easy

Pick one:

Hard

Medium

Easy

Pick one:

Hard

Medium

    <button>Go!</button>

A: The callback for addEventListener doesn't give you the index of the button clicked but an event object. You can then access the button using event.target:
for(var i = 0; i < buttons.length; i += 1){
    buttons[i].addEventListener('click', function (e) {
        e.target.style.background = "red";
    });
}

As per @Sgnl:

since you are binding to the event to the object itself you could also
  use context aka this so e.target.style.background = "red"; becomes
  this.style.background = "red";

for(var i = 0; i < buttons.length; i += 1){
    buttons[i].addEventListener('click', function () {
        this.style.background = "red";
    });
}

A: *

*document.getElementsByClassName("quality"); returns the collection of all the elements matching the class name quality in a NodeList object. From the code you posted, it seems that you are having the listitem and not the button element for the quality class name.

*More importantly, the addEventListener callback would pass in the event information in the parameter to the callback. The property event.target returns the element on which the event was registered, which in this case is the listItem[i]. So, you need to use the e.target as e.target.style.background = "red";

var listItems = document.getElementsByClassName("quality");
for(var i = 0; i < listItems.length; i += 1){
listItems[i].addEventListener('click', function (e) {
    e.target.style.background = "red";
});
}

 <title>L.A. Hiking</title>
 <link rel="stylesheet" href="css/hiking.css">

Home

Contact

About

Pick one:

Hard

Medium

Easy

Pick one:

Hard

Medium

Easy

Pick one:

Hard

Medium

Easy

Pick one:

Hard

Medium

    <button>Go!</button>

A: In addition to everyone suggesting attaching an event to each li.quality element, you could also consider this pattern.
You can attach one event to the parent element (instead of having an event listener for each li.quality element) by taking advantage of Event Bubbling (see SO post here).

let selectionsElement = document.querySelector('#selections');

selectionsElement.addEventListener('click', function(event) {
  // stop event from bubbling further up the DOM tree
  event.stopPropagation();

  /*
    the `this` keyword will refer to the #selections element
    so we can't use it with this approach so we'll have to use `event`
  */

  // check if the element which triggered the event is li.quality
  if (event.target.classList.contains('quality')) {
    event.target.style.backgroundColor = 'red';
  }
});

 <title>L.A. Hiking</title>
 <link rel="stylesheet" href="css/hiking.css">

Home

Contact

About

Pick one:

Hard

Medium

Easy

Pick one:

Hard

Medium

Easy

Pick one:

Hard

Medium

Easy

Pick one:

Hard

Medium

    <button>Go!</button>


text:
Q: how to retrieve any inserted string in input type 'number' in html Is there any way of getting the inserted string(of any sort) from:
<input type="number" id='zipCode' name='zipcode' />

I'm trying to get value in console as:
console.log(document.getElementbyId('zipCode').value);

is giving just a blank output when any invalid string(string containing any alphabet or other special characters) is inserted which is also the same when actually left the field blank. But I want to retrieve the actual inserted value so that I can differentiate and validate the blank field with error message "Zipcode Field Empty!" and on invalid character string with error message "Invalid Zipcode!". Is there any way to retrieve any sort of inserted string from input type='number' field?

A: HTML input fields used for Zip Codes should be type=text and use the pattern attribute to provide hints to the browser
A numeric ZIP code is -- in a small way -- misleading.
Numbers should mean something numeric. ZIP codes don't add or subtract or participate in any numeric operations. 12309 - 12345 does not compute the distance from downtown Schenectady to my neighborhood.
ZIP codes aren't numbers -- they just happen to be coded with a restricted alphabet -- I suggest avoiding a numeric field. Same goes for credit card or social number
You can do <input type="text" pattern="\d*">. This will cause the numeric keyboard to appear on iOS (and Android?). Maybe it was pattern="[0-9]*"

"The semantically correct markup for a text field that can still
  contain whitespace and other special characters is <input type="text" inputmode="numeric"/> however as far as I am aware while inputmode is
  recommended by WhatWG it is not yet supported by any browsers. Its
  intent is to present the user with a numeric keypad on a device that
  has it but still behave as a text input." - davidelrizzo

A: From what I remember reading (example here - HTML5 input type=number value is empty in Webkit if has spaces or non-numeric characters?) there is no way of doing this with the input type set to number.


text:
Q: Is there any LTRIM function for MS ACCESS 2007? i am trying to ltrim 3 or 4 zeros from a column in Access 2007 but not getting any result where the data-type is text(from a csv data).

A: From what I read, MS Access in fact should support LTRIM.  Here is a workaround in case you need it:
SELECT
    IIF(string LIKE "0000*",
        MID(string, 5),
        IIF(string LIKE "000*", MID(string, 4), string)) output
FROM yourTable;

A: Here are a couple of quickly written LTrim & RTrim functions to operate with characters other than spaces:
Function LTrimChr(strStr As String, strChr As String) As String
    If strStr Like strChr & "*" Then
        LTrimChr = LTrimChr(Mid(strStr, 2), strChr)
    Else
        LTrimChr = strStr
    End If
End Function

Function RTrimChr(strStr As String, strChr As String) As String
    If strStr Like "*" & strChr Then
        RTrimChr = RTrimChr(Left(strStr, Len(strStr) - 1), strChr)
    Else
        RTrimChr = strStr
    End If
End Function

Expects the strChr to be a single character, e.g.:
?LTrimChr("000123456789000","0")
123456789000

?RTrimChr("000123456789000","0")
000123456789

A: In case of digits only, you can use Val to strip leading zeroes:
LTrimmedValue = CStr(Val(Value))
' "000123456789000" -> "123456789000"

A: MS Access supports ltrim(), but only for spaces.  So, assuming that your string has no spaces, you can use replace() and ltrim():
select replace(ltrim(replace(col, '0', ' ')), ' ', '0')

If you do have spaces, there is often a character you don't have, so you can replace the spaces first:
select replace(replace(ltrim(replace(replace(col, ' ', '~'
                                            ), '0', ' '
                                    )
                            ), ' ', '0'
                      ), '~', ' '
              )


text:
Q: Looking for type-casting rules in JS I'm looking for a concrete set of rules as to what gets automatically typecast and when.  I'm trying to come up with some guidelines for newer devs, e.g. it just came up that:
90 > '100'   // int compare
'90' > 100   // int compare
'90' > '100' // string compare

And the only answer I could come up with as to why is "because" :)

A: Note that '026' < 24 may return true in some browsers because the string is treated as an octal number (in this case 22).
Ideally you want to always type-cast manually. Either with a = ''+a to cast to string, or a = parseInt(a,10); to cast to integer.
That should be the explanation, rather than trying to explain automatic typecasting

A: If you really want to understand what's happening, then you should read the spec:

*

*http://bclary.com/2004/11/07/#a-11.9.3
A note on the conventions in that section:

Type(x) is used as shorthand for "the type of x"


text:
Q: Is there a way to check what you are running a python program in? I want to create a script for just Terminal and IDLE, but I don't know how. Using if 'idlelib' in sys.modules: works for seeing if it is running in IDLE, but is there a way to use the same code to find if it is in Terminal by replacing 'idlelib'?

A: You can try using psutil and os
import psutil
import os
if psutil.Process(os.getpid()).parent().name() in ["cmd.exe","bash"]:
    print("in cmd")

Using idle it returned 'pythonw.exe' which shows this works.


text:
Q: How to run a exe without command prompt(GUI)? I've to run a executable, while system start-up automatically. For that I added the exe path in registry in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
      Now the exe get started fine. but the command prompt also opened. so can I run the exe with silent mode, means without GUI.
      can I do it with c++ programming language?
      Or if there is any other way to do it possibly.
Thank you

A: Do not link your application as a console application, but link it as a windows GUI application.
This way windows will not allocate a console for you, and you don't have to resort to hacks to hide it.

A: For a simple solution you can hide the Console like that :
#include <windows.h>
...
int main()
{
    HWND hWnd = GetConsoleWindow();
    ShowWindow( hWnd, SW_HIDE );
    ...
}

First you get a Handle to the Console, then you hide it


text:
Q: Auto start PuTTY from command-line with a specific startup path I start multiple PuTTY sessions everyday with a specific path in each session.
I have made a command in batch file as
Start "c:\putty.exe" abc@1.1.1.1 -pw abc123 22

How do I proceed further to open PuTTY directly in a specific remote directory.
I have 20 sessions.
Please assist.

A: You need to create a file with two commands, the directory change and the shell start, like:
cd /path
/bin/bash

Then use the command-line parameter -m to "execute" the commands. You will also want to use the -t for force TTY back as the -m disables it.
putty.exe username@example.com -pw password -t -m commands.txt

To avoid a separate command file for each sessions, just generate it from the batch file:
set SCRIPT_FILE=%TEMP%\commands.txt
echo cd /path > %SCRIPT_FILE%
echo /bin/bash > %SCRIPT_FILE%
putty.exe username@example.com -pw password -t -m %SCRIPT_FILE%

References:

*

*PuTTY command-line

*Starting PuTTY session in a specific directory

*PuTTY: Run a remote command after login & keep the shell running

If you want GUI for managing sessions with specific initial remote path, you can use WinSCP.

*

*WinSCP can work as session manager for PuTTY

*and it can be configured to open PuTTY in a specific path.

(I'm the author of WinSCP)


text:
Q: Using Formula Field Syntax In Apex I have a complicated formula field that calculates the months between a start / end date on an OpportunityProduct. This formula takes into account many edge cases, and is subsequently used in our calculation of UnitPrice.
no_of_Months__c =
(
(Year_End_Date__c * 12) /* Calculate years as Number of Months */
+ Month_End_Date__c /* Add Number of Months */
+ (
DAY(End_Date__c) /* Add Day of Month / Number of Days in Month. Returns month percentage as a Decimal */
/ DAY(DATE(
IF(Month_End_Date__c = 12, Year_End_Date__c + 1, Year_End_Date__c),
/* Can't create a date with 13 months so need to add a year if in December */
IF(Month_End_Date__c = 12, 1, Month_End_Date__c+1),
1) -1) /* Need to find number of Days in Month by taking the Day from the 1st of next month - 1 day */
)
)
- (
(Year_Start_Date__c * 12)
+ Month_Start_Date__c
+ (IF(DAY(Start_Date__c) = 1, 0, (
DAY(Start_Date__c) - 1) /* Slight Difference here to subtract a day. We want to go from Start of day on StartDate to End of Day on EndDate*/
/ DAY(DATE(
IF(Month_Start_Date__c = 12, Year_Start_Date__c + 1, Year_Start_Date__c),
IF(Month_Start_Date__c = 12, 1, Month_Start_Date__c+1),
1) -1)
)

When a new OpportunityProduct is being created on the fly, I am unable to reference this formula field for obvious reasons (the record doesn't exist yet), so I have to manually calculate the number of months and use that in the UnitPrice calculation. Is there a way to copy this formula logic into my apex class easily, or do I have to rewrite this calculation using entirely new syntax? I am not the original author of the formula, so I would like to avoid the latter if possible.

A: Try this:
someSObject.recalculateFormulas();
Source:  https://salesforce.stackexchange.com/a/96803


text:
Q: Is there a visualisation tool for async python code? I would like to improve the performance of my python code. I am measuring the performance via python3 -m cProfile -o p0.prof tool.py.
tool.py contains a lot of asyncIO and multithreaded code. I am currently using snakeviz to visualise the profile. snakeviz shows how much time a function needs. Unfortunately this is not enough for my case, since code runs in parallel in tool.py. I need something like this:
main -----------------------------
func1  -------------------
func2            ----------------------

In the timelines above you can now see that there may be potential to speed up the program by calling func2 earlier and thus ending the execution of main earlier. Like this:
main -----------------------------
func1  -------------------
func2     ----------------------

Does such a tool exist?


text:
Q: Correctly deleting the pointers of a 3D matrix I wrote a program to create a 3D matrix (or multidimensional matrix), in which all the parameters (rows, columns, all are variable). The type of matrix I am working with looks something like this:

The program is working as intended. But I don't know if deleting the pointers is correctly freeing up memory. Am I deleting the pointers correctly?
#include <iostream>

using namespace std;

int main()
{
    int  vol;
    cout << "enter number of 2d arrays(vol value)" <<endl;
    cin >> vol;
    int row[10];
    cout<< "enter number of rows in each vol" << endl;
    for (int i = 0; i < vol ; i++)
    {
        cin >> row[i];
    }

    //================ Entering col for each rown in each vol  ================//
    int **col;
    col = new int *[vol];

    for (int i = 0; i < vol ; i++)
    {
        *(col+i) = new int [row[i]];
        for (int j = 0; j < row[i] ; j++)
        {
            cout<< "enter columns of " << j << "th row " <<" of vol " << i  <<" :  ";
            cin>>*(*(col+i)+j);
        }

    }

    //======= Printing the value of each col for each rown in each vol =======//
    cout<< "entered values are \n \n" << endl;

    for (int i = 0; i < vol; i++)
    {
        for (int j = 0; j < row[i]; j++)
        {
            cout<< *(*(col + i) + j);
            cout << "\t";
        }

        cout<< "\n" << endl;
    }

    //========================Creation of 3d matrix===========================//
    int ***p;

    p = new int **[vol];            //creating number of vol
    for (int i = 0; i < vol ; i++)  //creating rows for each vol
    {
        *(p + i) = new int *[row[i]];
    }

    for (int j = 0; j < vol ; j++)  //creating 1d array for each row
    {
        for (int k = 0; k < row[j] ; k++)
        {
            *(*(p + j) + k) = new int [*(*(col + j) + k)];
        }
    }

    //============Entering all the values in the 3d variable matrix===========//
    cout<< "entering elements into 3d matrix" << endl;
    cout << "enter all the values \n \n" << endl;
    for (int i = 0; i < vol ; i++)
    {
        for (int j = 0; j < row[i] ; j++)
        {
            for (int k = 0; k < *(*(col + i) + j) ; k++)
            {
                cout<< "enter the value in col " <<k <<", of row " << j<< ", of vol " << i << " : "<< endl;
                cin >> *(*(*(p + i) + j) + k);
            }
        }
    }

    //============Printing all the values in the 3d variable matrix===========//
    cout<< "Lets print all the values in 3d matrix \n\n" << endl;
    for (int i = 0; i < vol; i++)
    {
        for (int j = 0; j < row[i]; j++)
        {
            for (int k = 0; k < *(*(col + i) + j); k++)
            {
                cout<< *(*(*(p + i) + j) + k);
                cout << "\t";
            }

            cout<< " \n" << endl;
        }

        cout<< "\n\n============================" << endl;
    }

    //======================= deleting all pointers ========================//

    //Deleting the col pointer
    for (int i = 0; i < vol ; i++)
    {
        delete[] col[i];
    }

    delete[] col;

    //Deleting the p pointer
    for (int i = 0; i < vol ; i++)
    {
        for (int j = 0; j < row[vol] ; j++)
        {
            delete[] p[j];          //deleting the last arrays
        }
        delete[] p[i];
    }
    delete []p;

    system("pause");
    return 0;
}

A: You have to respect the way of deletion as much as the way of creation so you can do:
//Deleting the p pointer
for ( int i = 0; i < vol ; i++){
    for (int j = 0; j < row[vol] ; j++)
        delete[] p[i][j];
    delete[] p[i];
}

delete[] p;


text:
Q: Is it common for XML tags to be missing the beginning tag? I'm using the python module XMl ElementTree to parse a bunch of XML files. Normally a tag containing text will be written as,
<Tag>some text is here</Tag>

and if there is no text associated with the tag we'll have,
<Tag></Tag>

but some of my files only have,
<Tag/>

Is this common with XMLs or am I looking at a poorly constructed file?

A: A tag like <tag/> is an empty-element tag (also called a self-closing tag), which is shorthand for <tag></tag>: both represent an empty element.
Quoted from the W3C Recommendation on XML:

[Definition: An element with no content is said to be empty.]
The representation of an empty element is either a start-tag immediately followed by an end-tag, or an empty-element tag.
[Definition: An empty-element tag takes a special form:]
Tags for Empty Elements
[44] EmptyElemTag ::= < Name (S Attribute)* S? />
Empty-element tags may be used for any element which has no content, whether or not it is declared using the keyword EMPTY. For interoperability, the empty-element tag SHOULD1 be used, and SHOULD only be used, for elements which are declared EMPTY.
Examples of empty elements:

A word about non-XML (HTML) void elements
The above should not be confused with the non-XML concept of void elements in HTML, which may be written like <tag/> as well.
Quoted from W3C HTML Language Reference (I highlighted point 5):

A void element is an element whose content model never allows it to have contents under any circumstances.
start tags consist of the following parts, in exactly the following order:

*

*A < character.

*The element's tag name.

*Optionally, one or more attributes, each of which must be preceded by one or more space characters.

*Optionally, one or more space characters.

*Optionally, a / character, which may be present only if the element is a void element.

*A > character.

Void elements only have a start tag; end tags must not be specified for void elements.

So although one can have
 in a non-XML HTML document, it does not completely represent the same concept as in XML. It is not a self-closing tag, but a syntactic alternative for
, a void element, which is a concept foreign to XML.

A: If there is no opening tag for a closing tag the document is not a valid Xml. It's OK to have a tag without a value <Tag /> - which is an equivalent to <Tag></Tag> but it is not valid to have a closing tag without a corresponding opening tag. Elements also have to be correctly nested.

A: A common thing is <tag/>, which is an equivalent of <tag></tag>, useful when there is no inner content.
For example, you can see in html :

But </tag> alone is not valid in standard contexts.


text:
Q: react hook useEffect infinite loop Below is my code snipet.
When i receieve my prop and try to useSate, i recieve this infine loop even after following number of solutions.
const App = ({ center }) => {
  const position = [-1.29008, 36.81987];

  const [mapCenter, setMapCenter] = useState();

  useEffect(() => {
    if (center && center.length > 0) setMapCenter(center);
    else setMapCenter(position);
  }, [center, position]);

return (<div> </div>)

}

export default App;

A: The issue is that you are defining position array in functional component and its reference gets changed on each re-render and hence the useEffect executed again.
You can move declaration of position out of component since its a constant like
const position = [-1.29008, 36.81987];
const App = ({ center }) => {

  const [mapCenter, setMapCenter] = useState();

  useEffect(() => {
    if (center && center.length > 0) setMapCenter(center);
    else setMapCenter(position);
  }, [center, position]);

return (<div> </div>)

}

export default App;

or remove the dependency of position from useEffect
const App = ({ center }) => {
  const position = [-1.29008, 36.81987];

  const [mapCenter, setMapCenter] = useState();

  useEffect(() => {
    if (center && center.length > 0) setMapCenter(center);
    else setMapCenter(position);
  }, [center]);

return (<div> </div>)

}

export default App;

A: remove the dependency of position from useEffect


text:
Q: Strange behavior of os.popen().readlines I have to write a script, which should be python 2/3 compatible.
I need to use the input method and it should accept inputs without quotes.
Python 3 supports only raw_input for that
and Python 2 does only support input for that
I wrote a method that checks the python version and uses the corresponding input method (as shown below)
The Problem is:
output = os.popen('python --version').readlines()

returns
Python 2.7.15rc1
[]

So the list is actually empty despite the line beeing printed
If I change the text to ask for the git version
output = os.popen('git --version').readlines()

it returns
['git version 2.17.1\n']

like it should.
How can it be that this method is behaving so odd?
And has anybody an idea how to fix that?
I tried to run it on both python 2 and 3.
def input_23_comp(text=''):
    output = os.popen('python --version').readlines()
    output = output[0].strip()
    if (output[0:8] == 'Python 2'):
        raw_input(text)
    else:
        input(text)

A: python --version prints version info to stderr. You're capturing stdout. You need to capture stderr, or redirect stderr to stdout.
If you want to check the version of Python you're running on, though, running python --version is the wrong way to go. The version you invoke through that command may not even be the version you're running on. Use sys.version_info.


text:
Q: How to extract elements of a list into a folder in Python I have a list of image objects. I want to build a folder comprising the images of this list, so that I can download the folder.  Is there a way to do this?

A: The PIL Image object has a save function that you can make use of.
Simply loop over each Image object and call the save function and provide it with the path of the image.
Example:
for i, img in enumerate(list_of_imgs):
    img.save(f"{dir}/{i}.jpg")


text:
Q: Find zip codes associated with more than one state I have a database that contains 5 digit zip codes (ie 10001) and matching state abbreviations (ie NJ, NY, CA).  I've found that some of the zip codes have multiple states (ie 10001 = NJ and 10001 = NY) which is wrong.
   zip         State
 10001          NY
 10001          NJ
 10001          NY
 10001          NY
  ...           ...

Each State can have many zip codes, but each zip code should have only one state.
I'd like to find all the errors but can't seem to write a query to do so.
Any suggestions?

A: A different approach, but rather than just give you a count, this gives you the states involved.
SELECT zip, state
FROM dbo.table AS t
WHERE EXISTS
(
  SELECT 1 FROM dbo.table
  WHERE zip = t.zip AND state <> t.state
)
GROUP BY zip, state
ORDER BY zip, state;

Once you've identified the duplicates and removed them, add a unique constraint on zip,state so you're not doing this again next week, next month, etc.

A: I actually work with nationwide datasets on a daily basis and encounter this issue a lot.  The State designator in the prefix of the ZIP code indicates the state that the Post Office is located in, not necessarily the extents of the delivery area.  I was in contact with some higher-ups at USPS about some issues in the north-central part of the country and was told that the ZIP code program originally intended for the ZIP Codes to be confined by state boundaries, but in the early 80s they started to make exceptions in rural areas.  There are cases where a house in North Dakota is 10 miles away from a Montana Post Office, but the nearest Post Office in their own state is located several counties away. This is why these exceptions are made. It makes sense on the ground level, but not on a data level.  There are a lot of these exceptions in the USPS databases now.  The most prolific areas (that I have found) are along the MT/ND and SD/ND borders.

A: Just to point out the obvious:

Because ZIP codes are intended for efficient postal delivery, there are unusual cases where a ZIP code crosses state boundaries, such as a military facility spanning multiple states or remote areas of one state most easily serviced from an adjacent state. For example ZIP code 42223 spans Christian KY and Montgomery TN, and ZIP code 97635 spans Lake OR and Modoc CA.
http://en.wikipedia.org/wiki/ZIP_code

Be careful what you consider canonical data, and always trust someone providing you authentic data.

In this case, 0 is for NJ, so 10001 for NJ would be wrong, but 00001 would be accurate for NJ, and 1 is for NY, so 00001 would be wrong for NY, but 10001 would be accurate for NY. See also http://en.wikipedia.org/wiki/List_of_ZIP_code_prefixes
Also of note is that with the 1000 zip coverages in the previous link, you could accurately determine what zip codes you have that fall outside the range/state that they should be in ...

A: This should give you what you need:
select zip,count(distinct state)
from TheTable
 group by zip
 having count(distinct state)>1

That will give you a list of each zip code for which more than one state exists in the table.


text:
Q: Apache Ignite 2.7 release date I'm looking for Ignite 2.7 version release date, but there is no information over the web.
On apache site release date is 5 Novermber. But the last version is 2.6.
I've downloaded 2.7 nightly build, but I don't know how to use it with maven.

A: You can install what you've downloaded, in your local repository. Then you can use it in your project.
mvn install:install-file
    -Dfile=path/to/your/jar.jar
    -DgroupId=org.apache.ignite
    -DartifactId=ignite-core
    -Dversion=2.7.0
    -Dpackaging=jar

In your pom:
<dependency>
    <groupId>org.apache.ignite</groupId>
    <artifactId>ignite-core</artifactId>
    <version>2.7.0</version>
</dependency>

A: Apache Ignite 2.7 is not released yet. You can track the release process in this thread on the Apache Ignite dev list: http://apache-ignite-developers.2346864.n4.nabble.com/Apache-Ignite-2-7-Last-Mile-td36359i40.html


text:
Q: Send MVC actionresult to printer I have a controller with an action:
SomeController/ActionToBePrinted

ActionToBePrinted() returns an html view.
This action is called from a normal mvc razor view when pressing a button - how would I go about sending the content of the view to a printer when the button is pressed?
Aloha,
Hugo

A: You cant send direct to the printer.

*

*I suggest you to create a custom ActionResult, that returns a PDF file or something like that. ASP.NET MVC Action Results and PDF Content

*You can show a html page as well and open the print dialog using javascript like this
Click to Print This Page
But always the user has to start the print process, you cant do this programmatically.

A: You can perform a GET request (e.g. use window.open() and pass in URL or use AJAX) and put the returned HTML contents into a new window.  Then use
Window.print().  Then simply close the window when you are done.
You could tie this directly into a single view by adding something in the body, but I prefer to use JavaScript in these cases.  This keeps the design acting as a re-useable object or service that can be used across multiple views.  In other words, you setup the controller-model, but no view.  Instead, JavaScript steps in as the View.
Keep in mind that HTML is not a print format.  So if you need to control the layout, you should be using a print technology such as PDF.  XSLT provides an excellent means to create both HTML and PDF output using the same data, albeit it's a lot more work to create XSLT templates than it is to slap down  window.print
Personally, I have an MVC page acting as a service that takes URL parameters.  The page hooks into Adobe XSL-FO and uses the params to drive the output.


text:
Q: Date converstion using strptime skips UTC part I am trying to convert string variable to date object the output doesnt have the UTC component.
Here is the sample code .. Appreciate your help!
import datetime
data="2016-01-19T00:00:00.000-0800"
result2 = datetime.datetime.strptime(data[0:23],"%Y-%m-%dT%H:%M:%S.%f")
print(result2)

A: That's because you are slicing out the utc part of the string in data[0:23], if you want to get a datetime object with timezone information you can do this instead:
import datetime

data = "2016-01-19T00:00:00.000-0800"
result2 = datetime.datetime.strptime(data,"%Y-%m-%dT%H:%M:%S.%f%z")
print(result2)

>>> 2016-01-19 00:00:00-08:00


text:
Q: Why this code snippet can't compile whereas `print(square(3,0))` is ok? Why this code snippet can't compile whereas print(square(3,0)) is ok?
function square(iteratorMaxCount,currentNumber)

   if currentNumber<iteratorMaxCount
   then
      currentNumber = currentNumber+1
      return currentNumber, currentNumber*currentNumber
   end

end

print(square(3,0))

for i,n in square(3,0)
do
   print(i,n)
end

The compiler complains that:
> $lua main.lua 1   1 lua: main.lua:13: attempt to call a number value
> stack traceback:  main.lua:13: in main chunk  [C]: in ?

A: for i,n in square(3,0) is equivalent to for i,n in 1,1 and this means you are attempting to call 1 which is not a function and results in your error attempt to call a number value.
The first value in the expression list after in in the for loop definition needs to be a function, such as pairs or ipairs which are used when working with tables or arrays. If you're using some custom iterator, like square in your code, you want to create a function that defines the iterator storing limits as up values and returns an anonymous function, A function that does this is called an iterator factory.
function square(iteratorMaxCount,currentNumber)
    return function()
        if currentNumber<iteratorMaxCount then
            currentNumber = currentNumber+1
            return currentNumber, currentNumber*currentNumber
        end
    end
end

print(square(3,0)())
print(square(3,0))

for i,n in square(3,0) do
    print(i,n)
end

Alternatively you can pass initial state to the function by defining 2 more values in the for loop expression list, the invariant state and a control variable.
for i,n in square,3,0 do
    print(i,n)
end

Suggested Reading:

Programming in Lua: 7.2 – The Semantics of the Generic for

Related Topics:

Programming in Lua: 4.3.5 – Generic for

Programming in Lua: 7.1 – Iterators and Closures

Programming in Lua: 7.3 – Stateless Iterators


text:
Q: UTF-8 properties files in JavaEE I have a .properties file with ru_RU localization for my web project.
The words taken from this file by ResourceBoundle are displayed on jsp as "???"
I use Intellij IDEA 14 with tomcat8 on Linux, with option "Transparent native-to-ascii conversation", so file with russian symbols looks like key = "\uXXXX\uXXXX\uXXXX"
I think It's can be a problem with russian font. Am I mistaken?

A: .properties files have to be ISO-8859-1, no exceptions. What you see in the file is normal and correct, provided of course that those are \u04XX (the Unicode block for Cyrillic).
If the browser shows ?'s, it's another problem elsewhere. You may need make sure everything on the rendering side is using UTF-8. AFAIK, by default JavaEE uses ISO-8859-1, so you need to switch it explicitly to UTF-8.

A: I found the solution!
I foolishly forgotten about pageEncoding in page tag:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
so if pageEncoding not specified browser detects ISO-8859-1 as default encoding and shows ??? instead of cyrillic symbols.
SOLVED.


text:
Q: Rails Routes with Model Variable I am adding a blog to my site, so I created a model bpost, with variables title, content, and category. In the bpost model, I overwrote the to_param function:
def to_param
  {#id #title}.parametrize
end

So now all urls look like: /bposts/2-to-be-or-not-to-be, where "to be or not to be" is the title (2 is an example id).
I want instead the urls to look like: /:category/2-:title. I tried:
resources :bposts, :path => :category

OR
    match ':category/:id-:title', :to => :controller => :bposts, :action => :show
but neither seem to work. Any ideas on how to do this?

A: have a look at the guides for routing: http://guides.rubyonrails.org/routing.html
i guess what you want to have is a nested resource like
resources: :category do
  resources: :bposts
end
i think that :bposts is a bad name... make it posts or blog_posts.
another thing for you to look at is the gem-friendly id: https://rubygems.org/gems/friendly_id


text:
Q: Responsive table rendering, with headers that accommodate to new layout Is there some way of making table responsive, in such a way that this-:
┌─────────┬─────────┬──────────┐
│         │ ENTITY 1│  ENTITY 2│
├─────────┼─────────┼──────────┤
│ HEADER 1│    data │     data │
│ HEADER 2│    data │     data │
│ HEADER 3│    data │     data │
│ HEADER 4│    data │     data │
│ HEADER 5│    data │     data │
└─────────┴─────────┴──────────┘

becomes this (below say 800px browser width)-:
    ┬─────────┬──────────┐
    │ ENTITY 1│  ENTITY 2│
    ┼─────────┼──────────┤
    │       HEADER 1     │
    ┼─────────┼──────────┤
    │    data │     data │
    ┼─────────┼──────────┤
    │       HEADER 2     │
    ┼─────────┼──────────┤
    │    data │     data │
    ┼─────────┼──────────┤
    │       HEADER 3     │
    ┼─────────┼──────────┤
    │    data │     data │
    ┼─────────┼──────────┤
    │       HEADER 4     │
    ┼─────────┼──────────┤
    │    data │     data │
    ┼─────────┼──────────┤
    │       HEADER 5     │
    ┼─────────┼──────────┤
    │    data │     data │
    ┴─────────┴──────────┘

Can this be done with CSS only, or one would need to use JavaScript?

A:

.cell {
  text-align: center;
}
.cell:nth-child(1) { display: none; }

.mobile-row {
  display: table;
  width: 200%;
  text-align: center;
}

.mobile-row > td {
  width: 100%;
}

.no-mobile {
  display: none;
  @media (min-width: 704px) {
    display: table;
  }
}

    ENTITY 1
    ENTITY 2

      Header 1

      Header 1
      Stuff
      Stuff 2

      Header 2

      Header 1
      Stuff
      Stuff 2

      Header 3

      Header 1
      Stuff
      Stuff 2

You could maybe think about having an extra hidden row for mobile view.
See my mobile first style.


text:
Q: Why is too hard to create a simple proyect with rails? Only i want to create a simple proyect with ruby and rails, but i think its harder than it looked.
I have a version of ruby 2.6.8, i created a new project with this command  rails new blog, after that cd to blog
i applied this command: bin/rails server
i am facing this error: bin/rails:4:in require_relative': cannot load such file -- .../rb/blog/config/boot (LoadError) from bin/rails:4:in '

A: check with command:
ruby -v

that you ruby version same as in gemfile file, also as mention before don't forget run "bundle" after creating new project or add new gem to gemfile.
If this didn't help and you rails version is 6 you can manually fix problem -  create boilerplate config/boot.rb:
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)

require 'bundler/setup' # Set up gems listed in the Gemfile.
require 'bootsnap/setup' # Speed up boot time by caching expensive operations.

i am only start learning rails but i think if you only beginner then try fix problem in another way such  reinstall rails, ruby etc. bc in future it can cause problem, its not normal when you just create new project and it already dont work, something wrong.


text:
Q: Reorder a multidimensional array containing objects I have a large array object that looks something like this:
$items = Array
(
[0] => stdClass Object
    (
        [id] => 1
        [day] => 2
        [created] => 2014-10-22 21:32:52
    )

[1] => stdClass Object
    (
        [id] => 3
        [day] => 3
        [created] => 2014-10-22 21:35:19
    )

[2] => stdClass Object
    (
        [id] => 4
        [day] => 3
        [created] => 2014-10-22 21:35:23
    )

)

I need to restructure it in such a way that I could output results based on a day value. For example all records associate with day = 3 and so on.
I already have a structure of code that is based on days of a week, so I need to run a separate loop for this array to insert the records that match each day of the existing structure.
For example:
$wk = array(1 => "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");

foreach ($wk as $k => $v) {
   ...
   // insert records from $items
}

Is there a way to rewrite my $items array to accomplish this? If yes, how? Appreciate any suggestions.

A: *

*create new array

*iterate over old array

*create index in new array if it doesn't exist

*add item of old array to new index

Something like this should work:
// Create new array
$daySortedItems = array();

// Iterate over old array
foreach ($items as $item) {
    // Create index in new array if it doesn't exist
    if (! isset($daySortedItems[$item->day])) {
        $daySortedItems[$item->day] = array();
    }

    // Add item of old array to new index
    $daySortedItems[$item->day][] = $item;
}

Hope that this, in combination with your previous question, solves your problem. Do note that throwing hot-fixes in like this is considered bad practice. A better solution is to fix the problem at a lower level: when querying the database, index the result set on the day key directly.


text:
Q: Adding memory dataset to current active map in ArcGIS Pro using ArcPy I am using ArcGIS Pro 2.7.2.
I'm creating a Python script that creates data in the 'memory' workspace as part of a task. I would then like to add the dataset to the current active map as a manual QC step. I run the script via a toolbox from ArcGIS Pro with an active map open.  According to the support page on writing geoprocessing output to memory, "You can add memory datasets to a map in ArcGIS Pro.", but I receive the below error with the following code.
mem_lyr = r"memory\OffshoreObjects"
aprx = arcpy.mp.ArcGISProject("CURRENT")
aprx_map = aprx.activeMap
arcpy.MakeFeatureLayer_management(mem_lyr, "OffshoreObjects_layer")
aprx_map.addLayer(mem_lyr)

File "C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\utils.py", line 191, in fn_
return fn(*args, **kw)
File "C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\_mp.py", line 1734, in addLayer
return
convertArcObjectToPythonObject(self._arc_object.addLayer(*gp_fixargs((add_layer_or_layerfile,
add_position), True)))
ValueError: memory\OffshoreObjects

I also get the same error when using .addDataFromPath but from what I understand this is as expected when working with memory datasets.
mem_lyr = r"memory\OffshoreObjects"
aprx = arcpy.mp.ArcGISProject("CURRENT")
aprx_map = aprx.activeMap
aprx_map.addDataFromPath(mem_lyr)

A: I was able to replicate the problem. I think the issue here is that the default behaviour of the Make FeatureLayer tool is to add the layer to the map. Then immediately using the addLayer() method you add the layer that has already been added  and it blows up.
The very simple solution is to remove from your code the line:
aprx_map.addLayer(mem_lyr)

As for addDataFromPath() I am not surprised that did not work as it states in the help file:

The addDataFromPath method provides a way to add a layer to a map in a
similar way to how the Add Data From Path button works in the
application

Having read that statement I doubt that you have ever been able to navigate to a in_memory dataset through the add data button in ArcMap or ArcGIS Pro.


text:
Q: imagemagick convert does not work through php imagemagick convert does not work through php shell_exec but does through a shell.
In a shell convert file.pdf file.png works fine. But when I have this within a php file as shell_exec('convert file.pdf file.png'); Then I get no output! I have the permissions to do this, so I think it isn't that that's the problem; I have checked the directory I am in by way of getcwd() and this is also ok.
I know shell_exec works because I have used it earlier in the code and that works fine.
Any ideas?

A: I got the solution thanks to Crontab from another thread. I quote from there:

[I]f you're trying to convert a PDF to a PNG using ImageMagick ...
  even using the full path to ImageMagick's convert won't work if the
  script's PATH doesn't contain the path location to Ghostscript also.
  Without messing with any user paths, you could add:
putenv("PATH=/usr/local/bin:/usr/bin:/bin");

Or something similar depending on your setup. The gs executable has
  to be in your script user's path somewhere or ImageMagick will fail to
  convert PDF or EPS files.

A: Try the full path to convert, i.e. shell_exec('/usr/bin/convert file.pdf file.png);. You can use which convert to find the location on your system.

A: There are several reason why this could happen, but I suggest reading this page and the user comments:
http://php.net/manual/en/function.shell-exec.php


text:
Q: file_get_contents with context to change user agent didn't work I'am trying to get the read and like number of an page.

The url is: https://mp.weixin.qq.com/s/NPavBeHc8VdWXeSL6kfLRg
(you must activate a mobile user agent to see read and like number. There are at the bottom left of the page.
You must refresh the page.)
The problem is that read and like number are hidden when isn't a mobile user agent that visit the site.
So i tried to use file_get_contents() with a context that send user agent with http as other stackoverflow post said. But didn't work :(.
There is my code:
$url = 'https://mp.weixin.qq.com/s/NPavBeHc8VdWXeSL6kfLRg';

$opts = array('http' =>
    array(
        'header'  => 'User-agent: Mozilla/5.0 (Linux; Android 4.4.4; HM NOTE 1LTEW Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36 MicroMessenger/6.0.0.54_r849063.501 NetType/WIFI',
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents($url, false, $context);

print_r($result);

I also tried to modify the php.ini with

user_agent= "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Mobile Safari/537.36"

A: From HTTP context options:

user_agent string
Value to send with User-Agent: header. This value will only be used
  if user-agent is not specified in the header context option above.

If you opt for header, you need to set the header name as well, not just the value!


text:
Q: I have a string "user@domain+12223334444" and I want to replace "+1" with space. How can I achieve it with str.replace command? This string is in a column of dataframe. After running the below code, I am getting an error
patients_test["contact"] = patients_test["contact"].str.replace("+1", " ")

Error: nothing to repeat at position 0

A: Make the + into [+] so it's a character class matching the character +, not  a modifier to make the previous thing be repeated one-or-more times.
patients_test["contact"] = patients_test["contact"].str.replace("[+]1", " ")

You could also use "\\+1" or r"\+1", but I strongly advise the [+] approach as it works the same way no matter what kind of quoting context is being used.

A: Pandas str.replace does a regular expression match / replace by default.
That complexity is not necessary here, use
patients_test["contact"] = patients_test["contact"].str.replace("+1", " ", regex=False)

To use exact text matching without using a regular expression.


text:
Q: Xcode 6 Swift WKWebView keyboard settings I'm using a WKWebView to load a website and everything is working fine. However, I do not have access to the keyboard properties the same way I do with a textfield. Can someone point me to some resources that will help me access properties (through the gui or programmatically) of the keyboard on the web?

A: The Text Programming Guide for iOS, has a section called Configuring the Keyboard for Web Views that states the following:

Although the UIWebView class does not support the UITextInputTraits protocol directly, you can configure some keyboard attributes for text input elements. For example, you can include autocorrect and autocapitalize attributes in the definition of an input element to specify the keyboard's behaviors, as shown in the following example.
<input type="text" size="30" autocorrect="off" autocapitalize="on">

You can also control which type of keyboard is displayed when a user touches a text field in a web page. To display a telephone keypad, an email keyboard, or a URL keyboard, use the tel, email, or url keywords for the type attribute on an input element, respectively. To display a numeric keyboard, set the value of the pattern attribute to "[0-9]*" or "\d*".
These keywords and the pattern attribute are part of HTML 5 and are available in iOS. The following list shows how to display each type of keyboard, including the standard keyboard.
Text: <input type="text"></input>
Telephone: <input type="tel"></input>
URL: <input type="url"></input>
Email: <input type="email"></input>
Zip code: <input type="text" pattern="[0-9]*"></input>

That, of course, only solves some very specific problems in a limited number of situations, but as far as I know that's all we've got to work with, even with WKWebView.
I would love for someone to prove me wrong and let us know how to add a keyboard accessory view, or change the appearance of the keyboard when it's focused on a form element inside a web view in an iOS app.

A: I have an HTML auth page that I display in WKWebView. The autocorrect / suggestion bar appears above the keyboard for the username field. Since I don't control the HTML, I used the following Swift 3 code and javascript to add the autocorrect attribute as mentioned above:
    var webView: WKWebView!

override func loadView() {

    let autocorrectJavaScript = "var inputTextElement = document.getElementById('username');"
    + "   if (inputTextElement != null) {"
    + "     var autocorrectAttribute = document.createAttribute('autocorrect');"
    + "     autocorrectAttribute.value = 'off';"
    + "     inputTextElement.setAttributeNode(autocorrectAttribute);"
    + "   }"
    let userScript = WKUserScript(source: autocorrectJavaScript, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
    let webConfiguration = WKWebViewConfiguration()
    webConfiguration.userContentController.addUserScript(userScript)
    webView = WKWebView(frame: .zero, configuration: webConfiguration)
    view = webView
}

Note: The bar above the keyboard still remains, with other options, just not the suggestions.


text:
Q: Can a message acknowledgement be spoofed in SocketIO? In SocketIO you're able to get acknowledgements by providing a callback function, e.g. as per SocketIO's documentation:
// server-side
io.on("connection", (socket) => {
  socket.on("update item", (arg1, arg2, callback) => {
    console.log(arg1); // 1
    console.log(arg2); // { name: "updated" }
    callback({
      status: "ok"
    });
  });
});

// client-side
socket.emit("update item", "1", { name: "updated" }, (response) => {
  console.log(response.status); // ok
});

In my code, I prompt a user for a response and assume that the callback triggered can only be by the user I prompted. Is this assumption correct and is it a secure way to implement request-response functionality in SocketIO?

A:
Can a message acknowledgement be spoofed in SocketIO?

Not very easily and not at all if using https.
If your socket.io connection was initiated with https, then you can be sure that a response from that socket is indeed from that same endpoint (e.g. from your server).  If the client sends a message and is waiting for a response from the server and gets a response, then that response is indeed from the endpoint that you connected to.  No other computer can take over that socket or inject into it.
If your socket.io connection was initiated with http, then there could be man-in-middle attacks that could alter responses while in flight, though that is more difficult with socket.io because it runs over the webSocket transport which has some security measures built-in.
If you really need this to be secure then initiate the socket.io connection with https and you should be fine.


text:
Q: Jslider reflected in pannel I don't know why, although I am trying to make a color picker and for some reason the slider gets reflected in the panel, if I use one of the sliders and resize the frame the thing disappears.
Here is what I see:

I tried to change how different components are rendered, I tried to change the change listener, I tried to change as well the panel, but nothing changed.
I used repaint and tried not to use repaint.
This is my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import javax.swing.JSlider;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.FlowLayout;
import javax.swing.BoxLayout;
import net.miginfocom.swing.MigLayout;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class ThemeBuilder extends JFrame {

    private JPanel contentPane;
    private JPanel colorShow;
    private JPanel pnlButtons;
    private JPanel pnlSldG;
    private JPanel pnlSldB;
    private JPanel pnlSldAlpha;
    private JPanel pnlSldR;
    private JButton btnBackground;
    private JButton btnText;
    private JButton btnPanels;
    private JButton btnButtonsText;
    private JButton btnSideList;
    private JButton btnButtonLabels;
    private JButton btnButtonContours;
    private JButton btnSideListForeground;
    private JButton btnForeground;
    private JLabel label;
    private JSlider sldG;
    private JSlider sldB;
    private JSlider sldAlpha;
    private JSlider sldR;
    private JMenuBar menuBar;
    private JMenuItem mntmFile;

    /**
     * Create the frame.
     */
    public ThemeBuilder() {
        makeSliders();
        makeBtns();
        makePnls();
        makeFrame();
    }

    private void makeFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 431, 476);
        menuBar = new JMenuBar();
        setJMenuBar(menuBar);
        mntmFile = new JMenuItem("File");
        menuBar.add(mntmFile);
    }

    private void makePnls(){

        pnlButtons = new JPanel();
        GridBagConstraints gbc_pnlButtons = new GridBagConstraints();
        gbc_pnlButtons.gridwidth = 2;
        gbc_pnlButtons.anchor = GridBagConstraints.NORTH;
        gbc_pnlButtons.gridx = 0;
        gbc_pnlButtons.gridy = 5;
        pnlButtons.setLayout(new MigLayout("", "[97px][71px][95px][113px][79px][89px][111px]", "[23px][][][][][][][][]"));

        pnlSldB = new JPanel();
        GridBagConstraints gbc_pnlSldB = new GridBagConstraints();
        gbc_pnlSldB.anchor = GridBagConstraints.NORTH;
        gbc_pnlSldB.insets = new Insets(0, 0, 5, 5);
        gbc_pnlSldB.fill = GridBagConstraints.HORIZONTAL;
        gbc_pnlSldB.gridx = 0;
        gbc_pnlSldB.gridy = 3;

        colorShow = new JPanel();
        colorShow.setBackground(Color.GRAY);
        GridBagConstraints gbc_colorShow = new GridBagConstraints();
        gbc_colorShow.gridheight = 3;
        gbc_colorShow.insets = new Insets(0, 0, 5, 0);
        gbc_colorShow.fill = GridBagConstraints.BOTH;
        gbc_colorShow.gridx = 1;
        gbc_colorShow.gridy = 1;
        colorShow.setOpaque(true);
        colorShow.setDoubleBuffered(true);

        pnlSldG = new JPanel();
        GridBagConstraints gbc_pnlSldG = new GridBagConstraints();
        gbc_pnlSldG.gridheight = 2;
        gbc_pnlSldG.insets = new Insets(0, 0, 5, 5);
        gbc_pnlSldG.fill = GridBagConstraints.BOTH;
        gbc_pnlSldG.gridx = 0;
        gbc_pnlSldG.gridy = 1;

        pnlSldR = new JPanel();
        GridBagConstraints gbc_pnlSldR = new GridBagConstraints();
        gbc_pnlSldR.insets = new Insets(0, 0, 5, 5);
        gbc_pnlSldR.fill = GridBagConstraints.BOTH;
        gbc_pnlSldR.gridx = 0;
        gbc_pnlSldR.gridy = 0;

        pnlSldAlpha = new JPanel();
        GridBagConstraints gbc_pnlSldAlpha = new GridBagConstraints();
        gbc_pnlSldAlpha.insets = new Insets(0, 0, 5, 5);
        gbc_pnlSldAlpha.fill = GridBagConstraints.BOTH;
        gbc_pnlSldAlpha.gridx = 0;
        gbc_pnlSldAlpha.gridy = 4;

        pnlSldR.add(sldR);
        pnlSldG.add(sldG);
        pnlSldB.add(sldB);
        pnlSldAlpha.add(sldAlpha);
        pnlButtons.add(btnButtonLabels, "cell 0 0,alignx left,aligny center");
        pnlButtons.add(btnButtonContours, "cell 1 0,alignx left,aligny center");
        pnlButtons.add(label, "cell 4 0,alignx left,aligny center");
        pnlButtons.add(btnButtonsText, "cell 0 1,alignx left,aligny center");
        pnlButtons.add(btnText, "cell 0 3,alignx left,aligny center");
        pnlButtons.add(btnPanels, "cell 1 3,alignx left,aligny center");
        pnlButtons.add(btnSideListForeground, "cell 0 5");
        pnlButtons.add(btnSideList, "cell 1 5,alignx left,aligny center");
        pnlButtons.add(btnBackground, "cell 0 8,alignx left,aligny center");
        pnlButtons.add(btnForeground, "cell 1 8");

        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        GridBagLayout gbl_contentPane = new GridBagLayout();
        gbl_contentPane.columnWidths = new int[]{0, 0, 0};
        gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0};
        gbl_contentPane.columnWeights = new double[]{1.0, 1.0, Double.MIN_VALUE};
        gbl_contentPane.rowWeights = new double[]{1.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
        contentPane.setLayout(gbl_contentPane);

        contentPane.add(pnlButtons, gbc_pnlButtons);
        contentPane.add(pnlSldB, gbc_pnlSldB);
        contentPane.add(colorShow, gbc_colorShow);
        contentPane.add(pnlSldG, gbc_pnlSldG);
        contentPane.add(pnlSldR, gbc_pnlSldR);
        contentPane.add(pnlSldAlpha, gbc_pnlSldAlpha);

        pnlButtons.repaint();
        pnlSldAlpha.repaint();
        pnlSldR.repaint();
        pnlSldB.repaint();
        pnlSldG.repaint();
        btnPanels.repaint();
        contentPane.repaint();

    }

    private void makeSliders(){
        sldR = new JSlider();
        sldR.setMaximum(240);
        sldR.setMajorTickSpacing(50);
        sldR.setSnapToTicks(true);
        sldR.setPaintTicks(true);
        sldR.setPaintLabels(true);
        sldR.setValue(104);

        sldG = new JSlider();
        sldG.setMaximum(240);
        sldG.setSnapToTicks(true);
        sldG.setPaintTicks(true);
        sldG.setPaintLabels(true);
        sldG.setMajorTickSpacing(50);
        sldG.setValue(104);

        sldB = new JSlider();
        sldB.setMaximum(240);
        sldB.setSnapToTicks(true);
        sldB.setPaintTicks(true);
        sldB.setPaintLabels(true);
        sldB.setMajorTickSpacing(50);
        sldB.setValue(104);

        sldAlpha = new JSlider();
        sldAlpha.setMaximum(240);
        sldAlpha.setSnapToTicks(true);
        sldAlpha.setPaintTicks(true);
        sldAlpha.setPaintLabels(true);
        sldAlpha.setMajorTickSpacing(50);
        sldAlpha.setValue(240);
    }

    private void makeBtns(){
        btnButtonLabels = new JButton("Button Labels");
        btnButtonContours = new JButton("Button Contours");
        label = new JLabel("");
        btnButtonsText = new JButton("Buttons Text");
        btnText = new JButton("Top Menu Labels");
        btnPanels = new JButton("Top Menu");
        btnSideListForeground = new JButton("Side List Foreground");
        btnSideList = new JButton("Side List Background");
        btnBackground = new JButton("Background");
        btnForeground = new JButton("Foreground");
    }

    public JPanel getContentPane() {
        return contentPane;
    }

    protected JPanel getColorShow() {
        return colorShow;
    }

    protected JPanel getPnlButtons() {
        return pnlButtons;
    }

    protected JPanel getPnlSldG() {
        return pnlSldG;
    }

    protected JPanel getPnlSldB() {
        return pnlSldB;
    }

    protected JPanel getPnlSldAlpha() {
        return pnlSldAlpha;
    }

    protected JPanel getPnlSldR() {
        return pnlSldR;
    }

    protected JButton getBtnBackground() {
        return btnBackground;
    }

    protected JButton getBtnText() {
        return btnText;
    }

    protected JButton getBtnPanels() {
        return btnPanels;
    }

    protected JButton getBtnButtonsText() {
        return btnButtonsText;
    }

    protected JButton getBtnSideList() {
        return btnSideList;
    }

    protected JButton getBtnButtonLabels() {
        return btnButtonLabels;
    }

    protected JButton getBtnButtonContours() {
        return btnButtonContours;
    }

    protected JButton getBtnSideListForeground() {
        return btnSideListForeground;
    }

    protected JButton getBtnForeground() {
        return btnForeground;
    }

    protected JLabel getLabel() {
        return label;
    }

    protected JSlider getSldG() {
        return sldG;
    }

    protected JSlider getSldB() {
        return sldB;
    }

    protected JSlider getSldAlpha() {
        return sldAlpha;
    }

    protected JSlider getSldR() {
        return sldR;
    }
}

This is the wrapper (just for readability):
import java.awt.Color;

import javax.swing.JComponent;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class ThemeWrapper {

    private Theme theme;
    private ThemeBuilder builder;
    private int r, g, b, a;

    public ThemeWrapper(Theme theme) {
        this.builder = new ThemeBuilder();
        this.builder.setVisible(true);
        this.theme = new Theme();
        this.r = builder.getSldR().getValue();
        this.g = builder.getSldG().getValue();
        this.b = builder.getSldB().getValue();
        this.a = builder.getSldAlpha().getValue();
        initializeBehaviors();
    }

    public void initializeBehaviors(){

        builder.getSldR().addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {

                if(e.getSource() == builder.getSldR()){
                    changeColor();
                }
            }
        });

        builder.getSldG().addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {

                if(e.getSource() == builder.getSldG()){
                    changeColor();
                }
            }
        });

        builder.getSldB().addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {

                if(e.getSource() == builder.getSldB()){
                    changeColor();
                }
            }
        });

        builder.getSldAlpha().addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {

                if(e.getSource() == builder.getSldAlpha()){
                    changeColor();
                }
            }
        });
    }

    private void changeColor(){
        r = builder.getSldR().getValue();
        g = builder.getSldG().getValue();
        b = builder.getSldB().getValue();
        a = builder.getSldAlpha().getValue();
        applyColor(builder.getColorShow());
    }

    private void applyColor(JComponent component){
        component.setBackground(new Color(r, g, b, a));
        component.repaint();
    }

    public void disposeFrames(){
        builder.setVisible(false);
        builder.dispose();
    }

    public Theme getTheme() {
        return theme;
    }
}

A: component.setBackground(new Color(r, g, b, a));

Swing doesn't paint components with transparent backgrounds correctly.
You need to make sure the background is painted to remove painting artifacts. Check out Backgrounds With Transparency for more information and solutions.
Also:

*

*Swing components are double buffered by default so there is no need to use setDoubleBuffered(true).

*All components are painted when the frame is made visible so there is no need to invoke repaint() on individual components.

A: No I just figured it out, it's because you have to repaint the frame!
private void changeColor(){
    r = builder.getSldR().getValue();
    g = builder.getSldG().getValue();
    b = builder.getSldB().getValue();
    a = builder.getSldAlpha().getValue();
    applyColor(builder.getColorShow());
    builder.repaint();
}


text:
Q: does Jaeger provide a trace api does jaeger provide a way of querying the trace data without using the UI provided. I'm aware that zipkin provides an API to directly access the trace data etc.
Use-case: i'm trying to use the trace data to pull together a custom report for internal purposes. I could scrape the data from the UI but wondered if there was an easier way.

A: Your best chance is to get the data from whatever storage the Jaeger collector is using (Cassandra, Elastic.) (https://www.jaegertracing.io/docs/1.6/deployment/ )
My suggestion is to store in Elastic and use Kibana to accomplish what you need.

A: Old topic but the current version of Jaeger Query UI is a single page app and has an underlying API that allows the same queries capabilities as the UI.


text:
Q: PHP variable in a Ajax call I have to create a site that looks like tumblr and instagram and shows all pictures which are stored in one directory.
When you scroll to the end of the page I want to load new pictures but I am a Ajax beginner and dont have a clue how to do this. I think my program will work but I need a PHP variable in the Ajax call.
How can I do this?

A: You can simply echo it into the script the same way you would echo it onto an html page
<script>
...
var phpvar = <?= $php_variable ?>;
...
</script>


text:
Q: Supervisor not detecting file I am trying to run a command via a proxy.  When I run this command in shell it works
http_proxy=http://username:password@proxy:29800 /home/www/program -env prod
But when I put this into my supervisor config it tells me it can't find this file
[program:goprogram]
command = http_proxy=http://username:password@proxy:29800 home/www/program -env prod
directory = /home/www/program
enviroment=PATH='/home/www/env/bin:/usr/bin'
user = user
autorestart = true

Now, I assume it has to do with the http_proxy or syntax, but not sure how to fix it.

A: Since you are trying to set up an environment variable in the command itself, you might try a different way to call said command:
command = /bin/sh -c 'http_proxy=http://username:password@proxy:29800 home/www/program -env prod'

That way:

*

*you don't have to add that environment variable to the environment section (or the credentials would be visible to all  supervisord process' and child process' environments)

*you set http_proxy only for the command to be executed.

A: You need to set the http_proxy variable. Either the way @VonC described it or:
[program:goprogram]
command = home/www/program -env prod
directory = /home/www/program
enviroment=
    PATH='/home/www/env/bin:/usr/bin'
    http_proxy=http://username:password@proxy:29800
user = user
autorestart = true

More information can be found in this SO question.


text:
Q: Machinist for Non-ActiveRecord Models Is it possible to use Machinist to create blueprints for non-activerecord models?  Seems to generate an error no matter what I try!
If this is impossible with Machinist, is there another fixture generating gem that can do it?  I've also read that Factory Girl has issues with this.

A: I did a little bit of investigating into Machinist 2 beta 1 and it looks like it supports plain ruby objects. Here's what I did to get it working. Happy to learn of any simpler solutions.
require 'rubygems'
require 'machinist'
require 'faker'

class YourObject
 attr_accessor :field1, :field2
end

# For all Objects
class Object
 extend Machinist::Machinable

 def self.blueprint_class
   Machinist::Blueprint
 end
end

# Or just one object
YourObject.send(:extend, Machinist::Machinable)
YourObject.class_eval do
 def self.blueprint_class
   Machinist::Blueprint
 end
end

YourObject.blueprint do
 field1 { rand(1000) }
 field2 { Faker::Name }
end

obj = YourObject.make

A: In case anyone's curious, one of the problems (there may be others) with FactoryGirl and POROs is that it doesn't handle constructors with arguments. You can make due per the answer here.


text:
Q: Como escrever uma lista encadeada simples em C++ sem usar ? Estou usando o operador delete para liberar um bloco de memoria  alocado via new, porém, ao executar o código pelo terminal ele parece não executar. Nenhum erro de código, simplesmente não executa no terminal. Se eu comentar a linha de código em que eu uso o delete, ai sim o código é executado normalmente no terminal. Tentei executar o mesmo código no IDE Dev-C++ e nele funciona normal. Alguém saberia me diz porque isso acontece? E como consertar?
o Delete está comentado da função RemovePosicao() na linha 157, ao executar com ele comentado então é executado no terminal, se tirar o comentário, então, acontece o que já foi mencionado anteriormente.
    #include <iostream>
    using namespace std;

    /*
    1 - instanciar lista
    2 - inserir início
    3 - inserir fim
    4 - inserir por posição
    5 - imprimir
    5.5 - tamanho
    6 - remover inicio
    7 - remover fim
    8 - remover posição
    */

// delete apontador
void ExibirMenu()
{
    cout << "\n[1] - Inserir no inicio da lista\n";
    cout << "[2] - Inserir no fim da lista\n";
    cout << "[3] - Inserir por posicao\n";
    cout << "[4] - Imprimir lista\n";
    cout << "[5] - Remover no inicio da lista\n";
    cout << "[6] - Remover no fim da lista\n";
    cout << "[7] - Remover por posicao\n";
}

struct noLista
{
    int      dado;
    noLista *prox;
};

noLista *inicializar() { return NULL; }

void inserirInicio(noLista *&l, int info)
{
    noLista *novo = new noLista;
    novo->dado    = info;
    novo->prox    = l;
    l             = novo;
}

bool RemoveInicio(noLista *&ApontadorInicioLista)
{
    if (ApontadorInicioLista != NULL)
    {
        noLista *PonteiroPegaPosicaoExcluir = ApontadorInicioLista;
        ApontadorInicioLista = ApontadorInicioLista->prox;
        // delete (PonteiroPegaPosicaoExcluir);
        return true;
    }
    else
    {
        return false;
    }
}

void inserirFim(noLista *&l, int info)
{
    noLista *novo = new noLista;
    novo->dado    = info;
    novo->prox    = NULL;
    if (l == NULL) { l = novo; }
    else
    {
        noLista *p = l;
        while (p->prox != NULL) { p = p->prox; }
        p->prox = novo;
    }
}

bool RemoveFim(noLista *&ApontadorInicioLista)
{
    noLista *PonteiroPercorre = ApontadorInicioLista;
    noLista *PonteiroGuardaPosicaoAnterior;
    if (ApontadorInicioLista == NULL) { return false; }
    else if (ApontadorInicioLista->prox == NULL)
    {
        ApontadorInicioLista = NULL;
        return true;
    }
    else
    {
        while (PonteiroPercorre->prox != NULL)
        {
            PonteiroGuardaPosicaoAnterior = PonteiroPercorre;
            PonteiroPercorre              = PonteiroPercorre->prox;
        }
        PonteiroGuardaPosicaoAnterior->prox = NULL;
        return true;
    }
}

void imprimir(noLista *l)
{
    while (l != NULL)
    {
        cout << l->dado << "\n";
        l = l->prox;
    }
}

int tamanho(noLista *l)
{
    int cont = 0;
    while (l != NULL)
    {
        cont++;
        l = l->prox;
    }
    return cont;
}

bool inserir_posicao(noLista *&l, int info, int pos)
{
    int tam = tamanho(l);
    if (pos > tam + 1) { return false; }
    else if (pos <= 0)
    {
        return false;
    }
    else
    {
        if (pos == 1) { inserirInicio(l, info); }
        else if (pos == tam + 1)
        {
            inserirFim(l, info);
        }
        else
        {
            int      cont = 1;
            noLista *novo = new noLista;
            novo->dado    = info;
            // novo->prox
            noLista *p = l;
            while (cont < pos - 1)
            {
                p = p->prox;
                cont++;
            }
            novo->prox = p->prox;
            p->prox    = novo;
        }
        return true;
    }
}

bool RemovePosicao(noLista *&ApontadorInicioLista, int Posicao)
{
    int Tamanho = tamanho(ApontadorInicioLista);
    if (Posicao > Tamanho) { return false; }
    else if (Posicao <= 0)
    {
        return false;
    }
    else
    {
        if (Posicao == 1) { RemoveInicio(ApontadorInicioLista); }
        else
        {
            int      Contador = 1;
            noLista *PonteiroPegaPosicaoAnterior;
            noLista *PonteiroPegaPosicaoDelete = ApontadorInicioLista;
            noLista *PonteiroPegaPosicaoPosteriro;
            while (Contador != Posicao)
            {
                PonteiroPegaPosicaoAnterior = PonteiroPegaPosicaoDelete;
                PonteiroPegaPosicaoDelete =
                    PonteiroPegaPosicaoDelete->prox;
                PonteiroPegaPosicaoPosteriro =
                    PonteiroPegaPosicaoDelete->prox;
                Contador++;
            }
            PonteiroPegaPosicaoAnterior->prox =
                PonteiroPegaPosicaoPosteriro;
            // delete PonteiroPegaPosicaoDelete;
        }
        return true;
    }
}

int main(int argc, char const *argv[])
{
    noLista *l1 = inicializar();
    int      Terminar, opcao, valor, posicao;
    do {
        ExibirMenu();
        cout << "\nDigite uma opcao : ";
        cin >> opcao;
        switch (opcao)
        {
            case 1:
                cout << "\nQual valor a ser inserido ? ";
                cin >> valor;
                inserirInicio(l1, valor);
                cout << "\nOperacao realizada com sucesso ! \n";
                break;
            case 2:
                cout << "\nQual valor a ser inserido ? ";
                cin >> valor;
                inserirFim(l1, valor);
                cout << "\nOperacao realizada com sucesso ! \n";
                break;
            case 3:
                cout << "\nQual valor a ser inserido ? ";
                cin >> valor;
                cout << "\nEm qual posicao ? ";
                cin >> posicao;
                if (inserir_posicao(l1, valor, posicao))
                {
                    cout << "\nOperacao realizada com sucesso ! \n";
                }
                else
                {
                    cout << "\nPosicao invalida ! \n";
                }
                break;
            case 4:
                cout << "\nAbaixo estao os elementos da lista \n\n";
                imprimir(l1);
                break;
            case 5:
                if (RemoveInicio(l1))
                {
                    cout << "\nOperacao realizada com sucesso ! \n";
                }
                else
                {
                    cout << "\nLista vazia, impossivel realizar "
                            "operacao ! \n";
                }
                break;
            case 6:
                if (RemoveFim(l1))
                {
                    cout << "\nOperacao realizada com sucesso ! \n";
                }
                else
                {
                    cout << "\nLista vazia, impossivel realizar "
                            "operacao ! \n";
                }
                break;
            case 7:
                cout << "\nQual a posicao que voce deseja excluir ? ";
                cin >> posicao;
                if (RemovePosicao(l1, posicao))
                {
                    cout << "\nOperacao realizada com sucesso ! \n";
                }
                else
                {
                    cout << "\nPosicao invalida ! \n";
                }
        }

        cout << "\n\
Deseja encerrar as operacoes com a lista ? Digite [0] para encerrar : ";
        cin >> Terminar;

    } while (Terminar != 0);
}

A: O código como escreveu tem alguns problemas. Mas na máquina Windows 10 que estou usando funcionou em gcc e MSVC apesar dos avisos de variável não inicializada do compilador da Microsoft.

*

*Em RemoveFim() não há um delete para o nó.

*Se tem void inserirInicio() e void inserirInicio() então ao invés de bool inserir_posicao() devia ter bool inserirPosicao(). E se as 3 retornarem bool o código fica mais simples.

*nomes incrivelmente longos, como em

  bool RemovePosicao(noLista *&ApontadorInicioLista, int Posicao)
{
    int Tamanho = tamanho(ApontadorInicioLista);
    if (Posicao > Tamanho) { return false; }
    else if (Posicao <= 0)
    {
        return false;
    }
    else
    {
        if (Posicao == 1) { RemoveInicio(ApontadorInicioLista); }
        else
        {
            int      Contador = 1;
            noLista *PonteiroPegaPosicaoAnterior;
            noLista *PonteiroPegaPosicaoDelete = ApontadorInicioLista;
            noLista *PonteiroPegaPosicaoPosteriro;
            while (Contador != Posicao)
            {
                PonteiroPegaPosicaoAnterior = PonteiroPegaPosicaoDelete;
                PonteiroPegaPosicaoDelete =
                    PonteiroPegaPosicaoDelete->prox;
                PonteiroPegaPosicaoPosteriro =
                    PonteiroPegaPosicaoDelete->prox;
                Contador++;
            }
            PonteiroPegaPosicaoAnterior->prox =
                PonteiroPegaPosicaoPosteriro;
            // delete PonteiroPegaPosicaoDelete;
        }
        return true;
    }
}

não ajudam em nada a ler o código.
Veja essa opção, que também funciona:
bool noLista::RemovePosicao(int Posicao)
{
    if (Posicao > tamanho) return false;
    if (Posicao < 1) return false;
    if (Posicao == 1) return RemoveInicio();
    int   Contador = 1;
    Node* ant      = nullptr;
    Node* p        = inicio;
    Node* prox     = nullptr;
    while (Contador != Posicao)
    {
        ant  = p;
        p    = p->prox;
        prox = p->prox;
        Contador++;
    };  // while()
    ant->prox = prox;
    delete p;
    tamanho -= 1;
    return true;
}

*

*Não há razão para usar essas funções assim em C++ e passar em todas uma referência ao ponteiro para o início da lista. As funções fazem parte da classe (struct no seu caso). Apenas declare lá e tudo fica mais simples.

*entenda que uma lista não é um nó e um nó não é uma lista. Não programe assim. Uma lista é um conjunto, possivelmente vazio, de nós. E cada nó tem ou indica um dado, o elemento da lista. No seu caso é apenas um int. E em geral dentro do elemento tem um campo que é chamado chave, porque na lista está em geral implícita uma questão de ordem, uma noção de comparação. Em termos simples deve estar definido o operador < para a classe de coisas que tem dentro da lista.

*main() deve ser a primeira função de seu programa, se possível em um arquivo separado.

*um cout de 7 linhas é bem melhor que 7 cout de uma linha
Você escreveu:
void ExibirMenu()
{
    cout << "\n[1] - Inserir no inicio da lista\n";
    cout << "[2] - Inserir no fim da lista\n";
    cout << "[3] - Inserir por posicao\n";
    cout << "[4] - Imprimir lista\n";
    cout << "[5] - Remover no inicio da lista\n";
    cout << "[6] - Remover no fim da lista\n";
    cout << "[7] - Remover por posicao\n";
}

Mas void ExibirMenu() podia ser simplesmente int menu() e retornar a opção.

Compare com:

char menu()
{
    char opcao[30]{0};
    do {
        cout << "\
\n\
[0] - Sair\n\
[1] - Inserir no inicio da lista\n\
[2] - Inserir no fim da lista\n\
[3] - Inserir por posicao\n\
[4] - Imprimir lista\n\
[5] - Remover no inicio da lista\n\
[6] - Remover no fim da lista\n\
[7] - Remover por posicao\n\
\n\
      Digite uma opcao (0 para sair): ";
        cin.getline(opcao, 30);

    } while ((opcao[0] < '0') || (opcao[0] > '7'));

    return (opcao[0] - '0');
}

Que tem a vantagem de ler a linha toda. E é possivelmente mais fácil de ler e de alterar. E em main() já pode usar o valor diretamente como em
    while(true)
    {
        switch (menu())
        {
        }
    }

E em uma única chamada a cout.
Considere essas definições:
// noLista.h
struct Node
{
    int   dado;
    Node* prox;
};

struct noLista
{
    Node*   Inicio();
    void    Imprimir();
    bool    InserirFim(int info);
    bool    InserirInicio(int info);
    bool    InserirPosicao(int info, int pos);
    bool    RemoveFim();
    bool    RemoveInicio();
    bool    RemovePosicao(int Posicao);
    int     Tamanho();

    noLista();  // inicializar
    ~noLista(); // apaga tudo

   private:
    Node* inicio;
    int   tamanho;
};
// fim de noLista.h

Isso seria um modo mais simples de escrever o que fez, em C++. Assim as funções da lista ficam associadas a uma lista. Em geral se escreve que os métodos de noLista ficam associados a instâncias da classe.
E o tamanho faz parte da lista, dentro da struct, assim não precisa percorrer a lista a cada vez que precisa do tamanho dela. E pode usar esse valor para controlar outras funções.
Exemplo:
    noLista l1; // l1 e uma lista
    l1.imprimir(); // se refere a lista l1.

    noLista minhalista[10]; // 10 listas ligadas
    minha_lista[4],imprimir(); // imprime o conteudo da 5a lista

Um exemplo em C++ de uma lista encadeada simples
Vou deixar um exemplo (com seu código) a seguir.

*

*Entenda que, a menos que seja obrigado por um enunciado ou um projeto ou uma máquina sem recursos, não deve usar ponteiros para um lado só: é mais complicado e não mais simples. Sem ponteiros para os dois lados toda vez que precisar navegar pela lista pode precisar se reposicionar no início (ou no fim) e começar de novo. Ou salvar o ponteiro faltante na função de novo e de novo e novo... Veja no exemplo abaixo as funções que removem ou inserem no fim.

*evite misturar entrada e saída com as funções da lista. Use estruturas genéricas e sempre vai poder usar as mesmas funções

*C++ tem listas em <list>. Sempre é por ver os métodos oferecidos,

*Em geral funções que inserem ou removem por posição não são assim úteis em listas e pilhas, e uma função que lista todos só existe para teste. list é um container voltado à navegação simples e inserção rápida. E em geral se insere e remove por uma ordem determinada pelo operador < que deve existir para a classe contéudo da lista.

*veja no exemplo como codificar as funções que manipulam a lista: elas ficam DENTRO da estrutura e por isso não precisa passar um ponteiro para a lista. Isto é encapsulamento e é em geral muito mais conveniente.
O código do exemplo
Há muitas razões para escrever assim, mas programas em C++ costumam ter um arquivo de código e um arquivo de cabeçalho para cada classe.
Nesse caso aqui tem a classe Node, que aqui é uma struct, e a classe noLista que é também uma struct.
Assim nesse exemplo o normal é ter 3 arquivos: noLista.h com as declarações, noLista.cpp com a implementação das funções, e o arquivo .cpp que chama as funções.
Assim você pode escrever vários programas que usam noLista.cpp. Ou pode escrever várias implementações de teste para a struct definida em noLista.h
noLista.h
// noLista.h
struct Node
{
    int   dado;
    Node* prox;
};

struct noLista
{
    Node*   Inicio();
    void    Imprimir();
    bool    InserirFim(int info);
    bool    InserirInicio(int info);
    bool    InserirPosicao(int info, int pos);
    bool    RemoveFim();
    bool    RemoveInicio();
    bool    RemovePosicao(int Posicao);
    int     Tamanho();

    noLista();  // inicializar
    ~noLista(); // apaga tudo

   private:
    Node* inicio;
    int   tamanho;
};
// fim de noLista.h

uma implementação de NoLista.h
#include <iomanip>
#include <iostream>
#include "noLista.h"
using namespace std;

// constroi uma lista vazia
noLista::noLista()
{
    inicio  = nullptr;
    tamanho = 0;
};  // inicializar

// apaga a lista
noLista::~noLista()
{
    for (int i = 0; i < tamanho; i += 1) RemoveInicio();
};

// os metodos

Node* noLista::Inicio() { return inicio; }

void noLista::Imprimir()
{
    int   nc = 0;
    cout << "Total de " << tamanho << " elementos:\n\n";
    Node* p = inicio;
    for ( int i = 0; i<tamanho; i+=1, p=p->prox)
    {
        cout << setw(4) << p->dado << " ";
        if (++nc % 10 == 0) cout << "\n";  // 10 por linha
    }
    cout << "\n";
}

bool noLista::InserirInicio(int info)
{
    Node* novo = new Node;
    novo->dado = info;
    novo->prox = inicio;
    inicio     = novo;
    tamanho += 1;
    return true;
}

bool noLista::InserirFim(int info)
{
    Node* novo = new Node;
    novo->dado = info;
    novo->prox = NULL;
    if (tamanho == 0) return InserirInicio(info);
    Node* p = inicio;
    while (p->prox != NULL) { p = p->prox; }
    p->prox = novo;
    tamanho += 1;
    return true;
}

bool noLista::InserirPosicao(int info, int pos)
{
    if (pos > tamanho + 1) return false;
    if (pos <= 0) return false;
    if (pos == 1) return InserirInicio(info);
    if (pos == tamanho) return InserirFim(info);
    Node* novo = new Node;
    novo->dado = info;

    Node* p = inicio;
    // avanca pos - 1 nodes
    for (int cont = 1; cont < pos; cont += 1) p = p->prox;
    novo->prox = p->prox;
    p->prox    = novo;
    tamanho += 1;
    return true;
}

bool noLista::RemoveFim()
{
    if (tamanho == 0) return false;
    if (tamanho == 1) { return RemoveInicio(); }
    Node* ant = nullptr;
    Node* p = inicio;
    while (p->prox != NULL)
    {
        ant = p;
        p              = p->prox;
    }
    if (ant != nullptr)
        ant->prox = NULL;
    else
        inicio = nullptr;
    delete p;
    tamanho -= 1;
    return true;
}

bool noLista::RemoveInicio()
{
    if (tamanho == 0) return true;  // vazia
    Node* novo_inicio = inicio->prox;
    delete inicio;
    inicio = novo_inicio;
    tamanho -= 1;
    return true;
}

bool noLista::RemovePosicao(int Posicao)
{
    if (Posicao > tamanho) return false;
    if (Posicao < 1) return false;
    if (Posicao == 1) return RemoveInicio();
    int   Contador = 1;
    Node* ant      = nullptr;
    Node* p        = inicio;
    Node* prox     = nullptr;
    while (Contador != Posicao)
    {
        ant  = p;
        p    = p->prox;
        prox = p->prox;
        Contador++;
    };  // while()
    ant->prox = prox;
    delete p;
    tamanho -= 1;
    return true;
}

int noLista::Tamanho() { return tamanho; }

As funções tem em geral umas 10 linhas de código e não há muito que comentar. É praticamene seu código afinal.
main() com o meu original
#include <iostream>
using namespace std;

#include "noLista.h"
char        menu();

int main(void)
{
    noLista l1;
    int     posicao = 0;
    int     valor = 0;

    while(true)
    {
        switch (menu())
        {
            case 0:
                return 0; // fim
                break;

            case 1:
                cout << "\nQual valor a ser inserido ? ";
                cin >> valor;
                l1.InserirInicio(valor);
                cout << "\nOperacao realizada com sucesso ! \n";
                break;

            case 2:
                cout << "\nQual valor a ser inserido ? ";
                cin >> valor;
                l1.InserirFim(valor);
                cout << "\nOperacao realizada com sucesso ! \n";
                break;

            case 3:
                cout << "\nQual valor a ser inserido ? ";
                cin >> valor;
                cout << "\nEm qual posicao ? ";
                cin >> posicao;
                if ( l1.InserirPosicao(valor, posicao))
                    cout << "\nOperacao realizada com sucesso ! \n";
                else
                    cout << "\nPosicao invalida ! \n";
                break;

            case 4:
                cout << "\nAbaixo estao os elementos da lista \n\n";
                l1.Imprimir();
                break;

            case 5:
                if (l1.RemoveInicio())
                    cout << "\nOperacao realizada com sucesso ! \n";
                else
                    cout << "\nLista vazia, impossivel realizar "
                            "operacao ! \n";
                break;

            case 6:
                if (l1.RemoveFim())
                    cout << "\nOperacao realizada com sucesso ! \n";
                else
                    cout << "\nLista vazia, impossivel realizar "
                            "operacao ! \n";
                break;

            case 7:
                cout << "\nQual a posicao que voce deseja excluir ? ";
                cin >> posicao;
                if (l1.RemovePosicao(posicao))
                    cout << "\nOperacao realizada com sucesso ! \n";
                else
                    cout << "\nPosicao invalida ! \n";
        }
    };  // while()
    return 0; // para contentar o compilador
}

char menu()
{
    char opcao[30]{0};
    do
    {
        cout << "\
\n\
[0] - Sair\n\
[1] - Inserir no inicio da lista\n\
[2] - Inserir no fim da lista\n\
[3] - Inserir por posicao\n\
[4] - Imprimir lista\n\
[5] - Remover no inicio da lista\n\
[6] - Remover no fim da lista\n\
[7] - Remover por posicao\n\
\n\
      Digite uma opcao (0 para sair): ";
        cin.getline(opcao, 30);

    }   while ((opcao[0] < '0') || (opcao[0] > '7'));

    return (opcao[0] - '0');
}

E pode ver como parece mais simples.
Por outro lado, como os arquivos estão separados, pod eusar outros programas de teste sem mexer nonoLista.cpp...
um programa de teste para as funções
#include <iostream>
using namespace std;
#include "noLista.h"
int main(void)
{
    noLista l1;
    int     posicao = 0;
    int     valor   = 0;
    for ( int valor = 20; valor>=1; valor-=1 )
       l1.InserirPosicao(valor,1);
    l1.Imprimir();
    cout << "Tamanho agora: " << l1.Tamanho() << endl;
    while (1)
    {
        if (l1.RemovePosicao(1))
            cout << "RemoveFim() ok, restam " << l1.Tamanho() << "\n";
        else
        {
            cout << "RemoveFim() Erro restam " << l1.Tamanho() << "\n";
            break;
        }
    }
    l1.Imprimir();
    return 0;  // para contentar o compilador
}

Esse teste apenas insere 20 paras na primeira posição, mostra e depois remove o primeiro até dar erro, de modo que a lista ao final vai estar vazia...
Assim pode escrever pequenos programas e testar as funções sem mexer no código da lista...
Saída desse teste
Total de 20 elementos:

   1    2    3    4    5    6    7    8    9   10
  11   12   13   14   15   16   17   18   19   20

Tamanho agora: 20
RemoveFim() ok, restam 19
RemoveFim() ok, restam 18
RemoveFim() ok, restam 17
RemoveFim() ok, restam 16
RemoveFim() ok, restam 15
RemoveFim() ok, restam 14
RemoveFim() ok, restam 13
RemoveFim() ok, restam 12
RemoveFim() ok, restam 11
RemoveFim() ok, restam 10
RemoveFim() ok, restam 9
RemoveFim() ok, restam 8
RemoveFim() ok, restam 7
RemoveFim() ok, restam 6
RemoveFim() ok, restam 5
RemoveFim() ok, restam 4
RemoveFim() ok, restam 3
RemoveFim() ok, restam 2
RemoveFim() ok, restam 1
RemoveFim() ok, restam 0
RemoveFim() Erro restam 0
Total de 0 elementos:


text:
Q: Android: disable setting which keeps device screen on when plugged in How can I disable the development setting which prevents screen from turning off when plugged in?
Basically I want to detect user inactivity on an Android device by detecting when screen goes off, but if this setting is enabled this will never happen.
From what I found, WRITE_SECURE_SETTINGS permission should be used (rooting device/using private APIs is not a problem).

A: You could try something like this:
Settings.System.putInt(getContentResolver(), Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);


text:
Q: SELECT CASE when DISTINCT I need to list all cities in a database where there is an active employee. If the city exists in more than one state, I want to append the state name to it. So I'm trying to do something like:
SELECT Locations.LocationID,
    CASE
        WHEN Locations.City IS NOT DISTINCT
            THEN Locations.City + '(' + ISNULL(Locations.State,'') + ')'
        ELSE Locations.City
    END as LocationDescription
FROM Locations
    INNER JOIN Employees on Locations.LocationID = Employees.LocationID
WHERE Employees.Active=1
ORDER BY LocationDescription

Obviously this isn't correct syntax where I'm using DISTINCT, just not sure how to go about this.

A: I would go with the option to add the state every time, however, if you really want to do it this way you can use GROUP BY and IN clauses...
WHEN Locations.City IN (SELECT Locations.City FROM Location GROUP BY City HAVING COUNT(*) > 1)

A: You could do it using a correlated subquery, but wouldn't it be easier to always append the state? It would make the output more consistent too...
There are probably smarter ways to do it, but this should work.
SELECT l.LocationID,
    CASE
        WHEN (SELECT COUNT(City) FROM Locations WHERE L.city = city) > 1
            THEN l.City + '(' + ISNULL(l.State,'') + ')'
          ELSE l.City
    END as LocationDescription
FROM Locations L
    INNER JOIN Employees on l.LocationID = Employees.LocationID
WHERE Employees.Active=1
ORDER BY LocationDescription