text:
Q: web based screen recording is there any way to have access to the client's system screen through the browser? i'm implementing an e-learning web application i need to implement screen-casting right through my application so i want to find a way of recording screen through the web browser exactly like Screenr service, i searched but found no suitable api, there was just a chrome extetntion and html2canvas that didn't exactly match my needs, they were able to capture browser tab! not the whole system screen. i know that Screenr is doing it through Java but i'm looking for a better and dependency free way of doing it, do you have any suggestion for me? thanks.

A: Ok after some search and questions, i ended up with this answer:
to implement this, the best way is to use a java applet that get the user screen, of course it needs java installed and that's a disadvantage but this is the only way for now, i hope in the future some api for this is implemented in html just like filesystem api or the api that is used to access the user camera.


text:
Q: Regex - All before an underscore, and all between second underscore and the last period? How do I get everything before the first underscore, and everything between the last underscore and the period in the file extension?
So far, I have everything before the first underscore, not sure what to do after that.
.+?(?=_)

EXAMPLES:

*

*111111_SMITH, JIM_END TLD 6-01-20 THR LEWISHS.pdf

*222222_JONES, MIKE_G URS TO 7.25 2-28-19 SA COOPSHS.pdf

DESIRED RESULTS:

*

*111111_END TLD 6-01-20 THR LEWISHS

*222222_G URS TO 7.25 2-28-19 SA COOPSHS

A: You could use 2 capture groups:
^([^_\n]+_).*\b([^\s_]*_.*)(?=\.)

*

*^ Start of string

*([^_\n]+_) Capture group 1, match any char except _ or a newline followed by matching a _

*.*\b Match the rest of the line and match a word boundary

*([^\s_]*_.*) Capture group 2, optionally match any char except _ or a whitespace char, then match _ and the rest of the line

*(?=\.) Positive lookahead, assert a . to the right

See a regex demo.
Another option could be using a non greedy version to get to the first _ and make sure that there are no following underscores and then match the last dot:
^([^_\n]+_).*?(\S*_[^_\n]+)\.[^.\n]+$

See another regex demo.

A: You can match the following regular expression that contains no capture groups.
^[^_]*|(?!.*_).*(?=\.)

Demo
This expression can be broken down as follows.
^        # match the beginning of the string
[^_]*    # match zero or more characters other than an underscore
|        # or
(?!      # begin negative lookahead
  .*_    # match zero or more characters followed by an underscore
)        # end negative lookahead
.*       # match zero or more characters greedily
(?=      # begin positive lookahead
  \.     # match a period
)        # end positive lookahead

.*_ means to match zero or more characters greedily, followed by an underscore. To match greedily (the default) means to match as many characters as possible. Here that includes all underscores (if there are any) before the last one. Similarly, .* followed by (?=\.) means to match zero or more characters, possibly including periods, up to the last period.
Had I written .*?_ (incorrectly) it would match zero or more characters lazily, followed by an underscore. That means it would match as few characters as possible before matching an underscore; that is, it would match zero or more characters up to, but not including, the first underscore.

If instead of capturing the two parts of the string of interest you wanted to remove the two parts of the string you don't want (as suggested by the desired results of your example), you could substitute matches of the following regular expression with empty strings.
_.*_|\.[^.]*$

Demo
This regular expression reads, "Match an underscore followed by zero of more characters followed by an underscore, or match a period followed by zero or more characters that are not periods, followed by the end of the string".

A: Looks like you're very close. You could eliminate the names between the underscores by finding this
(_.+?_)
and replacing the returned value with a single underscore.
I am assuming that you did not intend your second result to include the name MIKE.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Label color, or bar color, by row for Google Timeline Chart I am using the Google Timeline Chart API, documented here:
https://developers.google.com/chart/interactive/docs/gallery/timeline
Here is an example of what I have:

What I want to do is use two colors, some rows will be color A and some rows will be color B, depending on a simple boolean.
However, I don't see a way to do this given the configuration options for this API.
To be specific if a file exited with code > 0, I want to color the row yellow, if it exited with code 0, I want the row to be green. I don't care if it's the bar color or the label color, just something.

A: I didn't expect this to work, but it did:

To achieve this, you use the API like so:
    var options = {
      colors: colors,
    };

    chart.draw(dataTable, options);

where colors is a one-dimensional array of string, that represents the color to be used for each row.


text:
Q: I want to add Html.DropDownListFor dynamically using Javascript View MVC5 Most of the questions asked regarding this are just to append a plain dropdown Html. But I was trying to dynamically adds (append) the Html.DropDownListFor helper as I need to get the list of selection from the server. The objective for this code is to submit list of Judge.JudgeBoothMark to the controller. Here is my DropDownListFor Html helper:

    @Html.LabelFor(b => b.Booths)
    @Html.DropDownListFor(m => m.Judge.JudgeBoothMark[0].BoothId, new SelectList(Model.Booths, "Id", "BoothId"), "--Select Booth--", new { @class = "form-control" })
    @Html.ValidationMessageFor(b => b.Judge.JudgeBoothMark)

I used this button to add the dropdownlistfor:
<button type="button" id="addBooth">Add Booth</button>

I want to add this kind of dropdownlistfor Html helper through javascript dynamically as the number 0 from m.Judge.JudgeBoothMark[0] count will add up as I click on the button. Here is my Javascript code:
@section scripts{
  }

Notice that the dropdownlistfor that I am using here has index 1. I can run this code fine, but the index number will be only 1, unchanged. The data that will be submitted/saved to my controller is the first and second added dropdownlist [0,1].
I cannot increase the number as I don't know how to do it. I've tried so many ways (eg; tried using the count variable, but cannot find proper way), but cannot seems to solve this problem.
Is there any way to resolve this? or is there any better way to approach my objective here?
Thanks in advance.


text:
Q: Options of accessing wordpress data from mobile app There is an existing wordpress website and I would like to make native app(probably will do crossplatform native with React Native as I have experience with it) for it. So my question is: is there an API or plugin that exposes API via which I could securely access wordpress data(posts, widgets/their data and etc.)?
Main reason is for admin of the website to post data once and have it on both, app and website.
Making Hybrid/Web app is declined, as app should feel and look native and all these wordpress to mobile plugins that "convert" website are not an option.
Thank you in advance for any suggestions and/or links.

A: You can access WordPress data using WordPress REST API. If you want to know how to use the REST API from a React Native app, then give a read to this article.


text:
Q: Redefine output for a specific TS1 code point (=glyph?) By now I know how to make \textminus in tex4ht work, but this does not seem to be enough to display a proper minus with the \num macro of siunitx. Joseph Wright provided a workaround, but I'd like to know how to make this work at a more general level.
\documentclass{scrartcl}
\usepackage{textcomp}
\pagestyle{empty}

\DeclareTextSymbolDefault\homegrowntextminus{TS1}
\DeclareTextSymbol\homegrowntextminus{TS1}{61}

\begin{document}
  +5 \homegrowntextminus 5
\end{document}

Is there a way to configure tex4ht so that it prints a proper minus sign (as in the pdflatex output below) when converting to HTML without knowing or modifying \homegrowntextminus?

GitHub MWE: https://github.com/krlmlr/lm-template/tree/tex4ht-own-textminus.

A: What was showed in textminus in tex4ht may be good for small changes, but correct process is different. Because textcomp is basically font selection package, existing tex4ht support is not done by redefining macros in textcomp.4ht file, but a special mapping file for font used by textcomp, tcrm.htf exists. It is located in texmf-dist/tex4ht/ht-fonts/unicode/jknappen/tc directory. You can copy this file to your working dir and edit it according to your needs.
These .htf files are used by tex4ht processor to convert glyphs in the dvi file to internal representation, which is then converted using .4hf files to actual characters.
Structure of .htf files is described in tex4ht help. We need to find position of \textminus in this file and correct provided definition. It corresponds to position in font encoding. textcomp package uses TS1 font encoding, which is defined in ts1enc.def. If we search for \textminus, we find this line:
\DeclareTextSymbol{\textminus}{TS1}{61}

This means that \textminus is defined on position 61 in the tcrm.htf file:
 '-' ''            61

as you can see, - is hardcoded here. We can modify that to use unicode minus instead:
 '−' ''            61

It is best to use this hexadecimal form, because it is used by .4hf files to convert to the actual character.
If you compile your file with htlatex textput now, and watch output of tex4ht command, you will see this line:
 (/home/mint/texlive/2012/texmf-dist/tex4ht/ht-fonts/iso8859/1/charset/unicode.4hf

if you search this file for x2212, you will find line:
 '−' ''  '-' ''

this means that unicode minus is converted back to -. This is why this work only with unicode output with
 htlatex texput "xhtml, charset=utf-8" " -cunihtf -utf8"

different .4hf file is used now:
 (/home/mint/texlive/2012/texmf-dist/tex4ht/ht-fonts/unicode/charset/unicode.4hf)

different definition is used there:
 '−' '' '\226\\136\\146\' ''

this converts entity to the unicode value.
Now back to this question, situation is simpler, as you have added your own symbol at position 61, where original \textminus is placed and which we already redefined. So this will work also for \homegrowntextminus.


text:
Q: cp -p will preserve times for some files but not all? I have a source directory on a machine with a bunch of files, all with the same permissions, that I want to copy to another directory, that is mounted via SMB.
[tmark@dexter JR09141045 roche_454_transfer]$ ls -l /source_dir
total 71348
-rwxrwxrwx 1 adminrig lifelabs 19768377 Mar 25 23:29 1.TCA.454Reads.fna
-rwxrwxrwx 1 adminrig lifelabs 53093396 Mar 25 23:29 1.TCA.454Reads.qual
-rwxrwxrwx 1 adminrig lifelabs     1035 Mar 25 23:29 454AllControlMetrics.csv
-rwxrwxrwx 1 adminrig lifelabs     2657 Mar 25 23:29 454AllControlMetrics.txt
-rwxrwxrwx 1 adminrig lifelabs     4607 Mar 25 23:29 454BaseCallerMetrics.csv
-rwxrwxrwx 1 adminrig lifelabs    14518 Mar 25 23:29 454BaseCallerMetrics.txt
-rwxrwxrwx 1 adminrig lifelabs      351 Mar 25 23:23 454DataProcessingDir.xml
-rwxrwxrwx 1 adminrig lifelabs      702 Mar 25 23:29 454QualityFilterMetrics.csv
-rwxrwxrwx 1 adminrig lifelabs     1609 Mar 25 23:29 454QualityFilterMetrics.txt
-rwxrwxrwx 1 adminrig lifelabs    13496 Mar 25 23:29 454RuntimeMetricsAll.csv
-rwxrwxrwx 1 adminrig lifelabs    26967 Mar 25 23:29 454RuntimeMetricsAll.txt
-rwxrwxrwx 1 adminrig lifelabs     1675 Mar 25 14:48 dataRunParams.xml
-rwxrwxrwx 1 adminrig lifelabs     7134 Mar 25 23:29 gsRunProcessor.log

The target directory is mounted via SMB and I'm trying to copy the set of files all at once.
[tmark@dexter JR09141045 target_dir]$ cd /target_dir
[tmark@dexter JR09141045 target_dir]$ cp -p /source_dir/* ./
cp: preserving times for `./454AllControlMetrics.csv': Operation not permitted
cp: preserving times for `./454AllControlMetrics.txt': Operation not permitted
cp: preserving times for `./454BaseCallerMetrics.csv': Operation not permitted
cp: preserving times for `./454BaseCallerMetrics.txt': Operation not permitted
cp: preserving times for `./454DataProcessingDir.xml': Operation not permitted
cp: preserving times for `./454QualityFilterMetrics.csv': Operation not permitted
cp: preserving times for `./454QualityFilterMetrics.txt': Operation not permitted
cp: preserving times for `./454RuntimeMetricsAll.csv': Operation not permitted
cp: preserving times for `./454RuntimeMetricsAll.txt': Operation not permitted
cp: preserving times for `./dataRunParams.xml': Operation not permitted
cp: preserving times for `./gsRunProcessor.log': Operation not permitted

[tmark@dexter JR09141045 target_dir]$ ls -l
total 71264

-rwxrwxrwx 1 tmark 1008 19768377 Mar 25 23:29 1.TCA.454Reads.fna
-rwxrwxrwx 1 tmark 1008 53093396 Mar 25 23:29 1.TCA.454Reads.qual
-rwxr-xr-x 1 tmark 1008     1035 Apr  1  2015 454AllControlMetrics.csv
-rwxr-xr-x 1 tmark 1008     2657 Apr  1  2015 454AllControlMetrics.txt
-rwxr-xr-x 1 tmark 1008     4607 Apr  1  2015 454BaseCallerMetrics.csv
-rwxr-xr-x 1 tmark 1008    14518 Apr  1  2015 454BaseCallerMetrics.txt
-rwxr-xr-x 1 tmark 1008      351 Apr  1  2015 454DataProcessingDir.xml
-rwxr-xr-x 1 tmark 1008      702 Apr  1  2015 454QualityFilterMetrics.csv
-rwxr-xr-x 1 tmark 1008     1609 Apr  1  2015 454QualityFilterMetrics.txt
-rwxr-xr-x 1 tmark 1008    13496 Apr  1  2015 454RuntimeMetricsAll.csv
-rwxr-xr-x 1 tmark 1008    26967 Apr  1  2015 454RuntimeMetricsAll.txt
-rwxr-xr-x 1 tmark 1008     1675 Apr  1  2015 dataRunParams.xml
-rwxr-xr-x 1 tmark 1008     7134 Apr  1  2015 gsRunProcessor.log

Note that the times and permissions on the first two files are the same as in the source directory, but differ for the remaining files.
So, it seems that I can copy some files and preserve their permissions and times, but not with other files, even though all the source files come from the same place and have the same permissions and (more or less) times, and I'm copying them all to the same directory at the same time - and hence with the same umask, etc.
So, why can I preserve the times for some, but not all files ?
I'd be happy to provide more details (umask, Linux version, smb.conf, etc etc.) except I can't understand how any of those details could explain what I'm seeing - as they ought to be constant here.

A: I know this is old, but I was having the same issue of trying to copy over cifs shares.  I have several commands set up in sudoers with the NOPASSWD option and one is cp.  If I do sudo cp -r from.file to.file it seems to work.  If you have the ability to do sudo, this may be an option.

A: On Unix the timestamps cannot be preserved on the files the user does not own.
This is why the following command fails if file1 and file2 are owned by different users in case file2 already exists:
cp -p file1 file2

Seems it is your case because source files are owned by adminrig and target files are owned by tmark.
Not sure if there is a workaround as forcing with -f does not solve the issue.
If you can, try changing ownership of target files...


text:
Q: How to get list of all subcategories which are set "Include in Navigation Menu" as no I have tried to get all sub categories which are not include in navigation menu but those are being active, of current category in list page.
$children = Mage::getModel('catalog/category')->getCategories(10); //10 current category id

Even this category collection also return only subcategories which are include in navigation menu.
How to get category which isn't include in navigation menu?

A: Try this:
$collection = Mage::getResourceModel('catalog/category_collection')
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('is_active', 1) //only active categories
    ->addAttributeToFilter('include_in_menu', 0) //only categories not included in menu
    ->addAttributeToFilter('parent_id', 10)//get only subcategories of the category with id 10
    ->addAttributeToSort('position')//sort by position
;

foreach ($collection as $category) {
    //do something with $category
}


text:
Q: How to turn this into an alias? I frequently use this command:
grep -rnw donkey | grep market | cut -c -80
How can I change it into an alias on Linux?
I tried:
alias search='grep -rnw $1 | grep $2 | cut -c -200'

But when I run it with
search hello world

it gives me:
cut: Usage: grep [OPTION]... PATTERN [FILE]...
hello: No such file or directory
cut: Try 'grep --help' for more information.
world: No such file or directory
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.

A: Unfortunately, bash alias doesn't accept parameters like some other shells.
But you can get around it by declaring search as a function which you can add to your .bashrc file
function search { grep -rnw $1 | grep $2 | cut -c -200; }
export -f search

See: Make bash alias that takes a parameter
In the link the example uses an alias which seems to be unessessary.
You can put the function with export -f search directly into .bashrc and name the function as search.
If all else fails another option is to write a script called search.
e.g.  create a script named search containing:
#!/bin/sh
grep -rnw $1 | grep $2 | cut -c -200;

Place this somewhere in a path defined in $PATH like /usr/bin or
perhaps $HOME/bin.  If using $HOME/bin put that path in your environment like.
export PATH=$PATH:$HOME/bin


text:
Q: How to find uncommon elements from three arrays? A,B,C are the arrays :
A = {1,2,3,4}
B = {8,1,2,3}
C = {1,2,9,3}

Result is the uncommon values from three arrays
Result = {4,8,9}
Asking for the logic what I can implement ?

A: There might be some other better answers. But here is the most simple one.

*

*On line 4 I took the Intersection of 3 sets

*On line 7 I took the Union of three sets

*On line 10 the difference or XOR operation, of Union and intersection

I hope it helps:-
>>> a = {1,2,3,4}
>>> b = {8,1,2,3}
>>> c = {1,2,9,3}

>>> d = a & b & c
>>> print(d)
{1, 2, 3}

>>> e = a | b | c
>>> print(e)
{1, 2, 3, 4, 8, 9}

>>> f = d^e
>>> print(f)
{4, 8, 9}


text:
Q: How much overhead is using emulated stack in GWT?
I'm considering using GWT's emulated stack in web-mode and I wanted to hear, based on people's experience how much performance overhead it added?
From what I read in the above link all of the overhead is the couple of arrays and their handling as a stack which is very reasonable in my eyes.
I just want to make sure there's no cat in the bag.
Also, a reasonable increase in the size of the js files is ok by me as my users connect to very long sessions and can wait the few additional ms.
Thanks,
Ittai

A: I don't have any data on execution speed, but Googler David Chandler stated in this discussion that removing stack info can reduce compiled JS size by as much as 15%.
<set-property name="compiler.stackMode" value="strip"/>


text:
Q: How to ensure a Bluetooth connection is closed when it was started in another activity? The APP I am developing connects to a Bluetooth Printer (the microFlash 2te for those curious) .
The Bluetooth connection is managed by a BluetoothConnectionManager class with a message handler at activity level to handle the information from the BluetoothChatService.
When I leave the activity in a controlled environment I make sure to disconnect the Bluetooth connection by stopping the bluetoothConnectionManager which stops all threads.
However when the user exits with the back button I cannot ensure the threads are stopped. This causes issues if I try and connect the socket as the Bluetooth device is already connected.
Is there away I can find and use or kill the bluetoothConnectionManager created by another activity? Or is there a way to ensure that a bluetoothConnectionManager stops when an activity is closed?
Attached is my connect thread class inside the BluetoothConnectionManager:
    private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        mmDevice = device;
        BluetoothSocket tmp = null;

        // Get a BluetoothSocket for a connection with the
        // given BluetoothDevice
        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            Log.e(TAG, "create() failed", e);
        }
        mmSocket = tmp;
    }

    public void run() {
        Log.i(TAG, "BEGIN mConnectThread");
        setName("ConnectThread");

        // Always cancel discovery because it will slow down a connection
        mAdapter.cancelDiscovery();

        //stop();

        // Make a connection to the BluetoothSocket
        try {
            // This is a blocking call and will only return on a
            // successful connection or an exception
            d("About to connect to socket...");
            mmSocket.connect();

        } catch (IOException e) {
            connectionFailed();
            // Close the socket
            try {
                mmSocket.close();

            } catch (IOException e2) {
                d(e2.getMessage().toString());
                Log.e(TAG,
                        "unable to close() socket during connection failure",
                        e2);
            }
            return;
        }

        // Reset the ConnectThread because we're done
        synchronized (BluetoothConnectionManager.this) {
            mConnectThread = null;
        }

        // Start the connected thread
        connected(mmSocket, mmDevice);
    }

    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "close() of connect socket failed", e);
        }
    }
}


text:
Q: Arbitrary selects failing using cx_Oracle with instant client I am trying to select data from an ORACLE 12c database using cx_Oracle, but I am getting the exception: "cx_Oracle.OperationalError: ORA-03113: end-of-file on communication channel".
My query behaves fine using Pycharm (jdbc:oracle:thin driver). Using cx_Oracle in python 3.6, however, the query fails unless I reduce the number of IDs in the IN clause from 500 to about 250. The Cursor.fetchall() function is what throws the exception. I do not have privileged access to the database in order to check things like locks or load, but could these be the cause of the issue? According to our DBA, there is nothing wrong on the Oracle db server, and since the query works fine otherwise, I am inclined to believe it. I have messed with the client-side sqlnet.ora as well, which has allowed exceptions to eventually be thrown instead of hanging forever, but I still cannot fetch the data.
def select(self, query, *args):
    cur = self.dbh.cursor()
    cur.prepare(query)
    try:
        cur.execute(None, args)
        return cur.fetchall()
    # my attempt to handle the issue
    except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError) as e:
        # cx_Oracle.OperationalError: ORA-03113: end-of-file on communication channel
        self.logger.error('Oracle Error: {}'.format(traceback.format_exc()))
        raise e

The code calls select like this. For brevity, I've omitted the full string IDs
ids = ['1', '2', '3', ...]
query = """\
select * from my_table where id in(:0,:1,:2,:3,:4, ...)
"""
self.select(query, *ids)

The query fails without the placeholders (with the IDs placed directly in the query) as well.
I expect to be able to run any select query using an IN clause with up to 1000 IDs without receiving the ORA-03113 Exception.
Edit:
I installed oracle-instantclient18.5-basic-18.5.0.0.0-3.x86_64.rpm* on ubuntu 18.04.2, have cx_Oracle version 7.1.2, and I am connecting to Oracle 12.1.0.2.0.
The query is on the underlying tables of BMC Software's ARS. I will start working to try to replicate the problem with a local table structure, but it is a mess and will take some time. If I am able to create a local copy of the tables, I'm not sure I'd be able to replicate the issue, as identical queries with different IDs work fine. That makes it seem data driven, however, after I reduced the query to 250 IDs, I swapped the 250 from the first half to the second half, and got the same success result, so it doesn't seem to be just one bad row.
Is there more helpful logging I can enable on the client side to get more information?
Edit2: I should also add that the issue does not just occur with one query. I've seen the same issue with select queries to completely different tables.
Edit3: I just found out that by commenting out some of the columns that I'm selecting also can make the query work. columns like this:
to_char(to_date('1970-01-01','YYYY-MM-DD') + numtodsinterval(EventStart,'SECOND'),'YYYY-MM-DD HH24:MI:SS')

This may indicate that some kind of timeout is being reached which may or may not be configured in my sqlnet.ora:
DISABLE_OOB=on
SQLNET.RECV_TIMEOUT=60
SQLNET.SEND_TIMEOUT=60
TCP.CONNECT_TIMEOUT=300
SQLNET.OUTBOUND_CONNECT_TIMEOUT=300
ENABLE=BROKEN
TRACE_LEVEL_CLIENT=ADMIN
TRACE_FILE_CLIENT=sqlnet

Edit 4: I've tried some more things.
I installed the same version of instant client, except on a windows 7 machine, and ran the same query against the same db instance. The query succeeded.
I also narrowed down that for this particular query, it will accept 499 IDs, but fails with 500. it doesn't matter which ID I comment out from the query.
I also tried tricking the query into thinking there were fewer IDs by using a sub-select instead:
IN(
    select regexp_substr(:0,'[^,]+', 1, level) from dual connect by regexp_substr(:0, '[^,]+', 1, level) is not null
)

I got the error "cx_Oracle.DatabaseError: ORA-01460: unimplemented or unreasonable conversion requested", after which I realized made sense because Oracle will only allow a string to be up to 4000 bytes long.

A: I think I finally found a way to get everything functioning. I finally came across this link:
https://ardentperf.com/2010/09/08/mysterious-oracle-net-errors/
It turns out that this solved my problem. I am still having trouble getting cx_Oracle to honor a connection string of the same format as the tnsnames.ora file, but I changed my code to refer to the tnsnames.ora for now as follows:
connection_info = {
    'user': self.config.get(self.db, 'user'),
    'pass': self.config.get(self.db, 'password')
}
connection_string = '{user}/{pass}@TEST'\
    .format(**connection_info)
connection = cx_Oracle.connect(connection_string)

where my tnsnames.ora contains the following:
TEST =
 (DESCRIPTION =
   (ADDRESS_LIST =
     (ADDRESS = (PROTOCOL = TCP)(Host = myhost.com)(Port = 1521))
   )
   (SDU=1024)
 (CONNECT_DATA =
   (SID=mysid)
 )
)

The key here is the SDU=1024, which inexplicably fixes this issue.
https://docs.oracle.com/cd/B28359_01/network.111/b28317/sqlnet.htm#NETRF184
Documentation from the above link indicates that the default for SDU is 8192 bytes (8 KB) and my understanding is that there is supposed to be auto-negotiation of this value. This does not appear to be the case, and I don't know what past defaults have been.


text:
Q: triangle type function with only 2 angles given Implement a function that is given 2 positive integers representing 2 angles of a triangle. If the triangle is right, isosceles, or both, the function should return 1, 2 or 3, respectively. Otherwise it should return 0.
im actually just started learning C language and cant move on cause i cant find an answer to this problem.
would like a reference to see where are my mistakes.
dont need to print it, only the function.
without using loops only if statements.
int TriangleType (unsigned num1, unsigned num2){
    int result;
    if(num1 == 90 || num2 == 90 || num1 + num2 == 90){
        result = 1;
    } else if(num1 == num2 || 180 - (num1+num2) == num1 || 180 - (num1+num2) == num2) {
        result = 2;
    } else if((num1 == 90 || num2 == 90 || num1 + num2 == 90) && (num1 == num2 || 180 - (num1+num2) == num1 || 180 - (num1+num2) == num2)){
        result = 3;
    } else if (num1 + num2 >= 180){
        result = -1;
    } else {
        result = 0;
    }
    return result;
}

thats the start so u can see what is the direction...
maybe got mistakes even here at the start =)

A: int TriangleType (unsigned num1, unsigned num2)
{
    //Calculate the third angle and keep in num3
        unsigned num3 = 180 - (num1 + num2);

    //We declare a variable "result" and initialize it with 0
    //This way if none of our if conditions match, we would simply return 0 by "return result;".
    unsigned int result = 0;

        if (num1 == 90 || num2 == 90 || num3 == 90) //if any of our angles are 90-degree
                result += 1; //Add 1 to result (which is 0 at this point)
        if ((num1==num2) || (num2 == num3) || (num1 == num3)) //if any two angles are same i.e. isosceles
                result += 2; //Add 2 to result (which is 1 if previous if condition was true otherwise its 0) )

    /*
    At this point :
     1) If it was neither right-angled or isoscles
        both the if statements will be false and result will remain 0

     2) If it was right-angled we did "result += 1" i.e. "result = result + 1"
        So, In case first "if" condition is true, result is 1 otherwise its 0

     3) If it was isoscles we did "result += 2" i.e. "result = result + 2"
        So, second "if" condition is true, result becomes result + 2 ie
        if result was 0 it becomes 2 or if it was 1 it becomes 3.
    */

        return result;
}

A: Correct logic is:
int TriangleType(unsigned num1, unsigned num2)
{
  int result;
  if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {
    if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)
      result = 3;
    else
      result = 1;
  } else if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2) {
    result = 2;
  } else if (num1 + num2 >= 180) {
    result = -1;
  } else {
    result = 0;
  }
  return result;
}

In your program there is a mistake in logic in the first if statement. You are asking whether the triangle is right and if so you evaluate is as one. But in reality it can be right and isosceles at the same time, but it's checked just in third if statement to which you won't get since you return one. So you have to check the condition in that first statement.
if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {
    if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)
      result = 3;
    else
      result = 1;
  }

Then it should work correctly.
Good practice for the future is use function for any for loop, condition, etc. so you do not need to copy you code. It is much more efficient to write just one function, more readable for the other programmers and if there is a mistake, you will need to fix it at just one place and not multiple ones.
I would write it as:
int is_isosceles(unsigned num1, unsigned num2)
{
  if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)
    return 1;
  else
    return 0;
}

int TriangleType(unsigned num1, unsigned num2)
{
  int result;
  if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {
    if (is_isosceles(num1, num2))
      result = 3;
    else
      result = 1;
  } else if (is_isosceles(num1, num2)) {
    result = 2;
  } else if (num1 + num2 >= 180) {
    result = -1;
  } else {
    result = 0;
  }
  return result;
}

Condition functions can be of type bool, but include library:
#include <stdbool.h>

A: Let me try and sketch a solution without giving you the complete code...
int TriangleType (unsigned num1, unsigned num2){

    int right = 0;
    int isosceles = 0;
    int result = 0;

    if( /* conditions for right angle */ ){
        right = 1;
    }

    if( /* conditions for isosceles */ ) {
        isosceles = 1;
    }

    if ( right == 1 && isosceles == 1 ) {
        result = 3;
    } else if ( right == 1) {
        result = 1;
    } else if ( isosceles == 1 ) {
        /* ... */
    } /*...*/
    return result;
}

It could be made shorter but since you are just starting out this is probably best.


text:
Q: Normal approximation to Poisson's distribution
Historic data of a computer network suggest that connections with this network follow a Poisson's distribution with an average of 5 connections per minute. Find $t_0$, which has probability equal to $0.9$ to happen at least once before $t_0$

I made an approximation using $\lambda=12$, since $5/60 =1/12$, but my answer doesn't match with the book (book says it's ~$27.5$ seconds, and mine ~$17.0$ seconds)
Could someone help me?

A: Let $(X_t)_{t \in [0,\infty)}$ be a Poisson process where $t$ is minutes.
$$\begin{aligned}P(X_{t_0}\geq 1)&=0.9\\
1-P(X_{t_0}=0)&=0.9\\
1-\frac{e^{-\lambda t_0}(\lambda t_0)^0}{0!}&=0.9\\
e^{-\lambda t_0}&=0.1\\
t_0&=-\ln(0.1)/\lambda
\end{aligned}$$
If we express $t_0$ in seconds we get $t_0\cdot 60\approx 27.63$ where $\lambda =5$.


text:
Q: Why is $dy dx = r dr d \theta$
Possible Duplicate:
Explain $\iint \mathrm dx\mathrm dy = \iint r \mathrm d\alpha\mathrm dr$

I'm reading the proof of Gaussian integration. When we change to polar coordinates, why do we get an "extra" r in there?

\begin{align}
\int_{-\infty}^{\infty} \int_{-\infty}^{\infty} e^{-(x^2+y^2)}\ dx dy
&= \int_0^{2\pi} \int_0^{\infty} e^{-r^2}r\ dr\ d\theta\\
\end{align}

I've looked at a few different proofs:

*

*http://www.math.uconn.edu/~kconrad/blurbs/analysis/probint.pdf
"The differential dx dy represents an element of area in cartesian
coordinates, with the domain of integration extending over the
entire xy-plane. An alternative representation of the last integral
can be expressed in plane polar coordinates r, $\theta$"

*http://www.umich.edu/~chem461/Gaussian%20Integrals.pdf
but none explain this step fully enough for me to really see why this happened.

A: When you make the change of variables $x=r\cos \theta,y=r\sin \theta$, the integral becomes
$$ \int_D f(x,y)dxdy=\int_{D'} f(r\cos \theta,r\sin\theta) J(r,\theta) drd\theta \ \ (F)$$
where $D'$ is the changed domain, where $r,\theta$ belong, and $\displaystyle J(r,\theta)=\left| \begin{matrix} \frac{\partial x}{\partial r}& \frac{\partial x}{\partial \theta}\\ \frac{\partial y}{\partial r}& \frac{\partial y}{\partial \theta}\end{matrix}\right| $ is the jacobian matrix.
The formula $(F)$ stays true even when you make different change of variables for $x,y$. This is the theory behind $dxdy=rdrd\theta$.
For a proof of $(F)$ you need to use Jordan measurable sets (I think ) and the definition of the double integral. Of course, this works in higher dimensions, with more intricate computations.
You can take a look in the wikipedia article: http://en.wikipedia.org/wiki/Multiple_integral

A: Changing coordinates in multiple integrals requires adding the Jacobian as a factor. The Jacobian in this case is $r (\cos^2 \theta + \sin^2 \theta) = r$.


text:
Q: Download excel file from unix server to windows client I recently started working on an app development using java. Purpose of the app is to process some api & output information in the form of excel file. JAR is located at server and runs when user send request at client(local machine).
The app generates excel file successfully but at the server location. I tried to using JAVA ChannelSftp approach to download from server to my local machine(client location) but it creates a new file at JAR location(i.e at Server location) instead of client location.
The code snippet is as below & this creates a file at JAR location with file name C:\Users\PFName-CFName_Co.xlsx
String SerDir=System.getProperty("user.home") + "/Desktop/";
String LocDir="C:\Users\";
String SerFC = SerDir+PFName+"-"+CFName+"_Co.xlsx";
String LocFC = LocDir+PFName+"-"+CFName+"_Cos.xlsx";
Session session = null;
ChannelSftp sftpChannel=null;
Channel channel = null;
JSch jsch = new JSch();
    try
    {
        session = jsch.getSession(username, hostname, 22);
        session.setConfig("StrictHostKeyChecking","no");
        session.setPassword(password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        channel = session.openChannel("sftp");
        channel.connect();
        sftpChannel =(ChannelSftp) channel;
        sftpChannel.cd(SerDir);
        File file = new File(SerFC);
        byte[] buffer = new byte[1024];
        BufferedInputStream bis;
        bis = new BufferedInputStream(sftpChannel.get(file.getName()));
        File newFile = new File(LocDir + file.getName());
        // Download file
        OutputStream os = new FileOutputStream(newFile);
        BufferedOutputStream bos = new BufferedOutputStream(os);
        int readCount;
        while ((readCount = bis.read(buffer)) > 0) {
            bos.write(buffer, 0, readCount);
    }
bis.close();
bos.close();

Please check & help me on how to download the file to client location(anywhere in c drive)


text:
Q: Remove/Override RabbitMq TopologyRecoveryException logs in .NET As per the RabbitMq java client API, https://www.rabbitmq.com/api-guide.html#recovery

Unhandled exceptions related to connection, channel, recovery and
  consumer lifecycle are delegated to the exception handler. Exception
  handler is any object that implements the ExceptionHandler interface.
  By default, an instance of DefaultExceptionHandler is used. It prints
  exception details to the standard output.
It is possible to override the handler using
  ConnectionFactory#setExceptionHandler. It will be used for all
  connections created by the factory:

we have
ConnectionFactory factory = new ConnectionFactory();
cf.setExceptionHandler(customHandler);

What is the same implementation for .NET RabbitMq client? Adding this code is still writing console logs and not executing my logic and How do I remove the existing event handler?
var factory = new ConnectionFactory() { HostName = "localhost" };
var connection = factory.CreateConnection();
connection.CallbackException += (x, y) => {
   Console.WriteLine("Handled"); // not printing
};

I would like to override/remove the logs which are printing to console because of topologyrecoveryexception.

Could anyone help me on how to override this default behavior of logs to console by RabbitMq.Client using v4.1. Any help is greatly appreciated.

A: First you should upgrade to the latest 5.X .NET client.
Then, notice in the ChangeLog file that console logging was replaced by event source (link).
CallbackException is used when one of your callbacks raises an exception, I believe. It has nothing to do with exceptions generated by the library.

NOTE: the RabbitMQ team monitors the rabbitmq-users mailing list and only sometimes answers questions on StackOverflow.


text:
Q: Finding consecutive characters but ignore space & case? I'm looking to match the following strings so that I can later truncate them from the string in JS.
For ex:
matched: i like eeeting pie and a a a a a bananas.
matched: My name iIIs John Doe and A a A a AA AAA I'm cool.
This is the regex I currently have, but it doesn't match if there is a space in between or if there are more than 3 consecutive letters:
(.)\1\1

A: You can use
/(\S)(?:\s*\1){2,}/gi
/\b(\S)(?:\s*\1){2,}/gi

If you need to make sure you only start matching at the word boundary, you need to use the second regex.
See the JavaScript demo:

const text = "i like eeeting pie and a a a a a bananas. My name iIIs John Doe and A a A a AA AAA I'm cool.";
const re = /(\S)(?:\s*\1){2,}/gi;
document.body.innerHTML = text.replace(re, '$&')
// Second regex demo:
document.body.innerHTML += "
" + text.replace(/\b(\S)(?:\s*\1){2,}/gi, '$&')

The regex has the i case insensitive flag and matches

*

*(\S) - Group 1: any non-whitespace char

*(?:\s*\1){2,} - two or more occurrences of

*

*\s* - zero or more whitespaces

*\1 - the value of Group 1.

See the regex scheme:


text:
Q: How do we implement custom API-only authentication in Laravel This isn't a question so much in need of an answer, but further suggestions and answers and recommendations are welcome.  I want to share with the world how I resolved this issue and hope it helps others.
Laravel comes with several pre-designed authentication solutions that you can spin up with a few artisan commands.  These include:

*

*standard users table authentication

*OAuth2 (via the Laravel Passport package)

*Social media based authentication (via the Laravel Socialite package)

As useful as all of these are, in this age of micro-services, Laravel doesn't provide much in the way of an out-of-the-box bootstrap for API-only authentication using custom APIs.
I was faced with this problem several months ago and I searched Google and Stackoverflow for an answer.  I found helpful articles which helped to point the way, and these are cited.  It took some effort to understand how to glue them together and step-debugging to iron out the kinks.
The answer is provided in the hope that it helps others - and myself, where I have to do the same thing again in the future.
Assumptions and Scope:

*

*you've created your own API like https://example.com/login and https://example.com/logout

*you're running a website that requires authentication, but not via models and tables or social media

*your API manages interactions with tables, including user-login/logout

*you use the Laravel Passport add-on for OAuth2 authentication (acknowledgements to @ShuvoJoseph for bringing this to my attention)

A: The solution involves seven PHP files

*

*app/Http/Controllers/HomeController.php - homepage controller; the destination for an authenticated user

*app/Providers/ApiUserProvider.php - a custom provider to bootstrap and register the logged-in user, and implements the interface Illuminate\Contracts\Auth\UserProvider

*app/CoreExtensions/SessionGuardExtended.php - custom guard-controller to log-in the user and receives the authentication values and stores them in session array; extends class Illuminate\Auth\SessionGuard

*app/ApiUser - if you're using OAuth2 (Laravel's Passport); custom user class that exposes the OAuth access_token; extends Illuminate\Auth\GenericUser and implements the interface Illuminate\Contracts\Auth\Authenticatable

*config/auth.php - the auth config which instructs the Auth() facade to return the custom session guard

*app/Providers/AuthServiceProvider.php - the auth bootstrap

*app/Providers/AppServiceProvider.php - the main application bootstrap

Source research/investigation material are cited for you to investigate for yourself and comprehend the background context to their existence.  I make no claims to be a genius who created the solution from scratch through my own mojo, but rather that - like all innovators - I build on the efforts of others.  The unique selling point of my article is that I provide a complete packaged solution, whereas the cited sources provide solutions to niche parts of the overall answer.  Together, after much trial and error, they helped me to form a complete solution.
A really useful article to understands how config/auth.php affects execution in AuthManager.php is https://www.2hatslogic.com/blog/laravel-custom-authentication/
No code modifications are made to the following, but they're included to acknowledge the role they play and their importance in the process:

*

*vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php - main authorization factory manager

*Auth() facade - returns the shrink-wrapped Illuminate\Auth\SessionGuard class instance by default, unless it's instructed to do otherwise through the config/auth.php file - Auth() is used ubiquitously throughout Laravel code to retrieve the session guard

The Code
app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

/**
 * Handles and manages the home-page
 *
 * @category controllers
 */
class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        blah
    }

    ... other methods ...

}

app/Providers/ApiUserProvider.php
Sources:

*

*Using Laravel 5.8 authentication with external JSON API (Creating own ServiceProvider)

*https://laracasts.com/discuss/channels/laravel/replacing-the-laravel-authentication-with-a-custom-authentication

*Custom user authentication base on the response of an API call
<?php
namespace App\Providers;

use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use App\ApiUser;

/**
 * Delegates API user login and authentication
 *
 * @category providers
 */
class ApiUserProvider implements UserProvider
{

    /**
     * Custom API Handler
     * Used to request API and capture responses
     *
     * @var \Path\To\Your\Internal\Api\Handler
     */
    private $_oApi = null;

    /**
     * POST request to API
     *
     * @param string  $p_url      Endpoint URL
     * @param array   $p_arrParam Parameters
     * @param boolean $p_isOAuth2 Is OAuth2 authenticated request? [Optional, Default=True]
     *
     * @return array
     */
    private function _post(string $p_url, array $p_arrParam, bool $p_isOAuth2=true)
    {
        if (!$this->_oApi) {
            $this->_oApi = new \Path\To\Your\Internal\Api\Handler();
        }
        $arrResponse = $this->_oApi->post($p_url, $p_arrParam, $p_isOAuth2);
        return $arrResponse;
    }

    /**
     * GET request to API
     *
     * @param string $p_url     Endpoint URL
     * @param array $p_arrParam Parameters [Optional, Default = array()]
     *
     * @return array
     */
    private function _get(string $p_url, array $p_arrParam=[], bool $p_isOAuth2=true)
    {
        if (!$this->_oApi) {
            $this->_oApi = new \Path\To\Your\Internal\Api\Handler();
        }
        $arrResponse = $this->_oApi->get($p_url, $p_arrParam);
        return $arrResponse;
    }

    /**
     * Retrieve a user by the given credentials.
     *
     * @param array $p_arrCredentials
     *
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $p_arrCredentials)
    {
        $arrResponse = $this->_post('/login', $p_arrCredentials, false);
        if ( $arrResponse['result'] ) {
            $arrPayload = array_merge(
                $arrResponse['data'],
                $p_arrCredentials
            );
            return $this->getApiUser($arrPayload);
        }
    }

    /**
     * Retrieve a user by their unique identifier.
     *
     * @param mixed $p_id
     *
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveById($p_id)
    {
        $arrResponse = $this->_get("user/id/{$p_id}");
        if ( $arrResponse['result'] ) {
            return $this->getApiUser($arrResponse['data']);
        }
    }

    /**
     * Validate a user against the given credentials.
     *
     * @param \Illuminate\Contracts\Auth\Authenticatable $p_oUser
     * @param array                                      $p_arrCredentials
     *
     * @return bool
     */
    public function validateCredentials(UserContract $p_oUser, array $p_arrCredentials)
    {
        return $p_oUser->getAuthPassword() == $p_arrCredentials['password'];
    }

    /**
     * Get the api user.
     *
     * @param mixed $p_user
     *
     * @return \App\Auth\ApiUser|null
     */
    protected function getApiUser($p_user)
    {
        if ($p_user !== null) {
            return new ApiUser($p_user);
        }
        return null;
    }

    protected function getUserById($id)
    {
        $user = [];

        foreach ($this->getUsers() as $item) {
            if ($item['account_id'] == $id) {
                $user = $item;

                break;
            }
        }

        return $user ?: null;
    }

    protected function getUserByUsername($username)
    {
        $user = [];

        foreach ($this->getUsers() as $item) {
            if ($item['email_address'] == $username) {
                $user = $item;

                break;
            }
        }

        return $user ?: null;
    }

    /**
     * The methods below need to be defined because of the Authenticatable contract
     * but need no implementation for 'Auth::attempt' to work and can be implemented
     * if you need their functionality
     */
    public function retrieveByToken($identifier, $token) { }
    public function updateRememberToken(UserContract $user, $token) { }

}

app/CoreExtensions/SessionGuardExtended.php
Sources:

*

*Extending Laravel 5.2 SessionGuard

*Using Laravel 5.8 authentication with external JSON API (Creating own ServiceProvider)
<?php
namespace App\CoreExtensions;

use Illuminate\Auth\SessionGuard;
use Illuminate\Contracts\Auth\Authenticatable;

/**
 * Extended SessionGuard() functionality
 * Provides added functionality to store the OAuth tokens in the session for later use
 *
 * @category guards
 *
 * @see https://stackoverflow.com/questions/36087061/extending-laravel-5-2-sessionguard
 */
class SessionGuardExtended extends SessionGuard
{

    /**
     * Log a user into the application.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $p_oUser
     * @param  bool  $p_remember
     * @return void
     */
    public function login(Authenticatable $p_oUser, $p_remember = false)
    {

        parent::login($p_oUser, $p_remember);

        /**
         * Writing the OAuth tokens to the session
         */
        $key = 'authtokens';
        $this->session->put(
            $key,
            [
                'access_token' => $p_oUser->getAccessToken(),
                'refresh_token' => $p_oUser->getRefreshToken(),
            ]
        );
    }

    /**
     * Log the user out of the application.
     *
     * @return void
     */
    public function logout()
    {
        parent::logout();

        /**
         * Deleting the OAuth tokens from the session
         */
        $this->session->forget('authtokens');
    }

}

app/ApiUser
Sources:

*

*Using Laravel 5.8 authentication with external JSON API (Creating own ServiceProvider)
*https://laracasts.com/discuss/channels/laravel/replacing-the-laravel-authentication-with-a-custom-authentication

*Custom user authentication base on the response of an API call
<?php
namespace App;

use Illuminate\Auth\GenericUser;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;

class ApiUser extends GenericUser implements UserContract
{

    /**
     * Returns the OAuth access_token
     *
     * @return mixed
     */
    public function getAccessToken()
    {
        return $this->attributes['access_token'];
    }

    public function getRefreshToken()
    {
        return $this->attributes['refresh_token'];
    }

}

app/Providers/AuthServiceProvider.php
<?php
namespace App\Providers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Auth::provider('frank_sinatra', function ($app, array $config) {
            // Return an instance of Illuminate\Contracts\Auth\UserProvider...

            return new ApiUserProvider();
        });

    }
}

app/Providers/AppServiceProvider.php
Sources:

*

*Extending Laravel 5.2 SessionGuard
Note:
There is a couple of nuanced issues regarding the change to coding in this PHP file.
If you want to understand more, look at vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php, AuthManager::resolve() in particular.

*

*References to config/auth.php 'session' and 'token' are served by hard-coded methods AuthManager::createSessionDriver() and AuthManager::createTokenDriver()
(Tell me please if you know of a way to extend AuthManager.php in the app)

*AppServiceProvider.php to the rescue!  Custom guards can be registered in AppServiceProvider::boot() and intercepted before the default code can be executed.

*I'm OK with point 2 above, but couldn't we do something clever like return the custom session-guard name or instance from AppServiceProvider, have setCookieJar(), setDispatcher(), setRequest() in a specialized public method in AuthManager.php, which can be hooked into AppServiceProvider.php or driven by config/auth.php to execute after creating the custom session-guard in AuthManager.php?

*Without the cookies or sessions, the user's identity isn't preserved through the redirect. The only way to resolve this is to include the setCookieJar(), setDispatcher() and setRequest() in AppServiceProvider within our current solution.

<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Auth;
use App\CoreExtensions\SessionGuardExtended;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @see https://stackoverflow.com/questions/36087061/extending-laravel-5-2-sessionguard
     *
     * @return void
     */
    public function boot()
    {

        /**
         * Extending Illuminate\Auth\SessionGuard()
         * This is so we can store the OAuth tokens in the session
         */
        Auth::extend(
            'sessionExtended',
            function ($app) {

                $guard = new SessionGuardExtended(
                    'sessionExtended',
                    new ApiUserProvider(),
                    app()->make('session.store'),
                    request()
                );

                // When using the remember me functionality of the authentication services we
                // will need to be set the encryption instance of the guard, which allows
                // secure, encrypted cookie values to get generated for those cookies.
                if (method_exists($guard, 'setCookieJar')) {
                    $guard->setCookieJar($this->app['cookie']);
                }

                if (method_exists($guard, 'setDispatcher')) {
                    $guard->setDispatcher($this->app['events']);
                }

                if (method_exists($guard, 'setRequest')) {
                    $guard->setRequest($this->app->refresh('request', $guard, 'setRequest'));
                }

                return $guard;
            }
        );
    }
}

config/auth.php
Sources:

*

*https://www.2hatslogic.com/blog/laravel-custom-authentication/
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        //'guard' => 'web', /** This refers to the settings under ['guards']['web'] */
        'guard' => 'webextended', /** This refers to the settings under ['guards']['webextended'] */
        'passwords' => 'users', /** This refers to the settings under ['passwords']['users'] */
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session', /** This refers to Illuminate/Auth/SessionGuard */
            'provider' => 'users', /** This refers to the settings under ['providers']['users'] */
        ],

        'webextended' => [
            'driver' => 'sessionExtended', /** @see app/Providers/AppServiceProvider::boot() */
            'provider' => 'users', /** This refers to the settings under ['providers']['users'] */
        ],

        'api' => [
            'driver' => 'token', /** This refers to Illuminate/Auth/TokenGuard */
            'provider' => 'users',
            'hash' => false,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'frank_sinatra',  /** @see app/Providers/AuthServiceProvider::boot() */
            //'model' => App\User::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    [
        blah
    ],

    [
        other settings
    ],

];

How To Use This Solution
Very simple.  There's no change in the overall approach.  In other words, we use the Auth() facade.
When logging in with your custom API /login?username=<username>&password=<password>
request()->flash();
$arrData = request()->all();

if ( Auth::attempt($arrData, true) ) {
    return redirect('home');
} else  {
    return back()->withErrors(
        [
            'username' => "Those credentials can't be found",
            'password' => "Those credentials can't be found",
        ]
    );
}

When logging out with your custom API /logout
Auth::logout();
return redirect('home');

A: The problem with this approach is that it doesn't handle Password Reset, which requires tokens to be stored in a local database and is a pain to override.


text:
Q: How to uninstall python? I had uninstalled python 3.10 because I want to run python 3.7.5
so I uninstalled all and there is no python folder or files in C drive.
but the registry have lots of python files and I don't know how to clean up this all files

A: One of the comments above has shown you the correct way to uninstall any version of Python.
If you have to use multiple versions of Python, it's recommended to use a version manager. Some good choices are Conda and pyenv-win.


text:
Q: Making this equation into Quadratic form produces two different answers I have an equation...
$6+2x^2-3x=8x^2$
I can turn it into a quadratic form like this
$6x^2+3x-6$ or $-6x^2-3x+6$
Depending if I move the variable from the left to right or right to left.
Given the quadratic formula
$x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}$
The first equation is,
$a = 6, b = 3, c = -b$
The second gives
$a = -6, b = -3, c = 6$
But if I plug both of those into the quadratic formula I get two different answers (which makes sense). But how could we have two different answers to equivalent equations? Which one is correct? I'm sure I'm doing something totally wrong. I've been trying to figure it out for a while now.

A: The solutions of $-6x^2-3x+6 =0 $ are;
$x= \dfrac{3\pm\sqrt{9+144}}{-12} = \dfrac{3\pm\sqrt{153}}{-12} = \dfrac{-3+\sqrt{153}}{12}$ or $\dfrac{-3-\sqrt{153}}{12}$
While the solution of $6x^2+3x-6=0$ are;
$x= \dfrac{-3\pm\sqrt{9+144}}{12} = \dfrac{-3\pm\sqrt{153}}{12}= \dfrac{-3-\sqrt{153}}{12}$ or $\dfrac{-3+\sqrt{153}}{12}$
Which are both equal .It was just a matter of you expanding them.


text:
Q: GcmTaskService and threading
*

*Does onRunTask run on a different thread?
This is not clearly explained in the documentation here https://developers.google.com/android/reference/com/google/android/gms/gcm/GcmTaskService. Or Is there other documentation I should look at?

*The documentation says:

Per service, two tasks with the same tag will never execute
  concurrently. Should a newly-scheduled task arrive while an existing
  task is still running, the new task will be dropped. In addition,
  different tasks may be scheduled concurrently, each invoked in a
  separate thread, if their schedules overlap. It is up to you to ensure
  thread safety when scheduling multiple tasks.

I'm confused about this part:

In addition, different tasks may be scheduled concurrently, each invoked in a
  separate thread, if their schedules overlap.

Does this still refer to a task with same tag, or is it referring to two tasks with different tags?
I was thinking it's referring to two tasks with different tags, because it says Per service, two tasks with the same tag will never execute concurrently.
In other words, my understanding is there will never be two tasks with same tag executing concurrently, but two tasks with different tags can be executed concurrently. Is this correct?


text:
Q: How do I update a document with info for a specific user using an identifier? I'm using mongoose on a nodejs & express server.
Schema:
var MatchSchema = new mongoose.Schema({
  name: String,
  // list of Strings which are their _id in User collection
  players: [String],
  geolocations: {playerId: {lat: Number, lon: Number}},
});

My routing
router.post('/:id', function(req, res) {
  Match.update(
    {_id: req.params.id},
    {
      $set: {
        `geolocation.${req.body.myPlayerId}`: {
          lat: req.body.lat,
          lon: req.body.lon
        }
      }
    }
  );
});

This will cause a syntax error: geolocation.${req.body.myPlayerId} (formatted String in ES6)
I'm fine with using a list of JS Object if that helps me solve this easier. Maybe I could rethink my design to just store the geolocation info in each User document then get all geolocation info and send it to each player when a request is made.

A: Have you tried the combination of findById and save?
Match.findById(req.params.id, function(err, matchDoc) {

    if (err) throw err;

    matchDoc['geolocations'][${req.body.myPlayerId}] = {lat: req.body.lat, lon: req.body.lon}
    matchDoc.save();
});


text:
Q: Regex adding ; to the string Is it normal for regex to add ; (semicolon) in extract? For example, in SharePoint workflow I have this [^/]*$ RegEx (with Extract selected) get the file name and put it in a collection. The RegEx puts a ; at end of the extract string.
For example:
input: http://www.abc.com/sites/sales/document library/2013 june sale 05450 12 (draft).pdf
Regex: [^/]*$
output: 2013 june sale 05450 12 (draft).pdf;
I think since it puts in a Collection Variable that's why it puts the trailing ;
What are you all opinions?

A: Since you are already using a negative character class you can as well expand it to:
[^/;]*$

It looks a little weird since you are selecting multiple characters using the star (*) but if you claim it works for you then this one should too.


text:
Q: Fundamental theorem of calculus for distributions I want to show that if $f\in C([0,1])$ and the distributional derivative $f'$ on $(0,1)$ is in $L^1((0,1))$, then
$$f(1) - f(0) = \int_0^1 f'(x)\,dx$$
I am having a lot of trouble getting started. Seems like a combination of using smooth functions and convolutions is probably how I need to go about this, but I'm having trouble coming up with a proof.

A: Let's look at $(f',\varphi)$, where the test function $\varphi$ equals $1$ on $[h,1-h]$, $0\le\varphi\le 1$, and $\varphi$ is supported by $[0,1]$. Since $f'\in L^1$, dominated convergence shows that $(f',\varphi)\to \int_0^1 f'$ as $h\to 0+$.
On the other hand,
$$
(f',\varphi)=-(f,\varphi') = -\int_0^h f(x)\varphi'(x)\, dx - \int_{1-h}^h f(x)\varphi'(x)\, dx .
$$
We can more specifically fix a smooth $\psi$ that increases from $0$ to $1$ on $[0,1]$ and then take $\varphi(x)=\psi(x/h)$ on $0\le x\le h$. Then the first integral becomes
$$
-\frac{1}{h}\int_0^h f(x)\psi'(x/h)\, dx = -\int_0^1 f(ht)\psi'(t)\, dt .
$$
By dominated convergence again, this converges to $-f(0)\int_0^1\psi' =-f(0)$ as $h\to 0+$. The second integral can be handled in the same way.

A: Given $f'\in L^1([0,1])$ let us define a function
$$g(x) = \int_0^x f'(t) dt.$$
Now for each $\phi\in \mathcal{D}([0,1])$, if we have
$$\int_0^1 [f(x)-g(x)] \phi'(x) dx = 0,$$
this implies that $f - g$ is an a.e. constant function (it is a classic result).
Since $f-g$ is continuous, when we plug in the point $0$ into $f-g$, we see that the constant function is $f(0)$ thus $f(x) = g(x) + f(0)$.


text:
Q: how to load remote m3u8 to jw player 6 via php script? hi all i am trying to load remote m3u8 using php script in jw player but i get the following error:
playlist could not be loaded: no playable sources found
could anyone tell me how to fix the above error?

get.php:
<?php
header('Access-Control-Allow-Origin: *');

if (isset($_GET['url']) && preg_match('`^http://`', $_GET['url'])) {
   echo file_get_contents('http://www.examplesite.com/'.$_GET['url'].'.m3u8');
}
?>

A: In JW6, the provider option is no longer used.
So, change this:
provider: 'video',

To this:
type: 'hls',

And you should be all set!

A: The problem is the .php, jwplayer and most others accept a limited amount of file extensions.
You need to either:
1.- Set up a rewrite rule on your server so that foo.m3u8 gets sent to foo.php and then echo the m3u8 contents through that. or;
2.- Set up a specific subdomain where m3u8 files are parsed by the PHP Interpreter and call them directly.
Also don't forget to set
header("Content-type: application/x-mpegURL");

In both cases.


text:
Q: Não consigo trazer os dados do array que esta mostrando no console import React from "react";

function TrackingResult({ data }) {
  if (!data || !data.length) return null;

  return (
    <>

Tracking Result

        {data.map(item => {
          const { data, origem, destino, status } = item;
          console.log(item.evento)
          return (

              {origem}
              data: {data}
              destino: {destino}
              status: {status}

          );
        })}

    </>
  );
}

export default TrackingResult;

A: Provável que você esteja usando o map de maneira errada ou eu desconheço essa maneira descrita aí...
Eu usaria da seguinte forma
{data.map((item, index) => {
  return (

      {item.origem}
      data: {item.data}
      destino: {item.destino}
      status: {item.status}

  );
})}

Por precaução, adicionaria um useEffect para renderizar sua tela novamente caso o data mude


text:
Q: How to cancel asyncio tasks by name? I have N number of asyncio tasks running like this.
import asyncio

def main(tasks):
   for task in tasks:
      await

asyncio.create_task(do_something(task),name=task['name'])
asyncio.run(main(tasks))

After sometime, I need to cancel only the particular task using task name.

A: You could find the task by name using asyncio.all_tasks():
task, = [task for task in asyncio.all_tasks() if task.get_name() == name]
task.cancel()

Note that get_name() requires Python 3.8. For earlier Python versions you can maintain your own name-to-task dictionary when you create the tasks.


text:
Q: Solve recurrence $T(n) = T(\frac34n) + \sqrt n$ How can I solve the following recurrence relation?
$T(n) = T(\frac34n) + \sqrt n$
I have attempted to solve it with the substitution method.
I believe that the general pattern is $T(n) = T((\frac34)^kn) + n^{\frac1{2^k}}$,
but I cannot think of what method I need to follow to reach the closed form.

A: An elementary way which doesn't use the Master Theorem could be:
$\begin{align*}
T(n) = T\left(\frac{3}{4} n\right) + \sqrt{n} \iff T(4n^2) = T(3n^2) + 2n
\end{align*}$
Thus, let us assume that $T(n) = C n^{\alpha}$ for some $C, \alpha$, is solution for the previous relation.
Then: $C(4^{\alpha} - 3^{\alpha})n^{2\alpha} = 2n$.
Then: $C(4^{\alpha} - 3^{\alpha})n^{2\alpha - 1} = 2$.
Now, this is true for all $n \in \mathbb{N}$, so $\alpha = \dfrac{1}{2}$ in order for $n^{2\alpha - 1} = 1$.
Then: $C = \dfrac{2}{\sqrt{4} - \sqrt{3}}$.
Now: $T(n) = \dfrac{2}{\sqrt{4} - \sqrt{3}} \sqrt{n}$.
Let us verify if $T$ is indeed a solution of your relation.
$\begin{align*}
T\left(\dfrac{3}{4} n\right) + \sqrt{n} & = C\sqrt{\dfrac{3}{4} n} + \sqrt{n} \\
& = \left[\dfrac{C}{2}\sqrt{3} + 1\right] \sqrt{n} \\
& = \left[\dfrac{1}{\sqrt{\frac{4}{3}} - 1} + 1\right] \sqrt{n} \\
& = \dfrac{2}{\sqrt{4} - \sqrt{3}} \sqrt{n} \\
& = C \sqrt{n} \\
& = T(n)
\end{align*}$
Which is coherent with the Master Theorem.

A: You can use the Master Theorem, for which $a=1$, $b=\frac{4}{3}$, and $d=\log_ba=0$.  Certainly $\sqrt{n}=\Omega(n^d)=\Omega(1)$.
If $\sqrt{n}$ satisfies the regularity condition, which it does(*), then the Master Theorem tells us that $T(n)=\Theta(\sqrt{n})$.

(*) The regularity condition is $\sqrt{\frac{3n}{4}}\le k \sqrt{n}$, for some $k<1$ and for all $n$ sufficiently large.  This is easily checked with $k=\sqrt{\frac{3}{4}}\approx 0.866<1$.


text:
Q: Функция в Dart/Flutter Вот функция:
getWeather(city, clientAPI) {
  return (http.get(Uri.parse('http://api.openweathermap.org/data/2.5/weather?q=$city&appid=${clientAPI}'))).then((value) => value.body);
}

Она возвращает Instance of 'Future', а мне нужно строку или словарь, или же JSON. Как это можно реализовать?

A: http.get это асинхронная функция, следовательно она будет возвращать Future. Решить эту проблему можно так:
Future<Map<String, dynamic>> getWeather(String city, String clientAPI) async {
  var response = await http.get(Uri.parse('http://api.openweathermap.org/data/2.5/weather?q=$city&appid=${clientAPI}'));

  if (response.statusCode == 200) {
    Map<String, dynamic> jsonResponse =
        convert.jsonDecode(response.body) as Map<String, dynamic>;
   return jsonResponse;
  } else {
    throw Exception('Request failed with status: ${response.statusCode}.');
  }

  return body;
}

Замете что метод getWeather тоже стал асинхронным и возвращает Future<Map<String, dynamic>>, чтобы его использовать вам также придётся использовать async/await, либо then.

Как правильно использовать: Futures, Streams и Async/Await во Flutter?


text:
Q: Wordpress in a sub-directory Ok, so I set this up:
One wordpress site in the main folder so that is at domain.com and works fine.
The other is domain.com/ja now the main page works BUT for the pages e.g. domain.com/ja/about it redirects to domain.com/about
How can I solve this?

A: It may problem with your .htaccess file.
Open your .htaccess file and change it.
    # BEGIN WordPress
    <IfModule mod_rewrite.c>

    RewriteEngine On

    RewriteBase /ja/

    RewriteRule ^index\.php$ - [L]

    RewriteCond %{REQUEST_FILENAME} !-f

    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule . /ja/index.php [L]

    </IfModule>

    # END WordPress

A: A thought you modify your wp-config file?
define( 'PATH_CURRENT_SITE', '/ja/' );


text:
Q: Google Places API - Place Details : Is the 2 letter Country Code based on any Standard? The 'address_components' node, in the Place Details service response of Google Places API, shows a Country Code under 'shot_name'. Does this code follows any particular standard like ISO 3166? In the online documentation (https://developers.google.com/places/web-service/details), its seen as if they use the 2-letter postal abbreviation.
If this is just an abbreviation from Google, is it possible to get the entire list of country codes that Google follows so as to build a mapping? Please advise.
We are currently working on a project that requires to integrate Google Places API with a system that supports both ISO-3166 2 and 3 letter codes.

A: Countries must be passed as as a two-character, ISO 3166-1 Alpha-2 compatible country code.
As stated here (same for places details): https://developers.google.com/maps/documentation/javascript/places-autocomplete


text: Q: multilabel feature selection I'm trying to find examples of implementing multi-label feature selection through using any of problem transformation methods in python, but unfortunately I couldn't found a clear example.


text:
Q: Why Joomla Bootstrap and official bootstrap have different css? I am using Joomla 3.2.1 and I did a MVC component and a menu to it so now in /components/com_MY_COMPONENT_NAME/views/ONE_VIEW_NAME/tmpl/default.php I can write any HTML/PHP I want.
I have been doing tests of some bootstrap examples and I realize that the CSS is not exactly the same.
Eg. Button btn btn-primary must has (inspecting with fire-bug in bootstrap's website):
background-color: #006DCC;
background-image: linear-gradient(#08C, #04C);

But... trying the same (coping the whole table) on my Joomla I see that the css is:
background-color: #206991;
background-image: none;

Here the result:

You can appreciate that the font-size is different, but also are line-height, border-radius and margin-bottom
This may sound quite trivial, but the point is why are different. If I continue using bootstrap classes I may find some unexpected behaviours/problems.
There is no joomla template that ensures me that using bootstrap like the original?

A: Simple answer. As Bootstrap has been progressing, then went for a new sort of style since version 3. They've gone for a more of a flat UI style.
Joomla still has Bootstrap 2.3.2 and therefore uses the older style which isn't flat. Updating the Bootstrap files on your server will be an extremely big task as so many things we're changes, for example the grid class names. I'm not sure when Bootstrap 3 will be used but I assume it might come with Joomla 4.x


text:
Q: inject html into
* with js or jquery I'm building a Chrome extension, and trying to inject HTML into a
. But it's not showing up. Here is my code:
$('.tab-nav-bar .tab-nav-bar-center ul').append('
new li
');

And here is the HTML it's being injected into:

            Files

If I do $('body').append('
'); it works fine. So I tried multiple permutations of the part that I guess is not working - eg: '.tab-nav-bar.tab-nav-bar-center.ul', 'ul.tab-nav-bar.tab-nav-bar-center' etc. but can't seem to get it.
I know (I think) my manifest.json is working since the 'body' version works, but for what it's worth, here it is:
{
  "name": "Insert HTML",
  "description": "Inserts HTMLS",
  "version": "2.0",
  "permissions": [
    "activeTab"
  ],

    "content_scripts": [
       {
          "matches":    ["https://app.asana.com/*"],
                "js": ["jquery-1.8.1.min.js", "javascript.js" ]
       }
    ],

    "web_accessible_resources": [
        "go.css",
            "shawn-test.html"
        ],

  "icons": {
      "128": "icon/icon_128.png",
      "16": "icon/icon_16.png",
      "48": "icon/icon_48.png"
  },

  "browser_action": {
    "default_title": "goo goo"
  },
  "manifest_version": 2
}

A: try
 $('ul.tab-nav-bar.tab-nav-bar-center').append('
new li
');

$('.tab-nav-bar tab-nav-bar-center ul') does not work because it will look for ul as child for .tab-nav-bar-center but in your case tab-nav-bar-center is class for ul itself. So in your case $('ul.tab-nav-bar.tab-nav-bar-center') should work.

A: You have two classes on the ul
It should be something like this
$('ul.tab-nav-bar.tab-nav-bar-center').append('
new li
');

If you are searching in 'tab-nav-div' then
$('.tab-nav-div ul.tab-nav-bar.tab-nav-bar-center').append('
new li
');

JSFiddle https://jsfiddle.net/ne76vrmy/


text:
Q: RAID 5/6 rebuild time calculation I plan to build some storage schema but I have to anticipate downtime, maintenance and rebuild Time.
Some guys said to me that a 10 disk RAID6 of 10To  (SATA) rebuild will last for about a week ! and some company policy ask for stopping activity on Array when rebuilding.
If I use RAID 5 or 6 or 5+1 or 6+1 is there an approximate formula that can give me hint on rebuild time depending on disk size and type (SAS/SATA/SSD).
something like rpm x size(Mb) x type-factor x nb-of-disk ...
I would like to be able to anticipate all rebuild time scenario depending on Size/type of RAID/type of Disk.
I know it may depend on hardware quality, but let says I am out of dedicated hardware like 3PAR / STOREWIZE / NETAPP or likes. I am using conventional servers with traditional SAS or SATA drives with software RAID.

A: The theoretical absolute minimum rebuild time is the time needed to write a complete disk worth of data : the capacity of a disk divided by the average sustained write speed a disk can maintain without cache.
(Note: that average sustained write speed  will probably be not even near the performance numbers quoted in the specs.)
Larger disks take longer.
Slower disks take longer.
Parity calculations take extra time.
Real world numbers will vary but will certainly be (much) larger and depend on your RAID level , the number of remaining disks, load on the system while the array rebuild takes place, the controller etc.
Also see What are the different widely used RAID levels and when should I consider them?

A: It depends upon your RAID controller (or software RAID stack). As others mentioned, first don't use RAID-5 with large hard drives (it's OK for up to 1TB SSDs and not much else).
In my experience, rebuild time vary largely with storage solicitation. For idle systems, most of controllers will require 36 to 72 hours to rebuild arrays of 8 to 12 TB drives (depending upon your controller type and disk size).
When the system is under IO load during rebuild, however, it's not uncommon to see this duration grow to a week length.
Notice that Helium drives have a much better reliability record than standard drives; in my experience UltraStar He drives failure rate is low enough to still make RAID-6 relevant (a typical 100 TB to 1 PB system won't see more than one rebuild in a 5 years time span).

A: You can calculate the best-case rebuild rate fairly simply: as rebuild is sequential, the needed time is capacity / transfer rate. For example, rebuilding a 10 TB disk with a 200 MB/s transfer rate needs at least 10000000 / 200 = 50000s = ~14h.
Now take this result and trow it away, as it is an overly optimistic scenario: it suppose 100% disk availability for the rebuild operation and totally sequential reads/writes. Toss in the mix some non-rebuild (ie: application) load, cap the rebuild itself to 30% (to not grind other applications to an halt) and you are suddenly in the 10x (eg: a week) rebuild time.
These long rebuild times are the reason while I avoid RAID5/6 in many system, favoring mirroring instead. Anyway, with such big drives, absolutely avoid RAID5, which is too much exposed to double failure and/or URE issues.
If you want to play with the number, give a look here


text:
Q: Converting multiple text files to a csv to create a labelled dataset I have text files in multiple folders(folder names are the names of categories/labels). I want to generate  a csv file(dataset) that also has a column as the label(folder name) of that category of text.
import csv
import os

folder = os.path.dirname("/home/jaideep/Desktop/folder/ML DS/Csv/Datasets/")
folder_list = os.listdir(folder)

with open("/home/jaideep/Desktop/folder/ML DS/Csv/data.csv", "w") as outfile:
    writer = csv.writer(outfile)
    writer.writerow(['Label', 'Email','Message'])
    for f in folder_list:
        file_list = os.listdir(folder+"/"+f+"/")
        print(file_list)
        for file in file_list:
            with open(file, "r")  as infile:
                contents = infile.read()
                outfile.write(f+',')
                outfile.write(contents)

But I'm getting
File "/home/jaideep/Desktop/folder/ML DS/Csv/Main.py", line 15, in <module>
    with open(file, "r")  as infile:

FileNotFoundError: [Errno 2] No such file or directory: 'file2.txt'

I know there are similar questions previously asked, but I couldn't file solution to my issue. Any help would be appreciated, thanks.

A: os.listdir only lists the filenames of a directory, so you need to reconstruct the path.
You may want to check out glob for that matter.
This version should solve your issue.
import csv
import os

folder = os.path.dirname("/home/jaideep/Desktop/folder/ML DS/Csv/Datasets/")
folder_list = os.listdir(folder)

with open("/home/jaideep/Desktop/folder/ML DS/Csv/data.csv", "w") as outfile:
    writer = csv.writer(outfile)
    writer.writerow(['Label', 'Email','Message'])
    for f in folder_list:
        file_list = os.listdir(os.path.join(folder, f))
        print(file_list)
        for file in file_list:
            with open(os.path.join(folder, f, file), "r")  as infile:
                contents = infile.read()
                outfile.write(f+',')
                outfile.write(contents)


text:
Q: Regex to extract text before and after dash (i.e '-') symbol I need a some R code to extract text from a character vector before the dash symbol. For instance, if I have a vector like this one:
vec <- ("1-2", "3-4", "5-6")

the first regex shoudl give me ("1", "3", "5") and the second regex should give me ("2", "4", "6")...
Thanks a million

A: first match
gsub( "(.*)-(.*)", "\\1",  c( "1234-5678", "1234-5678") )
# [1] "1234" "1234"

gsub( "(.*)-(.*)", "\\1",  c("1-2", "3-4", "5-6"))
# [1] "1" "3" "5"

second match
gsub( "(.*)-(.*)", "\\2",  c( "1234-5678", "1234-5678") )
# [1] "5678" "5678"

gsub( "(.*)-(.*)", "\\2",  c("1-2", "3-4", "5-6"))
# [1] "2" "4" "6"


text:
Q: Parsing text file in python using pyparsing I am trying to parse the following text using pyparsing.
acp (SOLO1,
     "solo-100",
     "hi here is the gift"
     "Maximum amount of money, goes",
     430, 90)

jhk (SOLO2,
     "solo-101",
     "hi here goes the wind."
     "and, they go beyond",
     1000, 320)

I have tried the following code but it doesn't work.
flag = Word(alphas+nums+'_'+'-')
enclosed = Forward()
nestedBrackets = nestedExpr('(', ')', content=enclosed)
enclosed << (flag | nestedBrackets)

print list(enclosed.searchString (str1))

The comma(,) within the quotation is producing undesired results.

A: Well, I might have oversimplified slightly in my comments - here is a more complete
answer.
If you don't really have to deal with nested data items, then a single-level parenthesized
data group in each section will look like this:
LPAR,RPAR = map(Suppress, "()")
ident = Word(alphas, alphanums + "-_")
integer = Word(nums)

# treat consecutive quoted strings as one combined string
quoted_string = OneOrMore(quotedString)
# add parse action to concatenate multiple adjacent quoted strings
quoted_string.setParseAction(lambda t: '"' +
                            ''.join(map(lambda s:s.strip('"\''),t)) +
                            '"' if len(t)>1 else t[0])
data_item = ident | integer | quoted_string

# section defined with no nesting
section = ident + Group(LPAR + delimitedList(data_item) + RPAR)

I wasn't sure if it was intentional or not when you omitted the comma between
two consecutive quoted strings, so I chose to implement logic like Python's compiler,
in which two quoted strings are treated as just one longer string, that is "AB CD " "EF" is
the same as "AB CD EF".  This was done with the definition of quoted_string, and adding
the parse action to quoted_string to concatenate the contents of the 2 or more component
quoted strings.
Finally, we create a parser for the overall group
results = OneOrMore(Group(section)).parseString(source)
results.pprint()

and get from your posted input sample:
[['acp',
  ['SOLO1',
   '"solo-100"',
   '"hi here is the giftMaximum amount of money, goes"',
   '430',
   '90']],
 ['jhk',
  ['SOLO2',
   '"solo-101"',
   '"hi here goes the wind.and, they go beyond"',
   '1000',
   '320']]]

If you do have nested parenthetical groups, then your section definition can be
as simple as this:
# section defined with nesting
section = ident + nestedExpr()

Although as you have already found, this will retain the separate commas as if they
were significant tokens instead of just data separators.


text:
Q: OCR Tesseract - Tess4J behaving weirdly I am trying to extract text out of an image. The issue is that I am using the below given code to process the image and print the extracted text.
    public class Test {

    public static void extractText(String filename)
    //    public static void main(String[] args)
    {
        System.setProperty("jna.library.path", "32".equals(System.getProperty("sun.arch.data.model")) ? "lib/win32-x86" : "lib/win32-x86-64");

        File imageFile = new File("img_perspective.png");
        Tesseract instance = Tesseract.getInstance();  // JNA Interface Mapping
    //  Tesseract1 instance = new Tesseract1(); // JNA Direct Mapping

        try {
            String result = instance.doOCR(imageFile);
            System.out.println(result);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}

When I use the main method, the OCR engine works very well and extracts the text. But when I am trying to convert this main method to the method named "extractText()" and trying to call it from another class, it throws exception:
org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.patternrecognition.preprocessing.Preprocessing] in context with path  [/ImagePreprocessing] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: com.sun.media.imageio.plugins.tiff.TIFFImageWriteParam
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1718)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1569)
at net.sourceforge.tess4j.Tesseract.doOCR(Unknown Source)
at net.sourceforge.tess4j.Tesseract.doOCR(Unknown Source)
at com.patternrecognition.preprocessing.test.extractText(test.java:19)

I don't know what is wrong with this. I am using exactly the same code with hardcoded filename. Only the method is changed.
This is so frustrating. Can someone help please.

A: Make sure jai-imageio.jar is in the classpath. And call ImageIO.scanForPlugins(); before OCR.
tess4j with Spring mvc

A: If you are using a web application, make sure the jai-imageio.jar is in WEB-INF/lib folder. It worked for me.


text:
Q: What should I learn: Quartz or OpenGL ES? I'm learning to program for the iPhone. I'm trying to figure out how to do some really cool custom view animations. What should I learn, Quartz or OpenGL ES?
For whoever says OpenGL ES, could I use it to animate my views or is only Quartz suitable for the task? Thanks.
Also any resources / the book or anything that teaches you this stuff in the most painless manner?

A: By Quartz, you probably mean Core Animation.  Quartz is simply the Mac / iPhone 2-D drawing API, where Core Animation handles animation of views and layers.
It is very difficult to use OpenGL for performing custom animations on views, but Core Animation is designed for this purpose.  It has been my recommendation to people that if they are thinking about doing 2-D animations, even in games, they should look at Core Animation first and go to OpenGL ES only if Core Animation's performance is unacceptable.  Core Animation lets you do a lot with just a little code, and there are now plenty of great references out there on the topic (such as Marcus Zarra and Matt Long's new book).
You may wish to refer to some of these other questions for more:

*

*iPhone board game: OpenGL ES or CoreGraphics?

*Core Animation or OpenGL for simple iPhone game

*Quartz 2D vs OpenGL ES Learning Curve

A: You can actually animate views without even going into Quartz. There's a lot you can do with UIKit. Apple's documentation recommends:

In general, you should use the highest-level framework that meets the requirements of your application. Use lower-level frameworks only when you need more precise control or more powerful capabilities.

A: If you want to animate your views, start with Core Animation. It can do a lot for you already. If after trying you can't get the effect you want with CoreAnimation alone, then use it in conjunction with Quartz. If that still can't suit your exact need, then only investigate OpenGL.

A: If you want to animate the movement of views around the screen then core animation is what you want.
If you want to run a custom animation inside a view then you should use OpenGLES for the best performance.
You can do both at once.


text:
Q: error with multline, but not equation I am working with the first of 3 very long equations and am trying to get it where it will be relatively easy to read. However I get the following error
! Missing } inserted.
<inserted text>
                }
l.95 \end{multline}

If I use equation instead of multline the code works, but then it is not readable since it is such a long expression.
Can anyone help me figure this out?
\documentclass[12]{article}
\usepackage{amsmath}
 \begin{document}
\begin{multline}
\dot{u}= \frac{R^2\, X_a + R^2\, X_t \\
+R_{earth}^2\, T_{13}\, g_0\, m \\
-R^2\, m\, q\, \omega \\
+R^2\, m\, r\, v \\
-R^3\, T_{13}\, T_{21}^2\, m\, \omega_{earth}^2\, \cos^2\lambda \\
-R^3\, T_{13}\, T_{31}^2\, m\, \omega_{earth}^2\, \cos^2\lambda \\
+R^2\, T_{31}\, m\, v\, \omega_{earth}\, \cos\lambda \\
-R^2\, T_{21}\, m\, \omega\, \omega_{earth}\, \cos\lambda \\
-\frac{R^3\, T_{11}\, T_{23}^2\, m\, \omega_{earth}^2\, \sin(2\lambda)}{2} \\
-\frac{R^3\, T_{11}\, T_{33}^2\, m\, \omega_{earth}^2\,\sin(2\lambda)}{2} \\
-R^2\, T_{33}\, m\, v\, \omega_{earth}\, \sin\lambda  \\
+R^2\, T_{23}\, m\, \omega\, \omega_{earth}\, \sin\lambda  \\
+R^3\, T_{11}\, T_{21}\, T_{23}\, m\, \omega_{earth}^2\, \cos^2\lambda \\
+R^3\, T_{11}\, T_{31}\, T_{33}\, m\, \omega_{earth}^2\, \cos^2\lambda \\
+\frac{R^3\, T_{13}\, T_{21}\, T_{23}\, m\, \omega_{earth}^2\, \sin(2\lambda)}{2} \\
+\frac{R^3\, T_{13}\, T_{31}\, T_{33}\, m\, \omega_{earth}^2\, \sin(2\lambda)}{2}}{R^2 \, m}
\end{multline}
\end{document}

Edit:
Thanks for all the help. Can you explain why the usage of \, is incorrect? I was under the impression that it would provide a narrow space between two adjacent symbols.

A: You can't split lines in the middle of the numerator. I suggest you to use a different approach, since the denominator is quite short:
\documentclass[12pt]{article}
\usepackage{amsmath}

\begin{document}
\begin{multline}
\dot{u}=\frac{1}{R^2m}\Bigl(
  R^2 X_a + R^2 X_t
  +R_{\mathrm{earth}}^2 T_{13} g_0 m
  -R^2 m q \omega
  +R^2 m r v
\\
  -R^3 T_{13} T_{21}^2 m \omega_{\mathrm{earth}}^2 \cos^2\lambda
  -R^3 T_{13} T_{31}^2 m \omega_{\mathrm{earth}}^2 \cos^2\lambda
\\
  +R^2 T_{31} m v \omega_{\mathrm{earth}} \cos\lambda
  -R^2 T_{21} m \omega \omega_{\mathrm{earth}} \cos\lambda
\\
  -\tfrac{1}{2}R^3 T_{11} T_{23}^2 m \omega_{\mathrm{earth}}^2 \sin(2\lambda)
  -\tfrac{1}{2}R^3 T_{11} T_{33}^2 m \omega_{\mathrm{earth}}^2\sin(2\lambda)
\\
  -R^2 T_{33} m v \omega_{\mathrm{earth}} \sin\lambda
  +R^2 T_{23} m \omega \omega_{\mathrm{earth}} \sin\lambda
\\
  +R^3 T_{11} T_{21} T_{23} m \omega_{\mathrm{earth}}^2 \cos^2\lambda
  +R^3 T_{11} T_{31} T_{33} m \omega_{\mathrm{earth}}^2 \cos^2\lambda
\\
  +\tfrac{1}{2}R^3 T_{13} T_{21} T_{23} m \omega_{\mathrm{earth}}^2 \sin(2\lambda)
  +\tfrac{1}{2}R^3 T_{13} T_{31} T_{33} m \omega_{\mathrm{earth}}^2 \sin(2\lambda)
\Bigr)
\end{multline}
\end{document}

Note that I removed all \, which are not required and are actually wrong. Also the "earth" subscripts have been rendered in upright type.
Also the inner fractions with denominator 2 have been rendered with 1/2 as coefficient.

A: An alternate presentation may be more readable:
\documentclass[12]{article}
\usepackage{amsmath}
\def\oea{\omega_\mathrm{earth}}
\begin{document}
\begin{equation}
\dot{u}= \frac{A+B+C+D+E+F}{R^2 \, m}
\end{equation}
where
\[
\begin{aligned}
A =& +R^2\, X_a + R^2\, X_t \\
&+R_{earth}^2\, T_{13}\, g_0\, m \\
&-R^2\, m\, q\, \omega \\
&+R^2\, m\, r\, v \\
&-R^3\, T_{13}\, T_{21}^2\, m\, \oea^2\, \cos^2\lambda \\
&-R^3\, T_{13}\, T_{31}^2\, m\, \oea^2\, \cos^2\lambda \\
&+R^2\, T_{31}\, m\, v\, \oea\, \cos\lambda \\
&-R^2\, T_{21}\, m\, \omega\, \oea\, \cos\lambda \\\\
B =& -\frac{R^3\, T_{11}\, T_{23}^2\, m\, \oea^2\, \sin(2\lambda)}{2} \\\\
C =& -\frac{R^3\, T_{11}\, T_{33}^2\, m\, \oea^2\,\sin(2\lambda)}{2} \\\\
D =&-R^2\, T_{33}\, m\, v\, \oea\, \sin\lambda  \\
&+R^2\, T_{23}\, m\, \omega\, \oea\, \sin\lambda  \\
&+R^3\, T_{11}\, T_{21}\, T_{23}\, m\, \oea^2\, \cos^2\lambda \\
&+R^3\, T_{11}\, T_{31}\, T_{33}\, m\, \oea^2\, \cos^2\lambda \\\\
E =& +\frac{R^3\, T_{13}\, T_{21}\, T_{23}\, m\, \oea^2\, \sin(2\lambda)}{2} \\\\
F =& +\frac{R^3\, T_{13}\, T_{31}\, T_{33}\, m\, \oea^2\, \sin(2\lambda)}{2}
\end{aligned}
\]
\end{document}

A: This produces a multiline expression in the numerator but the result isn't really readable, it would be better to restructure the formula and perhaps name some subterms
\documentclass[12pt]{article}
\usepackage{amsmath}
 \begin{document}
\newcommand\omea{\omega_{\mathrm{earth}}}
\begin{equation}
\dot{u}= \frac{
\begin{aligned}R^2\, X_a + R^2\, X_t \\
+R_{earth}^2\, T_{13}\, g_0\, m \\
-R^2\, m\, q\, \omega \\
+R^2\, m\, r\, v \\
-R^3\, T_{13}\, T_{21}^2\, m\, \omea^2\, \cos^2\lambda \\
-R^3\, T_{13}\, T_{31}^2\, m\, \omea^2\, \cos^2\lambda \\
+R^2\, T_{31}\, m\, v\, \omea\, \cos\lambda \\
-R^2\, T_{21}\, m\, \omega\, \omea\, \cos\lambda \\
-\frac{R^3\, T_{11}\, T_{23}^2\, m\, \omea^2\, \sin(2\lambda)}{2} \\
-\frac{R^3\, T_{11}\, T_{33}^2\, m\, \omea^2\,\sin(2\lambda)}{2} \\
-R^2\, T_{33}\, m\, v\, \omea\, \sin\lambda  \\
+R^2\, T_{23}\, m\, \omega\, \omea\, \sin\lambda  \\
+R^3\, T_{11}\, T_{21}\, T_{23}\, m\, \omea^2\, \cos^2\lambda \\
+R^3\, T_{11}\, T_{31}\, T_{33}\, m\, \omea^2\, \cos^2\lambda \\
+\frac{R^3\, T_{13}\, T_{21}\, T_{23}\, m\, \omea^2\, \sin(2\lambda)}{2} \\
+\frac{R^3\, T_{13}\, T_{31}\, T_{33}\, m\, \omea^2\, \sin(2\lambda)}{2}
\end{aligned}}{R^2 \, m}
\end{equation}
\end{document}


text:
Q: Alternative to loop for for boolean / nonzero indexing of numpy array I need to select only the non-zero 3d portions of a 3d binary array (or alternatively the true values of a boolean array).  Currently I am able to do so with a series of 'for' loops that use np.any, but this does work but seems awkward and slow, so currently investigating a more direct way to accomplish the task.
I am rather new to numpy, so the approaches that I have tried include a) using
np.nonzero, which returns indices that I am at a loss to understand what to do with for my purposes, b) boolean array indexing, and c) boolean masks.  I can generally understand each of those approaches for simple 2d arrays, but am struggling to understand the differences between the approaches, and cannot get them to return the right values for a 3d array.
Here is my current function that returns a 3D array with nonzero values:
def real_size(arr3):
    true_0 = []
    true_1 = []
    true_2 = []
    print(f'The input array shape is: {arr3.shape}')

    for zero_ in range (0, arr3.shape[0]):
        if arr3[zero_].any()==True:
            true_0.append(zero_)
    for one_ in range (0, arr3.shape[1]):
        if arr3[:,one_,:].any()==True:
            true_1.append(one_)
    for two_ in range (0, arr3.shape[2]):
        if arr3[:,:,two_].any()==True:
            true_2.append(two_)

    arr4 = arr3[min(true_0):max(true_0) + 1, min(true_1):max(true_1) + 1, min(true_2):max(true_2) + 1]
    print(f'The nonzero area is: {arr4.shape}')
    return arr4

# Then use it on a small test array:
test_array = np.zeros([2, 3, 4], dtype = int)
test_array[0:2, 0:2, 0:2] = 1

#The function call works and prints out as expected:
non_zero = real_size(test_array)
>> The input array shape is: (2, 3, 4)
>> The nonzero area is: (2, 2, 2)

# So, the array is correct, but likely not the best way to get there:
non_zero

>> array([[[1, 1],
        [1, 1]],

       [[1, 1],
        [1, 1]]])

The code works appropriately, but I am using this on much larger and more complex arrays, and don't think this is an appropriate approach.  Any thoughts on a more direct method to make this work would be greatly appreciated.  I am also concerned about errors and the results if the input array has for example two separate non-zero 3d areas within the original array.
To clarify the problem, I need to return one or more 3D portions as one or more 3d arrays beginning with an original larger array.  The returned arrays should not include extraneous zeros (or false values) in any given exterior plane in three dimensional space.  Just getting the indices of the nonzero values (or vice versa) doesn't by itself solve the problem.

A: Assuming you want to eliminate all rows, columns, etc. that contain only zeros, you could do the following:
nz = (test_array != 0)
non_zero = test_array[nz.any(axis=(1, 2))][:, nz.any(axis=(0, 2))][:, :, nz.any(axis=(0, 1))]

An alternative solution using np.nonzero:
i = [np.unique(_) for _ in np.nonzero(test_array)]
non_zero = test_array[i[0]][:, i[1]][:, :, i[2]]

This can also be generalized to arbitrary dimensions, but requires a bit more work (only showing the first approach here):
def real_size(arr):
    nz = (arr != 0)
    result = arr
    axes = np.arange(arr.ndim)
    for axis in range(arr.ndim):
        zeros = nz.any(axis=tuple(np.delete(axes, axis)))
        result = result[(slice(None),)*axis + (zeros,)]
    return result

non_zero = real_size(test_array)


text:
Q: Поиск четвертого двузначного четного числа Как в найти четвёртое двузначное чётное число, которое при умножении на 16 больше 300?

for (let i = 10; i <= 99; i += 4){
     if (i % 2 == 0 && 16 * i > 300){
         document.write(i)
         break;
      }
 }

A:

var count = 0;
var i;
for (i = 10; i <= 99; i += 2) {
  if (16 * i > 300) {
    if (++count == 4)
      break;
  }
}
console.log(count, i);

A:

// Первое число, которое при умножении на 16 дает число больше, чем 300
let start = Math.ceil(301 / 16);
if (start < 10) // Если оно однозначное
  start = 10;  // то тогда первое двузначное будет 10
else if (start % 2)  // если оно не однозначное, но нечетное
  start++;  // значит нам нужно следующее число
// Теперь нужно просто найти четвертое четное число, считая от текущего
const end = start  + (4 - 1) * 2;
console.log(end);