text:
Q: Is it possible to "hack" Python's print function? Note: This question is for informational purposes only. I am interested to see how deep into Python's internals it is possible to go with this.
Not very long ago, a discussion began inside a certain question regarding whether the strings passed to print statements could be modified after/during the call to print has been made. For example, consider the function:
def print_something():
    print('This cat was scared.')

Now, when print is run, then the output to the terminal should display:
This dog was scared.

Notice the word "cat" has been replaced by the word "dog". Something somewhere somehow was able to modify those internal buffers to change what was printed. Assume this is done without the original code author's explicit permission (hence, hacking/hijacking).
This comment from the wise @abarnert, in particular, got me thinking:

There are a couple of ways to do that, but they're all very ugly, and
  should never be done. The least ugly way is to probably replace the
  code object inside the function with one with a different co_consts
  list. Next is probably reaching into the C API to access the str's
  internal buffer. [...]

So, it looks like this is actually possible.
Here's my naive way of approaching this problem:
>>> import inspect
>>> exec(inspect.getsource(print_something).replace('cat', 'dog'))
>>> print_something()
This dog was scared.

Of course, exec is bad, but that doesn't really answer the question, because it does not actually modify anything during when/after print is called.
How would it be done as @abarnert has explained it?

A: A simple way to capture all output from a print function and then process it, is to change the output stream to something else, e.g. a file.
I'll use a PHP naming conventions (ob_start, ob_get_contents,...)
from functools import partial
output_buffer = None
print_orig = print
def ob_start(fname="print.txt"):
    global print
    global output_buffer
    print = partial(print_orig, file=output_buffer)
    output_buffer = open(fname, 'w')
def ob_end():
    global output_buffer
    close(output_buffer)
    print = print_orig
def ob_get_contents(fname="print.txt"):
    return open(fname, 'r').read()

Usage:
print ("Hi John")
ob_start()
print ("Hi John")
ob_end()
print (ob_get_contents().replace("Hi", "Bye"))

Would print

Hi John
  Bye John

A: Let's combine this with frame introspection!
import sys

_print = print

def print(*args, **kw):
    frame = sys._getframe(1)
    _print(frame.f_code.co_name)
    _print(*args, **kw)

def greetly(name, greeting = "Hi")
    print(f"{greeting}, {name}!")

class Greeter:
    def __init__(self, greeting = "Hi"):
        self.greeting = greeting
    def greet(self, name):
        print(f"{self.greeting}, {name}!")

You'll find this trick prefaces every greeting with the calling function or method. This might be very useful for logging or debugging; especially as it lets you "hijack" print statements in third party code.

A: Monkey-patch print
print is a builtin function so it will use the print function defined in the builtins module (or __builtin__ in Python 2). So whenever you want to modify or change the behavior of a builtin function you can simply reassign the name in that module.
This process is called monkey-patching.
# Store the real print function in another variable otherwise
# it will be inaccessible after being modified.
_print = print

# Actual implementation of the new print
def custom_print(*args, **options):
    _print('custom print called')
    _print(*args, **options)

# Change the print function globally
import builtins
builtins.print = custom_print

After that every print call will go through custom_print, even if the print is in an external module.
However you don't really want to print additional text, you want to change the text that is printed. One way to go about that is to replace it in the string that would be printed:
_print = print

def custom_print(*args, **options):
    # Get the desired seperator or the default whitspace
    sep = options.pop('sep', ' ')
    # Create the final string
    printed_string = sep.join(args)
    # Modify the final string
    printed_string = printed_string.replace('cat', 'dog')
    # Call the default print function
    _print(printed_string, **options)

import builtins
builtins.print = custom_print

And indeed if you run:
>>> def print_something():
...     print('This cat was scared.')
>>> print_something()
This dog was scared.

Or if you write that to a file:
test_file.py
def print_something():
    print('This cat was scared.')

print_something()

and import it:
>>> import test_file
This dog was scared.
>>> test_file.print_something()
This dog was scared.

So it really works as intended.
However, in case you only temporarily want to monkey-patch print you could wrap this in a context-manager:
import builtins

class ChangePrint(object):
    def __init__(self):
        self.old_print = print

    def __enter__(self):
        def custom_print(*args, **options):
            # Get the desired seperator or the default whitspace
            sep = options.pop('sep', ' ')
            # Create the final string
            printed_string = sep.join(args)
            # Modify the final string
            printed_string = printed_string.replace('cat', 'dog')
            # Call the default print function
            self.old_print(printed_string, **options)

        builtins.print = custom_print

    def __exit__(self, *args, **kwargs):
        builtins.print = self.old_print

So when you run that it depends on the context what is printed:
>>> with ChangePrint() as x:
...     test_file.print_something()
...
This dog was scared.
>>> test_file.print_something()
This cat was scared.

So that's how you could "hack" print by monkey-patching.
Modify the target instead of the print
If you look at the signature of print you'll notice a file argument which is sys.stdout by default. Note that this is a dynamic default argument (it really looks up sys.stdout every time you call print) and not like normal default arguments in Python. So if you change sys.stdout print will actually print to the different target even more convenient that Python also provides a redirect_stdout function (from Python 3.4 on, but it's easy to create an equivalent function for earlier Python versions).
The downside is that it won't work for print statements that don't print to sys.stdout and that creating your own stdout isn't really straightforward.
import io
import sys

class CustomStdout(object):
    def __init__(self, *args, **kwargs):
        self.current_stdout = sys.stdout

    def write(self, string):
        self.current_stdout.write(string.replace('cat', 'dog'))

However this also works:
>>> import contextlib
>>> with contextlib.redirect_stdout(CustomStdout()):
...     test_file.print_something()
...
This dog was scared.
>>> test_file.print_something()
This cat was scared.

Summary
Some of these points have already be mentioned by @abarnet but I wanted to explore these options in more detail. Especially how to modify it across modules (using builtins/__builtin__) and how to make that change only temporary (using contextmanagers).

A: First, there's actually a much less hacky way. All we want to do is change what print prints, right?
_print = print
def print(*args, **kw):
    args = (arg.replace('cat', 'dog') if isinstance(arg, str) else arg
            for arg in args)
    _print(*args, **kw)

Or, similarly, you can monkeypatch sys.stdout instead of print.

Also, nothing wrong with the exec … getsource … idea. Well, of course there's plenty wrong with it, but less than what follows here…

But if you do want to modify the function object's code constants, we can do that.
If you really want to play around with code objects for real, you should use a library like bytecode (when it's finished) or byteplay (until then, or for older Python versions) instead of doing it manually. Even for something this trivial, the CodeType initializer is a pain; if you actually need to do stuff like fixing up lnotab, only a lunatic would do that manually.
Also, it goes without saying that not all Python implementations use CPython-style code objects. This code will work in CPython 3.7, and probably all versions back to at least 2.2 with a few minor changes (and not the code-hacking stuff, but things like generator expressions), but it won't work with any version of IronPython.
import types

def print_function():
    print ("This cat was scared.")

def main():
    # A function object is a wrapper around a code object, with
    # a bit of extra stuff like default values and closure cells.
    # See inspect module docs for more details.
    co = print_function.__code__
    # A code object is a wrapper around a string of bytecode, with a
    # whole bunch of extra stuff, including a list of constants used
    # by that bytecode. Again see inspect module docs. Anyway, inside
    # the bytecode for string (which you can read by typing
    # dis.dis(string) in your REPL), there's going to be an
    # instruction like LOAD_CONST 1 to load the string literal onto
    # the stack to pass to the print function, and that works by just
    # reading co.co_consts[1]. So, that's what we want to change.
    consts = tuple(c.replace("cat", "dog") if isinstance(c, str) else c
                   for c in co.co_consts)
    # Unfortunately, code objects are immutable, so we have to create
    # a new one, copying over everything except for co_consts, which
    # we'll replace. And the initializer has a zillion parameters.
    # Try help(types.CodeType) at the REPL to see the whole list.
    co = types.CodeType(
        co.co_argcount, co.co_kwonlyargcount, co.co_nlocals,
        co.co_stacksize, co.co_flags, co.co_code,
        consts, co.co_names, co.co_varnames, co.co_filename,
        co.co_name, co.co_firstlineno, co.co_lnotab,
        co.co_freevars, co.co_cellvars)
    print_function.__code__ = co
    print_function()

main()

What could go wrong with hacking up code objects? Mostly just segfaults, RuntimeErrors that eat up the whole stack, more normal RuntimeErrors that can be handled, or garbage values that will probably just raise a TypeError or AttributeError when you try to use them. For examples, try creating a code object with just a RETURN_VALUE with nothing on the stack (bytecode b'S\0' for 3.6+, b'S' before), or with an empty tuple for co_consts when there's a LOAD_CONST 0 in the bytecode, or with varnames decremented by 1 so the highest LOAD_FAST actually loads a freevar/cellvar cell. For some real fun, if you get the lnotab wrong enough, your code will only segfault when run in the debugger.
Using bytecode or byteplay won't protect you from all of those problems, but they do have some basic sanity checks, and nice helpers that let you do things like insert a chunk of code and let it worry about updating all offsets and labels so you can't get it wrong, and so on. (Plus, they keep you from having to type in that ridiculous 6-line constructor, and having to debug the silly typos that come from doing so.)

Now on to #2.
I mentioned that code objects are immutable. And of course the consts are a tuple, so we can't change that directly. And the thing in the const tuple is a string, which we also can't change directly. That's why I had to build a new string to build a new tuple to build a new code object.
But what if you could change a string directly?
Well, deep enough under the covers, everything is just a pointer to some C data, right? If you're using CPython, there's a C API to access the objects, and you can use ctypes to access that API from within Python itself, which is such a terrible idea that they put a pythonapi right there in the stdlib's ctypes module. :) The most important trick you need to know is that id(x) is the actual pointer to x in memory (as an int).
Unfortunately, the C API for strings won't let us safely get at the internal storage of an already-frozen string. So screw safely, let's just read the header files and find that storage ourselves.
If you're using CPython 3.4 - 3.7 (it's different for older versions, and who knows for the future), a string literal from a module that's made of pure ASCII is going to be stored using the compact ASCII format, which means the struct ends early and the buffer of ASCII bytes follows immediately in memory. This will break (as in probably segfault) if you put a non-ASCII character in the string, or certain kinds of non-literal strings, but you can read up on the other 4 ways to access the buffer for different kinds of strings.
To make things slightly easier, I'm using the superhackyinternals project off my GitHub. (It's intentionally not pip-installable because you really shouldn't be using this except to experiment with your local build of the interpreter and the like.)
import ctypes
import internals # https://github.com/abarnert/superhackyinternals/blob/master/internals.py

def print_function():
    print ("This cat was scared.")

def main():
    for c in print_function.__code__.co_consts:
        if isinstance(c, str):
            idx = c.find('cat')
            if idx != -1:
                # Too much to explain here; just guess and learn to
                # love the segfaults...
                p = internals.PyUnicodeObject.from_address(id(c))
                assert p.compact and p.ascii
                addr = id(c) + internals.PyUnicodeObject.utf8_length.offset
                buf = (ctypes.c_int8 * 3).from_address(addr + idx)
                buf[:3] = b'dog'

    print_function()

main()

If you want to play with this stuff, int is a whole lot simpler under the covers than str. And it's a lot easier to guess what you can break by changing the value of 2 to 1, right? Actually, forget imagining, let's just do it (using the types from superhackyinternals again):
>>> n = 2
>>> pn = PyLongObject.from_address(id(n))
>>> pn.ob_digit[0]
2
>>> pn.ob_digit[0] = 1
>>> 2
1
>>> n * 3
3
>>> i = 10
>>> while i < 40:
...     i *= 2
...     print(i)
10
10
10

… pretend that code box has an infinite-length scrollbar.
I tried the same thing in IPython, and the first time I tried to evaluate 2 at the prompt, it went into some kind of uninterruptable infinite loop. Presumably it's using the number 2 for something in its REPL loop, while the stock interpreter isn't?


text:
Q: Replicating Lilypond titles in LaTeX I'm working on a huge project that automatically and without any human intervention generates music scores. Most of the time this is with Lilypond. But some of the scores use graphical notation and for those I use TikZ and pdfLaTeX. The problem is that I want to match Lilypond's title header look in LaTeX but I am struggling.
First is Lilypond

Next is my effort:

And here is the LaTeX code that my software generates:
\documentclass[11pt]{memoir}
\usepackage{tikz}
\usepackage[top=5mm,left=15mm,right=15mm]{geometry}
\usepackage{parskip}
\usepackage{newcent}

\begin{document}
\begin{center}
(Dedication) \\
\smallskip\textbf{\LARGE{Title}} \\
\medskip\textbf{\large{Style}} \\
\end{center}
\vspace{-8pt}
\noindent
\begin{minipage}[t][0em][b]{0.33\textwidth}Poet \end{minipage}
\begin{minipage}[t][0em][b]   {0.33\textwidth}\begin{center}\textbf{\large{Instrument}}   \end{center}\end{minipage}
\begin{minipage}[t][0em][b]{0.33\textwidth}\hfill Composer\end{minipage}\\
\medskip
\noindent
\begin{minipage}[c][1em][b]{0.5\textwidth}Meter \end{minipage}
\begin{minipage}[c][1em][b]{0.5\textwidth}\hfill Arranger\end{minipage}\\
Piece

\end{document}

So there are a few issues:

*

*My "Composer" does not appear to be flush right

*I'm really not fond of the \vspace{-8pt} bit. The software will use different fonts and paper sizes and I worry that anything hardcoded like that will eventually look bad. I've never used minipages before so I don't know if I'm doing that stuff correctly. Basically I just experimented with the parameters till it looked OK.

*I don't know why the "Piece" entry is spaced so awkwardly in the Lilypond example but I prefer the more even spacing in mine, so that's not an issue.

*I can play around with the geometry more on my own but if anyone has any suggestions for the spacing I would appreciate that as well.

*There will not always be entries for the "Poet", "Meter", and "Piece". So right now using \hfill seems to do the trick of keeping the same spacing. Is that the best way to handle that assuming I keep using minipages?
It doesn't need to be a perfect copy but I do want it to look the same to the casual observer.

A: I suggest, first of all, a key-value syntax. Then you can divide the space using a tabular with three equal size columns, with left, center and right alignment.
The dedication is typeset only if present, and in a unique center aligned column, so its width will not influence the positioning of the other elements.
\documentclass[11pt]{memoir}
\usepackage[top=5mm,left=15mm,right=15mm]{geometry}
\usepackage{newcent}
%\usepackage{array} % not needed with memoir
\usepackage{xparse}

\ExplSyntaxOn
\keys_define:nn { bfootdav/lilyheader }
 {
  dedication .tl_set:N = \l_bfootdave_lilytitle_dedication_tl,
  title .tl_set:N = \l_bfootdave_lilytitle_title_tl,
  style .tl_set:N = \l_bfootdave_lilytitle_style_tl,
  instrument .tl_set:N = \l_bfootdave_lilytitle_instrument_tl,
  poet .tl_set:N = \l_bfootdave_lilytitle_poet_tl,
  composer .tl_set:N = \l_bfootdave_lilytitle_composer_tl,
  arranger .tl_set:N = \l_bfootdave_lilytitle_arranger_tl,
  meter .tl_set:N = \l_bfootdave_lilytitle_meter_tl,
  piece .tl_set:N = \l_bfootdave_lilytitle_piece_tl,
 }

\NewDocumentCommand{\makepieceheader}{m}
 {
  \group_begin:
  \keys_set:nn { bfootdav/lilyheader } { #1 }
  \bfootdav_make_piece_header:
  \group_end:
 }

\cs_new_protected:Npn \bfootdav_make_piece_header:
 {
  \noindent\begin{tabular}
   {
    @{}
    >{\raggedright}p{.33333\textwidth}
    @{}
    >{\centering}p{.33333\textwidth}
    @{}
    >{\raggedleft\arraybackslash}p{.33333\textwidth}
    @{}
   }
  \tl_if_empty:NF \l_bfootdave_lilytitle_dedication_tl
   {
    \multicolumn{3}{@{}>{\centering}p{\textwidth}@{}}
     {
      ( \l_bfootdave_lilytitle_dedication_tl )
     }
    \\
   }
  & \LARGE\bfseries\strut \l_bfootdave_lilytitle_title_tl &
  \\
  & \large\bfseries\strut \l_bfootdave_lilytitle_style_tl &
  \\
  \l_bfootdave_lilytitle_poet_tl &
  \bfseries\l_bfootdave_lilytitle_instrument_tl &
  \l_bfootdave_lilytitle_composer_tl
  \\
  \l_bfootdave_lilytitle_meter_tl && \l_bfootdave_lilytitle_arranger_tl
  \\
  \l_bfootdave_lilytitle_piece_tl &&
  \end{tabular}
 }
\ExplSyntaxOff

\begin{document}
\makepieceheader{
  dedication=Dedication,
  title=Title,
  style=Style,
  poet=Poet,
  instrument=Instrument,
  composer=Composer,
  meter=Meter,
  arranger=Arranger,
  piece=Piece
}

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rails API saving belongs_to association I'm trying to have below in more of a Rails way.
Given appointment belongs to service:
appointment = Appointment.new(appointment_params)
appointment.service = Service.find(params[:service][:id])
appointment.save

What I've tried so far:
appointment = Appointment.new(appointment_params)
appointment.build_service(params[:service])
appointment.save

However with this approach I'm getting ForbiddenAttributesError
I cannot use accepts_nested_attributes_for because in strong params I need to use service_attributes but my UI application sends AJAX request without _attributes but rather just service with its attributes.
I don't really like where Rails enforces you to use _attributes popular Javascript frameworks like Angular.js and React.js does not enforce or encourage this pattern after all. Is there a way to override this and still use strong parameters with benefit of using accepts_nested_attributes_for?

A: Try just setting the ID.  It would be helpful to see your model file, though.
appointment.service_id = params[:service][:id]

or
appointment.service_id = Service.find(params[:service][:id]).id # if you know service exists...


text:
Q: Bitrise is trying to code sign an embedded framework with wrong provisioning profile My iOS project has an embedded framework. I am trying to build it on Bitrise, but it fails because it tries to code sign this framework with the same provisioning profile as the actual project.
This is the error it produces (split onto separate lines for readability):
❌  Code Sign error: Provisioning profile does not match bundle identifier:
The provisioning profile specified in your build settings
("Profile Name") has an AppID of "com.example.mainidentity"
which does not match your bundle identifier
"com.example.frameworkidentity".

I've tried it with Force code signing with Provisioning Profile, with Force code signing with Identity, without either and various other permutations. Changing the Code Signing Identity from iOS Developer to Don't Code Sign in the framework's Build Settings. Etc.
I've left Code Sign on Copy on in the Build Phases of the main project.
Nothing seems to work.
It's my understanding that an embedded framework should just sign with the iOS Developer identity as you archive a project.
-
The project archive's fine on my local machine.
Environment & info:
Using a workspace, the embedded framework does have it's own pods, as does the main project.
I'm using Xcode 7.3 on OS X 10.11.6
The provisioning profile is an iOS UniversalDistribution type one.
The Bitrise workflow is using:

*

*Certificate and profile installer - 1.7.0

*Xcode: Create Archive - 1.9.2
If any other info is needed or anything needs clarifying let me know!
Thank you!!

A: You should not use "Force code signing with Provisioning Profile" in this case, as that (this is simply an option passed to Xcode) will force that specific profile to be used for every part of the project!
You can find more information here: https://bitrise-io.github.io/devcenter/ios/code-signing/#full-manual-full-control
TL;DR; don't use a full Provisioning Profile ID, rather use "Force Identity" if you really have to (and maybe just a category for Force Prov Profile, like "iPhone Distribution"), Xcode will figure out which profile to use, based on the Identity and bundle IDs etc.
That said, since Xcode 7 the recommended way is to use "Export Options Plist", and in Xcode 8 if you opt-in for automatic code signing that's your only option. In short, the recommended way is to do an initial signing with development code signing, and then specify the "export method" for Xcode (in case of Bitrise this is an option of the Xcode Archive step). The only this to note here is that you need both development and distribution certs & profiles to be available. But once you do, selecting the right one for distribution is as easy as setting the "export method" option (Xcode Archive step) to the type you want to use (e.g. ad-hoc or app-store).
More info: https://bitrise-io.github.io/devcenter/ios/code-signing/#using-export-options-available-for-xcode-7-and-xcode-archive-step-v191
P.S.: if you'd want to migrate to the new code signing options you should reset the inputs you previously specified - probably the fastest way, if you use the Web UI, is to remove the Xcode Archive step, and then add a new one to the same spot.


text:
Q: Am trying to change my insert query to bulk insert, how do i do that? I'm trying to change the query below on Mysql, the query it's self it's a normal insert query and it takes time to run.What i want is to change it to Bulk-Insert query. I have been reading about bulk insert but am still struggling on how i can change my query.
Bulk-Insert is new to me and am required to use it.I've tried to read about it but can't implement it,and the below query takes time to run.
insert into dbo.WaR
SELECT *
FROM OPENQUERY (M_Prod_full, ''SELECT CODE,OPERATOR_C
where (group like ''''SM%'''' or DN like ''''088%'''')
and type = ''''S'''' and type_R = ''''O''''
and to_char(date, ''''YYYYMM'''') = ''''' + @YM + ''''''')

I am expecting a way to implement a bulk insert in my code i provided and i want the bulk insert to reduce the time it takes to run.


text:
Q: Date object will return 1537865065664 on two Difference Date Object in java I want time difference in second using new Date().getTime() in java.
But i will return me long digit like this 1537865065664.
How can i get difference between two Date() object.
I will attached few part of my code below.
     Date starttime=new Date();
      long diff=  new Date().getTime() - starttime.getTime()
 System.out.println("hangupClicked New Time :: "+new Date().getTime()+" :: "+starttime.getTime());

Output ::
hangupClicked New Time :: 1537865248609 :: 1537865348612

A: The difference obtained using date1.getTime() - date2.getTime() is in milliseconds. You can divide the output by 1000 to get difference in seconds.
(date1.getTime() - date2.getTime())/1000;

A: new Date().getTime() returns time in milliseconds. So if you want in seconds, you need to divide the difference by 1000.
 Date starttime=new Date();
  long diff=  (new Date().getTime() - starttime.getTime())/1000;

A: java.time
    Instant startTime = Instant.now();
    Duration diff = Duration.between(startTime, Instant.now());
    System.out.println("Difference in seconds: " + diff.getSeconds());

This snippet just printed:
Difference in seconds: 0

This is as expected since there isn't a full second between the two calls to Instant.now().
What went wrong in your code?
You were calculating the difference in milliseconds between your two Date objects correctly. You did not print the difference and therefore never saw that it was correct. And you did not convert it to seconds.
To illustrate the first point I added this line to your code:
    System.out.println("diff (milliseconds):: " + diff);

Then I got this output from it:
hangupClicked New Time :: 1537890219204 :: 1537890219204
diff (milliseconds):: 0

That said, you shouldn't use Date in 2018. That class is long outdated and poorly designed at the same time. You should prefer to use java.time, the modern Java date and time API.
Links

*

*Oracle tutorial: Date Time explaining how to use java.time.

*All about java.util.Date on Jon Skeet's coding blog

A: If you want in second then divide the diff by 1000 then you will get in second. Date().getTime() return the value in milliseconds.

A: The return type of getTime() is milliseconds from 01-01-1970 to the specified date. So in order to get difference in seconds use below
(date.getTime() - date2.getTime())/1000;


text:
Q: iphone - will it leak? This is something I don't understand. Look at this method (copied from http://blog.blackwhale.at/2009/07/uibutton-in-uitableview-footer/)
See that footerView is allocated on the beginning of the code and never released.
As far as I understand, the object should be autoreleased or at least released after used on a regular case, but as this method is run automatically by the tables when they are built, where exactly will this view be released...
or will it leak? I have seen Apple samples of code with stuff like that, so I suppose the object is being released somewhere... but where?
// custom view for footer. will be adjusted to default or specified footer height
// Notice: this will work only for one section within the table view
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {

    if(footerView == nil) {
        //allocate the view if it doesn't exist yet
        footerView  = [[UIView alloc] init];

        //we would like to show a gloosy red button, so get the image first
        UIImage *image = [[UIImage imageNamed:@"button_red.png"]
  stretchableImageWithLeftCapWidth:8 topCapHeight:8];

        //create the button
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setBackgroundImage:image forState:UIControlStateNormal];

        //the button should be as big as a table view cell
        [button setFrame:CGRectMake(10, 3, 300, 44)];

        //set title, font size and font color
        [button setTitle:@"Remove" forState:UIControlStateNormal];
        [button.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

        //set action of the button
        [button addTarget:self action:@selector(removeAction:)
                        forControlEvents:UIControlEventTouchUpInside];

        //add the button to the view
        [footerView addSubview:button];
    }

    //return the view for the footer
    return footerView;
}

thanks.

A: Seeing as footerView is an instance variable on this class, this code is correct.  footerView is not autoreleased (by you, anyway) so it will continue to exist as long as you don't release it (because you "own"/retained it by allocating it).  The proper place to do that would be in this class's dealloc method.
As long as you do that, this code looks correct to me.  :)

A: footerView is an instance variable.  Is it released in the dealloc of the class?


text:
Q: Which API's are needed to get enabled for Google Custom search? We are calling API by URL:
https://www.googleapis.com/customsearch/v1?key=MY_KEY&cx=CUSTOM_SEARCH_ID&q=flower

Getting error in reponse:
"error": { "errors": [ { "domain": "usageLimits", "reason": "accessNotConfigured", "message": "Access Not Configured. Please use Google Developers Console to activate the API for your project." } ], "code": 403, "message": "Access Not Configured. Please use Google Developers Console to activate the API for your project." }

We have enabled Custom Search API and Google + API. Still getting above error. should we need to enable some other API too?
Please help.

A: No, I believe that custom search API is the only API that you need to enable.
So, I would consider whether you have the right key and CSE ID.
To verify your CSE ID, do a test query from here (fill in ):
https://console.developers.google.com/project/PROJECT_ID/apiui/api/customsearch/method/search.cse.list
If your query works there, but still doesn't work in your code, then perhaps the issue is your key.  If you are just doing a simple URL request (as you show in your Q), then I would expect you are using a server key.  And, of course, the key you are using must be from the same project where you have enabled the CSE API.

A: Go to https://console.developers.google.com/apis/dashboard
In the dashboard screen there is an Enable API link(near Dashboard heading)
Choose the API you want to enable.
The enabled API will be listed in the dashboard.
Call the API by URL and check.


text:
Q: How to access a chart to add a data point in c# I am trying to write a class to update chart data.  I have created the chart through windows forms which has autogenerated the code in Form1.cs and Form1.Designer.cs
Here is what i think is the relevant part from Form1.designer.cs:
private void InitializeComponent()
{
    System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
    System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
    System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
    System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint1 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 2D);
    System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint2 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 3D);
    System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint3 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 2D);
    System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint4 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 25D);
    System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint5 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 2D);
    System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint6 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 3D);
    System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint7 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D);
    this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
    this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
    this.tableLayoutPanel1.SuspendLayout();
    ((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit();
    this.SuspendLayout();

I have written another class called UpdateGraph.cs which has a method to add an extra point to the graph
namespace DataLogger
{
    class UpdateGraph
    {
        public void addGraphPoints()
        {
            chart1.Series.Points.AddXY(0, 10);
        }
    }
}

The problem is I get an error with message

The name chart1 does not exist in the current context

So if anyone could explain how I can access the chart to modify the data (or what i should be refering to) I would really appreciate it as I am a bit stumped at the moment.

A: You could try this one:
using System.Windows.Forms.DataVisualization.Charting;

class UpdateGraph
{
    public Chart Chart1 { get; set; }

    public UpdateGRaph(Chart chart)
    {
        Chart1 = chart;
    }

    public void AddGraphPoints()
    {
        Chart1.Series.Points.AddXY(0, 10);

    }
}

A: Forms Designer will create a local chart in InitializeComponent() - maybe there's a way to prevent it but I've yet to find it.
  The trick is to get the chart out of your control hierarchy. For example, my chart in Designer.cs is added to grpStuff:
this.grpStuff.Controls.Add(chrtStuff);

and its name can be found in Designer.cs also:
chrtStuff.Name = "chartName";

SO - in my code I find the chart by:
chrt = (System.Windows.Forms.DataVisualization.Charting.Chart)grpStuff.Controls("chartName");

A: chart1.Series["Your series name"].Points.AddXY(0, 10);


text:
Q: .net docking controls I have created a CustomControl to show information labels and that can be minimized/restored with an arrow button:

It should be docked to the top of a form.
Then in the same form usually I have a center panel with all the normal controls, here it is showm in yellow just to highlight it.

Finally I have a bottom panel containing all the commands/buttons available on the form. This is docked to the bottom.
The problem is that I don't know how to set the center panel to automatically consume the available space when I collapse the top panel. That is, there's no a "Center" Docking style.
If I dock the middle panel to the top, then when I collapse the top one I get:

If I anchor the middle panel to all the edges, I get:

If I dock the middle panel to fill the area, then it fills all the client area of the form, regardless the existence of the other panels.
Yes I could create an event in the top control to notify who is interested about the size change but.. It's an ugly solution because it's not automatic: in every form I'll have to listen to the event and resize the middle panel accordingly.
Is there an elegant solution to this problem?

A: Set the DockStyle to Fill:

Add this control after the other two. To ensure it comes after the other two, CTRL-X it, then CTRL-V it back in.

A: You do want DockStyle.Fill however if that middle control is going 'behind' the top and bottom docked controls, then you need to re-order the controls. Internall WinForms processes the items in the order they were added to the parent.  In VisualStudio designer, right-click on your middle panel that is docked to Fill, and select "Bring to Front" or "Move to Back". I forget which one it is offhand, but one of them should fix your issue.

A: Using Split container will solve the problem.
Drag a Panel and make the panel dock property to top (which has ur expander/collapse button).
Now drag a split container and change the oreintation to horizontal.and change dockstyle to fill.
Now in the splitcontainer top panel drag ur custom control and add ur form controls to the bottom splitter panel.
When you want to hide the hide ur custom control write the following logic in button click on top panel
private void btnExpandCollapseOptions_Click(object sender, EventArgs e)
    {
        if (splMainContainer.Panel1Collapsed)
        {
            splMainContainer.Panel1Collapsed = false;
            btnExpandCollapseOptions.Image = ImageResource.collapseMinus;
//changing image to collapse/expand from imageresource.resx file
        }
        else
        {
            splMainContainer.Panel1Collapsed = true;
            btnExpandCollapseOptions.Image = ImageResource.ExpandPuls;
        }

    }

the bottom contorl will occupy the total space when custom control collapses


text:
Q: Not sure how these two options are different in interpreting $\lim_{x\to a} f(x) = L$ I came across a multiple choice question asking "What do we mean when we write $\lim\nolimits_{x \to a} f(x) = L$?" The only two of the four answers that made sense are

*

*As $x$ gets closer to $a$, $f(x)$ gets closer to $L$.

*We can make $f(x)$ as close as we like to $L$, by choosing $x$ closer to $a$.

Using the precise definition of a limit, I knew that the answer was 2., but I am unsure how these two answers are different.
The only thing that I could come up with is that option 1. has to do with continuity, for $x$ getting closer to $a$ is not sufficient to conclude that $f(x)$ gets closer to $L$, unless $L=f(a)$, but I'm not sure.
Edit: I added $L=f(a)$ in the last sentence of the preceding paragraph.

A: They are different. Because the first statement only says we're getting closer, but not as close as we want (see Example 1). Moreover we can get as close as we want without constantly getting closer (see Example 2, in which $L=f(a)$).
Let me explain with an example:
Example 1. Let $f:[0,1]\rightarrow\mathbb{R}$ be the function $f(x)=x$. Now if $L=1$, $a=1$ both statements hold.
However you can now take $L=2$. I claim that the first statement hold, but the second doesn't.
Indeed, the first holds. Since $f(x)$ is monotonically increasing, it gets larger as $x$ gets closer to $1$. In particular as $x$ gets closer to $1$, $f(x)$ get closer to $L=2$. Formally, $|2-f(x)| = 2-x$ decreases as $x$ gets closer to $1$.
On the other hand, the second property doesn't hold. Because no matter how close you get to $1$, $f(x)$ will always be at least $1$ point far from $L=2$.
If you take $L=f(a)$ the statements still don't mean the same thing (the first one would imply continuity but it is much stronger).
Example 2. For instance consider
$$f(x) = \begin{cases} x & \text{there is no } n \text{ s.t. } x=1-\frac{1}{n}\\ 1 & \text{if }  x=1-\frac{1}{n} \end{cases}$$
Take $L=f(1)=1$. Then the second statement holds, but the first doesn't. Because $f(\frac{1}{2})=1$, and if $x=\frac{98}{100}$ then $f(x)=\frac{98}{100}\not = 1$. Clearly the value $f$ gives to $\frac{1}{2}$ is closer to $1$ then the value it gives $\frac{98}{100}$ even though $\frac{98}{100}$ is closer to $a=1$.

A: Both of the statements are defective. In 1.) you do not need to get arbitrarily close to $L$, as is necessary for a limit, and in 2.) one can not exclude that there are multiple values for $L$ that $f(x)$ gets close to for $x$ approaching $a$. For instance in $f(x)=\sin(1/x)$  you can chose $x$ arbitrarily close to $a=0$ so that $f(x)$ is equal to any value in $[−1,1]$.

Under the assumption that the "dynamics" of "getting closer" includes that the distance has to go to zero, the first variant seems to be more correct. A more formal formulation of the dynamical statement would be that the sets of function values $f((a-δ,a+δ)\cap D_f)$ gets more concentrated around $L$ the smaller $δ$ gets, the radius shrinking to zero.
The second variant in my view describes a limit value, that is, the sets $f((a-δ,a+δ)\cap D_f)$ need not concentrate around $L$, they just need to all contain $L$ in their closure, the radius of the sets can remain above some positive bound.

Or in still other words, in the sequential interpretation of the limit, the first condition demands that $f(x_k)\to L$ for all $x_k\to a$, while the second condition only demands that $f(x_k)\to L$ for at least one sequence $x_k\to a$.

A: The reason the second definition is better is primarily because of sets other than $\mathbb{R}$ limits can exist in any sets that have distance measures. If you think about for example $\mathbb{R^2}$ getting closer to a number doesn't mean the same thing as in $\mathbb{R}$ In $\mathbb{R}$ it is very simple to think about following a point along a function to infinity to approach a point but this is more complicated in other dimensions as there is not necessarily a set path to follow.
Another issue with the first definitions is discontinuities that aren't related to the limit. For example $\lim_{x\to\infty}\frac{1}{x}=0$ but if you look at the left side of the y-axis and try to follow the function you would be justified saying that the limit is $-\infty$ since as you move x closer to $\infty$ it gets closer to $-\infty$
The third reason is that it doesn't say anything about how close, like in my last issue while $\frac1x$ might approach 0 as it goes to $\infty$ it also gets closer to $-1$ and really any negative number.

A: The second answer would be the more correct of the two.
The reason is because of the notion of "arbitrary closeness."
The limit of a function $f(x)$ as $x \to a$ exists and is equal to $L$ if and only if given any $\epsilon > 0$, we can find another number $\delta$ for which whenever $x$ is within a $\delta$-neighborhood of $a$, it necessarily follows that $f(x)$ is within the associated $\epsilon$-neighborhood of $L$.
The $\delta$, however, is not a universal $\delta$. If you change $\epsilon$ we may need to recalculate $\delta$, but we are assured that such a $\delta$ exists by the underlying definition of limit.


text:
Q: Xcode text rendering bug? Sometimes in Xcode, when I am towards the end of a file, the editor starts scrambling the lines. I have a video of it below. You can see when I close the bracket the text goes back to normal:
http://vimeo.com/18678901
Any idea if there are ways around this? Restarting Xcode doesn't help.

A: Looks like a bug. Please file that on bugreporter.apple.com along with the version of Xcode you were using at the time. If it's reproducible and you can attach the project/file to the bug, please do. For extra credit, post the bug # here so I can follow up on it, thanks.
P.S. Please check the Console for silent exceptions from Xcode. My colleague reminded me to ask you about this.


text:
Q: How to clear value select input and out of anothor loops in node.js **I have database here**
-----------------------------
| year | month | day | name |
-----------------------------
| 2017 | JAN   |  1  | John |
| 2017 | JAN   |  3  | Max  |
| 2017 | FEB   |  4  | Alex |
-----------------------------

and in select.jade I have three select input :
| select year |    |select month|   |select day|

if I selected year
| 2017 |  |select month| | select day|

I get result :
------------------------------
| year | month | day | name  |
------------------------------
| 2017 | JAN  |  1   | John  |
| 2017 | JAN  |  3   | Max   |
| 2017 | FEB  |  4   | Alex  |
------------------------------

if I selected year , month
| 2017 | |JAN | | select day |

I get result :
------------------------------
| year | month | day | name  |
------------------------------
| 2017 | JAN  |  1   | John  |
| 2017 | JAN  |  3   | Max   |
------------------------------

if I selected year , month , day :
| 2017 | |JAN | | 1 |

I get result :
------------------------------
| year | month | day | name  |
------------------------------
| 2017 | JAN  |  1   | John  |
------------------------------

if I change selected month form JAN to FEB :
| 2017 | | FEB | | 1 |

Which is not in database and I want to clear value in selected day as :
| 2017 |  | FEB |  | select day |

and get result :
-----------------------------
| year | month | day | name |
-----------------------------
| 2017 | FEB   |  4  | Alex |
-----------------------------

How to do this out of loops condition.
code here :
db.select_years(function(err, selectYears) {
  if (err) return next(err);
  db.select_months(req.body.inputyear, function(err, selectMonths) {
        if (err) return next(err);
        for (var i = 0; i < selectMonths.length; i++) {
          selectMonths[i].monthName = moment({
            month: Number(selectMonths[i].month) - 1
          }).format("MMMM");
        }
        db.select_days(req.body.inputyear, req.body.inputmonth, function(err, selectDays) {
          if (err) return next(err);
          db.getresult(req.body.inputyear, req.body.inputmonth, req.body.inputday, function(err, result) {
            if (err) return next(err);
            var count = 0;
            if (result.length == 0) {
              // here if Which is not in database
            } else {
              for (var i = 0; i < result.length; i++) {
                if (Number(result[i].sum) > 0) {
                  count += Number(result[i].sum);
                }
                result[i].sum = numeral(result[i].sum).format('0,0');
              }
            }
            count = numeral(count).format('0,0');
            res.render("selectvalue", {
              result: result,
              selectYears: selectYears,
              selectMonths: selectMonths,
              selectordays: selectordays,
              count: count
            });
          });
        });
      });
    });


text:
Q: React-input-mask inability to paste correct phone My input has following code
<InputMask
                        id='phone'
                        name='phone'
                        type='tel'
                        value={this.state.phone}
                        mask='+63(\999) 999-99-99'
                        maskChar='X'
                        onChange={(e: SyntheticEvent<HTMLInputElement>): void => {
                            this.setState({
                                phone: e.currentTarget.value.replace(/[^\d.+]/g, ''),
                            });
                        }}
                        onBlur={this.validateInput}
                        onPaste={(e) => this.handlePaste(e)}
                        className='form-control'
                        placeholder='Your Phone'
                    />

here +639 digits that can not be deleted. But when I try to paste phone number I get incorrect phone.
For example i paste +639055943784
and get +63(963) 963-90-55 which is not desired result.
My paste handler is
    handlePaste = (e) => {
    this.setState({phone: e.clipboardData.getData("Text")})
}

A: Try that one
handlePaste = (e) => {
  const number = e.clipboardData.getData("Text");
  const formattedNumber = number.replace(/639+/i, '')
  this.setState({phone: formattedNumber})
}

There also could be edge cases when pasted value will contain another 639s, but I think you can fetch it independently

A: I created a package that exposes an input component that displays a masked value according to the mask it receives.
The mask will change keeping the cursor at the correct position (even if you change part of the value in the middle of the input, paste some characters, or delete a part of it, and even if the mask changes).
I created a live demo for your use case, using the mask +63(9XX) XXX-XX-XX and defining custom mask rules that uses X as the user provided characters (instead of 9, because you want a digit 9 static in the mask) and associated it with a regex that only accepts a digit/number:
https://codesandbox.io/s/react-phone-mask-70fwc?file=/src/index.js:123-141
import React from "react";
import { MaskedInput } from "react-hook-mask";

const mask = "+63(9XX) XXX-XX-XX";
const maskGenerator = {
  rules: new Map([["X", /\d/]]),
  generateMask: () => mask
};

const PhoneMaskedInput = () => {
  const [value, setValue] = React.useState("");

  return (

Phone Number:

      <MaskedInput
        maskGenerator={maskGenerator}
        value={value}
        onChange={setValue}
      />

Value: {value ? "+639" + value : undefined}

  );
};

You can see a demo with several examples at:
https://lucasbasquerotto.github.io/react-masked-input
To install the package: npm i react-hook-mask
This component wraps a default input, but the package also expose hooks to make you able to use it with any kind of component as well as the option to use dynamic masks and dynamic rules (as in the example above).
You can see more information about the package at:
https://www.npmjs.com/package/react-hook-mask


text:
Q: DataContractSerializer in WinRT I was practicing the WinRT API but encountered some problems need your help.
I want to try the DataContractSerializer and reference this site:
http://winrtstoragehelper.codeplex.com/
The code:
Stream inStream = Task.Run(() => readStream.OpenRead()).Result;

I think it should be (bug?):
Stream inStream = await Task.Run(() => readStream.OpenRead());

But the most weird thing is that if I only use:
Stream inStream = readStream.OpenRead());

and I pass this stream into:
DataContractSerializer.WriteObject

The API will be stuck forever.
But if I use:
Stream inStream = await Task.Run(() => readStream.OpenRead());

And pass this stream into the WriteObject then it will work fine.
I have no idea why this symptom only occurred if I don't use Task.Run and await for the stream.
Could any one give me some advice or suggestion?

But
Stream inStream = readStream.OpenRead() method did not be named "async"
I don't know why I need to create Task on purpose to do this.
Thanks.

A: The answer is in the project description:

"ObjectStorageHelper is a Generic class that simplifies storage of
  data in WinRT applications while still maintaining the async
  *principles* of Metro-style apps."

All File/IO operations in WinRT are by nature asynchronous, hence the need to use methods that are also asynchronous (in order to get any result, at least).  The new "await" keyword is one way to accomplish this, although you could also explicitly assign a callback function to handle the completion of the async operation.


text:
Q: Passing props in protected route reactjs I'm using protected routes in my reactjs application and I would like to know how to pass props in a protected route or if there is a more elegant way to solve my problem.
The reason why I feel the need to pass a props in a protected route, is that the logout button lies within the protected components and I need to communicate to the parent component, which contains all the routes, that the user is trying to log out.
Here is the relevant code:
Parent component:
render() {
    const PrivateRoute = ({ component: Component, ...rest }) => (
        <Route {...rest} render={(props) => (
            isAuthenticated === true
            ? <Component {...props} /*I tried inserting handleLogout={this.handleLogout} here */ />
            : <Redirect to="/Login"/>
        )} />
    )

return (
<HashRouter basename={BASE_URL}>

    <PrivateRoute
        exact
        path={'/login'}
        component={Login}
      />
    <PrivateRoute
        exact
        path={'/Main/'}
        component={Main}
    />
</HashRouter>
)};

Unfortunately, I don't know how else I could resolve this issue.
Is it considered bad practice to pass props in a route component? If so, how else can I handle this and if not, how do I pass the prop properly?

A: Here is a more general solution to pass as many props to the component as you want:
render() {
  const PrivateRoute = ({ component: Component, data, ...rest }) => (
    <Route {...rest} render={(props) => (
        isAuthenticated === true
        ? <Component {...props} {...data} />
        : <Redirect to="/Login"/>
    )} />
  );

  return (
    <HashRouter basename={BASE_URL}>
      <PrivateRoute
        exact
        path={'/login'}
        component={Login}
        data={{
            handleLogout=this.handleLogout,
            ...
            someProp=this.prop
        }}
      />
      <PrivateRoute
        exact
        path={'/Main/'}
        component={Main}
        data={{
            handleLogout=this.handleLogout,
            ...
            someProp=this.prop
        }}
      />
    </HashRouter>
  );
}

A: Add an extra prop to your PrivateRoute HOC
render() {
  const PrivateRoute = ({ component: Component, handleLogout, ...rest }) => (
    <Route {...rest} render={(props) => (
        isAuthenticated === true
        ? <Component handleLogout={handleLogout} {...props} />
        : <Redirect to="/Login"/>
    )} />
  );

  return (
    <HashRouter basename={BASE_URL}>
      <PrivateRoute
        exact
        path={'/login'}
        component={Login}
        handleLogout={this.handleLogout}
      />
      <PrivateRoute
        exact
        path={'/Main/'}
        component={Main}
        handleLogout={this.handleLogout}
      />
    </HashRouter>
  );
}

A: Declare your PrivateRoute outside of the class :
const PrivateRoute = ({ component: Component, handleLogout, isAuthenticated, ...rest }) => (
        <Route {...rest} render={(props) => (
            isAuthenticated === true
            ? <Component {...props} handleLogout={handleLogout} />
            : <Redirect to="/Login"/>
        )} />
);

Then pass handleLogout to your PrivateRoute props :
render() {
    return (
        <HashRouter basename={BASE_URL}>

                <Route
                     exact
                     path={'/login'}
                     component={Login}
                />
                <PrivateRoute
                     exact
                     path={'/Main/'}
                     component={Main}
                     handleLogout={this.handleLogout}
                     isAuthenticated={isAuthenticated}
                />

        </HashRouter>
    )
};

You may want to declare you PrivateRoute like below in order to pass any prop to the component by spreading all props :
const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
        <Route {...rest} render={(props) => (
            isAuthenticated === true
            ? <Component {...props} {...rest} />
            : <Redirect to="/Login"/>
        )} />
);


text:
Q: Updating Claims Value in ASP.NET MVC In the account login, I added values to the claims as
 // Initialization.
 var claims = new List < Claim > ();
 try {
   // Setting
   TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
   string nme = textInfo.ToTitleCase(Name.ToLower());
   string surN = textInfo.ToTitleCase(surName.ToLower());
   claims.Add(new Claim(ClaimTypes.Name, Name));
   claims.Add(new Claim("surName", surN));
   claims.Add(new Claim("Name", nme));
   claims.Add(new Claim("Customer_Id", Customer_Id));
   claims.Add(new Claim("User_Id", UserId));
   claims.Add(new Claim("TimeZone", timeZone));
   var claimIdenties = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
   var ctx = Request.GetOwinContext();
   var authenticationManager = ctx.Authentication;
   // Sign In.
   authenticationManager.SignIn(new AuthenticationProperties() {
     IsPersistent = false
   }, claimIdenties);
   var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

   var claimsPrincipal = new ClaimsPrincipal(identity);
   Thread.CurrentPrincipal = claimsPrincipal;

 } catch (Exception ex) {
   // Info
   throw ex;

Now I want to update the Claims value in "Customer_Id" with a new value in another controller.
How do I update this claim?

A: I recently needed to achieve something similar. Add your claims to the IdentityModel where it says Add custom user claims here
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
   userIdentity.AddClaim(new Claim(ClaimTypes.Name, Name));
   userIdentity.AddClaim(new Claim("surName", surN));
   userIdentity.AddClaim(new Claim("Name", nme));
   userIdentity.AddClaim(new Claim("Customer_Id", Customer_Id));
   userIdentity.AddClaim(new Claim("User_Id", UserId));
   userIdentity.AddClaim(new Claim("TimeZone", timeZone));

Then insert this line just under the class definition at the top of the controller that you want to access the claims.
ApplicationUserManager userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));

Now to modify the claim in any of your controller actions
ApplicationUser user = await userManager.FindByNameAsync("your username");
user.Customer_Id = "your new id";
await userManager.UpdateAsync(user);


text:
Q: Python Function call stack: train_function error indices[124,9] = 8871 is not in [0, 8871)
     [[node sequential_11/embedding-layer/embedding_lookup (defined at <ipython-input-77-c69fd3d9a614>:22) ]] [Op:__inference_train_function_19388]

Errors may have originated from an input operation.
Input Source operations connected to node sequential_11/embedding-layer/embedding_lookup:
 sequential_11/embedding-layer/embedding_lookup/15542 (defined at C:\Users\OMER\anaconda3\envs\tensorflow\lib\contextlib.py:113)

Function call stack:
train_function

I'm getting the above error can you help with this?


text:
Q: Getting and observing/listening androd run-time permissions result back into application Code
 private void pickPermissions(){

   showDialog("", "You have denied some necessary permissions permanently"
                    + " We will direct you to [Settings] screen, Turn on all permissions at [Settings] -> [Permissions].",
            "Go To Settings", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    //Todo: open setting screen for permission result
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
                    //finish();
                }
            }, "No, Close App", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish();
                }
            },false);

}

please guide me how to know whether user granted all permissions or not in my app using onActivityResult()? and is there any way to get the user back(automatically) to the app from settings screen once they grant all the permissions in app settings screen, without them pressing back button?

A: Using the ContextCompat#checkSelfPermissions method you can get the state of permission grant for each permission you requested individually, if any of them aren't granted then you can take the user to the settings screen as your code does.
About checking whether the user has granted the permissions after that, you can try hooking up the permission check in the onResume method and going through the dialog flow again.


text:
Q: Compute the value of Fresnel's Integral So, my teacher wants us to compute the value of the Fresnel integral:
$$\int_0^\infty\cos(x^2)dx=\sqrt{\frac{\pi}{8}}$$
The problem is that we cannot use complex analysis to prove that and we should do that using the Euler identity:
$$\int_0^\infty\cos(x^2)dx=\frac{1}{2}\int_0^\infty e^{iw^2}dw+\frac{1}{2}\int_0^\infty e^{-iw^2}dw$$
But I have that integral of $e^{-iw^2}$ and I cannot solve that :(
I am an engineering student, so basically, I only have the "basic" calculus, just simple/double/triple integrals, some notions about series, ODE's and PDE's, but nothing as deep as in the regular Math degree, so probably there's no need to use hard stuff to figure this out.

A: You can use double integrals and change of variables. Consider the surface $e^{-y^2}\cos(x^2)$ in the positive octant, and determine the volume bounded by it. Compute the integrals both in polar coordinates and in Cartesian coordinates, and equate the values. Then you can solve for the value of your integral.
To do it in Cartesian coordinates, you have a product of the Fresnel integral, $I$ and the Gaussian integral with value $\frac{\sqrt{\pi}}{2}$. Then
$$V = \frac{\sqrt{\pi}}{2}I$$
By expressing $V$ with polar cooridinates, and using the substitution $u = p^2\cos^2(\theta)$ then the substitution $\tan(\theta)=t$, you get the integral
$$V = \frac{1}{2}\int_{0}^{\infty}\frac{t^2}{t^4+1}dt$$ Using partial fractions you can get that this is $\frac{\pi\sqrt{2}}{8}$. Then by equating your two values of $V$ you can solve for I and get $$I = \sqrt{\frac{\pi}{8}}$$ as desired.

A: Here is a (non-rigorous) proof with Fourier Transforms I discovered. It involves double integrals mostly.
Define the Fourier Cosine Transform of $f(x)$ to be:
$$\mathcal{F}_{c}(f(x))=\frac{1}{\sqrt{2 \pi}}\int_{-\infty}^{\infty} f(y) \cos(xy) \ dy.$$ One can see that $\mathcal{F}_c$ is self-adjoint by checking the definition using the inner product: $$\langle f(x), g(x) \rangle= \int_{\mathbb{R}} f(x)g(x) \ dx. $$ The definition more specifically is $$\left \langle \mathcal{F}_c(f), g \right \rangle=\left \langle f, \mathcal{F}_c (g) \right \rangle.$$ To prove it is true, expand the left hand side into a double integral, and use Fubini's theorem to get the right hand side.
We compute the inner product of $$\left \langle \mathcal{F}_c \left(\cos(x) \right), \frac{1}{\sqrt{|x|}} \right \rangle$$ in two ways.
Expanding the inner product, we get the inner product equal to $$\left \langle \sqrt{2 \pi} \delta(1-x) , \frac{1}{\sqrt{|x|}} \right \rangle= \sqrt{2 \pi},$$ from the integral property of Dirac Delta function $\delta(x).$
On the other hand, exploiting the self-adjoint property, $$\sqrt{2 \pi}=\left \langle \cos(x), \mathcal{F}_c \left( \frac{1}{\sqrt{|x|}} \right ) \right \rangle =\frac{1}{\sqrt{2\pi}} \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} \frac{\cos(x) \cos(xy)}{\sqrt{|y|}} \ dy \ dx.$$
Apply the change of variables $$x=u, y=\frac{v}{u}$$ which has Jacobian
$$\frac{\partial(x,y)}{\partial(u,v)}= \frac{1}{u}$$ to get
$$\frac{1}{\sqrt{2\pi}} \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} \frac{\cos(u) \cos(v)}{\sqrt{|uv|}} \ dv \ du.$$
Since the first half of the proof showed that this integral is $\sqrt{2 \pi},$ we see
$$2\pi= \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} \frac{\cos(u) \cos(v)}{\sqrt{|uv|}} \ dv \ du= \left (\int_{-\infty}^{\infty} \frac{\cos(u)}{\sqrt{|u|}}  \ du \right)^2.$$
So $$\sqrt{2 \pi}=\int_{-\infty}^{\infty} \frac{\cos(u)}{\sqrt{|u|}}  \ du=2 \int_{0}^{\infty} \frac{\cos(u)}{\sqrt{u}}  \ du. $$
As a result,
$$\frac{\sqrt{\pi}} {\sqrt{2}}= \int_{0}^{\infty} \frac{\cos(u)}{\sqrt{u}}  \ du.$$ Lastly, let $u=z^2, du = 2z \ dz$ to get that
$$\frac{\sqrt{\pi}} {\sqrt{2}}= \int_{0}^{\infty} 2 \cos(z^2)  \ dz,$$ so
$$\int_{0}^{\infty} \cos(z^2)  \ dz =\frac{\sqrt{\pi}}{\sqrt{8}}.$$

A: Hint: note that $$I=\int_{0}^{\infty}\cos\left(x^{2}\right)dx\stackrel{x^{2}=u}{=}\frac{1}{2}\int_{0}^{\infty}u^{-1/2}\cos\left(u\right)du
 $$ $$=\frac{1}{2\sqrt{\pi}}\int_{0}^{\infty}\cos\left(u\right)\int_{0}^{\infty}v^{-1/2}e^{-uv}dvdu
 $$ and now using the Fubini theorem we can exchange the integrals and get $$I=\frac{1}{2\sqrt{\pi}}\int_{0}^{\infty}v^{-1/2}\int_{0}^{\infty}\cos\left(u\right)e^{-uv}dudv=\textrm{Re}\left(\frac{1}{2\sqrt{\pi}}\int_{0}^{\infty}v^{-1/2}\int_{0}^{\infty}e^{u\left(i-v\right)}dudv\right)
 $$ $$\textrm{Re}\left(\frac{1}{2\sqrt{\pi}}\int_{0}^{\infty}\frac{v^{-1/2}}{v-i}dv\right)=\frac{1}{2\sqrt{\pi}}\int_{0}^{\infty}\frac{v^{1/2}}{v^{2}+1}dv\stackrel{z=\sqrt{v}}{=}\frac{1}{\sqrt{\pi}}\int_{0}^{\infty}\frac{z^{2}}{z^{4}+1}dz
 $$ and the last integral is simple to evaluate using partial fractions. Note that $$\int_{0}^{\infty}\frac{z^{2}}{z^{4}+1}dz=\frac{1}{2\sqrt{2}}\left(\int_{0}^{\infty}\frac{z}{z^{2}-\sqrt{2}z+1}-\frac{z}{z^{2}+\sqrt{2}z+1}dz\right)
 $$ $$=\frac{1}{2\sqrt{2}}\left(\lim_{a\rightarrow\infty}\frac{1}{2}\int_{0}^{a}\frac{2z-\sqrt{2}+\sqrt{2}}{z^{2}-\sqrt{2}z+1}-\frac{2z+\sqrt{2}-\sqrt{2}}{z^{2}+\sqrt{2}z+1}dz\right)
 $$ $$=\frac{1}{2\sqrt{2}}\left(\lim_{a\rightarrow\infty}\frac{1}{2}\int_{0}^{a}\frac{2z-\sqrt{2}}{z^{2}-\sqrt{2}z+1}-\frac{2z+\sqrt{2}-\sqrt{2}}{z^{2}+\sqrt{2}z+1}dz+\int_{0}^{a}\frac{\sqrt{2}}{z^{2}-\sqrt{2}z+1}dz\right)$$ and I think you can conclude by yourself from here.

A: After using Euler's, use Gaussian Integral:
$$\int_{-\infty}^{\infty}e^{-a(x+b)^2}dx=\sqrt{
\frac{\pi}{a}}$$
or Integral of a Gaussian Function:
$$\int_{-\infty}^{\infty}ae^{-(x-b)^2/2c^2}dx=\sqrt{2}a\,|c|\sqrt{\pi}$$

A: We have to prove: $$\int_{0}^{\infty} \cos(ax^2) dx =\sqrt{\frac{\pi}{8a}}$$
Now, we consider the LHS.
$$ LHS = \int_{0}^{\infty} \cos(ax^2) dx $$
Now, we make the substitution: $$x \rightarrow x^{\frac{1}{4}}$$
Therefore, we get:
$$ LHS =\frac{1}{4}\int_{0}^{\infty} x^{-\frac{3}{4}}\cos(a\sqrt{x}) dx $$
Now by Maclaurin series,
$$\cos (a\sqrt{x}) = \sum\limits_{n=0}^{\infty} \frac{(-1)^n(a\sqrt x)^{2n}}{2n!}$$
This can also be written as:
$$\cos (a\sqrt x) = \sum\limits_{n=0}^{\infty} \frac{(-x)^n(a)^{2n}n!}{2n!n!}$$
On plugging the value into LHS, we get:
$$ LHS =\frac{1}{4} \int_{0}^{\infty} x^{-\frac{3}{4}} \sum\limits_{n=0}^{\infty} \frac{(-x)^n(a)^{2n}n!}{2n!n!} dx$$
Now, by Ramanujan's Master Theorem, we get
$$ LHS = \frac{1}{4} \int_{0}^{\infty} x^{-\frac{3}{4}}\sum\limits_{n=0}^{\infty}\frac{(-x)^n(a)^{2n}n!}{2n!n!} dx = \frac{1}{4}\frac{\Gamma(\frac{1}{4})\Gamma(\frac{3}{4})}{\sqrt{a}\Gamma(\frac{1}{2})}$$
Therefore, by Euler's Reflection Formula, we get
$$\int_{0}^{\infty}\cos(ax^2) dx =\sqrt{\frac{\pi}{8a}}$$

A: $$
\begin{aligned}
\int_{\infty}^{\infty}\left[\cos \left(t^2\right)-i \sin \left(t^2\right)\right] d t
= & \int_{-\infty}^{\infty} e^{-t^2 i} d t \\
= & \int_{-\infty}^{\infty} e^{-\left[\frac{(1+i) t}{\sqrt{2}}\right]^2} d t \\
= & \frac{\sqrt{2}}{1+i} \sqrt{\pi} \\
= & \sqrt{\frac{\pi}{2}}(1-i)
\end{aligned}
$$
By comparing the real parts on both sides, we get
$$
\int_{-\infty}^{\infty} \cos \left(t^2\right) d t=\sqrt{\frac{\pi}{2}}
$$
Hence $$
\int_0^{\infty} \cos \left(t^2\right) d t=\frac{1}{2} \sqrt{\frac{\pi}{2}}
$$


text:
Q: in-app review is not opening when user click on button in-app review is not opening when user click on button. I am using xamarin.forms android and using ref link
i am using same code in github. I think i might be missing some thing
i downloaded nuget StoreReviewPlugin (version 2.0 latest)  to my shared & android project
  private async void OnRating_Clicked(object sender, EventArgs e)
        {
              //i also tried true & false
                await CrossStoreReview.Current.RequestReview(false);
}

in my app, i dont have login page. could this be a issue?

A: You need to install PlayCore nuget package in your Android project to view the review dialog.
https://www.nuget.org/packages/PlayCore/?WT.mc_id=appreviews-blog-jamont
Also your app must be in the Testing phase and downloaded from the play store for it to work.
Here is a complete example:
https://www.youtube.com/watch?v=zE9J8Trwid4


text:
Q: How can I fix this CUDA / Darknet installation error? I'm trying to install darknet on Google Collab, and in doing so I ran the following code / commands:
!git clone https://github.com/AlexeyAB/darknet
!apt-get update
!apt-get upgrade
!apt-get install build-essential
!apt-get install cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
!apt-get install libavcodec-dev libavformat-dev libswscale-d
!apt-get install libopencv-dev
%cd darknet
!ls
!sed -i 's/OPENCV=0/OPENCV=1/g' Makefile
!sed -i 's/GPU=0/GPU=1/g' Makefile
!ls
%cd ../
!ls
!apt install g++-5
!apt install gcc-5
!apt update
!apt upgrade
import tensorflow as tf
device_name = tf.test.gpu_device_name()
!/usr/local/cuda/bin/nvcc --version
%cd darknet
!wget https://pjreddie.com/media/files/yolov3.weights
!make
!./darknet detect cfg/yolov3.cfg yolov3.weights data/person.jpg
def imShow(path):
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
image = cv2.imread(path)
height, width = image.shape[:2]
resized_image = cv2.resize(image,(3width, 3height), interpolation = cv2.INTER_CUBIC)
fig = plt.gcf()
fig.set_size_inches(18, 10)
plt.axis("off")
#plt.rcParams['figure.figsize'] = [10, 5]
plt.imshow(cv2.cvtColor(resized_image, cv2.COLOR_BGR2RGB))
plt.show()
def upload():
from google.colab import files
uploaded = files.upload()
for name, data in uploaded.items():
with open(name, 'wb') as f:
f.write(data)
print ('saved file', name)
def download(path):
from google.colab import files
files.download(path)
imShow('/content/drive/My Drive/face/img/bv.jpg')

From that string of commands, it returns the following error:
CUDA status Error: file: ./src/dark_cuda.c : () : line: 239 : build time: Jun 16 2020 - 20:18:49

 CUDA Error: invalid argument
CUDA Error: invalid argument: File exists
darknet: ./src/utils.c:326: error: Assertion `0' failed.

I've tried installing this before, and it worked previously. Apparently, there may have been a recent update which caused this bug, but I'm not sure.


text:
Q: If close date "Month" is Jan, then field equal oppty amount Trying to create a formula field that will populate the opportunity dollar value if the month in the close date is January. I tried a few things but its not working. I tried putting "January" as well.
IF(  CloseDate = MONTH(01),  Amount * 0.5 , 0)

Error:

Error: Incorrect parameter type for function 'MONTH()'. Expected Date,
  received Number

A: The MONTH function needs to go around your date field, like this
IF( MONTH(CloseDate) = 1, Amount * 0.5 , 0)


text:
Q: NDK build error (error: linker command failed with exit code 1 (use -v to see invocation)) Application.mk
APP_STL := gnustl_static
APP_ABI := all

Android.mk
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE := libz
LOCAL_SRC_FILES := ../prebuild/libz.a
LOCAL_EXPORT_C_INCLUDES := ../prebuild/include/
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libssl
LOCAL_SRC_FILES := ../prebuild/libssl.a
LOCAL_EXPORT_C_INCLUDES := ../prebuild/include
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libcrypto
LOCAL_SRC_FILES := ../prebuild/libcrypto.a
LOCAL_EXPORT_C_INCLUDES := ../prebuild/include
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libjson-c
LOCAL_SRC_FILES := ../prebuild/libjson-c.a
LOCAL_EXPORT_C_INCLUDES := ../prebuild/include
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libcurl
LOCAL_SRC_FILES := ../prebuild/include/libcurlall/$(TARGET_ARCH_ABI)/libcurl.a
LOCAL_EXPORT_C_INCLUDES := ../prebuild/include
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := curl-ndk
LOCAL_SRC_FILES := ../cpp/curl-http.cpp
LOCAL_STATIC_LIBRARIES := libcurl libssl libcrypto libz libjson-c
LOCAL_LDLIBS := -lz -llog -ljnigraphics
include $(BUILD_SHARED_LIBRARY)

clean project and I'm trying to cross compile NDK then show given below error:
/Volumes/Work/Android/Projects/app/src/main/jni/../prebuild/libz.a: error adding symbols: File in wrong format
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [/Volumes/Work/Android/Projects/app/src/main/obj/local/arm64-v8a/libcurl-ndk.so] Error 1

Its working on 32 bits fine but 64 bit its show error
Thanks in advance

A: You're using one prebuilt for all ABIs. You need one prebuilt for each ABI you target. The typical way to write a prebuilt module is like this:
include $(CLEAR_VARS)
LOCAL_MODULE := libz
LOCAL_SRC_FILES := ../prebuild/$(TARGET_ARCH_ABI)/libz.a
LOCAL_EXPORT_C_INCLUDES := ../prebuild/include/
include $(PREBUILT_STATIC_LIBRARY)

Then you can have prebuild/armeabi-v7a/libz.a, prebuild/arm64-v8a/libz.a, etc. Disable ABIs you don't want to build for (or don't have prebuilts for) using APP_ABI in your Application.mk.


text:
Q: Removing access privileges to backup while maintaining current setup I have a giant directory, and I am dealing with a backup.
I would like to store this backup in as safe of a way as possible.
One of the ways of doing that is removing rwx privileges through chmod.
Best would be if I could somehow lock the folder to anyone other than root.
I can do that by running chmod -R, but that effectively removes whatever access settings there were on all files beforehand. I don't want that for we may want to use this backup one day and then it would be good not to have changed whatever mod settings we have set within the folder.
So how can I best remove access privileges for all but root without permanently loosing whatever access setting was there before, within the folder?
Is there some 'lock folder' mechanism?

A: You could set the permissions on the directory where the backup is stored to 0700, owned by root:root. This will prevent anyone but root from accessing the files through normal means, and is trivially reversible when you restore the backup.
Alternatively, you can introduce a new directory level just above the root of the backup target location, which can be set to those same permissions. That way you won't touch any permissions on the backup at all.


text:
Q: View Dask Task Graph I am using the Dask submit and gather paradigm to do something like:
data_future = client.scatter(data, broadcast=True)

futures = []
for i in range(10):
    futures.append(dask.submit(some_func, i, data_future))

results = dask_client.gather(futures)

Is there some way to view/visualize the DAG in this paradigm after the computation has completed?
The documentation appears to be well suited for the Dask delayed paradigm. In case it matters, this is for a distributed cluster.

A: As of 2019-06-21, not really, no.
You can view it live on the dashboard's /graph page but there isn't any convenient code to render a static image of the graph today.  I would say that this is in scope, but not something that current maintainers are thinking very hard about today.


text:
Q: Isomorphic function fields of projective curves, bijection of points. Suppose curves $C$, $D \in \mathbb{CP}^2$ are nonsingular. If their function fields are isomorphic, i.e. $K_C \cong K_D$, then do we necessarily have a bijection of points on $C$ and $D$? Can we do stronger and say something like $C$ and $D$ are necessarily isomorphic as ringed spaces? How can one intuitively arise at an answer to this question?
EDIT: It would be nice if I got an answer that did not talk about birational equivalence or manifolds...

A: It can be shown that two algebraic varieties are birationally equivalent if and only if their function fields are isomorphic.
In particular, two non-singular projective curves are birationally equivalent if and only they are isomorphic. You can prove this by observing that by Serre's GAGA a non-singular projective complex curve is just a (holomorphic) compact connected complex manifold $C$ of dimension $1$. In particular, by the maximum principle you can uniquely extend a morphism defined on an open, dense subset $U$ of $C$ to the whole of $C$.


text:
Q: Mongo-Hadoop streaming I'm new to Mongodb and Hadoop. I'm trying to access mongodb data as input to hadoop mapreduce job. i don't quite know how to specify which collection to use to get data from. this is what i tried:
hadoop jar/usr/local/Cellar/hadoop/2.6.0/libexec/share/hadoop/tools/lib/hadoop-streaming-2.6.0.jar
-input user/test/input/
-output user/test/output/
-inputformat com.mongodb.hadoop.mapred.MongoInputFormat
-outputformat com.mongodb.hadoop.mapred.MongoOutputFormat
-io mongodb
-D mongo.input.uri=mongodb://localhost/my_dbs.collectionName
-D stream.io.identifier.resolver.class=com.mongodb.hadoop.streaming.io.MongoIdentifierResolver
-mapper /Users/wordcountMapper.py
-reducer /Users/wordcountReducer.py
-libjars /usr/local/Cellar/hadoop/2.6.0/libexec/share/hadoop/tools/lib/mongo-hadoop-streaming.jar

But i get the following error:
ERROR streaming.StreamJob: Unrecognized option: -D
Usage: $HADOOP_PREFIX/bin/hadoop jar hadoop-streaming.jar [options]

and when i tried this, i get another error:
 hadoop jar /usr/local/Cellar/hadoop/2.6.0/libexec/share/hadoop/tools/lib/hadoop-streaming-2.6.0.jar
-input user/input/
-output user/test/output
-inputformat com.mongodb.hadoop.mapred.MongoInputFormat
-outputformat com.mongodb.hadoop.mapred.MongoOutputFormat
-io mongodb -jobconf mongo.input.uri=mongodb://localhost/my_dbs.collectionName
-jobconf stream.io.identifier.resolver.class=com.mongodb.hadoop.streaming.io.MongoIdentifierResolver
-mapper /Users/wordcountMapper.py
-reducer /Users/wordcountReducer.py
-libjars /usr/local/Cellar/hadoop/2.6.0/libexec/share/hadoop/tools/lib/mongo-hadoop-streaming.jar

`ERROR streaming.StreamJob: Unrecognized option: -libjars
Usage: $HADOOP_PREFIX/bin/hadoop jar hadoop-streaming.jar [options]`

Please help.

A: Please check this link for better idea on how to connect MongoDB to Hadoop.
Edit:
or,
Instead of giving jar with -libjars option, you can directly write it in your driver program as:
args.add("-libjars");
args.add("/some/path/to/your/jar");


text:
Q: How to define this hasManyThrough relation? I have the following models. Event belongs to a Casefile. Casefile and User are many-to-many.
class Casefile extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class)->withTimestamps();
    }

    public function events()
    {
        return $this->morphMany('App\Event', 'casefile');
    }
}

class User extends Authenticatable
{
    public function casefiles()
    {
        return $this->belongsToMany(Casefile::class)->withTimestamps();
    }
}

class Event extends Model
{
    public function casefile()
    {
        return $this->belongsTo('App\Casefile');
    }

    public function users()
    {
        return $this->hasManyThrough('App\User', 'App\Casefile');
    }
}

When I try to:
App\Event::find(526)->users()->get();

It gives:

Illuminate/Database/QueryException with message 'SQLSTATE[42S22]:
  Column not found: 1054 Unknown column 'casefiles.event_id' in 'field
  list' (SQL: select users.*, casefiles.event_id from users
  inner join casefiles on casefiles.id = users.casefile_id
  where casefiles.event_id = 526)'

How can I define the "Event has many Users" relation through Casefile?

A: It's not possible to use HasManyThrough here without a pivot model for the casefile_user table.
You can define a BelongsToMany relationship instead:
public function users()
{
    return $this->belongsToMany('App\User', 'casefile_user', 'casefile_id', null, 'casefile_id');
}

A: If you not followed laravel naming convention for column name. Then you can specify your column name like this
public function users()
    {
        return $this->hasManyThrough(
            'App\User',
            'App\Casefile',
            'event_id', // Foreign key on casefiles table...
            'user_id', // Foreign key on users table...
        );
    }

For more Laravel HasManyThrough Relationship


text:
Q: partial search JSON How to partial search the JSON to match the JSON value?
Filter is matching full value of the city name and search is case-sensitive
Example: if I type p in text box it should match all city value with p as array
output should be as

[{"CM_CITY_CODE":"515134", "CM_CITY_NAME":"Puttaparthi(AP)", "CM_HUB":"Thirupati", "CM_STATE":"Andhra Pradesh", "CM_DT_PICKUP_CITY":"0", "CM_DROP_CITY":"1", "CM_ADDEDBY":"", "CM_ADDED_DATE":"", "CM_EDITEDBY":"", "CM_EDITED_DATE":""},{"CM_CITY_CODE":"517408", "CM_CITY_NAME":"Palamaner", "CM_HUB":"Vellore", "CM_STATE":"Andhra Pradesh", "CM_DT_PICKUP_CITY":"0", "CM_DROP_CITY":"1", "CM_ADDEDBY":"", "CM_ADDED_DATE":"", "CM_EDITEDBY":"", "CM_EDITED_DATE":""}]

Here is what I tried

(function () {

    var cityjson = [{"CM_CITY_CODE":"04262", "CM_CITY_NAME":"Gudalur", "CM_HUB":"Coimbatore", "CM_STATE":"", "CM_DT_PICKUP_CITY":"1", "CM_DROP_CITY":"1", "CM_ADDEDBY":"VigneshkumarP", "CM_ADDED_DATE":"2020-12-17 13:18:23", "CM_EDITEDBY":"", "CM_EDITED_DATE":""},
    {"CM_CITY_CODE":"505001", "CM_CITY_NAME":"Hyderabad", "CM_HUB":"Hyderabad", "CM_STATE":"", "CM_DT_PICKUP_CITY":"0", "CM_DROP_CITY":"1", "CM_ADDEDBY":"", "CM_ADDED_DATE":"", "CM_EDITEDBY":"", "CM_EDITED_DATE":""},
    {"CM_CITY_CODE":"506001", "CM_CITY_NAME":"Warangal", "CM_HUB":"Hyderabad", "CM_STATE":"Telangana", "CM_DT_PICKUP_CITY":"0", "CM_DROP_CITY":"1", "CM_ADDEDBY":"", "CM_ADDED_DATE":"", "CM_EDITEDBY":"", "CM_EDITED_DATE":""},
    {"CM_CITY_CODE":"515134", "CM_CITY_NAME":"Puttaparthi(AP)", "CM_HUB":"Thirupati", "CM_STATE":"Andhra Pradesh", "CM_DT_PICKUP_CITY":"0", "CM_DROP_CITY":"1", "CM_ADDEDBY":"", "CM_ADDED_DATE":"", "CM_EDITEDBY":"", "CM_EDITED_DATE":""},
    {"CM_CITY_CODE":"516001", "CM_CITY_NAME":"Kadappa", "CM_HUB":"Hyderabad", "CM_STATE":"Tamil Nadu", "CM_DT_PICKUP_CITY":"0", "CM_DROP_CITY":"1", "CM_ADDEDBY":"", "CM_ADDED_DATE":"", "CM_EDITEDBY":"Vivek", "CM_EDITED_DATE":"2020-11-03 10:23:26"},
    {"CM_CITY_CODE":"517001", "CM_CITY_NAME":"Chitoor", "CM_HUB":"Vellore", "CM_STATE":"Andhra Pradesh", "CM_DT_PICKUP_CITY":"1", "CM_DROP_CITY":"1", "CM_ADDEDBY":"", "CM_ADDED_DATE":"", "CM_EDITEDBY":"", "CM_EDITED_DATE":""},
    {"CM_CITY_CODE":"517325", "CM_CITY_NAME":"Madanapalli", "CM_HUB":"Thirupati", "CM_STATE":"Tamil Nadu", "CM_DT_PICKUP_CITY":"0", "CM_DROP_CITY":"0", "CM_ADDEDBY":"", "CM_ADDED_DATE":"", "CM_EDITEDBY":"", "CM_EDITED_DATE":""},
    {"CM_CITY_CODE":"517408", "CM_CITY_NAME":"Palamaner", "CM_HUB":"Vellore", "CM_STATE":"Andhra Pradesh", "CM_DT_PICKUP_CITY":"0", "CM_DROP_CITY":"1", "CM_ADDEDBY":"", "CM_ADDED_DATE":"", "CM_EDITEDBY":"", "CM_EDITED_DATE":""}]

    var getData = function (request, response) {
        let x = cityjson.filter(function(item){
            return item.CM_CITY_NAME == request.term;
        })
        if(x.length>0)
        {
            console.log(x)
            response($.map(x, function (item) {
                return {
                    label: x.CM_CITY_NAME,
                    data: item
                };
            }));
        }
        else{
        alert('else')

        }

    };

    //on select of from dropdown
    var selectTo = function (event, ui) {
        return false
    }
    //to address autocomplete
    $("#selector").autocomplete({
        source: getData,
        select: selectTo,
        minLength: 2
    });

  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="selector">

A: I had to add jQuery UI to get the autocomplete
You had a few issues
return item.CM_CITY_NAME.indexOf(request.term) !=-1

If you want this case INsensitive, change
return item.CM_CITY_NAME.toLowerCase().indexOf(request.term.toLowerCase()) !=-1

The above will return any string found in the city.
If you want the typed term to match the cityname from the beginning you need
return item.CM_CITY_NAME.toLowerCase().indexOf(request.term.toLowerCase()) ===0

If you do not need IE11 compatibility, you can change the above to
return item.CM_CITY_NAME.toLowerCase().startsWith(request.term.toLowerCase())

Here is the other change you need
if (x.length > 0) {
      const resp = $.map(x, function(item) {
        return {
          label: item.CM_CITY_NAME, // item., not x.
          data: item
        };
      })

      response(resp);
    }

$(function() {

  var cityjson = [{"CM_CITY_CODE":"04262","CM_CITY_NAME":"Gudalur","CM_HUB":"Coimbatore","CM_STATE":"","CM_DT_PICKUP_CITY":"1","CM_DROP_CITY":"1","CM_ADDEDBY":"VigneshkumarP","CM_ADDED_DATE":"2020-12-1713:18:23","CM_EDITEDBY":"","CM_EDITED_DATE":""},{"CM_CITY_CODE":"505001","CM_CITY_NAME":"Hyderabad","CM_HUB":"Hyderabad","CM_STATE":"","CM_DT_PICKUP_CITY":"0","CM_DROP_CITY":"1","CM_ADDEDBY":"","CM_ADDED_DATE":"","CM_EDITEDBY":"","CM_EDITED_DATE":""},{"CM_CITY_CODE":"506001","CM_CITY_NAME":"Warangal","CM_HUB":"Hyderabad","CM_STATE":"Telangana","CM_DT_PICKUP_CITY":"0","CM_DROP_CITY":"1","CM_ADDEDBY":"","CM_ADDED_DATE":"","CM_EDITEDBY":"","CM_EDITED_DATE":""},{"CM_CITY_CODE":"515134","CM_CITY_NAME":"Puttaparthi(AP)","CM_HUB":"Thirupati","CM_STATE":"AndhraPradesh","CM_DT_PICKUP_CITY":"0","CM_DROP_CITY":"1","CM_ADDEDBY":"","CM_ADDED_DATE":"","CM_EDITEDBY":"","CM_EDITED_DATE":""},{"CM_CITY_CODE":"516001","CM_CITY_NAME":"Kadappa","CM_HUB":"Hyderabad","CM_STATE":"TamilNadu","CM_DT_PICKUP_CITY":"0","CM_DROP_CITY":"1","CM_ADDEDBY":"","CM_ADDED_DATE":"","CM_EDITEDBY":"Vivek","CM_EDITED_DATE":"2020-11-0310:23:26"},{"CM_CITY_CODE":"517001","CM_CITY_NAME":"Chitoor","CM_HUB":"Vellore","CM_STATE":"AndhraPradesh","CM_DT_PICKUP_CITY":"1","CM_DROP_CITY":"1","CM_ADDEDBY":"","CM_ADDED_DATE":"","CM_EDITEDBY":"","CM_EDITED_DATE":""},{"CM_CITY_CODE":"517325","CM_CITY_NAME":"Madanapalli","CM_HUB":"Thirupati","CM_STATE":"TamilNadu","CM_DT_PICKUP_CITY":"0","CM_DROP_CITY":"0","CM_ADDEDBY":"","CM_ADDED_DATE":"","CM_EDITEDBY":"","CM_EDITED_DATE":""},{"CM_CITY_CODE":"517408","CM_CITY_NAME":"Palamaner","CM_HUB":"Vellore","CM_STATE":"AndhraPradesh","CM_DT_PICKUP_CITY":"0","CM_DROP_CITY":"1","CM_ADDEDBY":"","CM_ADDED_DATE":"","CM_EDITEDBY":"","CM_EDITED_DATE":""}];

  var getData = function(request, response) {
  console.log("term",request.term)
    let x = cityjson.filter(function(item) {
      return item.CM_CITY_NAME.toLowerCase().startsWith(request.term.toLowerCase())
    })
    if (x.length > 0) {
      const resp = $.map(x, function(item) {
        return {
          label: item.CM_CITY_NAME,
          data: item
        };
      })
      console.log(resp)
      response(resp);
    } else {
      console.log('else')

    }

  };

  //on select of from dropdown
  var selectTo = function(event, ui) {
    return false
  }
  //to address autocomplete
  $("#selector").autocomplete({
    source: getData,
    select: selectTo,
    minLength: 2
  });

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha512-uto9mlQzrs59VwILcLiRYeLKPPbS/bT71da/OEBYEwcdNUk8jYIy+D176RYoop1Da+f9mvkYrmj5MCLZWEtQuA==" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" integrity="sha512-aOG0c6nPNzGk+5zjwyJaoRUgCdOrfSDhmMID2u4+OIslr0GjpLKo7Xm0Ao3xmpM4T8AmIouRkqwj1nrdVsLKEQ==" crossorigin="anonymous" />
<input type="text" id="selector">

A: you can use startsWith() method which determines whether a string begins with the characters of a specified string.
cityjson.filter(function(item){ return item.CM_CITY_NAME.toLowerCase().startsWith(request.term.toLowerCase())})


text:
Q: Unhandled Exception: Converting object to an encodable object failed: Photography my cloud_firestore looks like this:

all_images:{imageUrl:[]}, couplePhoto:String, female:String,
  image_url:String, info:String, male:String

my model class:
import 'package:json_annotation/json_annotation.dart';
part 'Model.g.dart';

@JsonSerializable()
class Photography {
  final List<AllImages> all_images;
  final String couplePhoto;
  final String female;
  final String image_url;
  final String info;
  final String male;

  Photography(this.all_images, this.couplePhoto, this.female, this.image_url,
      this.info, this.male);

  factory Photography.fromJson(Map<String, dynamic> json) =>
      _$PhotographyFromJson(json);

  Map<String, dynamic> toJson() => _$PhotographyToJson(this);
}

@JsonSerializable()
class AllImages {
  final List<String> imageUrl;

  AllImages(this.imageUrl);

  factory AllImages.fromJson(Map<String, dynamic> json) =>
      _$AllImagesFromJson(json);

  Map<String, dynamic> toJson() => _$AllImagesToJson(this);
}

Currently, I haven't adminPanel to data insert. so, now I need to read data.
When running this database, the error is coming in here.
    Future<Photography> postsMap = Firestore.instance
        .collection('photography')
        .document("0yUc5QBGHNNq6WK9CyyF")
        .setData(jsonDecode(jsonEncode(Photography)));

A: At this line:
.setData(jsonDecode(jsonEncode(Photography)));

You are referencing the Type object for the Photograph class, instead you need to pass an instance (so you would need to call the constructor with the required values, and pass the result of that).
.setData(jsonDecode(jsonEncode(Photography(<pass-in-constructor-args-here>))));

A: if you are using json_serialization library be careful. sometimes the generated method in your case "_$AllImagesToJson()" not working properly. look inside this. I know that json_serialization library is not working properly in terms of generic objects


text:
Q: Has Tolkien ever commented on the relative leadership skills of prominent Middle-earth figures? If we look at some of the prominent figures in Middle-earth at the time of the War of the Ring:

*

*Théoden

*Denethor

*Aragorn

*Elrond

*Gandalf

All of these are 'leaders' of one form or another, but some are more effective than others. Of course there are various aspects of leadership: charisma, inspiring others to follow you, decisiveness, impartiality, and so on. How many of these characters could be described as alpha males?
What has Tolkien said about the leadership skills of these characters?
Is there any sort of commentary in his notes or letters, or anything to suggest clearly how he rated them all as leaders?

A: The closest thing to 'Gorilla vs. Shark' 'Elrond vs. Aragorn' in Tolkien's writings is the answer to the question 'Who would have the ability to beat Sauron with the One Ring?'
Here I rely on Stan Brown's excellent FAQ of the Rings, and the answer is Gandalf the White, with Aragorn coming up second. (Of course, any Ring-aided victory would have been a defeat for Middle-earth). All the relevant speculation is contained within Letter #246.
Yet the question tends to characterize Middle-earth's leaders by the moniker 'alpha males'.
Tolkien's leaders are anything but alpha males. They don't rule for greed, nor preferential access to females. They do what is right.
The alpha male stereotype is what some of Tolkien's villains conform to:

*

*Ar-Pharazôn (usurped the throne, wedded his cousin against her will)

*Celegorm (became a de facto ruler at Nargothrond, intended to marry Lúthien against her will)

*Brodda and Lorgan the Easterlings

In short, Tolkien's rightful monarchs are patently different from the politicians of our age (JFK, Berlusconi, Putin, Bill Clinton etc.)


text:
Q: Why doesn't SC QUERY show all services? Are some services hidden? I'm trying to find out why a service is in STOP_PENDING state, but the service seems to be hidden.
It doesn't show up in a general sc query, nor in services.msc or in Powershell's Get-Service.
Here's what happened:
I used findstr to search for a string in a set of files, and it found it in a binary file that contained lots of ASCII BELL characters. So my console was issuing an endless string of beeps. So I opened another console to stop the beeping:
net stop beep

No problem, beeping stopped. But when I issue a net start beep, I always get the error:

The service is starting or stopping.  Please try again later.

I can see the service's state if I do:
sc query beep

but a general sc query doesn't show the service.
QUESTIONS:
Why isn't the beep service listed? Why doesn't it show up in sc query, services.msc or Get-Services? Are there such things as hidden services?
Also, how can I get this service to restart? This service always reacts this way. If I stop it, it gets stuck in STOP_PENDING state and stays there until I reboot.

A: sc can control both regular services and drivers (which in low-level terminology are both "services" but drivers have a service type of KERNEL_DRIVER). beep is a driver. By default, sc lists only non-driver services though. (Also, it only lists entries in state "active" by default.)
This is apparent from the output of sc /?:
USAGE:
  sc <server> [command] [service name] <option1> <option2>...

[...]

QUERY and QUERYEX OPTIONS :
   If the query command is followed by a service name, the status
   for that service is returned.  Further options do not apply in
   this case.  If the query command is followed by nothing or one of
   the options listed below, the services are enumerated.
    type=    Type of services to enumerate (driver, service, all)
             (default = service)
    state=   State of services to enumerate (inactive, all)
             (default = active)

[...]

SYNTAX EXAMPLES
sc query                - Enumerates status for active services & drivers
sc query messenger      - Displays status for the messenger service
sc queryex messenger    - Displays extended status for the messenger service
sc query type= driver   - Enumerates only active drivers
sc query type= service  - Enumerates only Win32 services
sc query state= all     - Enumerates all services & drivers

[...]

As you can see here, it says the type= argument allows to select either service, driver or all, with a default of service.1 (Similarly, the state= argument has a default of active.)
So, to list all active services/drivers, you can use sc query type= all. To list also inactive ones, you can use sc query type= all state= all.
As to how to restart the beep driver: As far as I know, there is no way. beep is not really designed to be stopped. It is half-working though (and it is set as STOPPABLE), so it at least does stop the beeping and it doesn't crash the system when you stop it (like some other drivers will unfortunately do), but it neither cleans up its state correctly and it gets stuck in STOP_PENDING for all times because it never tells the service manager that it is now STOPPED. The only way (that I know of) to get the beep back is rebooting the computer.
By the way, if you are looking for a more powerful GUI for service management (including driver-type services), take a look at Process Hacker. It has a tab "Services" which not only allows you to list and control all the services but also to edit them in ways that services.msc won't let you do (for example changing their path). But bear in mind, with great power comes great responsibility. You can wreck your system with it too.

Footnotes:
1. And here we have to understand that sc attempts to speak "usertalk" and calls services of type KERNEL_DRIVER "driver" instead of "service", even though they are (from a low-level perspective) technically both services. This is similar to how both creating and opening a file is done using CreateFile because it creates a file handle, yet every UI in the world will not consider opening an existing file as "creation" of anything. These sort of distinctions of perspective unfortunately often make terminology very confusing because the same term can mean either something entirely different or like here partly the same thing but partly not, all depending on whether you look at it from the perspective of the kernel, the user-mode API, or the Windows Shell (to name a few).


text:
Q: Multiple Series Timeline with HighCharts Looking to see if this chart is possible with HighCharts before jumping aboard any JS charting library - all advice very much appreciated, such as suggesting alternatives which will definitively support what I need.

*

*X-axis is a simple timeline.

*Y-axis will have various categories (labels left and right sides)

*For each category I will have zero to many events with start and end dates

*I would like to have a fine horizontal line representing each
category (display only, no data)

*On each line, I would like to display a thicker bar representing
events, from start to end date.

Doesn't sound too complicated, but I haven't seen an example of this type of graph anywhere on Tinterweb.
Thanks in advance,
Monty

A: *

*X-axis is a simple timeline.
The X-axis being a datetime works just fine.  Depending on the span of time for the displayed chart it will automatically format the labels.  You can modify the default formatting using dateTimeLabelFormats and tickInterval.  The datetime can be controlled down to the millisecond.

*

*Y-axis will have various categories (labels left and right sides)
You can have as many Y-axis as you need.  You can place them on either or both sides of the chart.  Here is an example of a chart with two Y-axis.  You can also have as many series as you need on the chart.  You can tie each of them to a specific Y-axis and give them all different types if you want (ex spline, bar, pie and etc).

*

*For each category I will have zero to many events with start and end dates
If you do have a data point that does not have any data then you can specify it as null.  Then continue on with the data points that have data.

*

*I would like to have a fine horizontal line representing each category (display only, no data)

*On each line, I would like to display a thicker bar representing events, from start to end date.
I think you are referring to grid lines here.  If so, then you can change the  gridLineWidth.  You can also change the color and if needed you can add minor grid lines and manipulate them as you see fit.  This can be done on either axis or both.

*

*Additional Notes
You can also send additional data to a point for displaying in the tooltip. As demonstrated here.  In the example the locked, unlocked, and potential are user defined variables.  You can draw objects in a chart.  You can make your charts zoomable.  You can drill down into a chart to show additional data based on data element.  And the list goes on.   There is a lot you can do.  If all else fails you can add your own custom events and function to control anything else.
If I have a question on anything I search through the reference or demos.  if I still can't figure out how to do something I will ask here and get an answer that works for me.