text:
Q: jQuery Validate require_from_group - How to implement two groups, with only one being ultimately required? I have a form where a user is supposed to be able to search for data by entering EITHER an address (in individual street, city, country, state fields) OR one of 4 particular codes the company uses internally to describe the data.
I've assigned the address fields one class name (per the Validate rule) and the special codes fields another.
My problem is that I can't figure out how to NOT require one or the other of those two groups if the other group's fields are all filled in. IE - if the user completes all the address fields, he should not be required to fill in any of the special codes text boxes and conversely if the user populates one of the special codes, she should not be required to fill in address values.
I'm using C# and jQuery Validate 1.11 - with a fix to the original require_from_group function which resolved a reported issue of skipping all validations after an initial group validation (or something like that).
Here is the code on the form showing the fields in question:

    Address

            Street

            <asp:TextBox id="txtAddress" runat="server" Width="250px" MaxLength="65" CssClass="GroupAddress"></asp:TextBox>

            City

            <asp:TextBox id="txtCity" runat="server" Width="120px" MaxLength="60" CssClass="GroupAddress"></asp:TextBox>

            Country

            <asp:DropDownList ID="ddlCountries" CssClass="GroupAddress" runat="server" DataValueField="CountryCode" DataTextField="CountryName" AutoPostBack="true" OnSelectedIndexChanged="ddlCountries_SelectedIndexChanged"></asp:DropDownList>

            <asp:UpdatePanel ID="pnlStates" runat="server">
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="ddlCountries" EventName="SelectedIndexChanged"/>
                </Triggers>
                <ContentTemplate>
                        State

                        <asp:DropDownList ID="ddlStates" CssClass="GroupAddress" runat="server" DataValueField="GeopoliticalCode" DataTextField="GeopoliticalName"></asp:DropDownList>
                </ContentTemplate>
            </asp:UpdatePanel>

            CLLI Code

            <asp:TextBox id="txtClliCode" runat="server" Width="100px" MaxLength="11" CssClass="GroupIDCodes"></asp:TextBox>

            Site Code

            <asp:TextBox id="txtSiteCode" runat="server" Width="100px" MaxLength="8" CssClass="GroupIDCodes"></asp:TextBox>

            F&E Location Code

            <asp:TextBox ID="txtLocationCode" runat="server" MaxLength="10" Columns="12" CssClass="GroupIDCodes"></asp:TextBox>

            MUX Code

            <asp:TextBox id="txtMuxCode" runat="server" Width="50px" MaxLength="3" CssClass="GroupIDCodes"></asp:TextBox>

        <asp:Button id="btnSubmit" runat="server" Text="Search"     onclick="btnSubmit_Click"></asp:Button>
        <asp:Button id="btnClear" runat="server" Text="Clear" onclick="btnClear_Click" CausesValidation="False" CssClass="cancel"></asp:Button>

And here is how I'm utilizing the require_from_group2 function:
$(function () {
    jQuery.validator.messages.required = "";

    $('#userInputForm').validate({
        rules: {
            txtAddress: {
                minlength: 6,
                require_from_group2: [4, ".GroupAddress"]
            },
            txtCity: { require_from_group2: [4, ".GroupAddress"] },
            ddlCountries: { require_from_group2: [4, ".GroupAddress"] },
            ddlStates: { require_from_group2: [4, ".GroupAddress"] },
            txtClliCode: { require_from_group2: [1, ".GroupIDCodes"] },
            txtSiteCode: { require_from_group2: [1, ".GroupIDCodes"] },
            txtLocationCode: { require_from_group2: [1, ".GroupIDCodes"] },
            txtMuxCode: { require_from_group2: [1, ".GroupIDCodes"] }
        },
        //End rules
        groups: {
            Address: "txtAddress txtCity ddlCountries ddlStates",
            OtherCodes: "txtClliCode txtSiteCode txtLocationCode txtMuxCode"
        },
        //End groups
        messages: {
            txtAddress: { minlength: "Street requires at least 6 characters", require_from_group2: "All address fields are required when searching by address" },
            txtCity: { require_from_group2: "All address fields are required when searching by address" },
            ddlCountries: { require_from_group2: "All address fields are required when searching by address" },
            ddlStates: { require_from_group2: "All address fields are required when searching by address" },
            txtClliCode: { require_from_group2: "At least one of the bottom 4 code fields must be provided if not searching by address" },
            txtSiteCode: { require_from_group2: "At least one of the bottom 4 code fields must be provided if not searching by address" },
            txtLocationCode: { require_from_group2: "At least one of the bottom 4 code fields must be provided if not searching by address" },
            txtMuxCode: { require_from_group2: "At least one of the bottom 4 code fields must be provided if not searching by address" }
        },
        //End messages
        errorLabelContainer: "#errorMessageDetailContainerLeft"
    });
});

And just in case, here's the fixed require_from_group:
jQuery.validator.addMethod("require_from_group2", function (value, element, options) {
    var validator = this;
    var minRequired = options[0];
    var selector = options[1];
    var validOrNot = jQuery(selector, element.form).filter(function () {
        return validator.elementValue(this);
    }).length >= minRequired;

    // remove all events in namespace upload

    jQuery(selector, element.form).off('.require_from_group2');

    if (this.settings.onkeyup) {
        jQuery(selector, element.form).on({
            'keyup.require_from_group2': function (e) {
                jQuery(selector, element.form).valid();
            }
        });
    }
    if (this.settings.onfocusin) {
        jQuery(selector, element.form).on({
            'focusin.require_from_group2': function (e) {
                jQuery(selector, element.form).valid();
            }
        });
    }
    if (this.settings.click) {
        jQuery(selector, element.form).on({
            'click.require_from_group2': function (e) {
                jQuery(selector, element.form).valid();
            }
        });
    }
    if (this.settings.focusout) {
        jQuery(selector, element.form).on({
            'focusout.require_from_group2': function (e) {
                jQuery(selector, element.form).valid();
            }
        });
    }

    return validOrNot;
}, jQuery.format("Please fill at least {0} of these fields."));

Any help is certainly appreciated!

A: Your code is overly complex and I'm not sure require_from_group is the appropriate method for what you're trying to do.  It's only supposed to make any specific number of elements FROM a group of elements required.  In other words, if you have six items in your group and you specify "2" as the argument, then this method/rule will only be satisfied if any two fields from your group of six are filled out.
In your case, you want everything within one group filled out as opposed to everything in another group filled out, which is something else entirely.
With jQuery Validate, you cannot switch validation on/off dynamically.  Once defined and initialized, it stays "on".  However, you can use the .rules() method to dynamically over-write, add or remove any rule on any field(s) at any time.
I would make the user physically select one group or the other by clicking a radio or checkbox.  This will also reduce confusion about what the user is expected to fill in.  However, if you don't like that idea, you could instead use the blur, change, or another event on any field to trigger similar "rule altering" code.
Then based on the event, you can modify your rules accordingly.
$('input[name="radio"]:radio').on('change', function () {  // on selection event
    if ($('#one').is(':checked')) {            // if first radio is selected
        $('.inputGroup1 ').each(function () {  // add rules to first group
            $(this).rules('add', {
                required: true
            });
        });
        $('.inputGroup2').each(function () {  // remove rules from second group
            $(this).rules('remove');
        });
    } else {                                  // if second radio is selected
        $('.inputGroup2').each(function () {  // add rules to second group
            $(this).rules('add', {
                required: true
            });
        });
        $('.inputGroup1').each(function () {  // remove rules from first group
            $(this).rules('remove');
        });
    };
});

Proof of Concept:  http://jsfiddle.net/tF8Wp/


text:
Q: Docker build outputs not working in Bitbucket pipelines I'm trying to use the custom build output within docker to export some files in to the build environment for artifacts but even though the files seem to be outputted there's nothing I can find in the build agent.
For simplicity here's a cutdown version of a dockerfile that uses a scratch image as the final image with a single message file.
FROM debian as build
RUN echo "Hello World" > message

FROM scratch as final
COPY --from=build message .

And here's an example of the scripts run for out ci pipeline within the bitbucket-pipelines.yml
image: atlassian/default-image:2

pipelines:
  default:
     - step:
        name: Build
        script:
          - docker build -o build-output .
          - ls
          - find / -name "build-output" -type d
        services:
          - docker

Here's the log output from Bitbucket pipelines.
Images used:
    build : docker.io/atlassian/default-image@sha256:d8ae266b47fce4078de5d193032220e9e1fb88106d89505a120dfe41cb592a7b
+ docker build -o build-output .
Sending build context to Docker daemon  65.02kB
Step 1/4 : FROM debian as build
latest: Pulling from library/debian
627b765e08d1: Pulling fs layer
627b765e08d1: Verifying Checksum
627b765e08d1: Download complete
627b765e08d1: Pull complete
Digest: sha256:cc58a29c333ee594f7624d968123429b26916face46169304f07580644dde6b2
Status: Downloaded newer image for debian:latest
 ---> 0980b84bde89
Step 2/4 : RUN echo "Hello World" > message
 ---> Running in dfcb5471840d
Removing intermediate container dfcb5471840d
 ---> 245eb3333d6c
Step 3/4 : FROM scratch as final
 --->
Step 4/4 : COPY --from=build message .
 ---> a8805c31d962
Successfully built a8805c31d962

+ ls
Dockerfile
bitbucket-pipelines.yml

+ find / -name "build-output" -type d

As you can see the build-output directory is nowhere to be seen!
Here's a public build with the whole example - https://bitbucket.org/kev_bite/dockerbuildoutput/addon/pipelines/home#!/results/2

redpajama_set_name: RedPajamaStackExchange


text:
Q: Split field a string and compare each value with string linq c# I'm trying to search in DataTable with three string columns[start_date, end_date, expected_visits] using LINQ, but the third column has many lines as shown

So I split the third one with \n but I want to loop over date to compare it with text of txtSearchYear and return the result as DataTable, When I tried to use ForEach as shown in my code, An error appeared with me says A local or parameter named 'e' cannot be declared in this scope because that name is used in an enclosing local scope to define a local here is my code ...
var tblResult =
    tbl
        .AsEnumerable()
        .Where(x =>
            x.Field<string>("start_date").Substring(0, 4).Equals(txtSearchYear.Text.Trim())
            || x.Field<string>("end_date").Substring(0, 4).Equals(txtSearchYear.Text.Trim())
            || x.Field<string>("expected_visits").Split('\n').ToList().ForEach((e) =>
            {
                e.Substring(0, 4).Equals(txtSearchYear.Text.Trim())
            }));

if (tblResult.Any())
{
    GetData(tblResult.CopyToDataTable());
}
else
{
    DGVData.Rows.Clear();
}

A: I would directly compare the year and use the year (int) in lambda and trying to handle the dates as List or Array of Dates instead of comparing substrings, e.g.
DateTime now = DateTime.Now;

      int year = -1;
      if (!Int32.TryParse(txtSearchYear.Text.Trim(), out year) || year < 1900)
      {
        throw new InvalidProgramException($"Year {year} isn't valid for us.");
      }

      List<DateTime> dates = new List<DateTime>();
      dates.Add(now);
      dates.Add(now.Subtract(new TimeSpan(0, 10, 10)));
      dates.Add(now.Subtract(new TimeSpan(0, 20, 20)));
      /* ... */

      var myList = dates.AsEnumerable().Where(x => x.Year == year).ToList();
      Action<DateTime> action = new Action<DateTime>(MyDelegateAction);
      myList.ForEach(e => MyDelegateAction(e));

    }

    private static void MyDelegateAction(DateTime date) { /* do somewhat */; }

kind regards, heinrich.


text:
Q: Связь модели сериала со списком жанров У меня есть модель сериала, которая в свою очередь должна содержать в себе коллекцию моделей жанров.
Как организовать такую связь правильно? При попытке указания в модели списка, или же массива жанров, связать это дело правильно не удалось.
Модель сериала:
public class Serial
{
    public int SerialId { get; set; }
    public string SerialTitle { get; set; }
    public string SerialDescription { get; set; }
    public string PreviewImage { get; set; }
    public int Year { get; set; }
    public Genre[] Genres { get; set; }
    public int SeriesCount { get; set; }
    public int SeriesReleased { get; set; }
    public string Studio { get; set; }
    public int Country { get; set; }
}

Модель жанра:
public class Genre
{
    public int GenreId { get; set; }
    public string Description { get; set; }
}

При таком раскладе, в базе данных появляется у таблицы жанров дополнительное поле SerialId, туда можно указать только один айди сериала.

A: У вас отношение многие-ко-многим, делается так:
public class Serial
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }

    public virtual ICollection<Genre> Genres { get; set; }

    public Serial()
    {
        Genres = new List<Genre>();
    }
}

public class Genre
{
    public int Id { get; set; }
    public string Description { get; set; }

    public virtual ICollection<Serial> Serials { get; set; }

    public Genre()
    {
        Serials = new List<Serial>();
    }
}

https://metanit.com/sharp/entityframeworkcore/3.6.php


text:
Q: document object points to iframe document I'm trying to understand what's happening in my code.
So what I'm doing is
1. Iframe in a page - points to aspx page with some javascript. Worth noting its same domain so no issues with access.
2. Code in iframe window gets parent document object and injects requirejs into parent head with config in place to load my-custom-code.js
3. so my-custom-code.js is loaded into the head of the parent page and runs fine.
!!! This is what I don't get !!!
When I try to use window and document in my-custom-code.js they actually point to child(iframe) document and window???
So I want to understand HOW IT WORKS.
Thanks
UPDATE: iframe js file
var $doc = $(parent.document);
var head = $doc.find("head");
var body = $doc.find("body");
var reqConfigScript = "<script class='require-default-config'>var require = { deps: ['http:\/\/localhost/scripts/parent-main.js'], callback: function(main){ } };</script>";
body.append(reqConfigScript);
var parentScript = "<script src='http:\/\/" + location.host + "/scripts/require-2.1.11.min.js' type=\"text/javascript\"></script>";
head.append(parentScript);

A: Okay, it's a bit hard to guess because I don't know exactly how the library works... but try this:
parent.require = {
    deps: ['http:\/\/localhost/scripts/parent-main.js'],
    callback: function(main){ }
};
var parentScript = parent.document.createElement('script');
// important to use `parent.document` so the right document owns the script
parentScript.src = "http://"+location.host+"/script/require-2.1.11.min.js";
parentScript.type = "text/javascript";
parent.document.body.appendChild(parentScript);


text:
Q: Making Python loggers output all messages to stdout in addition to log file Is there a way to make Python logging using the logging module automatically output things to stdout in addition to the log file where they are supposed to go? For example, I'd like all calls to logger.warning, logger.critical, logger.error to go to their intended places but in addition always be copied to stdout. This is to avoid duplicating messages like:
mylogger.critical("something failed")
print("something failed")

A: All logging output is handled by the handlers; just add a logging.StreamHandler() to the root logger.
Here's an example configuring a stream handler (using stdout instead of the default stderr) and adding it to the root logger:
import logging
import sys

root = logging.getLogger()
root.setLevel(logging.DEBUG)

handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
root.addHandler(handler)

A: It's possible using multiple handlers.
import logging
import auxiliary_module

# create logger with 'spam_application'
log = logging.getLogger('spam_application')
log.setLevel(logging.DEBUG)

# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
log.addHandler(fh)

# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
ch.setFormatter(formatter)
log.addHandler(ch)

log.info('creating an instance of auxiliary_module.Auxiliary')
a = auxiliary_module.Auxiliary()
log.info('created an instance of auxiliary_module.Auxiliary')

log.info('calling auxiliary_module.Auxiliary.do_something')
a.do_something()
log.info('finished auxiliary_module.Auxiliary.do_something')

log.info('calling auxiliary_module.some_function()')
auxiliary_module.some_function()
log.info('done with auxiliary_module.some_function()')

# remember to close the handlers
for handler in log.handlers:
    handler.close()
    log.removeFilter(handler)

Please see: https://docs.python.org/2/howto/logging-cookbook.html

A: The simplest way to log to stdout using basicConfig:
import logging
import sys

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)

A: Here is a solution based on the powerful but poorly documented logging.config.dictConfig method.
Instead of sending every log message to stdout, it sends messages with log level ERROR and higher to stderr and everything else to stdout.
This can be useful if other parts of the system are listening to stderr or stdout.
import logging
import logging.config
import sys

class _ExcludeErrorsFilter(logging.Filter):
    def filter(self, record):
        """Only lets through log messages with log level below ERROR ."""
        return record.levelno < logging.ERROR

config = {
    'version': 1,
    'filters': {
        'exclude_errors': {
            '()': _ExcludeErrorsFilter
        }
    },
    'formatters': {
        # Modify log message format here or replace with your custom formatter class
        'my_formatter': {
            'format': '(%(process)d) %(asctime)s %(name)s (line %(lineno)s) | %(levelname)s %(message)s'
        }
    },
    'handlers': {
        'console_stderr': {
            # Sends log messages with log level ERROR or higher to stderr
            'class': 'logging.StreamHandler',
            'level': 'ERROR',
            'formatter': 'my_formatter',
            'stream': sys.stderr
        },
        'console_stdout': {
            # Sends log messages with log level lower than ERROR to stdout
            'class': 'logging.StreamHandler',
            'level': 'DEBUG',
            'formatter': 'my_formatter',
            'filters': ['exclude_errors'],
            'stream': sys.stdout
        },
        'file': {
            # Sends all log messages to a file
            'class': 'logging.FileHandler',
            'level': 'DEBUG',
            'formatter': 'my_formatter',
            'filename': 'my.log',
            'encoding': 'utf8'
        }
    },
    'root': {
        # In general, this should be kept at 'NOTSET'.
        # Otherwise it would interfere with the log levels set for each handler.
        'level': 'NOTSET',
        'handlers': ['console_stderr', 'console_stdout', 'file']
    },
}

logging.config.dictConfig(config)

A: The simplest way to log to file and to stderr:
import logging

logging.basicConfig(filename="logfile.txt")
stderrLogger=logging.StreamHandler()
stderrLogger.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
logging.getLogger().addHandler(stderrLogger)

A: For more detailed explanations - great documentation at that link.
For example: It's easy, you only need to set up two loggers.
import sys
import logging

logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('my_log_info.log')
sh = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('[%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s', datefmt='%a, %d %b %Y %H:%M:%S')
fh.setFormatter(formatter)
sh.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(sh)

def hello_logger():
    logger.info("Hello info")
    logger.critical("Hello critical")
    logger.warning("Hello warning")
    logger.debug("Hello debug")

if __name__ == "__main__":
    print(hello_logger())

Output - terminal:
[Mon, 10 Aug 2020 12:44:25] INFO [TestLoger.py.hello_logger:15] Hello info
[Mon, 10 Aug 2020 12:44:25] CRITICAL [TestLoger.py.hello_logger:16] Hello critical
[Mon, 10 Aug 2020 12:44:25] WARNING [TestLoger.py.hello_logger:17] Hello warning
[Mon, 10 Aug 2020 12:44:25] DEBUG [TestLoger.py.hello_logger:18] Hello debug
None

Output - in file:

UPDATE: color terminal
Package:
pip install colorlog

Code:
import sys
import logging
import colorlog

logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('my_log_info.log')
sh = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('[%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s', datefmt='%a, %d %b %Y %H:%M:%S')
fh.setFormatter(formatter)
sh.setFormatter(colorlog.ColoredFormatter('%(log_color)s [%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s', datefmt='%a, %d %b %Y %H:%M:%S'))
logger.addHandler(fh)
logger.addHandler(sh)

def hello_logger():
    logger.info("Hello info")
    logger.critical("Hello critical")
    logger.warning("Hello warning")
    logger.debug("Hello debug")
    logger.error("Error message")

if __name__ == "__main__":
    hello_logger()

output:

Recommendation:
Complete logger configuration from INI file, which also includes setup for stdout and debug.log:

*

*handler_file

*

*level=WARNING

*handler_screen

*

*level=DEBUG

A: Here's an extremely simple example:
import logging
l = logging.getLogger("test")

# Add a file logger
f = logging.FileHandler("test.log")
l.addHandler(f)

# Add a stream logger
s = logging.StreamHandler()
l.addHandler(s)

# Send a test message to both -- critical will always log
l.critical("test msg")

The output will show "test msg" on stdout and also in the file.

A: Since no one has shared a neat two liner, I will share my own:
logging.basicConfig(filename='logs.log', level=logging.DEBUG, format="%(asctime)s:%(levelname)s: %(message)s")
logging.getLogger().addHandler(logging.StreamHandler())

A: You could create two handlers for file and stdout and then create one logger with handlers argument to basicConfig. It could be useful if you have the same log_level and format output for both handlers:
import logging
import sys

file_handler = logging.FileHandler(filename='tmp.log')
stdout_handler = logging.StreamHandler(stream=sys.stdout)
handlers = [file_handler, stdout_handler]

logging.basicConfig(
    level=logging.DEBUG,
    format='[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s',
    handlers=handlers
)

logger = logging.getLogger('LOGGER_NAME')

A: You should use tee. Configure the app to write to stdout, and run
python3 app.py | tee log.txt

Then you'll get the log messages in your stdout as well as in log.txt.

A: I simplified my source code (whose original version is OOP and uses a configuration file), to give you an alternative solution to @EliasStrehle's one, without using the dictConfig (thus easiest to integrate with existing source code):
import logging
import sys

def create_stream_handler(stream, formatter, level, message_filter=None):
    handler = logging.StreamHandler(stream=stream)
    handler.setLevel(level)
    handler.setFormatter(formatter)
    if message_filter:
        handler.addFilter(message_filter)
    return handler

def configure_logger(logger: logging.Logger, enable_console: bool = True, enable_file: bool = True):
    if not logger.handlers:
        if enable_console:
            message_format: str = '{asctime:20} {name:16} {levelname:8} {message}'
            date_format: str = '%Y/%m/%d %H:%M:%S'
            level: int = logging.DEBUG
            formatter = logging.Formatter(message_format, date_format, '{')

            # Configures error output (from Warning levels).
            error_output_handler = create_stream_handler(sys.stderr, formatter,
                                                         max(level, logging.WARNING))
            logger.addHandler(error_output_handler)

            # Configures standard output (from configured Level, if lower than Warning,
            #  and excluding everything from Warning and higher).
            if level < logging.WARNING:
                standard_output_filter = lambda record: record.levelno < logging.WARNING
                standard_output_handler = create_stream_handler(sys.stdout, formatter, level,
                                                                standard_output_filter)
                logger.addHandler(standard_output_handler)

        if enable_file:
            message_format: str = '{asctime:20} {name:16} {levelname:8} {message}'
            date_format: str = '%Y/%m/%d %H:%M:%S'
            level: int = logging.DEBUG
            output_file: str = '/tmp/so_test.log'

            handler = logging.FileHandler(output_file)
            formatter = logging.Formatter(message_format, date_format, '{')
            handler.setLevel(level)
            handler.setFormatter(formatter)
            logger.addHandler(handler)

This is a very simple way to test it:
logger: logging.Logger = logging.getLogger('MyLogger')
logger.setLevel(logging.DEBUG)
configure_logger(logger, True, True)
logger.debug('Debug message ...')
logger.info('Info message ...')
logger.warning('Warning ...')
logger.error('Error ...')
logger.fatal('Fatal message ...')


text:
Q: python random.sample("abc",3) . how to use regular expressions in place of "abc" I am trying to generate random number in python using random.sample . This is how I am writing code .
import random
r = "".join(random.sample("abcdefghijklmnopqrstuvwxyz", 10))

Above code generates random numbers of length 10 whose letters are populated from the letters a-z. How can i use regular expressions over there like [a-z]?

A: Just use this instead
>>> from string import ascii_lowercase, ascii_uppercase
>>> ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

If you want to generate digits you can use range
>>> map(str, range(10))
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

A: If you have the pyparsing module handy, you can use the srange method to expand a regex character set to a string of characters:
>>> from pyparsing import srange
>>> srange('[a-z]')
u'abcdefghijklmnopqrstuvwxyz'
>>> srange('[a-z0-9]')
u'abcdefghijklmnopqrstuvwxyz0123456789'


text:
Q: How do I use group_concat() in MySQL? MySQL:
SELECT
group_concat(cu1.cu_inflow_type),count(cu1.cu_inflow_type)
FROM cs_test cu1
LEFT JOIN cs_test cu2
ON cu2.seq=cu1.seq
GROUP BY cu1.cu_inflow_type

Result:
    ======================================================================
group_concat(cu1.cu_inflow_type)    |    count(cu1.cu_inflow_type)
----------------------------------------------------------------------
001,001,001,001,001,001,001,00..    | 27
002,002                             | 2
003,003                             | 2
004,004,004                         | 3
005                                 | 1
006                                 | 1
----------------------------------------------------------------------

The query runs, but it isn't the result I want. I would like it to look like:
======================================================================
group_concat(cu1.cu_inflow_type)    |    count(cu1.cu_inflow_type)
----------------------------------------------------------------------
001,001,001,001,001,001,001,00..    | 27
002,002,003,003                     | 4             <-- add!
004,004,004                         | 3
005,006                             | 2             <-- add!
----------------------------------------------------------------------

'002,002' + '003,003' = 002,002,003,003
I don't understand how to use group_concat() in MySQL to get the desired result. Can someone help me?

A: You may please use some other field in the group by clause


text:
Q: PHPExcel error: Undefined index I want to export mysql table called "lokasi" in to excel but these are the errors I am getting:

Notice: Undefined index: no_lokasi in
  C:\xampp\htdocs\inventory\pages\report.php on line 14
Notice: Undefined index: nama_lokasi in
  C:\xampp\htdocs\inventory\pages\report.php on line 15
Notice: Undefined index: keterangan_lokasi in
  C:\xampp\htdocs\inventory\pages\report.php on line 16
Notice: Undefined index: no_lokasi in
  C:\xampp\htdocs\inventory\pages\report.php on line 14
Notice: Undefined index: nama_lokasi in
  C:\xampp\htdocs\inventory\pages\report.php on line 15

and here is my code:
<?php
    if($_SESSION["role"]!=1){
        header('location:login.php');
    }
    else {
        require_once dirname(__FILE__) . '\..\bower_components\phpexcel\Classes\PHPExcel.php';

        if(isset($_POST["submit"])){

            $objPHPExcel = new PHPExcel();
            $objWorksheet = $objPHPExcel->setActiveSheetIndex(0);

            $result = mysql_query("SELECT * FROM lokasi",$conn);

            $rowCount= 1;
            while($row=mysql_fetch_row($result)){
                $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['no_lokasi']);
                $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['nama_lokasi']);
                $objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $row['keterangan_lokasi']);
                $rowCount++;
            }

            $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
            $objWriter->save('some_excel_file.xlsx');
        }
?>

Print Preview

                                            Nama Lokasi
                                            Keterangan
                                            Action

                                <?php
                                    $result = mysql_query('SELECT * from lokasi');
                                    while($list = mysql_fetch_row($result)){
                                        echo'

                                                '.$list[0].'
                                                '.$list[1].'
                                                '.$list[2].'

                                        ';
                                    }
                                ?>

                                <form role="form" method="post">
                                    <button type="submit" class="btn btn-primary" name="submit">Submit</button>
                                </form>

<?php
    };
?>

A: You are using mysql_fetch_row to fetch the results and you are indexing like this
while($row=mysql_fetch_row($result)){
                $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['no_lokasi']);
                $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['nama_lokasi']);
                $objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $row['keterangan_lokasi']);
                $rowCount++;
}

change this to
while($row=mysql_fetch_row($result)){
                $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row[0]); // to corresponding row indexes
                $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row[1]);
                $objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $row[2]);
                $rowCount++;
}

Because The mysql_fetch_row() function fetches one row from a result-set and returns it as an enumerated array.


text:
Q: Having trouble including header files I can only use header files that I add to C:\SDL2-w64\include, but I Can't get it to link to the include folder inside my project folder.
for example: I have a folder called "MyProject" and its located at C:\Users\User\Desktop\MyProject, inside the project folder there is an "Include" folder located at \MyProject\Include then I add a header file called "head.h" to the Include path. in my code I use #include <head.h>, I then get the error cannot open source file "head.h", but if I add head.h to C:\SDL2-w64\include it works perfectly fine.
anyone know how to include the Include folder located in my project folder?

A: Assuming the file doing the including is located at C:\Users\User\Desktop\MyProject, try using #include "Include/head.h". This is because there is a difference between using quotations ("") and angle brackets (<>) in your includes.
The reason is explained in this answer: https://stackoverflow.com/a/3162067/19099501
But to summarize it, with most compilers, #include "blah.h" will search in the local directory first, and then the stuff it can reach from what's in your PATH variable, and #include <blah.h> will search from what's in PATH only. I am guessing that C:\SDL2-w64\include is in your PATH. That is probably why when you moved the header file to that location, it was able to find it.


text:
Q: java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer Exception I am new to JAX-RS Annotations, When I try to run this I got an error like

java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer,

Help me to resolve this issue and I added commons-logging 1.2 jar and jersey-bundle 1.18 jar.
index.html
Click Here

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                             http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">
    <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.javatpoint.rest</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

HelloService.java
package com.javatpoint.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class HelloService{
    @GET
    @Path("/{param}")
    public Response getMsg(@PathParam("param") String msg) {
        String output = "Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }
}

A: Use this web.xml servlet directive - change necessary info:
<servlet> <servlet-name>Jersey REST Service</servlet-name>  <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>  <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.javatpoint.rest</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>


text:
Q: HTML column below minimum width in Wordpress On a downloads overview page for a download manager plugin for Wordpress there are multiple columns and the shortcode column overlaps the author column. I've set that column's minimum width to 175px but when the window is resized still shrinks below it's minimum width.
.column-wpdmshortcode{
    -webkit-font-smoothing: subpixel-antialiased;
    border-bottom-color: rgb(225, 225, 225);
    border-bottom-style: solid;
    border-bottom-width: 1px;
    border-collapse: separate;
    color: rgb(50, 55, 60);
    display: table-cell;
    font-family: 'Open Sans', sans-serif;
    font-size: 14px;
    font-weight: normal;
    height: 22px;
    line-height: 19.6000003814697px;
    padding-bottom: 8px;
    padding-left: 10px;
    padding-right: 10px;
    padding-top: 8px;
    text-align: left;
    vertical-align: middle;
    width: 77px;
    word-wrap: break-word;

    min-width: 175px;
}

All inherited css properties:
http://spencerlarry.com/docs/all-inherited-styles.txt

I'm wondering how it's possible to have an element like this be below it's min-width.  Any ideas how I could fix this problem?

A: min-width and max-width are not supported on table cells.
From the CSS2.1 specification:

In CSS 2.1, the effect of 'min-width' and 'max-width' on tables,
  inline tables, table cells, table columns, and column groups is
  undefined.

So one thing you should do is to set the width of the cell (and not the min-width), and use the table-layout property to fixed so the cells widths will no be longer auto calculated.


text:
Q: How do I get all values of checkbox those are checked using ajax/jQuery in asp.net When i click the Select working days / hours Checkbox the list of days will be displayed. for example if i click the sunday checkbox check box the value entered in the checkbox should be call to javascript function. in case am not click the checkbox the value display should be Null.
DEMO LINK HTML
$(document).ready(function () {

            $("input#btnDocBusinesshours").click(function () { SaveDocBusinesshours(null) });
        });

Call Ajax Function
function callAjax(jparms) {
            $.ajax({
                type: "POST",
                url: jparms.url,
                data: jparms.data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (jparms.action == "SaveDocBusinesshours")
                        SaveDocBusinesshours(response.d)

                },
                failure: function (response) { response.d; }
            });
        }

Save Ajax Function
 function SaveDocBusinesshours(response) {
            var values = $('input[type="checkbox"].single:checked').map(function () {
                return $(this).val();
            }).toArray();

            if (response == null) {
                callAjax({
                    url: pageUrl + '/SaveDocBusinesshours',
                    data: '{"Doctorid": "' + $("#<%=hdnDoctorId.ClientID %>").val() + '","WorkingDaysID" : "' + $("#<%=hdnBusiness.ClientID %>").val() + '","Sunday" : "' + $("#<%=ChkSUN.ClientID %>").val() + '","Monday" : "' + $("#<%=ChkMON.ClientID %>").val() + '","Thuesday" : "' + $("#<%=ChkTUE.ClientID %>").val() + '"}',
                    action: "SaveDocBusinesshours"
                });
                window.location.reload();
            }
            else {
                loading(false);
                if (response.AjxContactId != null) {
                    $('#<%=hdnBusiness.ClientID%>').val(response.AjxContactId);
                }
                msg(true, response.Message);
            }

        }

Webmethod:
[WebMethod]
    public static UserAjax SaveDocBusinesshours(string Doctorid, string WorkingDaysID, string Sunday, string Monday, string Thuesday)
    {
        UserAjax oUserAjax = new UserAjax();
        return oUserAjax;
    }


text:
Q: When I new add java file or open java file, how can I set the default open state is checked the 'User Soft Wraps'?
This is my IntelliJ IDEA, a java file is open, you can see in the upper snapshot, but I want when I open the java file, the User Soft Wraps default is be checked, where I can set the option?

A: All you need to do is to set it in preferences.

A: You use Ctrl + Alt  + S or File -> Settingg to goto the Settings panel, then check the Eidtor->General -> Soft Wraps: Use soft wraps in editor.

Then it will default use User Soft Wraps in your IntelliJ IDEA.


text:
Q: Removing strings based on substrings I want to remove substrings from a string. These substrings are always between whitespaces and contain either push or pull.
Let's say I have the following string:
col-md-4 col-sm-6 col-md-pull-6 col-sm-push-4

How would I get the following (using PHP preg_replace)?
col-md-4 col-sm-6

A: You can do it like this:
$result = preg_replace('~(?:\s*+\S*pu(?:ll|sh)\S*)+~', '', $str);

pattern details:
~                # pattern delimiter
(?:              # open a non capturing group
    \s*+         # zero or more whitespaces (possessive)
    \S*          # zero or more non-whitespaces
    pu(?:ll|sh)  # push or pull
    \S*
)+               # repeat the non capturing group (1 or more)
~

Note: if the string begins with "push" or "pull", this pattern may let a leading whitespace, in this case, use rtrim to remove it.
Depending how looks your string, this variant that unrools the loop (?:[^p\s]+|p+(?!u(?:ll|sh)))*+ (that replaces more explicitly \S*) may be more performant:
(?:\s*+[^p\s]*+(?:p+(?!u(?:ll|sh))[^p\s]*)*+pu(?:ll|sh)\S*)+

about possessive quantifiers and lookarounds

A: [^ ]*(?:push|pull)[^ ]*

Try this.Replace by empty string.See demo.
or
\s*[^\s]*(?:push|pull)[^\s]*

https://regex101.com/r/aI4rA5/7
$re = "/[^ ]*(?:push|pull)[^ ]*/m";
$str = "col-md-4 col-sm-6 col-md-pull-6 col-sm-pull-4";
$subst = "";

$result = preg_replace($re, $subst, $str);

A: It also removes the spaces which exists before the sub-strings.
\h+\S*\b(?:push|pull)\b\S*|^\S*\b(?:push|pull)\b\S*\h+

Code:
$re = "/\\h+\\S*\\b(?:push|pull)\\b\\S*|^\\S*\\b(?:push|pull)\\b\\S*\\h+/m";
$str = "col-md-4 col-sm-6 col-md-pull-6 col-sm-pull-4\ncol-md-pull-6 foo bar";
$subst = "";

$result = preg_replace($re, $subst, $str);

DEMO


text:
Q: Problemas com médias Preciso inserir 3 notas, fazer a média com as 3 notas, depois com a maior nota e a segunda maior nota , depois com a maior nota e a pior nota.
#include<stdio.h>
int meio(int a, int b, int c)
{
    if(a>b && a<c)
    return a;
    else
    return b,c;
}
int menor (int a, int b, int c)
{
if (a<b && a<c)
return a;
else
return b,c;

}
int maior (int a, int b, int c)
{
if (a > b && a>c)
 return a;
else
 return b,c;
}
main()
{
float M,MDM;
int n1,n2,n3;
printf("\n primeira nota: ");
scanf("%d",&n1);
printf("\n segunda nota: ");
scanf("%d",&n2);
printf("\n terceira nota: ");
scanf("%d",&n3);
printf("\n Maior nota = %d",maior(n1,n2,n3));
printf("\n Menor nota = %d",menor(n1,n2,n3));
printf("\n Segunda maior nota=%d",meio(n1,n2,n3));
M=(n1+n2+n3)/3;
printf("\n media:%.2f",M);
}

A: No comando return b, c;, o operador vírgula retorna apenas o último elemento separado pela vírgula, e por isso não tem um sentido lógico no seu programa. Por exemplo, na função maior, ao invés de ser return b, c;, deveria ser calculado o maior entre os dois.
int maior (int a, int b, int c){
    if (a > b && a > c) return a;
    if (b > a && b > c) return b;
    return c;
}

Utilize a mesma lógica para as funções menor e meio e seu programa irá funcionar.


text:
Q: Using Dominated Convergence Theorem to compute limit? I want to compute the following limit using the Dominated Convergence Theorem:
$$\lim_{n\to \infty}\int_{0}^\pi f_{n}(x) dx$$
where $$f_{n}(x)=(sinx)^{1\over \log_{10}(log_{10}(n))} \text{ for }n>10. $$
So far, however, I haven't been able to find a suitable dominating function, $g(x)$.
If I'm not mistaken, $|f_{n}(x)|\leq 1$, but $g(x) = 1$ is not integrable since it's a constant function. I would appreciate any hints or tips in the right direction.

A: Note that for all $x$, $f_n(x)I_{[0,\pi]}(x)\leq I_{[0, \pi]}(x)$ and it is the case that $ I_{[0, \pi]}(x)$ is an integrable function.

A: $|(\sin{x})^{1\over \log_{10}(\log_{10}(n))}| \leq 1$ since $\sin{x}\geq 0$ on $[0,\pi]$
So by Bounded Convergence Theorem you have tha conclusion.


text:
Q: When to use Option I learn Scala for some time and can't clearly understand the usage of Option. It helps me to avoid null checks when I chain functions (according to docs). That's clear for me :)
Next I see that Option can be kind of indicator for developer that null value is possible here and it must be handled. Is it true? If yes should I use Option whereever it's possible? For example
class Racer {
    val car = new Car()
}

I have Racer class and I'm sure that car field can't be null (because it's constant and get a value when I create Racer instance). No need for Option here.
class Racer {
    var car = new Car()
}

Here I make it so that the car can change. And it's possible for someone to assign null to car. Should I use Option here? If yes I notice that all my class fields are candidates for Option. And my code looks like this
class Racer {
    var car: Option[Car] = None
    var currentRace: Option[Race] = None
    var team: Option[Team] = None
    ...
}

Does it look good? For me it seems kind of Option overusing.
def foo(): Result = {
    if( something )
        new Result()
    else
        null
}

I have a method which can return null. Should I return Option instead? Should I always do it if it's possible for method to return null?
Any thoughts about it would be helpful. Thanks in advance!
My question is similiar to Why option but I think it's not the same. It's more about when, not why. :)

A: While Option can makes your class definition look verbose, the alternative is to not know when you need to test whether a variable is defined.  I think that in your example, if your class were immutable (all the fields were vals), you would not need so many Options.
For your method foo, if you return null, you need to document it and the client needs to read that documentation.  Then the client will write a bunch of code like:
val result = foo(x)
if (result != null) {
  println(result)
}

If instead you define foo to return an Option[Result], the type system forces the client to handle the possibility of an undefined result.  They also have the full power of the collections classes.
result foreach println

An additional advantage of using the collections method with an Option instead of testing for null is that if your method is extended to a multi-element collection (such as a List), you might not need to change your code at all.  For example, you might initially assume your Racer can only have a single crew, so you define val crew: Option[Crew] and you might test if the crew is older than 30 with crew.forall(_.age > 30).getOrElse(false).  Now if you changed the definition to val crew: List[Crew] your old code would still compile and now you would check if all of your crew members are over 30.
Sometimes you need to deal with null because libraries you are using may return it.  For example, when you get a resource, you might get a null result.  Fortunately, it is easy to defensively wrap results so they are transformed into an option.
val resource = Option(this.getClass.getResource("foo"))

If getResource returned null then resource equals None, and otherwise it is a Some[URL].  Cool!
Unfortunately, Option is likely to have some overhead because it involves an extra object creation.  However, that overhead is minimal compared to a null pointer exception!

A: The idea behind Options is to get rid off null, so yes, you should use them instead of returning "null or a value". That's also why, if you want to model optional fields (0..1 relationship with other objects), using Option is definitely a good thing.
The little drawback is that it renders declaration of class with a lot of optional field a bit verbose, as you mentionned.
One more thing, in scala, you are encouraged to use "immutable objects", so in your example, the fields should be some vals. ;)

A: You should avoid null as much as possible in Scala. It really only exists for interoperability with Java. So, instead of null, use Option whenever it's possible that a function or method can return "no value", or when it's logically valid for a member variable to have "no value".
With regard to your Racer example: Is a Racer really valid if it doesn't have a car, currentRace and team? If not, then you shouldn't make those member variables options. Don't just make them options because it's theoretically possible to assign them to null; do it only if logically you consider it a valid Racer object if any of those member variables has no value.
In other words, it's best to pretend as if null doesn't exist. The use of null in Scala code is a code smell.
def foo(): Option[Result] = if (something) Some(new Result()) else None

Note that Option has many useful methods to work with.
val opt = foo()

// You can use pattern matching
opt match {
  case Some(result) => println("The result is: " + result)
  case None         => println("There was no result!")
}

// Or use for example foreach
opt foreach { result => println("The result is: " + result) }

Also, if you want to program in the functional style, you should avoid mutable data as much as possible, which means: avoid the use of var, use val instead, use immutable collections and make your own classes immutable as much as possible.

A: When it comes to functional programming in Scala, Option is much preferable than null since it is type-safe and plays nice with other constructs in the functional paradigm.
Especially, you can easily write idiomatic code using high-order functions on Option. This Scala Option Cheat Sheet is a helpful read on the topic.


text:
Q: How can i get a Mongoose custom error message? So I have this mongoose schema that I want to validate
const mongoose = require('mongoose')
const productSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, "You Must Include A Name"],
        toLowerCase: true,
    },
    price: {
        type: Number,
        required: [true, "Price Must Be Included"],
        min: 0
    },

})
const Product = mongoose.model('Product', productSchema);
module.exports = Product;

In index.js I extended Error class and wrote this middleware
app.use((err, req, res, next) => {
    if (err.name == 'CastError') next(new AppError(`This is a CastError${err.message}`, 400))
    else if (err.name == 'ValidationError') next(new AppError(err.message, 400))
    else {
        next(err)
    }
})
app.use((err, req, res, next) => {
    console.log(err.msg)
    const { message = 'Something Went Wrong', status = 500 } = err
    res.status(status).send(message)
})

When I make a validation error i get this: Product validation failed: price: Price Must Be Included
or when leave both name and price empty it get:Product validation failed: name: You Must Include A Name, price: Price Must Be Included
I just want: "Price Must Be Included"
or: "Name must be included"
How can I achieve that?

A: In your else if parse the err.message down to the message you want to emit and use that.  Here is one way to parse it using string split on colon
else if (err.name == 'ValidationError') {
  const messageParts = err.message.split(':');
  next(new AppError(messageParts[2], 400)
} else ...


text:
Q: A sequence of vectors $\{a_i\}$ in $\mathbb{R}^n$ is a Cauchy sequence . . . Prove that Cauchy sequences are convergent. A sequence of vectors $\{a_i\}$ in $\mathbb{R}^n$ is a Cauchy sequence if for each  $\epsilon> 0$ there exists $I \in \mathbb{N}$ such that $\|a_i -a_j\| < \epsilon$  for all $i, j \geq  I$. Prove that Cauchy sequences are convergent.
I was told I have to show that if the vectors are Cauchy that their elements must also be Cauchy, but I'm not sure how to go about doing this. The rest of the proof should fall into place accordingly.
Could someone show me how this particular part is done?

A: Hint:

*

*Show that every Cauchy sequence is bounded;

*Then there will be a convergent subsequence (Bolzano-Weierstrass), call it  $(x_r)_{r \in \mathbb N'}$. Let $\displaystyle a = \lim_{r \in \mathbb N'} x_r$, then $$ \lim_{r \in \mathbb N'} |x_r - a| = 0 \,\,\,\text{and}\,\,\,  \lim_{k \in \mathbb N, r \in \mathbb N'} |x_k - x_r| = 0$$

Now from $|x_k - a| \leq |x_k - x_r| + |x_r- a|$, you may get your result.

A: Let $a_i=(a_i^1,a_i^2,\ldots, a_i^n)$. Then for each $k\in[n]$ one has
$$|a_i^k-a_j^k|\leq\|a_i-a_j\|\ ,$$
hence $\bigl( a_i^k)_{i\geq1}$ is a Cauchy sequence in ${\mathbb R}$ and converges to some $\alpha^k\in{\mathbb R}$. Put $(\alpha^1,\ldots,\alpha^n)=:\alpha\in{\mathbb R}^n$. The triangle inequality in ${\mathbb R}^n$ then implies
$$\|a_i-\alpha\|\leq\sum_{k=1}^n|a_i^k-\alpha^k|\to0\qquad(i\to\infty)\ ,$$
and this guarantees $\lim_{i\to\infty}a_i=\alpha$.


text:
Q: How to debug UTF-16 output in DbgView? I want to display a UTF-16 string in DbgView, like this:
wchar_t nameholder = L'שלום עולם';

But I can't do this with OutputDebugStringW(). Do you have any solution?

A: For starters, this: wchar_t nameholder = L'שלום עולם'; doesn't compile at all in any encoding.  You really meant:
const wchar_t* nameholder = L"שלום עולם";

In any case, the root of the real solution is in th same thing I said on this answer.
Don't hardcode unicode characters (those above the normal ascii range) into a c++ source file.  Between compilers, ide editors, source code repos, diffing tools, and team members with a different setup, it's not a good idea to put unicode chars into a source code file.
So instead of this:
const wchar_t* nameholder = L"שלום עולם";

Use unicode escapes like this.
const wchar_t* nameholder = L"\u05e9\u05dc\u05d5\u05dd\u0020\u05e2\u05d5\u05dc\u05dd";

Then OutputDebugString will work better:
OutputDebugStringW(nameholder);

Disclaimer: I've never used Hebrew with DbgView, but it should work.  OutputDebugString with the above does work in Visual Studio:
'ConsoleApplication26.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ucrtbased.dll'.
The thread 0x2248 has exited with code 0 (0x0).
שלום עולם

Update

I tried Boris's suggestion and actually tried getting DbgView to run with my proposed changes.  And I tried both utf-16 with OutputDebugStringW and utf-8 with OutputDebugStringA.   Short answer: DbgView just mangles it.  So, pretty much everything I said is nearly moot.  I'll continue to stand by the fact that you should avoid non-ascii chars in source code.  But I don't have a solution for DbgView.

A: This made me curious, so i did a little experiment, building and running the following code on my Win7x64 machine with VS2017
#include <windows.h>

int main()
{
    static const wchar_t shalomolam[] = { 0x05E9, 0x05DC, 0x05D5, 0x05DD, 0x0020, 0x05E2, 0x05D5, 0x05DC, 0x05DD, 0xD, 0xA, 0 };
    static const wchar_t zdravstvuimir[] = { 0x0417, 0x0434, 0x0440, 0x0430, 0x0432, 0x0441, 0x0442, 0x0432, 0x0443, 0x0439, 0x0020, 0x041C, 0x0438, 0x0440, 0xD, 0xA, 0 };
    OutputDebugStringW(L"Hello World\r\n");
    OutputDebugStringW(shalomolam);
    OutputDebugStringW(zdravstvuimir);
    return(0);
}

Surprisingly, I've only got either English or system locale Unicode characters to print, having my system set to Hebrew locale the Hebrew would print, but the Russian characters are converted to '?', setting it to Russian and the same happens to Hebrew. Knowing it may have to do with the source file encoding, Visual Studio, etc (i agree with @selbie on this), i've double checked the binary with a hex editor, the strings are there, and they are fine, and it doesn't depend on what system locale i've run the build. This '?' substitution happens in both dbgview and Visual Studio debug output.
TBH, i've never even attempted to feed non-English Unicode characters to OutputDebugString until now, but hey, i guess your answer is - if you want a specific languages output for debug purposes - switch your locale to that language. Otherwise (such as, in case of multiple languages, or if you want to collect a log with dbgview on a user's machine) guess you are out of luck.


text:
Q: Subquery Has too Many Columns: Finding the item bought most frequently by the customers who spent the most I have 3 tables: Products (prod_id, prod_name, prod_price), Customers (cust_id, address, email, name), and Sales (sale_id, cust_id, prod_id).
I wrote a query to find the top 100 customers (in terms of total money spent on any products):
SELECT TOP 100 C.name AS customer_name,
SUM(P.prod_price) AS total_spent
FROM customers C
LEFT JOIN Sales S ON C.cust_id=S.cust_id
LEFT JOIN Products P ON S.prod_id=P.prod_id
GROUP BY C.cust_id
ORDER BY total_spent DESC;

This works (I think). Now I want to write a query to find the item that each of those customers bought the most times. So essentially I want to use the first query for a list of names, and then find the item that each of the people on that list bought the most. It doesn't matter how ties are resolved.
I first tried writing it with a nested subquery:
SELECT P.prod_name as best_seller,
C.name AS customer_name
FROM products P
JOIN Sales S ON P.prod_id=S.prod_id
JOIN Customers C on S.cust_id = C.cust_id
WHERE C.name IN
    (SELECT TOP 100 C.name AS customer_name,
    SUM(P.prod_price) AS total_spent
    FROM customers C
    JOIN Sales S ON C.cust_id=S.cust_id
    JOIN Products P ON S.prod_id=P.prod_id
    GROUP BY C.name
    ORDER BY total_spent)
GROUP BY C.name, P.prod_name;

This gives me the error "Invalid operation: subquery has too many columns;".
When I try not selecting the total_spent in the inner query, like this:
SELECT P.prod_name as best_seller,
C.name AS customer_name
FROM products P
JOIN Sales S ON P.prod_id=S.prod_id
JOIN Customers C on S.cust_id = C.cust_id
WHERE C.name IN
    (SELECT TOP 100 C.name AS customer_name
    FROM customers C
    JOIN Sales S ON C.cust_id=S.cust_id
    JOIN Products P ON S.prod_id=P.prod_id
    GROUP BY C.name
    ORDER BY SUM(P.prod_price))
GROUP BY C.name, P.prod_name;

I get results but they're wrong (it's a different selection of customers, and they all show the same product for the one they bought most often, which shouldn't be the case).
I want to use this query to test the query time of my db under different circumstances, so I don't necessary want to make it faster or better. I just can't figure out how to do it as a nested query.

A: If it's PostgreSQL (your query syntax points to SQL Server or Sybase) the query you can use is:
select
  c.name as customer_name,
  sum(p.prod_price) as total_spent
from customers c
left join sales s ON c.cust_id = s.cust_id
left join products p ON s.prod_id = p.prod_id
group by c.cust_id
order by sum(p.prod_price) desc
limit 100


text:
Q: VueJS pushing route with params shows old params in browser Scenario
I've a app where I use vue.js 2.6 and vue-router 3.0
in there I've links to detail pages like this

    <router-link  :to="{name: 'details', params: {key: item.shortKey}}">

what works
Now in the target view the parameter always has the correct value
Also when I first time click a link then I see the correct shortkey in the browser.
Not working
Now when I click another itemm I still see in the browser url the key of the item that was clicked first in the browser . Eventhough inside the code the route.params do have the correct value.
Both the View browser tools  and the code itself have the correct value.
What am I missing?
Also using router.push has the same result. Changing from history to hash mode also doesn't change the behavior
Shortened Router config
const routes = new Router({
  mode: 'history',
  routes: [{
    component: layout,
    path: '/',
    children: [
      {
        path: '/',
        name: 'home',
        component: Home,
        meta:{display:"home"}
      },
      {
        path:'list',
        name:'list',
        component: listItemsComponent,
      },

      {
        path: 'details/:key',
        name: 'details',
        component: detailComponent
      },
    ]
  }]
});

A: Try adding a unique key to each element in v-for like below -

    <router-link  :to="{name: 'details', params: {key: item.shortKey}}">

As per vue js docs,

To give Vue a hint so that it can track each node's identity, and thus
  reuse and reorder existing elements, you need to provide a unique key
  attribute for each item.

A: You can try to add '/' in your path : path: '/details/:key'


text:
Q: I'm looking for a story about card catalogs and aliens I'm looking for a story about aliens who are about to make first contact with Earth. These aliens are definitely better than humanity. The President of Earth, or the USA, tells people to destroy library indexes or card catalogs in order to conceal from the aliens a mysterious human quality, listed in these tools.  Humanity is saved from mediocrity by the leader's trickery.
The mysterious quality is not identified. It is a sham by the president to protect the humans from the comparison with the aliens. It gives the humans sufficient self-assurance to survive first contact.
The aliens are superior to the humans from all points of view : ethically, spiritually, intellectually, technologically, etc.
The story dates probably from the fifties or the sixties.

A: I'm looking for a story
"Sshhh . . .", a 1989 short story by David Brin. Aside from translations, it has appeared only in Amazing Stories, May 1989 and in Brin's collection Otherness. Any of these covers look familiar?
about aliens who are about to make first contact with Earth. These aliens are definitely better than humanity.

They also seemed omnipotent! Terrifically strong and coordinated, they lived, as corporeal entities, for thousands of years before going on to join their Universal Mind. Skills a human might spend a lifetime perfecting were the study of a lazy weekend to a Lentili. Their accomplishments, both as a race and as individuals, were awesome.
The Lentili spoke kindly of the arts and achievements of humankind, never qualifying their praise as some of us would have, allowing for the fact that these were, after all, the simple works of children. And yet, how could we avoid inserting those burning qualifiers ourselves?

The President of Earth, or the USA,

Joseph Tridden, President of the Interim Council of Terra

tells people to destroy library indexes or card catalogs in order to conceal from the aliens a mysterious human quality, listed in these tools.

"At the very start of our long relationship with a kind, decent race—one whose interest in our welfare is indisputable—we find it actually within our power to wreak untold psychic harm upon our benefactors. The Lentili have a mental block, something like an odd inferiority complex, and it concerns something so mundane to us that few human beings ever bother even thinking about it past the age of ten! It certainly isn't our fault. And yet we can hurt our new friends terribly if we are crass or rudely force them to see what they would rather not. We are duty bound to try to minimize that harm as best we can.
"Therefore, I have decided to ask you all to join me in making a grand sacrifice.
"Over the coming weeks, as we prepare to receive our visitors, our guests and future guides, we must expunge all references to this human talent from our literature, from our language, from our outward lives!
"To begin with, I have already given orders to various governmental agencies, using my emergency powers. Commencing this hour, the indexes to the UN Data Bank and the Library of Congress are being destroyed.
"Let me emphasize . . . no books will actually be burned! But in the laborious process of reconstruction, the new indexes will exclude all reference to this human ability that so disturbs our new friends.
"All of you can do the same, in your towns and villages and homes. We must not, of course, destroy our heritage. But we can at least make an effort to mask this thing, so that when the Lentili arrive we might spare them avoidable pain."

The mysterious quality is not identified. It is a sham by the president to protect the humans from the comparison with the aliens. It gives the humans sufficient self-assurance to survive first contact.

They walk among us like gods. But we have our revenge.
For the Lentili know Tridden must have been mad. They know there is no secret talent. We are not sheltering them from some bright truth, hiding something from them out of pity. Out of love.
They know it.
And yet, every now and then I have seen it. I've seen it! Seen it in their deep, expressive eyes, each time something new from our renaissance surprises them, oh, so briefly.
I have seen that glimmer of wonder, of unease. That momentary, fearful doubt.
That is when I pity the poor creatures.
Thank God, I can pity them.


text:
Q: In Java Concurrency In Practice by Brian Goetz Java Concurrency In Practice by Brian Goetz provides an example of a efficient scalable cache for concurrent use. Here is the code for the class:
public class Memoizer<A, V> implements Computable<A, V> {
    private final ConcurrentMap<A, Future<V>> cache
        = new ConcurrentHashMap<A, Future<V>>();
    private final Computable<A, V> c;

    public Memoizer(Computable<A, V> c) { this.c = c; }

    public V compute(final A arg) throws InterruptedException {
        while (true) {
            Future<V> f = cache.get(arg);
            if (f == null) {
                Callable<V> eval = new Callable<V>() {
                    public V call() throws InterruptedException {
                        return c.compute(arg);
                    }
                };
                FutureTask<V> ft = new FutureTask<V>(eval);
                f = cache.putIfAbsent(arg, ft);
                if (f == null) { f = ft; ft.run(); }
            }
            try {
                return f.get();
            } catch (CancellationException e) {
                cache.remove(arg, f);
            } catch (ExecutionException e) {
                throw launderThrowable(e.getCause());
            }
        }
    } }

Probably a stupid question but coudl anyone show me the concurrent usage of this class?
Like in a main?
Cheers,
Agata

A: Here is an example which calculates factorials:
public static void main(String[] args) throws Exception {

    //create a memoizer that performs factorials
    final Memoizer<Integer, Integer> memo = new Memoizer<Integer, Integer> (new Computable<Integer, Integer>() {
        @Override
        public Integer compute(Integer a) {
            int result = 1 ;
            for(int i = 1 ; i < a ; i++){
                result = result*i;
            }
            return result;
        }
    });

    //now call the memoizer
    System.out.println(memo.compute(10));

    //call it with 10 threads concurrently
    ExecutorService exec = Executors.newFixedThreadPool(10);
    ExecutorCompletionService<Integer> compService = new ExecutorCompletionService<Integer>(exec);
    for(int i = 0 ; i < 15 ; i++){
        compService.submit(new Callable<Integer>(){
            @Override
            public Integer call() throws Exception {
                return memo.compute(5);
            }
        });
    }
    exec.shutdown();
    for(int i = 0 ; i < 15 ; i++){
        System.out.println(compService.take().get());
    }
}

So if two threads try to compute the same factorial at exactly the same time, only one of them will actually perform the computation, because putIfAbsent is threadsafe. The second thread will simply get the future which was put in the map by the first thread and wait for it to finish.

A: I could imagine something like this:
class PrimeDetector implements Computable<BigInteger, Boolean> {
  public Boolean compute(BigInteger number) {
    // detect whether the number is prime and return true if it is
  }
}

Memoizer<BigInteger, Boolean> primeMemoizer =
        new Memoizer<BigInteger, BigInteger[]>(new PrimeDetector());
boolean isPrime = primeMemoizer.compute(
        new BigInteger("5625945193217348954671586615478165774647538956473535"));
...


text:
Q: Extra content at the end of the document XML PHP RSS I am trying to create a RSS feed. This is the PHP code for the feed in question below.
<?xml version="1.0" encoding="utf-8" ?>
<?php

include_once 'authorization.php';
header("Content-Type: text/xml; charset=UTF-8");

    $demo_id = "1";
  $stmt = $mysqli->prepare("SELECT * FROM demo_files WHERE demo_id = ?");

  $stmt->bind_param('i', $demo_id);
  $stmt->execute();
  $result = $stmt->get_result();

    while($row = $result->fetch_assoc()) {

        $demo_title=$row['demo_title'];
        $demo_content=$row['demo_content'];

        echo '<rss version="2.0">
        <channel>
        <title>Liorall</title>
        <link>Youtube Tutorial demo</link>
        <language>en-us</language>

          <item>
            <title>'.$post_title.'</title>
            <description>'.$post_content.'</description>
          </item>

        </channel>
        </rss>';
    }
    ?>

Am getting this error Extra content at the end of the document
Please how can i fix it.
Thanks in Advance.

A: You're initialising $demo_title and $demo_content at the top of your loop, but emitting $post_title and $post_content later.
That will generate an undefined variable warning from PHP that will appear in your output stream and your RSS reader is likely to complain about that.
I changed that on my test system and the output now appears well-formed, but it fails the W3C Validator with some other issues you should address.


text:
Q: Entity Framework 4 upgrade issue, Loading by both name and attribute is not allowed I just upgraded my project from asp.net 2 to asp.net 4. More precisely I converted the project from VS 2008 to VS 2010. I did this because I needed the new features of EF4. I am running into an issue though where I am getting this error message:

The types in the assembly 'XXX' cannot be loaded because the assembly
  contains the EdmSchemaAttribute, and the closure of types is being
  loaded by name.  Loading by both name and attribute is not allowed.

After some playing around I found that the cause is context.GetObjectByKey. I had a little function that would take an object id and build an EntityKey from it for use in GetObjectByKey. If I change that to context.ObjectName.FirstOrDefault(x => x.id == searchId) then I don't get the error anymore.
I'm in the process of updating all my code to the version that works but I'm wondering if anybody knows the reason for this? Or does it indicates some underlying issue with my code; perhaps that my EDM got munged in the conversion?

A: Is your entity really called "object?" That might be the problem. Having an entity with the same name as the root CLR type is certainly going to be an issue.


text:
Q: Logging in as root
Possible Duplicate:
What's wrong with always being root?

I have a server running in a datacenter with strong firewall & VPN protection. I have a few java apps which I have written myself running as these boxes.
Currently I only have root user and run everything as root.
Is there any reason why this might be a bad idea?

A: Your precautions have mitigated a large percentage of the threats that feast on low hanging fruit. I commend you for that.
Two Three broad categories of threats remain:
1. You.
You are your own worst enemy. I am mine. Running everything as root means that you are always one swift keystroke away from doom and lamentation. Even if you know your apps, there are always bugs and squirrely things waiting to be found that you didn't know about. If they are found with root, then weep and howl for your miseries which are coming upon you.
2. Others.
Even if you've mitigated the large percentage of threats that exist in the wild, there are always vulnerabilities that you hadn't thought of or didn't know about. Sure your firewall, VPN and etc. and etc. are safe, but really... maybe your switches aren't or your update server or your... you get the idea. If things are nicely segregated, then you can sleep that little bit better at night knowing that even if there's something that you didn't know about (and there is) at least you've put a few more hurdles in the path to total destruction.
3. Resource Depletion
Running a process as root means it has unfettered access to your server's resources and has the potential to bring it to its knees. Whether that's through a memory leak, maxxing out inodes or a few other possibilities - it's all bad and can more easily be mitigated by running it as a non-root user.


text:
Q: Error Creating MySQL table using Python I am busy trying to create a MySQL table using python to no avail. I am connected to MySQL and I have created the database but keep getting the following error message:
ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
'INT NOT NULL AUTO_INCREMENT,
EOD_Date DATE,
Symbol VARCHAR(10) NOT NULL,
Holding' at line 3

I have looked through the create table syntax documentation and I can't work out what the issue is http://dev.mysql.com/doc/refman/5.7/en/create-table.html
Here is my code to create the table:
cursor.execute("""CREATE TABLE prices
(
Index INT NOT NULL AUTO_INCREMENT,
EOD_Date DATE,
Symbol VARCHAR(10) NOT NULL,
Holdings_Q INT NOT NULL,
EOD_Price FLOAT(,2) NOT NULL,
OIL_Price FLOAT(,2) NOT NULL,
Account_Number INT NOT NULL,
Account_Type VARCHAR(50) NOT NULL,
Asset_Class VARCHAR(50) NOT NULL,
Security_Desc VARCHAR(100) NOT NULL,
Security_Type VARCHAR(30) NOT NULL,
Holdings_Val FLOAT(,2), NOT NULL
PRIMARY KEY (Index))ENGINE=InnoDB""")

Any suggestions or input would be greatly appreciated

A: Index is a reserved keyword in MySQL. If you have to use that as field name, you can escape it with tick like:
cursor.execute("""CREATE TABLE prices
(
`Index` INT NOT NULL AUTO_INCREMENT,
EOD_Date DATE,
Symbol VARCHAR(10) NOT NULL,
Holdings_Q INT NOT NULL,
EOD_Price FLOAT(,2) NOT NULL,
OIL_Price FLOAT(,2) NOT NULL,
Account_Number INT NOT NULL,
Account_Type VARCHAR(50) NOT NULL,
Asset_Class VARCHAR(50) NOT NULL,
Security_Desc VARCHAR(100) NOT NULL,
Security_Type VARCHAR(30) NOT NULL,
Holdings_Val FLOAT(,2), NOT NULL
PRIMARY KEY (`Index`))ENGINE=InnoDB""")


text:
Q: User Mode to Kernel Mode debugging in GDB I was debugging a program in which I hit
int 0x80
I know this means a system call and then the kernel executed it. However, GDB does not allow me to look at the instructions run by the kernel while executing this system call. It just executes the system call and takes me to the next instruction.
Is there anyway I can look into the kernel mode code while debugging a user mode program? If not, then what are the over best alternatives available to me?

A:
Is there anyway I can look into the kernel mode code while debugging a user mode program?

No.
(Actually, you could do that if you use UML, but that is likely too complicated for you to set up.)


text:
Q: Execute Result of Dynamic Postgres Query I have a table in my postgres db called rpt.view_refresh_schedule. This table contains the name of materialized views stored in my database that I would like to refresh on a schedule.
I have written the query below which takes each record in the rpt.view_refresh_schedule table and builds a dynamic query to refresh each table.
select CONCAT('REFRESH MATERIALIZED VIEW ' || view_name || ';') as script from rpt.view_refresh_schedule

The output of that query is as follows:
REFRESH MATERIALIZED VIEW mv_user_trading_activity;
REFRESH MATERIALIZED VIEW mv_orders;

I want to create a function that executes the dynamic queries that were produced as a result of my above sql. How can I do that? I have seen other posts which execute a query from a single string but this is multiple commands. In python I would just loop over the results and execute each one. Is there something similar in postgres? I have tried the LOOP function with no success.

A: If you are using psql, you can do this, without having to write a function:
select CONCAT('REFRESH MATERIALIZED VIEW ' || view_name || ';') as script from rpt.view_refresh_schedule
\gexec

A: Please give this a try:
DO $$
DECLARE
  cmd text;
BEGIN
  FOR cmd in select CONCAT('REFRESH MATERIALIZED VIEW ' || view_name) as script
               from rpt.view_refresh_schedule
  LOOP
    EXECUTE cmd;
  END LOOP;
END;
$$;

A: Unless your refresh schedule is truly dynamic meaning you update your table for a given materialized view often you do not need either function nor table. If you refresh interval is stable, for a given MV, you can define it on the create or alter materialized view. From the documentation section create_mv_refresh on create:

Use the create_mv_refresh clause to specify the default methods,
modes, and times for the database to refresh the materialized view. If
the master tables of a materialized view are modified, then the data
in the materialized view must be updated to make the materialized view
accurately reflect the data currently in its master tables. This
clause lets you schedule the times and specify the method and mode for
the database to refresh the materialized view.


text:
Q: Is it possible to compile but not showing a part? If I have a chunk of code which I'd like to hide when compiling, is there something like

\noshow{chunk of code}

So this chunk of code is still compiled but just not showing in the PDF? I know I can comment this part but problem is if I edit my own commands, the commented codes are not compiled and checked.

A: One way to accomplish this could be to typeset the stuff inside a box which you
never print. This does however not work for any content. In the below example
floats are not allowed and throw an error.
\documentclass[]{article}

\begin{document}
This shows up
\thesection% here it is 0
\setbox0\vbox{This is evaluated but never shows up, additional spaces
however might be a problem, which is why I put the \% at the end of the
lines. To show that it's evaluated, I run this: \stepcounter{section}}% no space here
\thesection% here it is 1
\end{document}

The following does also evaluate the contents, but only \AtEndDocument, so if
you need the contents to be evaluated where you put those, don't use this. The
advantage is, that anything should work here which doesn't produce an error.
\documentclass[]{article}

\usepackage{environ,atbegshi}

\makeatletter
\newcommand*\contents@DontShowMe{}
\newcommand\addto@DontShowMe[1]
  {%
    \xdef\contents@DontShowMe{\unexpanded\expandafter{\contents@DontShowMe#1}}%
  }

\NewEnviron{DontShowMe}[1][1]
  {%
    \ifnum#1=0
      \expandafter\BODY
    \else
      \expandafter\addto@DontShowMe\expandafter{\BODY}%
    \fi
  }
\AtEndDocument
  {%
    \clearpage
    \AtBeginShipout{\AtBeginShipoutDiscard}%
    \contents@DontShowMe
  }
\makeatother

\begin{document}
This shows up
\thesection% here it is 0
\begin{DontShowMe}
  This code doesn't show up and is evaluated at the end of the document. To show
  this: \stepcounter{section}
  \begin{figure}test\end{figure}
  To produce an error to check that it does evaluate uncomment this: %\PackageError{foo}{foo}{foo}
\end{DontShowMe}
\thesection% here it is still 0
\end{document}

One environment to rule them all:
You can use the optional argument to decide the point of evaluation. 0 means show, 1 means in a \vbox at this point (no floats usable), 2 means \AtEndDocument (and because the \AtEndDocument is added \AtEndDocument, it should be really late) floats should work here -- but captions don't make it to the \listof....
\documentclass[]{article}

\usepackage{environ,atbegshi}

\makeatletter
\newif\ifAtEnd@DontShowMe
\newcommand*\contents@DontShowMe{}
\newcommand\addto@DontShowMe[1]
  {%
    \xdef\contents@DontShowMe{\unexpanded\expandafter{\contents@DontShowMe#1}}%
  }

\NewEnviron{DontShowMe}[1][2]
  {%
    \ifcase#1
      \expandafter\BODY
    \or
      \setbox0\vbox{\BODY}%
    \or
      \global\AtEnd@DontShowMetrue
      \expandafter\addto@DontShowMe\expandafter{\BODY}%
    \fi
  }
\AtEndDocument
  {%
    \ifAtEnd@DontShowMe% only include this piece of code if it was used
      \AtEndDocument
        {%
          \clearpage
          \AtBeginShipout{\AtBeginShipoutDiscard}%
          \contents@DontShowMe
        }%
    \fi
  }
\makeatother

\begin{document}
\listoffigures
This shows up
\thesection% here it is 0
\begin{DontShowMe}
  This code doesn't show up and is evaluated at the end of the document.
  To show this: \stepcounter{section}
  \begin{figure}test\caption{test}\end{figure}
  To produce an error to check that it does evaluate uncomment this:
  %\PackageError{foo}{foo}{foo}
\end{DontShowMe}
\thesection% here it is still 0
\end{document}

A: We need to know more: how long is the hidden text? Will you provide the PDF to others or only a printout? And so on.
For example, you could simply use white »coloured« text:
\documentclass{article}
\usepackage{xcolor}

\begin{document}
This is text.
\textcolor{white}{This text will not be printed. However, you can copy it out of
  the pdf.}

  \llap{\textcolor{white}{invisible text, can't be copied.}}{However, you can do
    funny things, but only without a linebreak.}
\end{document}


text:
Q: jQuery submit preventDefault not working when AJAX is includet Let's say my code would be:
$("form").submit(function (e) {
    e.preventDefault();
    var logemail = $('input[name="logemail"]').val();
    var logpasswort = $('#logpasswort').val();

    if(logpasswort.length < 6)
    {
        alert('wrong pass');
        return false;
    }
});

everything works fine, but my code is:
$("form").submit(function (e) {
    e.preventDefault();
    var logemail = $('input[name="logemail"]').val();
    var logpasswort = $('#logpasswort').val();

    if(logpasswort.length < 6)
    {
        alert('wrong pass');
        return false;
    }

    $.ajax({
        type: 'post',
        url: 'connect.php',
        dataType, 'json',
        data: {mach: "login", email: logemail, passwort: logpasswort},
        success: function(data) {
            if(data["status"] == 'wrongpass'){
            {
                alert('wrong pass');
            }

            if(data["status"] == 'ok')
            {
                alert('good');
            }
        }
    });
});

And the form is just getting submitted because AJAX is included, even when if(logpasswort.length < 6) is true! what's wrong with that??

A: Your javascript is not getting parsed. Remove the extra "{" at the end of line:
if(data["status"] == 'wrongpass'){

Side note: stick with the consistent style of putting "{" either at the of the line or on the new line throughout your code.


text:
Q: Flask:Confused over using PUT/POST in Rest API Respected Elders/Programmers/Learned-people,
I have read a very popular answer here about using PUT or POST, but I couldn't decipher from it as to what is the correct way to do so. Almost every answer has comments saying this is wrong/this is right. Mighty confused here.
My requirements:
Sending 2 Json files to the server, one to be inserted in Database and other to be updated. I thought I would use PUT to update, and POST to Insert into the database. That way, on the client side itself I would decide whether to insert or update.
Confusion: Since, the client alone is responsible for its data to be created/updated on the server, even POST in my case upon being repeated would insert the same thing (insert into table values) over and over, behaving as idempotent  OR would give an error (Because of primary key conflict). Finally, it would not create something new upon firing it twice.
Question: Is it correct to use PUT for updation, and POST for insertion?

A: PUT can also be used for creating. What's important is the url. This is generally the accepted pattern:
PUT /collection/1234 <- Update a specific item OR create it
POST /collection <- Add a new item to a collection

Which one is right for you depends on a few things. Does the server determine the url of the new item, or does the client?
If the client can figure out what the url of a new item becomes, using PUT might be better because you can more easily turn it into an idempotent request.
Remember that with a PUT request the intent is always that you are replacing the resource at the target url with a new state.
However, if the server creates the url pattern (maybe you have an auto-incrementing id), POST is better. POST doesn't have to be on the parent collection but it's common.
If you want POST and want idempotence, you need some other way to figure out something was a repeated request. You get that for free with PUT. For example, the Stripe API solves this by adding a non-standard Idempotency-Key header.


text:
Q: localhost xampp curl port 80 error I seem to be having an issue with a single url endpoint while cUrl from local xampp.
I get an error message of Failed to connect to localhost port 1080: Connection refused even when I set curl_setopt($ch, CURLOPT_PORT, 80);.
But this only happens from a particular url (without ssl http://), other urls with https:// is fine. And all other cUrl to different endpoints are fine.
On a live server, the problematic endpoint, same code everything works fine.
Can anyone help me understand why this might be happening?

My http.conf: ServerName localhost:80

complete code
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_PORT, $_SERVER['SERVER_PORT']);

    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    // "Cache-Control: max-age=0",
    // "Connection: keep-alive",
    // "Keep-Alive: 300",
    "Content-Type: application/json",
    'Api-Key: ' . $apiKey,
    ));

    $output = curl_exec($ch);

    //curl_easy_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $errmsg = curl_error ( $ch );
    $httpcode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
    $httpHeaders = curl_getinfo($ch);

    curl_close($ch);

    print_r($ch);
    echo $httpcode;
    print_r($httpHeaders);
    print_r($errmsg); // Failed to connect to localhost port 1080: Connection refused

after spending the entire day, the fix was to set an empty value for proxy and use port 80
curl_setopt($ch, CURLOPT_PROXY, ''); //!! FIX
curl_setopt($ch, CURLOPT_PORT, $_SERVER['SERVER_PORT']);

A: I had the same issue , i solved it by running apache on other port,  you should to edit your httpd.conf


text:
Q: Java : check for null in setter using ternary learning Java and in a Car Dealership project.
tring to check input in my setter function for car make using ternary operator, eclipse doesn't like what i'm typing :
i'm a little confused as i want to express the followng:
if Make is null => set to Empty {if not} set to input
    public void setMake(String Make) {
        this.Make == null ? "" : this.Make;
    }

thanks in advance for the help .

A: It should be:
public void setMake(String Make) {
    this.Make = Make == null ? "" : Make;
}

You want to assign the result of the ternary conditional operator to your instance variable.
And when you want to refer to the Make passed to the method, you should write Make, not this.Make (which is the instance variable).


text:
Q: Can I log data from $_SESSION to apache's custom (access) log? When I have my user's IDs in $_SESSION['user']['id'] and I want to store this ID in apache2's custom log, is this possible?
Either with apache 2.2 or apache 2.4. Doesn't matter.
So for example, line as this:
61963   85.162.206.25   [14/Sep/2013:22:17:07 +0000]    9088    /index.php

Would become:
61963   85.162.206.25   [14/Sep/2013:22:17:07 +0000]    9088    /index.php  20

Indicating that it was user ID 20. // as $_SESSION['user']['id'] == 20


text:
Q: How do I interrupt a long task managed by SCons? I'm using SCons to manage a Python function long_task() that carries out a long calculation. If I call long_task() directly from a script, then I can interrupt it with Ctrl-C. However, if SCons is running long_task() and I press Ctrl-C, then long_task() continues to run until it completes, and then SCons says "Build interrupted. / building terminated because of errors". Is there a way to make Ctrl-C stop long_task() immediately in this situation?
If I use a signal handler in long_task() to handle SIGINT then it behaves as I want, but I'd rather not have to do this in each of several such long tasks.
If I press Ctrl-\ then both longtask() and SCons exit immediately, but this seems rather drastic.
I'm using SCons 3.0.1 and Python 3.6.5 under Ubuntu 18.04.
Here's a minimal SConstruct file:
#!/usr/bin/env python3

import time

def long_task(target, source, env):
    print('Starting long task')
    # Mimic a complex calculation
    for i in range(100):
        time.sleep(0.1)
    print('Finishing long task')

TestBuilder = Builder(action = long_task)

env = Environment(BUILDERS = {'TestBuild': TestBuilder})

env.TestBuild('dummy', [])

A: I highly encourage you to not run long running python logic as an action in a builder.
Instead run it via shell as a free standing python program.
This also simplifies building a time limit into such program so it doesn't run forever..
Running long running python logic inside SCons will limit parallel builds.
Basically just don't do it..
(BTW. I'm the SCons Project Co-Manager)


text:
Q: MapBox Place Picker leads to Fatal signal 6 I'm following these instructions trying to implement this Place Picker
But my app crashes everytime I start it with this error: A/libc: Fatal signal 6 (SIGABRT), code -6 (SI_TKILL) How can I fix it? I didn't find a solution online... Even I found GitHub issues with the same error but there was no answer. Can someone help?
Here's my code:
public class PlaceSelectionPluginActivity extends AppCompatActivity {

    private static final int REQUEST_CODE = 5678;
    private TextView selectedLocationTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Mapbox.getInstance(this, "***myToken***");

        setContentView(R.layout.activity_place_selection);
        selectedLocationTextView = findViewById(R.id.selected_location_info_textview);
        goToPickerActivity();
    }

    /**
     * Set up the PlacePickerOptions and startActivityForResult
     */
    private void goToPickerActivity() {
        startActivityForResult(
                new PlacePicker.IntentBuilder()
                        .accessToken("***myToken***")
                        .placeOptions(PlacePickerOptions.builder()
                                .statingCameraPosition(new CameraPosition.Builder()
                                        .target(new LatLng(40.7544, -73.9862)).zoom(16).build())
                                .build())
                        .build(this), REQUEST_CODE);
    }

    /**
     * This fires after a location is selected in the Places Plugin's PlacePickerActivity.
     * @param requestCode code that is a part of the return to this activity
     * @param resultCode code that is a part of the return to this activity
     * @param data the data that is a part of the return to this activity
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CANCELED) {
// Show the button and set the OnClickListener()
            Button goToPickerActivityButton = findViewById(R.id.go_to_picker_button);
            goToPickerActivityButton.setVisibility(View.VISIBLE);
            goToPickerActivityButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    goToPickerActivity();
                }
            });
        } else if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
// Retrieve the information from the selected location's CarmenFeature
            CarmenFeature carmenFeature = PlacePicker.getPlace(data);

// Set the TextView text to the entire CarmenFeature. The CarmenFeature
// also be parsed through to grab and display certain information such as
// its placeName, text, or coordinates.
            if (carmenFeature != null) {
                selectedLocationTextView.setText(String.format(
                        getString(R.string.selected_place_info), carmenFeature.toJson()));
            }
        }
    }
}

build.gradle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
        mavenCentral()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

app level build.gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.0"

    defaultConfig {
        applicationId "com.mycompany.placepickertest"
        minSdkVersion 26
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-places-v9:0.12.0'
}

activity_place_selection.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/go_to_picker_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="invisible"
        android:text="go to picker activity" />

    <TextView
        android:id="@+id/selected_location_info_textview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

Full stacktrace:
2020-05-17 01:00:57.244 14576-14628/com.mycompany.mapboxpickerattempt I/oxpickerattemp: --------- beginning of crash
2020-05-17 01:00:57.265 14576-14628/com.mycompany.mapboxpickerattempt A/libc: /usr/local/google/buildbot/src/android/ndk-release-r20/external/libcxx/../../external/libcxxabi/src/abort_message.cpp:73: abort_message: assertion "terminating with uncaught exception of type jni::PendingJavaException" failed
2020-05-17 01:00:57.265 14576-14628/com.mycompany.mapboxpickerattempt A/libc: Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 14628 (OnlineFileSourc), pid 14576 (oxpickerattempt)

A: It seems you have basically copy-pasted this example, which should be working: https://docs.mapbox.com/android/plugins/examples/place-picker/
Can you please share both the application level build.gradle and the project level build.gradle, as well as your activity_place_selection.xml ?
Can you change your project level build.gradle to link mapbox:

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://mapbox.bintray.com/mapbox' }

    }
}

A: This appears to require Java 8 declaration. Please add the following lines to your build.gradle (application level):

compileOptions {
 sourceCompatibility JavaVersion.VERSION_1_8
 targetCompatibility JavaVersion.VERSION_1_8
}

This is my build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.example.placepicker"
        minSdkVersion 24
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-places-v9:0.12.0'

}