text:
Q: Safely and efficiently parse and replace tokens in a string I'm trying to write a VBA function that will do some parsing / replacement according to tokens / placeholders.
Example:
Input: "Username %u, date is %d."
The function would replace %d with the current date and %u with the current username.
Sounds simple to implement, but here's a twist:
Regexps and Replace() are not safe. In the example above, if %u after replacement would contain another token (let's say "Andy%d"), there will be a recursive replacement and the output will mangled: "Username Andy20170820, date is 20170820".
I could write this efficiently in C++ or some other "proper" language but I'm relegated to the VBA. I don't want to work on Chars inside a string as that doesn't look very efficient (and I might be using this formula to parse 10000 lines in an Excel sheet).
Searched and googled and even DuckDuckWent but to no avail.

A: Actually, avoiding recursive replacement is quite easy - one would just loop through each char and replace on-the-fly, never coming back and avoiding the potential corruption. As I had originally written, what I had in my mind was a simple and elegant C++ parsing loop. Ported to VBA it would look horrible and be slow (the more I code in VBA the more I miss C++/C#).
Hence, here's another solution that is very robust and looks rather efficient, even though not as terse as one would like.
Tested, works. Safe, extendable and logical.

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'' Replace magic symbols (placeholders) with dynamic data.
''
'' Arguments: a string full of magic.
''
'' Placeholders consist of one symbol prepended with a %:
''    %d - current date
''    %t - current time
''    %u - username (user ID)
''    %n - full user name (usually name and surname)
''    %% - literal % (placeholder escape)
''    Using an unsupported magic symbol will treat the % literally, as if it had been escaped.
''    A single placeholder terminating the string will also be treated literally.
''    Magic symbols are case-sensitive.
''
'' Returns:   A string with no magic but with lots of beauty.
''
'' Examples:
'' "Today is %d" becomes "Today is 2018-01-26"
'' "Beautiful time: %%%t%%" yields "Beautiful time: %16:10:51%"
'' "There are %zero% magic symbols %here%.", true to its message, outputs "There are %zero% magic symbols %here%."
'' "%%% looks lovely %%%" would show "%% looks lovely %%" - one % for the escaped "%%" and the second one for the unused "%"!
''
'' Alexander Ivashkin, 26 January 2018
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function AI_ParseMagicSymbols(ByVal TextToParse As String) As String

Dim sFinalResult As String
Dim aTokenizedString() As String
Dim sTempString As String
Dim sPlaceholder As String
Dim sCurrentString As String
Dim iIterator As Integer
Dim iTokenizedStringSize As Integer
Dim bThisStringHasPlaceholder As Boolean

' Default placeholder is "%"
Const cPlaceholderSymbol As String = "%"

aTokenizedString = Split(Expression:=TextToParse, Delimiter:=cPlaceholderSymbol)
iTokenizedStringSize = UBound(aTokenizedString())
bThisStringHasPlaceholder = False
sFinalResult = ""

For iIterator = 0 To iTokenizedStringSize
sCurrentString = aTokenizedString(iIterator)

If bThisStringHasPlaceholder Then
    If sCurrentString <> "" Then
    sPlaceholder = Left(sCurrentString, 1)
    sTempString = Right(sCurrentString, Len(sCurrentString) - 1)

    ' This is the place where the MAGIC happens
    Select Case sPlaceholder
        Case "d":
        sCurrentString = Date & sTempString
        Case "t":
        sCurrentString = Time & sTempString
        Case "u":
        sCurrentString = Environ$("Username") & sTempString
        Case "n":
        sCurrentString = Environ$("fullname") & sTempString
        Case Else:
        sCurrentString = cPlaceholderSymbol & sCurrentString
    End Select
    Else
    ' We had two placeholders in a row, meaning that somebody tried to escape!
    sCurrentString = cPlaceholderSymbol
    bThisStringHasPlaceholder = False
    End If
End If

sFinalResult = sFinalResult & sCurrentString

If sCurrentString = "" Or (iIterator + 1 <= iTokenizedStringSize And sCurrentString <> cPlaceholderSymbol) Then
    ' Each string in the array has been split at the placeholders. If we do have a next string, then it must contain a magic symbol.

    bThisStringHasPlaceholder = True
    ' Even though it is called "...ThisString...", it concerns the NEXT string.
    ' The logic is correct as we will check this variable on the next iteration, when the next string will become ThisString.
Else
    bThisStringHasPlaceholder = False
End If

Next iIterator

AI_ParseMagicSymbols = sFinalResult

End Function


text:
Q: Ansible using AWS interactions throws exception I was trying to run a playbook to automate AWS but i encountered this exception which I can't understand. I have the following playbook:
- name: Just for testing
  hosts: windows-server
  gather_facts: no
  vars:
    aws_a_key: accesskey
    aws_s_key: secretkey
  tasks:
    - name: Ping
      win_ping:
    - name: Create a file to C:\Temp\test.conf
      win_file:
        path: C:\Temp\test.conf
        state: touch
    - name: Create another file to C:\Temp\test2.conf
      win_file:
        path: C:\Temp\test2.conf
        state: touch
    - name: Gather S3 facts
      aws_s3_bucket_facts:
        aws_access_key: "{{ aws_a_key }}"
        aws_secret_key: "{{ aws_s_key }}"
        region: eu-central-1

When I try to execute it I get the following error:
PLAY [Just for testing] *******************************************************************************************************

TASK [Ping] *******************************************************************************************************************
ok: [WIN-40NQ43PHHA5]

TASK [Create a file to C:\Temp\test.conf] *************************************************************************************
changed: [WIN-40NQ43PHHA5]

TASK [Create another file to C:\Temp\test2.conf] ******************************************************************************
changed: [WIN-40NQ43PHHA5]

TASK [Gather S3 facts] ********************************************************************************************************
fatal: [WIN-40NQ43PHHA5]: FAILED! => {"changed": false, "module_stderr": "Exception calling \"Create\" with \"1\" argument(s): \"At line:4 char:21
+ def _ansiballz_main():
+                     ~
An expression was expected after '('.
At line:12 char:27
+     except (AttributeError, OSError):
+                           ~
Missing argument in parameter list.
At line:14 char:7
+     if scriptdir is not None:
+       ~
Missing '(' after 'if' in if statement.
At line:21 char:7
+     if sys.version_info < (3,):
+       ~
Missing '(' after 'if' in if statement.
At line:21 char:30
+     if sys.version_info < (3,):
+                              ~
Missing expression after ','.
At line:21 char:25
+     if sys.version_info < (3,):
+                         ~
The '<' operator is reserved for future use.
At line:23 char:32
+         MOD_DESC = ('.py', 'U', imp.PY_SOURCE)
+                                ~
Missing expression after ','.
At line:23 char:33
+         MOD_DESC = ('.py', 'U', imp.PY_SOURCE)
+                                 ~~~~~~~~~~~~~
Unexpected token 'imp.PY_SOURCE' in expression or statement.
At line:23 char:32
+         MOD_DESC = ('.py', 'U', imp.PY_SOURCE)
+                                ~
Missing closing ')' in expression.
At line:23 char:46
+         MOD_DESC = ('.py', 'U', imp.PY_SOURCE)
+                                              ~
Unexpected token ')' in expression or statement.
Not all parse errors were reported.  Correct the reported errors and try again.
\"
At line:6 char:1
+ $exec_wrapper = [ScriptBlock]::Create($split_parts[0])
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ParseException

The expression after '&' in a pipeline element produced an object that was not valid. It must result in a command
name, a script block, or a CommandInfo object.
At line:7 char:2
+ &$exec_wrapper
+  ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : BadExpression
 ", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
    to retry, use: --limit @/Users/mpolgardi/ansible/test_playbook.retry

PLAY RECAP ********************************************************************************************************************
WIN-40NQ43PHHA5            : ok=3    changed=2    unreachable=0    failed=1

Can someone help me decode this error? I have no idea where to even look. Also is there a way for ansible to give me readable error messages?

A: According to the fine manual, use of aws_s3_bucket_facts requires python with both the boto and boto3 modules available to it.
What appears to be happening to you is that the windows machine is trying to execute that .py file as if it were PowerShell, and (of course) those two syntaxes are wholly incompatible.
Do you have ansible_python_interpreter set to a working binary? It is possible that switching gather_facts: to yes will surface any misconfiguration earlier, although I can't swear to it since I don't know if the winrm connection pre-empts fact gathering using just PowerShell, and wouldn't notice a bogus ansible_python_interpreter value.
While this isn't exactly what you asked, it's also quite a common behavior to use delegate_to: localhost and/or connection: local for those AWS-y tasks, since there is little to no value in having those tasks run on the target machine, given that the credentials are already present in the playbook (that is: it doesn't acquire credentials from anything on the target machine). That presumes, naturally, that you have a local python which has boto and boto3 installed in them, but that's presumably far more likely than convincing a random windows machine to work correctly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error when testing gpload based on windows When i try to execute gpload from Windows based ETL host.
Using gpload in a Windows environment produces the following error:
Error I Get:

gpload.py -f gpload.yml

gpload was unable to import The PyGreSQL Python module (pg.py) - DLL load failed with error code 193

A: You should check whether your pygresql installed correctly or not. Because from the gpload code
try:
    from pygresql import pg
except Exception, e:
    errorMsg = "gpload was unable to import The PyGreSQL Python module (pg.py) - %s\n" % str(e)
    sys.stderr.write(str(errorMsg))
    sys.exit(2)

we can know that this is an error about import pygresql (installed or not, version is right ?). If pygresql installed correctly, whether python version or PATH is right ? Please check them.


text:
Q: programming processing, can't bind to udp port in network I have a processing program working on a local machine. It reads data from a local udp port and uses this data to draw circles on my screen. It works, so that great.
But in production the program has to run on an other computer. And I cant get it to work. Processing is presenting me this error message:
opening socket failed!
> address:192.168.1.118, port:6666 [group:null]
> Cannot assign requested address: Cannot bind

Of cource I checked the IP adress and these are OK as it works fine on the local machine. Here is my code for the UDP part:
// import UDP library
import hypermedia.net.*;

String HOST_IP = "192.168.1.118";
UDP udp;  // define the UDP object

// get an array ready
int num = 20;
int[] xx = new int[num];
int[] yy = new int[num];

void setup() {
size(1024, 768);
smooth();
//noStroke();

// create a new datagram connection on port 6666
udp = new UDP(this, 6666, HOST_IP);
udp.listen( true );
}

//process events
void draw() {;}
/**
* To perform any action on datagram reception, you need to implement this
* handler in your code. This method will be automatically called by the UDP
* object each time he receive a nonnull message.
* By default, this method have just one argument (the received message as
* byte[] array), but in addition, two arguments (representing in order the
* sender IP address and his port) can be set like below.
*/
// void receive( byte[] data ) {       // <-- default handler
void receive( byte[] data ) {

background(255);

// get the "real" message =
// forget the ";\n" at the end <-- !!! only for a communication with Pd !!!

 data = subset(data, 0, data.length-2);
String message = new String( data );

// print the result
println(message );

On both machines I use Windows XP And they are connected via a switch and udp cables.
I don't know where to start troubleshooting and how. Any ideas?


text:
Q: Using custom objects with accounts This is my first time working with salesforce and I'm having a hard time finding information on what I can and can't do. I have professional edition.
Here's what I'm trying to do:
I have a group of fields that only apply to certain account types. There seems to be "record type" functionality for enterprise but since I don't have that I'm trying to do it with objects.
So when adding or editing an account I want a button to add a custom object that will be linked to the account, or if one already exists to simply edit the object. I'm able to define objects but I don't understand how to create an instance and link it to the account in question. I was able to create an instance of my object via a chatter action and link it manually with it's id and a lookup field but that's way too complicated for users. How do I make a "Add/Edit Object" button or link that takes care of this?
Also is there a decent resource for learning this stuff that I should go through? Everything I've found seems unrelated to the level of customization I'm attempting.

A: Generally speaking, a Professional Edition (PE) Org doesn't have access to Apex, Triggers or workflow rules that could be used to automate the creation and association of the custom object.
If you can get the Org updated to an Enterprise Edition (EE) Org you can create apex code behind the button or a trigger to perform the required actions. Of course, if that was the case you could use record types as you have already noted.
You might be able to hack something together using an OnClick JavaScript Custom Button with the optional Professional Edition API purchase. See also: OnClick JavaScript in PE

If you just want to allow users to associate the Account with a custom object you can create a lookup relationship between the two. See Overview of Object Relationships.

Even something like related lists for these objects would kind of work I guess

A Master Detail relationship from your custom object to Account will give you default controls like related lists. It does restrict your custom objects to only being related to a single Account though, so you can't reuse them across multiple Accounts.


text:
Q: Rational point in the sense of Serre In Serre's Algebraic groups and class fields Chapter V.1, he gave the following definition of a point $P$ rational over a field $K$:
We first fix a base field $k$ that is algebraically closed and $X$ is a nonsingular projective irreducible algebraic curve defined over $k$. Make a choice of a universal domain $\Omega$; this is an algebraically closed extension of $k$ of infinite transcendence degree over $k$. And then he wrote

By a point of $X$, we mean a point $P$ all of whose coordinates belong to $\Omega$; if we denote by $k(P)$ the field generated over $k$ by these coordinates, $k(P)$ is an extension of finite type over $k$. One says that $P$ is rational over a field $K$ if $k(P) \subset K$.

How does this compare to the usual definition that a $K$-rational point of $X$ implies that we have a morphism $\mathrm{Spec}\, K \rightarrow X$? Or is this a different concept totally?


text:
Q: Why Spring Boot inject same HttpServletResponse object to my Controller method for different request? I wonder why spring boot inject same response object to my controller method  parameter for different request, i use it like follow:
@Controller
@Slf4j
@Profile("default")
@RequestMapping("/test")
public class TestController {
    @RequestMapping("/test")
    @ResponseBody
    public void getDeviceImage(@RequestParam("serialNumber") String serialNumber, HttpServletResponse response) {
        return balabala;
    }
}

I add a breakpoint before return command, and i find that response object's address is same for different request.
I want to write some thing to response.getOutputStream(), and i found there exists previous buffered data.

A: HttpServletResponse can be used if you need to add some extra meta information like cookies etc. By default even if you don't specify HttpServletResponse in the arguments, in typical MVC, model is added to the newly constructed response before propagating to the view.
If you just need to return some response back, say a model or entity or a simple JSON, you don't  have to manually mess the HttpServletResponse. Unless you want to dig through cookies or headers etc.,. In your code, if you don't need to care about this, you might probably not need it.
As per the API doc for HttpServletResponse:

The servlet container creates an HttpServletResponse object and passes
  it as an argument to the servlet's service methods (doGet, doPost,
  etc).

What you see is probably the default configurations that Spring sets up.
With @ResponseBody, the return type is directly written back to response.
https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-responsebody

A: Finally, i find Response will been reused all the time, and Response's recycle method will been invoked for each request(org.apache.catalina.connector.Response#recycle).
But by default facade&outputStream&writer will not been cleaned, so i make system property "org.apache.catalina.connector.RECYCLE_FACADES" to be "true", after that issue disappears.


text:
Q: how to log hibernate parameters I have project pf JPA. My logs looks like this:
Hibernate: insert into TEST(DESCRIPTION, NAME, version, id) values (?, ?, ?, ?)
[08/12/14 06:26:26:026 GET] TRACE sql.BasicBinder: binding parameter [1] as [VARCHAR] - [desc]
[08/12/14 06:26:26:026 GET] TRACE sql.BasicBinder: binding parameter [2] as [VARCHAR] - [name]
[08/12/14 06:26:26:026 GET] TRACE sql.BasicBinder: binding parameter [3] as [INTEGER] - [0]
[08/12/14 06:26:26:026 GET] TRACE sql.BasicBinder: binding parameter [4] as [BIGINT] - [21]

I have trace of org.hibernate.type in log4j configuration. That's nice, but is there any way to write this type of output?
Hibernate: insert into TEST(DESCRIPTION, NAME, version, id) values (desc, name, 0, 21)

I was searching that in google, I can't manage to find this type of solution. This output looks readable, and easy to read log files. Why this does not have hibenrate?
My configuration is like that:
<category name="org.hibernate.type">
    <priority value="trace" />
</category>

A: I doubt this could be possible out of the box from Hibernate. You could explicitly proxy the connection, statement and prepared statements that are created by your application (using a decorator design pattern) and log the parameters that passed.

A: Use slf4j + Log4j
<dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.1</version> <!-- Use the latest version instead -->
    </dependency>

log4j.properties
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

# Root logger option
log4j.rootLogger=INFO, file, stdout

# Log everything. Good for troubleshooting
log4j.logger.org.hibernate=INFO

# Log all JDBC parameters
log4j.logger.org.hibernate.type=ALL

hibernate.cfg.xml
<property name="show_sql">true</property>

Now parameters will be logged.


text:
Q: How to add contact without adding Phone/Mobile number? I am trying to create a contact using ContentProviderOperation where basic idea is to create a contact which might don't have Phone or Mobile number at all but may have some other type of contact number which is adding using Phone.TYPE_CUSTOM with different label. Here is a code:
//ArrayList<ContentProviderOperation> ops;

 ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                        .withValue(ContactsContract.Contacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, mobileNumber)
                        .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                        .build());

                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                        .withValue(ContactsContract.Contacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber)
                        .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
                        .build());

and some contact type:
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                            .withValue(ContactsContract.Contacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber)
                            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM )
                            .withValue(ContactsContract.CommonDataKinds.Phone.LABEL, "Emergency: "+name+" "+surname+" 11111")
                            .build());

it don't create a main contact if both mobileNumber and phoneNumber are empty so if i provide some value of phoneNumber/mobileNumber then contact is create which containing custom contact information as well. So is there any way to create contact without Phone.TYPE_HOME/Phone.TYPE_MOBILE ?


text:
Q: Making gnome see xkb changes This is on Oracle Linux 6.3, but I bet it applies to any Gnome based distros.
I have edited /usr/share/X11/xkb/symbols/ru, to add a layout section:
partial alphanumeric_keys
xkb_symbols "stdwin" {
include "ru(common)"

name[Group1]= "Russian (stdwin)";

key <AE03> { [ 3, numerosign ] };
key <AE04> { [ 4, semicolon ] };
key <AE05> { [ 5, percent ] };
key <AE06> { [ 6, colon ] };
key <AE06> { [ 6, colon ] };
key <AE07> { [ 7, question ] };
key <AE08> { [ 8, asterisk ] };
key <AB10> { [ period, comma ] };
};

I've updated symbols.dir using xkbcomp: xkbcomp -lhlpR '*' -o ../symbols.dir
I've manually updated /usr/share/X11/xkb/rules/evdev.lst and /usr/share/X11/xkb/rules/evdev.xml.
If I try running gnome-keyboard-properties under strace, I can see it's reading the updated evdev.lst file. But it still won't ever show my new layout in the layout list.
I know that layout works, at least by xkb. If I run setxkbmap -variant stdwin, the proper layout becomes active, and I can normally use it.
What have I missed to make the gnome keyboard configuration applet (gnome-keyboard-properties) pick it up?


text:
Q: Exception for the proof of Cauchy's theorem Suppose a closed countour defined as:
$$
\begin{cases}
0 & y=1\mbox{, and,}0<x\leq1\\
1 & x=0\mbox{, and,}0\leq y\leq1\\
1 & x=1\mbox{, and,}0\leq y<1\\
x^{3}\sin(\frac{\pi}{x}) & y=0\mbox{, and,}0<x<1
\end{cases}
$$
Where $z=x+iy$.
This would look like:

Near the origin the countour varies infinite times.
Now, in many proofs of the Cauchy-Goursat theorem, we start with a triangle. We prove it for that case, then we generalize the theorem saying tha we can decompose any domain into triangles (intuitively, this is correct for most shapes).
But I can't see how this is possible near the origin, because it's too curvy (no triangule will fit there.
Is this case not considered in the proof or my intuition is wrong?

A: I don't know what proofs you have read, the ones I know proceed as follows:

*

*(Goursat) the integral over the boundary of each triangle (or rectangle) vanishes.

*From that follows that a holomorphic function defined on a convex domain (disk) has a primitive.

*(Cauchy's integral theorem for convex domains/disks), in a convex domain (disk), the integral of a holomorphic function over a closed path vanishes. That follows directly from the existence of a primitive and the fundamental theorem of calculus. Let $f$ be the holomorphic function, and $F$ its primitive. If we parameterize the path $\gamma \colon [a,b]\to \Omega$, and let $a = t_0 < t_1 < \dotsc < t_n = b$ be a partition such that $\gamma\lvert_{[t_{k-1},t_k]}$ is continuously differentiable for $1 \leqslant k \leqslant n$, then $$\begin{align}\int_\gamma f(z)\,dz &= \sum_{k=1}^n \int_{t_{k-1}}^{t_k} f(\gamma(t))\cdot \gamma'(t)\,dt\\ &= \sum_{k=1}^n \int_{t_{k-1}}^{t_k} (F\circ\gamma)'(t)\,dt\\ &= \sum_{k=1}^n F(\gamma(t_k)) - F(\gamma(t_{k-1}))\\ &= F(\gamma(b)) - F(\gamma(a)).\end{align}$$ If the path is closed, the last difference is $0$.

*Generalisation, all holomorphic functions have local primitives, and the integral of a holomorphic function over all null-homologous cycles vanishes.

At no point does one need to decompose a general contour into triangles, the existence of local primitives is the tool that yields all further results.


text:
Q: How to draw r = (20 day moving average / 20 weeks moving average) graph using cufflinks in python 3.x? I know how to draw MA20 an MA50 using python3 and cufflinks.
import pandas as pd
import yfinance as yf
df_twtr = yf.download('TWR',
                       start='2015-01-01',
                       end='2017-12-31',
                       progress=False,
                       auto_adjust=True)
import cufflinks as cf
from plotly.offline import iplot, init_notebook_mode

cf.go_offline()
init_notebook_mode()
qf = cf.QuantFig(df_twtr, title="TWR Price",
                 legend='top', name='TWR')
qf.add_volume()
qf.add_sma(periods=20, column='Close', color='red')
qf.add_sma(periods=50, color='green')
qf.iplot()

How can I draw another metric i.e. r = (20 day moving average / 20 week moving average) and add them to the same plot? if cufflinks  cannot do that, any other method or package is fine for me.

A: I found the answer. I used pandas to do that. here is the solution just in case somebody needs it:
# get data from yahoo
df = pdr.get_data_yahoo('VOO', start=start_date, end=end_date)

ma50d=df['Close'].rolling(50).mean()
ma50w=df['Close'].rolling(50*7).mean()
ratio1=ma50d.divide(ma50w, fill_value=0)

plt.plot(ratio1,label= 'Voo')
plt.legend(loc='best')
plt.title('VOO')
#plt.yscale("log") #logarithmic plot
plt.show()


text:
Q: ArcPy changing scalebar and grid parameters I'm trying to use ArcPy in ArcMap, so Python 2.7, to automate the basics for the maps I make on a daily basis. Rather than having myself setout certain elements I want Python via the ArcMap API to do it for me.
So far I have the maps created, datasource, extent sorted, captions updated etc. Now I turn to the grid and scale bar.
In my script the layout view is set to the extent of a feature class (plus a buffer either side), this means the scale bar and graticule grid changes based on the extent.
How do I get access to the properties in the scalebar/grid?
When it comes to captions I use the following and update the placeholder text:
for elm in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
    if elm.text == current_text:
        elm.text = text

I've seen in 2010 posts that ArcPy is not yet ready for altering scale bar and grid properties, has the situation changed?
Using this I can get to the width parameter but I want to set the division value
for elm in arcpy.mapping.ListLayoutElements(mxd, "MAPSURROUND_ELEMENT"):
    elm[1].elementWidth=11


text:
Q: Unable to show Dashboard of fabric I have installed the fabric, integrated jar files and API key.
I installed fabric plugin, sign in, crashlytics, answers, and crash.
In gradle, I add 2 meta data in AndroidManifest.
 <meta-data
        android:name="io.fabric.ApiKey"
        android:value="***" />

    <meta-data
        android:name="firebase_crashlytics_collection_enabled"
        android:value="false" />

I add maven and... in project gradle.
maven {
        url 'https://maven.fabric.io/public'
    }
classpath 'com.google.gms:google-services:4.2.0'
classpath 'com.google.firebase:firebase-plugins:1.2.0'
classpath 'io.fabric.tools:gradle:1.28.1'

I did all the necessary work, but fabric dashboard is not showing.
None of 3 steps have been taken, but I do it all.

A: Kevin from Fabric/Firebase here - are you integrating with Fabric or Firebase Crashlytics instructions (https://fabric.io/kits/android/crashlytics/install vs https://firebase.google.com/docs/crashlytics/get-started?platform=android)?
If you reach out to support@fabric.io with your app's package name and a link to this post, we can take a closer look at what's going wrong with the onboarding process for your app.


text:
Q: Wordpress, inserting URL in a shortcode I'm trying to display/insert a url into the shortcode below:
<?php echo do_shortcode('[sc_embed_player fileurl="http://www.example.com/wp-content/uploads/my-music/mysong.mp3"]'); ?>

I'm using a ACF field called "add_audio" which is a mp3 URL.
I used the default get field ( <?php the_field('field_name'); ?> )
code to call the the url.
I made a variable too and called ($variable) too.
But nothing worked!!
Here's the error i get

"Prase error:syntax error, unexpected 'add_audio'(T_STRING),
  expecting,''or')'in
  /app/public/wp-content/oxygen/component-framework/components/layouts/code-block.php(33):eval()'d
  code on line 43"

I used Oxygenbuilder plugin and ACF plugins.
<?php
/*
 * Easy Query Shortcode
 * [easy_query container="div" template="template_906184" posts_per_page="20" post_type="audio_files"]
 */
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
  'post_type' => array('audio_files'),
  'post_status' => 'publish',
  'order' => 'DESC',
  'orderby' => 'date',
  'posts_per_page' => 20,
  'paged' => $paged,
);

// WP_Query
$eq_query = new WP_Query( $args );
if ($eq_query->have_posts()) : // The Loop
$eq_count = 0;
?>

            <?php
while ($eq_query->have_posts()): $eq_query->the_post();
$eq_count++;
?>

                    <?php the_title(); ?>

<?php echo do_shortcode('[sc_embed_player_template1 fileurl="<?php the_field('add_audio'); ?>"]'); ?>

            <?php endwhile; wp_reset_query(); ?>

    <?php include(EQ_PAGING); ?>

<?php endif; ?>

A: Simply Try Removing  from your Code write it as follows:
<?php echo do_shortcode('[sc_embed_player_template1 fileurl="'.the_field('add_audio').'"]'); ?>


text: Q: how to get number of elements of a specific priority in POSIX message queue I can get the total number of messages in queue with msgctl(int msqid, int cmd, struct msqid_ds *buf) with using IPC_STAT as cmd and the msg_qnum field of msqid_ds struct. Is there a way to know the number of elements for a specific priority like 1, 2 etc.?


text:
Q: Como pegar apenas o valor de uma coluna no banco de dados Preciso pegar todos os registro de apenas uma coluna no banco de dados, e estou fazendo assim:
mycursor.execute("SELECT link FROM conteudo WHERE status = 'false'")

reviewlinks = mycursor.fetchall()

E ele funciona, exceto que o resultado vem dentro de (), por exemplo:
[('https://10reviewz.com/best-step-ladder-wirecutter/',), ('https://10reviewz.com/best-magnetic-stirrer-for-e-juice/',), ('https://10reviewz.com/best-luggage-cart-for-car-seat/',), ('https://10reviewz.com/best-marine-barometers/',), ('https://10reviewz.com/best-smart-scales-for-apple/',), ('https://10reviewz.com/best-golf-putters-for-alignment/',)]

Não entendo pq ele está retornando dessa maneira, pois preciso retornar apenas os links dentro do array, mas ele coloca o link dentro de () e ainda poem uma vírgula no final.
Pq isso está acontecendo ?

A: A definição do método fetchall é a seguinte:

O método busca todas (ou todas remanescentes) linhas do resultado de uma query e retorna uma lista de tuplas...

Haja visto que cada linha retornada pode ter mais que um campo, a vírgula do próximo elemento da tupla permanece ali mesmo que não exista (já que o conceito deste tipo de estrutura é justamente a imutabilidade).
Tendo isso em vista, considerando que cada linha retornará apenas um campo (link), você pode armazenar o primeiro valor de cada tupla (que será o link) em uma nova lista:
new_result = [f[0] for f in result]
print(new_result)

# ['https://10reviewz.com/best-step-ladder-wirecutter/',
# 'https://10reviewz.com/best-magnetic-stirrer-for-e-juice/',
# ...]


text:
Q: Issue to filter on table I have a JSON data like this:
[
  {
  "id": 6488,
  "type": "table",
  "content": "

 First

 Second

 Third

"
  }, {
    "id": 123123,
    "type": "another",
    "content": "xxxx"
  }
]

I'm using ngBindHtml to display the content, and it's working really well. The problem is only one: When the type is equivalent to table I want to make a filter on this, is there a way to do this? I searched a lot and I couldn't find a solution for this.
The view looks like this:
<input type="text" placeholder="Filter..." ng-model="$ctrl.search">

Id

Type

Content

Here's a link for demo so you could understand the situation better.
Any help would be appreciated.

A: If the goal of your filter is too search then here is what you can do:

 <input class="form-control" name="search" type="text" placeholder="Search" ng-model="search_points">

and add ->  ng-repeat="p in Product.productPoints | filter:search_points"
and bind it like {{p.code}} instead of ng bind
for Reference visit -> This


text:
Q: Change background color of ListView row programmatically (wpf) I have a class that populates a ListView by passing a list of objects. The class uses reflection to see the properties of each object in order to generate the ListView. How could I change the background color of a row in the ListView.
This page does exactly what I am looking for. The only problem is that my ListView is bound to the list of objects. In other words each item of the ListView is an object that is bound instead of a ListViewItem. I am assuming that is the reason why I cannot cast some item in the ListView to a ListViewItem.  For example when I do this:
ListViewItem someItem = (ListViewItem)listView1.Items[0];

I get an InvalidcastException because if I where to physically add the objects to the ListView like:
listview.items.add(someObject) then this will work, but because I am binding the list to the ListView that line does not work. I think that is the reason why I am not able to cast. The reason why I want to cast it is becasue a ListViewItem has a Background property.
EDIT
I am able to do that with the first 12 objects I have tried the folowing:
for (int i = 0; i < listView1.Items.Count; i++)
{
    var lvitem = listView1.ItemContainerGenerator.ContainerFromIndex(i) as ListViewItem;
    lvitem.Foreground = Brushes.Green;
}

and I get this error:

and I also have tried this:
foreach (Tiro t in listView1.Items)
{
    var lvitem = listView1.ItemContainerGenerator.ContainerFromItem(t) as ListViewItem;
    if (t.numero == 0 || t.numero == 37)
    {
        //lvitem.Background = Brushes.Green;
        lvitem.Foreground = Brushes.Green;
    }
    else if (t.numero % 2 == 0)
    {
        //lvitem.Background = Brushes.Red;
        lvitem.Foreground = Brushes.Red;
    }
    else
    {
        //lvitem.Background = Brushes.Gray;
        lvitem.Foreground = Brushes.Black;
    }

}

and I get the same error:

I don't understand why lvitem is null after the 12 iteration?
It only works with the items that are being displayed....

A: You could use the ItemContainerGenerator, e.g:
var lvitem = listView.ItemContainerGenerator.ContainerFromItem(item) as ListViewItem;
var lvitem = listView.ItemContainerGenerator.ContainerFromIndex(0) as ListViewItem;

However by default the ListView is virtualizing, this means ListViewItems are created on the fly as needed (only if the item is actually visible in the list), so the above methods will not return containers for items which are currently not visible.
This being the case it usually is preferable to define a binding on the Background property via a Setter in the ItemContainerStyle.

A: When using the ItemContainerGenerator then be aware that the containers are generated asynchronously. The generator exposes a status changed event you could listen to:
listView.ItemContainerGenerator.StatusChanged += new EventHandler(ContainerStatusChanged);

private void ContainerStatusChanged(object sender, EventArgs e)
{
    if (listView.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
    {
        foreach (Tiro t in listView1.Items)
        {
            ...
        }
    }
}

Not sure if that will create any weird drawing effects (flickering) or not.
Another option instead of building the listview items in code is to you use data templates. You might have to add a few properties to your view model for display purposes though.

A: You need to introduce ViewModels instead of shredding the WPF UI. e.g. I could create one as follows
public class ItemVM : INotifyPropertyChanged // if you want runtime changes to be reflected in the UI
{
  public string Text {... raise property change in setter }
  public Color BackgroundColor {... ditto... }
}

Next create a list of such objects as a property in your DataContext so that your ListView can bind to it.
// e.g. MainWindow
    public IEnumerable<ItemVM> Items { get; set; }

Now all you need to do is bind your ListView to this collection and wire up the DataContext of the UI properly
       <ListView x:Name="MyListView" ItemsSource="{Binding Items}" HorizontalContentAlignment="Stretch">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Text}">
                    <TextBlock.Background>
                        <SolidColorBrush Color="{Binding BackgroundColor}"/>
                    </TextBlock.Background>
                    </TextBlock>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Button Click="Button_Click" Content="Go PaleGreen"/>

Now changing the background color is easy. Just set the property of the corresponding ItemVM object to the Color you want. e.g. to set all items to go PaleGreen
private void Button_Click(object sender, RoutedEventArgs e)
    {
        foreach (var item in Items)
            item.BackgroundColor = Colors.PaleGreen;
    }

A: Assuming the items in your ListBox are of type Foo, and in the ListBox you will display Foo.ItemInfo for each Foo item, and finally let's say there's a property called Status that determines how you want each Foo.ItemInfo to be displayed in the ListBox with respect to the background, foreground, font style, and tooltip text.  Based on these requirements, add the following in your XAML:
<ListBox FontFamily="Courier New"
         HorizontalAlignment="Left"
      ...
      ...other ListBox attributes...
      ...
    <ListBox.Resources>
        <local:BGConverter x:Key="BackgroundConverter"/>
        <local:FGConverter x:Key="ForegroundConverter"/>
        <local:FSConverter x:Key="FontStyleConverter"/>
        <local:TTConverter x:Key="ToolTipConverter"/>
    </ListBox.Resources>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding ItemInfo}"
                Background="{Binding Converter={StaticResource BackgroundConverter}}"
                FontStyle="{Binding Converter={StaticResource FontStyleConverter}}"
                Foreground="{Binding Converter={StaticResource ForegroundConverter}}"
                ToolTip="{Binding Converter={StaticResource ToolTipConverter}}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Next, add the following into your MainWindow.xaml.cs (or whatever you've named the XAML's accompanying file) in C#:
public class BGConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Foo foo = (Foo)value;
        string bgColor = "Gray";

        switch(foo.Status)
        {
            case 0:
                bgColor = "White";
                break;

            case 1:
                bgColor = "Cyan";
                break;

            case 2:
                bgColor = "Yellow";
                break;
        }

        return bgColor;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

public class FSConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Foo foo = (Foo)value;
        string fStyle = "Normal";

        switch(foo.Status)
        {
            case 0:
                fStyle = "Normal";
                break;

            case 1:
                fStyle = "Oblique";
                break;

            case 2:
                fStyle = "Italic";
                break;
        }

        return fStyle;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

public class FGConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Foo foo = (Foo)value;
        string fgColor = "Black";

        switch(foo.Status)
        {
            case 0:
                fgColor = "Blue";
                break;

            case 1:
                fgColor = "Brown";
                break;

            case 2:
                fgColor = "DarkBlue";
                break;
        }

        return fgColor;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

public class TTipConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Foo foo = (Foo)value;
        string ttText = "No tool tips for this item.";

        switch(foo.Status)
        {
            case 0:
                ttText = "The item has not been processed";
                break;

            case 1:
                ttText = "The item has been processed but not saved";
                break;

            case 2:
                ttText = "The item has been processed and saved";
                break;
        }

        return ttText ;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

This is one way I've found that works...there's no doubt many other ways, and your mileage may vary...
In any event, HTH

A: After some googling i found out my own solution
I am using Listview.ItemsSource and as source i use List
Then i can set background of specify ListViewItem in List, and just refresh listview.
XAML:
 <ListView x:Name="listView" ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto" Grid.Row="1">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="IP"  DisplayMemberBinding="{Binding IP}" Width="Auto"/>
                        <GridViewColumn Header="PING" DisplayMemberBinding="{Binding Ping}" Width="Auto"/>
                        <GridViewColumn Header="Host Name" DisplayMemberBinding="{Binding DNS}" Width="Auto"/>
                        <GridViewColumn Header="Mac" DisplayMemberBinding="{Binding MAC}" Width="Auto"/>
                        <GridViewColumn Header="Výrobce" DisplayMemberBinding="{Binding Manufacturer}" Width="Auto"/>
                    </GridView>
                </ListView.View>
            </ListView>

Fill ListView with Items with Gray Background:
    List<ListViewItem> ITEMS = new List<ListViewItem>();
    private void button_Click(object sender, RoutedEventArgs e)
    {
        for (int i = 1; i < 20; i++)
        {
            ListViewItem OneItem = new ListViewItem();
            OneItem.Background = Brushes.LightGray;
            OneItem.Content = new Device() { IP = "1.1.1.1", Ping = "30ms", DNS = "XYZ", MAC = "2F:3C:5F:41:F9", Manufacturer = "Intel" };
            ITEMS.Add(OneItem);
            listView.ItemsSource = ITEMS;
        }
        listView.Items.Refresh();
    }
    public class Device
    {
        public string IP { get; set; }
        public string Ping { get; set; }
        public string DNS { get; set; }
        public string MAC { get; set; }
        public string Manufacturer { get; set; }
    }

Create Method for Row Change Color:
    private void ChangeRowColor(int RowIndex,SolidColorBrush NewBackground)
    {
        ITEMS[RowIndex].Background = NewBackground;
        listView.Items.Refresh();
    }

And use it:
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        ChangeRowColor(4, Brushes.Green);
    }

A:   List<ListViewItem> ITEMS = new List<ListViewItem>();
private void loadListView(ListView lv)
{
    int numberOfRows = 20;
    string[] student_number, first_name, last_name, middle_name, extension, course, year, section;
      //    ...... Assign values to the arrays above...
    for (int h = 0; h <= numberOfRows - 1; h++)
        {
            ListViewItem OneItem = new ListViewItem();
            OneItem.Background = course[h] == "Grade" ? Brushes.Red : Brushes.Transparent; //Decide the color of the Row
            OneItem.Content = new Student
            {
                Student_Number = student_number[h],
                Course = course[h],
                Section = section[h],
                Year = year[h],
                FullName = first_name[h] + " " + middle_name[h] + ". " + last_name[h] + " " + extension[h]
            };
            ITEMS.Add(OneItem);
            lv.ItemsSource = ITEMS;
        }
        lv.Items.Refresh();
}
public class Student
{
    public string Student_Number { get; set; }
    public string FullName { get; set; }
    public string Course { get; set; }
    public string Section { get; set; }
    public string Year { get; set; }
}

output screenshot


text:
Q: Mongodb query grouping optimizations I'm not very good at mongodb queries nor mongodb optimization so I'm searching whether my query could be somehow optimized.
I have collection of logs and I'd like to create some grouping query that will show how many of logs will expire in how many days for each tenant and organisation. One tenant can have multiple organisations.
This is how my java object looks like:
public class MetaData {

  @Id
  private UUID id;

  @Indexed
  private UUID tenantId;

  @Indexed
  private UUID orgId;

  @Indexed
  private String filename;

  @Indexed
  private OffsetDateTime uploadTime;

}

I like to have some data like:
{
  "tenantId": "UUID",
  "orgId": "UUID",
  "expirations": [{
      "expireInDays": 1,
      "logsCount": 5
    },
    {
      "expireInDays": 2,
      "logsCount": 5
    },
    {
      "expireInDays": 3,
      "logsCount": 5
    },
    {
      "expireInDays": 4,
      "logsCount": 5
    },
  ]
}

db.getCollection('metadata').aggregate([
    {
        "$match": {
            "uploadTime": {
                $gt: ISODate("2021-02-28"),
                $lt: ISODate("2021-04-28"),
            }
        }
    },
    {
        $project: {
            "tenantId": "$tenantId",
            "orgId": "$orgId",
            "days": {
                $trunc: {
                    $divide: [
                        {
                            $subtract: [
                                "$uploadTime",
                                ISODate("2021-02-28")
                            ]
                        },
                        86400000
                    ]
                }
            }
        }
    },
    {
        $group: {
            "_id": {
                "tenantId": "$tenantId",
                "orgId": "$orgId",
                "days": "$days"
            },
            "count": {
                $sum: 1
            }
        }
    },
    {
        $group: {
            "_id": {
                tenantId: "$_id.tenantId",
                orgId: "$_id.orgId",
            },
            "expirations": {
                $push: {
                    "expireInDays": "$_id.days",
                    "logsCount": {
                        $sum: "$count"
                    }
                }
            }
        }
    },
    {
        $project: {
            _id: 0,
            tenantId: "$_id.tenantId",
            orgId: "$_id.orgId",
            expirations: "$expirations"
        }
    }
],
    {
        allowDiskUse: true
    });

The thing is that it needs to write to the disk because of high volume of data and currently such query takes ~1 minute. I'm not quite sure if the grouping is written as best as it could be. My main concern is with the day computation and grouping. So can I somehow improve this?

A: The below query will reduce the execution time.
I would advise you to perform the below indexes to further improve the execution time:
Index - 1
db.getCollection('metadata').createIndex({"uploadTime": -1})

Apply partialIndexFilter if possible and include that condition in $match stage

Index - 2
db.getCollection('metadata').createIndex({
  "tenantId": 1,
  "orgId": 1,
})

Not sure if this will work, give it a try and check if it improves performance

Query:
db.getCollection('metadata').aggregate([
{
  "$match": {
    "uploadTime": {
      $gt: ISODate("2021-01-28"),
      $lt: ISODate("2021-04-28"),
    }
  }
},
{
  $group: {
    "_id": {
      "tenantId": "$tenantId",
      "orgId": "$orgId",
      "expireInDays": {
        $trunc: {
          $divide: [
            {
              $subtract: [
                "$uploadTime",
                ISODate("2021-02-28")
              ]
            },
            86400000
          ]
        }
      }
    },
    "count": {
      $sum: 1
    }
  }
},
{
  $group: {
    "_id": {
      tenantId: "$_id.tenantId",
      orgId: "$_id.orgId",
    },
    "expirations": {
      $push: {
        "expireInDays": "$_id.expireInDays",
        "logsCount": {
          $sum: "$count",
        }
      }
    }
  }
},
// Handle `$projection` pipeline from java, this will save you some time.
// {
//     $project: {
//         _id: 0,
//         tenantId: "$_id.tenantId",
//         orgId: "$_id.orgId",
//         expirations: "$expirations"
//     }
// }
], {
  allowDiskUse: true
});


text:
Q: Understanding powers of an element For example we have:
$$
\begin{aligned}
\mathbb{Z}_7^* &= \left\{[z]_7 \in \mathbb{Z}_7 : \gcd(z, 7) = 1, 1 \leq z < 7, \forall z \in \mathbb{Z}\right\} \\
 &= \{1, 2, 3, 4, 5, 6\} \\
\left<a\right> &\in \mathbb{Z}_7^* : \{a^b \mod 7: \forall a,b \in \mathbb{Z}_7^*\}
\end{aligned}
$$
This would produce:
$$
\begin{aligned}
\left<1\right> &= \{1\} \\
\left<2\right> &= \{1,2,4\} \\
\left<3\right> &= \{1,2,3,4,5,6\} \\
\left<4\right> &= \{1,2,4\} \\
\left<5\right> &= \{1,2,3,4,5,6\} \\
\left<1\right> &= \{1,6\}
\end{aligned}
$$
As such, the smallest primitive root $g = 3$ as $\left<3\right> = |\mathbb{Z}_7^*|$.
So, $g$ is our generator, that can construct $\mathbb{Z}_7^*$ and the element of $a \in \mathbb{Z}_7^*$ can be expressed as:
$$
3^z \equiv a \pmod7 \to z = \text{ind}_{7,3}(a)
$$
Now, my issue, how do I solve for $z$ given $a$:
Lets say $a = 4$ we want to solve:
$$
3^z \equiv 4 \pmod7 \to 3^z \mod 7 = 4 \mod7 = 4
$$
I think I understand this correctly, I just do not know how to solve for $z$.
Now this relates to a question I need to answer, just with different numbers. Both of which are $\mathbb{Z}_p^*$ where $p$ is a prime number, not sure if that is significant or not.

Draw the table order of $\mathbb{Z}_7^*$ choose the smallest $g$ and compute a table giving $\text{ind}_{7, g}(a) \forall a \in \mathbb{Z}_7^*$.

Now I believe I did the first part correct, the $\left<a\right>$ is the order table and $g = 3$.

A: This is the discrete logarithm problem, and we don't know a general-purpose efficient algorithm for solving it. However, you can figure out the answer by building up a table of answers for different values of the exponent $x$.
$$3^x = 4\pmod{7}$$
The powers of 3 (mod 7) are, in order: $3^0 \equiv 1,\;\;3^1 \equiv 3,\;\; 3^2 \equiv 2,\;\; 3^3 \equiv 6,\;\; 3^4 \equiv 4,\;\; 3^5 \equiv 5,\;\;  3^6 \equiv 1,$ and the cycle repeats for all higher powers.
Hence:
$$\begin{array}{r|rrrrrr}x&0&1&2&3&4&5&\cr 3^x\pmod{4}&1&3&2&6&4&5\cr\end{array} $$
And more generally,
$$\begin{array}{r|rrrrrr}3^x\pmod{4}&1&3&2&6&4&5\\\hline x&0&1&2&3&4&5&\\&6&7&8&9&10&11\\&12&13&14&15&16&17\\&18&19&20&21&22&23\\&&&\vdots&\vdots&& \end{array} $$

A: Let $g$ be a fixed number and $p$ a fixed modulus.  Computationally, "given $z$, find $g^z$" is (relatively) easy; "given $g^z$, find $z$" is hard.
So, construct your table "backwards".  For example, if $p=7$ and $g=3$, don't do
$$\matrix{\hbox{number}&1&2&3&4&5&6\cr \hbox{index}&?&?&?&?&?&?\cr}$$
but rather
$$\matrix{\hbox{number}&?&?&?&?&?&?\cr \hbox{index}&0&1&2&3&4&5\cr}\ .$$
Then all you have to calculate is
$$3^0=1\,,\ 3^1=3\,,\ 3^2=9=2\,,\ 3^3=2\times3=6\,,\ldots$$
to get
$$\matrix{\hbox{number}&1&3&2&6&4&5\cr \hbox{index}&0&1&2&3&4&5\cr}\ .$$
Finally (optional) sort the table so that the top row is in numerical order.


text:
Q: How to chain a fetch API to a function then to another function? I keep getting syntax error "Uncaught (in promise) ReferenceError: showQuestion is not defined" Trying to find ways to fix this problem. Also I'm still new to the whole thing.
fetch(
    'https://jservice.kenzie.academy/api/random-clue?valid=true'
)
    .then(response => response.json())
    .then(randomDataId => {
        const categoryDataId = randomDataId.categoryId;
        console.log(`category id is: ${categoryDataId}`);

        fetch(
            `https://jservice.kenzie.academy/api/clues?category=${categoryDataId}`
        )
            .then(response => response.json())
            .then(randomCatyId => {
                const rightAnswer =
                    randomCatyId.clues[randomData].answer;

                const showTitle =
                    randomCatyId.clues[randomData].category.title;

                const showQuestion =
                    randomCatyId.clues[randomData].question;

                showCategory.innerText = `Category: ${showTitle}`;

                h2Question.innerText = `Question: ${showQuestion}`;

                console.log('question: ' + showQuestion);
                console.log('answer: ' + rightAnswer);

                questionFetch();
            });
    });

function questionFetch() {
    h2Question.innerHTML = `Question: ${showQuestion}`;
}

A: fetch api is async in nature, and you are trying to read the data 'showQuestion' which is not yet available. please see the below code. use async-await, its much better way to play with fetch api.
 const randomData = 2; // fake Data

        async function GetDataFromApi(url) {
            const response = await fetch(url);

            return await response.json();
        }

        async function RunApp(params) {

            const randomDataId = await GetDataFromApi('https://jservice.kenzie.academy/api/random-clue?valid=true');

            const categoryDataId = randomDataId.categoryId;
            console.log(`category id is: ${categoryDataId}`);

            const randomCatyId = await GetDataFromApi(`https://jservice.kenzie.academy/api/clues?category=${categoryDataId}`);

            const rightAnswer = randomCatyId.clues[randomData].answer;
            const showTitle = randomCatyId.clues[randomData].category.title;
            const showQuestion = randomCatyId.clues[randomData].question;

            // showCategory.innerText = `Category: ${showTitle}`;

            // h2Question.innerText = `Question: ${showQuestion}`;

            console.log('question: ' + showQuestion);
            console.log('answer: ' + rightAnswer);

            questionFetch(showQuestion);
        }

        function questionFetch(showQuestion) {
            //h2Question.innerHTML = `Question: ${showQuestion}`;
        }

        RunApp();

A: The function questionFetch() does not have access to the showQuestion constant. This is because this constant is defined in the fetch request. The function showQuestion does not have access to data defined inside another function.
(more on 'scope' here: https://www.w3schools.com/js/js_scope.asp)
To fix this, you should supply the constant showQuestion as an argument when calling the function questionFetch:
                questionFetch(showQuestion); //we supply the constant to the function
            });
    });

/**
     * function takes an argument, calls it x, and applies it as x.
     * The name of the argument does not matter, 'x' just the label
     * this function uses to hold the data supplied
     * (in our case, the question string);
     * */
function questionFetch(x) {
    h2Question.innerHTML = `Question: ${x}`;
}

Please make sure to define and supply the [randomData] argument used in the second fetch function, as it is currently undefined.


text:
Q: Leave insignificant features into logistic regression I am making a model with logistic regression to predict binary sport events and have found some variables that may have an impact. Some features would however not contribute to the accuracy score of the model, but it would also not decrease it. My question is that should I leave these features or just throw them out?

A: Particularly with logistic regression, it's good to include any features that might reasonably contribute to outcome even if they aren't correlated with other features. As this page shows, there can be a significant bias from omitting potentially informative variables from a logistic regression in situations where omitting them might not bias a standard linear regression.
Remember that lack of statistical signficance doesn't necessarily mean that a variable is unrelated to outcome; it's possible that there is a real relation but you just didn't have enough power in your data and analysis to demonstrate it yet.
In general for predictive models it's best not to exclude features, just be careful that you're not overfitting the model; use a penalized method like ridge regression or LASSO if you are in danger of overfitting. The rule of thumb for logistic regression is that if you have more than 15-20 of the lower-prevalence class per feature in the model you probably won't have problems with overfitting.


text:
Q: Android Programming - Facebook Login runtime Below is the Fragment Class that contains the facebook login handler. The App crashes everytime it loads with a runtime exception. I have been trying to follow the facebook developer guides but I have a hit a brick wall.
public class HomeFragment extends Fragment {

    public HomeFragment(){}
    private static final String TAG = "HomeFragment";
    private UiLifecycleHelper uiHelper;
    private MainActivity app;
    LoginButton authButton;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setRetainInstance(true);
        uiHelper = new UiLifecycleHelper(this.getActivity(), callback);
        uiHelper.onCreate(savedInstanceState);

        app = (MainActivity) getActivity().getApplicationContext();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

         super.onCreate(savedInstanceState);

        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
       authButton = (LoginButton) rootView.findViewById(R.id.authButton);

        return rootView;
    }

    private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        if (state.isOpened()) {
            Log.i(TAG, "Logged in...");
        } else if (state.isClosed()) {
            Log.i(TAG, "Logged out...");
        }
    }

    @SuppressWarnings("unused")
    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            onSessionStateChange(session, state, exception);
        }
    };
    @Override
    public void onResume() {
        super.onResume();
        uiHelper.onResume();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);
    }
}

Here is the log file for the errors. I am  unable to figure out whats causing the runtime error.
12-01 14:55:44.801: E/AndroidRuntime(2565): FATAL EXCEPTION: main
12-01 14:55:44.801: E/AndroidRuntime(2565): Process: com.example.studygroup, PID: 2565
12-01 14:55:44.801: E/AndroidRuntime(2565): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.studygroup/com.example.studygroup.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.studygroup.MainActivity
12-01 14:55:44.801: E/AndroidRuntime(2565):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at android.app.ActivityThread.access$800(ActivityThread.java:144)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at android.os.Handler.dispatchMessage(Handler.java:102)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at android.os.Looper.loop(Looper.java:135)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at android.app.ActivityThread.main(ActivityThread.java:5221)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at java.lang.reflect.Method.invoke(Native Method)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at java.lang.reflect.Method.invoke(Method.java:372)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
12-01 14:55:44.801: E/AndroidRuntime(2565): Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.studygroup.MainActivity
12-01 14:55:44.801: E/AndroidRuntime(2565):     at com.example.studygroup.HomeFragment.onCreate(HomeFragment.java:32)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at android.app.Fragment.performCreate(Fragment.java:2031)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:863)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at android.app.BackStackRecord.run(BackStackRecord.java:833)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at android.app.Activity.performStart(Activity.java:5948)
12-01 14:55:44.801: E/AndroidRuntime(2565):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)
12-01 14:55:44.801: E/AndroidRuntime(2565):     ... 10 more

A: This is your error:
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.studygroup.MainActivity

try this instead:
app = ((MainActivity) getActivity()).getApplicationContext();

A: Okay, I got rid of that line as it wasn't required. The errors were fixed. However, how do I get the "Login with facebook" button to turn into "Logout"


text:
Q: Is there a macro player/recorder for games? A few games make their whole point in levels that are easy to figure out but hard to pull off. VVVVVV, Super Meat Boy and the Bit.Trip games fall squarely into this category, for example. You're basically expected to put in the obviously correct sequence of button presses and depresses at the right time; that's "all" there is to it. For whatever reason, this is a category of games that is having quite the draw on me as of late.
This however results in pretty hostile game design where there is very little room for error and plenty of triangular spikes with square hitboxes.
Certainly, pulling this off by yourself takes time, focus, determination, reflexes, muscle memory, skill and is very rewarding when you finally do beat the fucking pong boss and collect that trinket just out of reach. Sometimes, however, it dawns on you that perhaps one challenge isn't just worth it in the greater scheme of things.
For those times where you want to give up, cheat yourself and move along.
Is there any software able to record and replay keyboard and mouse input for games?** I'm afraid general-purpose tools like AHK wouldn't be able to do so with the required precision (relying on system sleep()s isn't reliable for example, while running on each frame sounds like a better idea.)

A: It appears that Hourglass comes as close to "TAS"ing for Windows as it can possibly be done nowadays. Here's a "test run" by diggidoyo of the first two levels of Super Meat Boy.

The author comments:

I can't get the audio to dump, and save states crash the game. I'm sure it's because of the multi-threads (can't run with this disabled). I only used frame advance, but the later levels will need save states to be efficient. Still, frame advancing brought the times to attractive low numbers.

Thus, while it's not quite ready for serious tool-assisted speedruns, it might just be enough tools to be effective as an anti-frustration solution. (It appears, however, that it conflicts with Steam.)

A: I've never used it, but a number of my friends have used AutoIt to write simple scripts that run macros. In games such as Magicka where you have to press a certain set of keys to activate a spell, it allows them to run around throwing out the biggest spells at the click of the button.
However, it is a simple programming language and would probably take some trail and error to work out for a non-programmer.


text:
Q: (Rails Kaminari) undefined method `current_page' for #I've watched episode about Kaminari at railscasts.com and tried to add this system to my blog.
But this error appears again and again and I don't understand why.
index action from posts controller:
  def index
@posts = Post.order("title").page(params[:page]).per(3)

if params[:tag]
  @posts = Post.tagged_with(params[:tag])
else
  @posts = Post.all
end

respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @posts }
  end
end

view file: index.html.erb:
<%= paginate @posts%>

<% @posts.each do |post| %>

<%= link_to post.title, post %>

    Created: <%= post.created_at.strftime("%Y/%m/%d")%> by
     <%=  link_to post.user.fullname, user_posts_path(post.user) %>

  <%= simple_format post.text %>

Tags: <%= raw post.tag_list.map { |t| link_to t, tag_path(t) }.join(', ')      %>

  <% end %>

A: You're declaring @posts twice in your controller. Try something like this:
if params[:tag]
  @posts = Post.tagged_with(params[:tag]).order("title").page(params[:page]).per(3)
else
  @posts = Post.order("title").page(params[:page]).per(3)
end

After removing the top @posts = Post.order("title").page(params[:page]).per(3) line.


text:
Q: Cannot find the right  with selector after loading the HTML I hope I can find a solution to this one. Here it goes:
After I have submitted my form to add a message to the database, I create a <div> with the load method. After that I do some stuff in the callback function.
When the function to create the new <div> has finished, it returns to the calling function that is supposed to prepend the message to the last inserted <div>.
That's where the problem starts:
I use the selector to find $(someDiv : last), but it puts it in the wrong <div>. So, I know it has something to do with the async process.
I haven't really worked out what I could do to fix this, because now I am not working from a callback function.
If you wanna see a live example The sourcecode is clutterd with debug code in the form of alerts, but you can see what it is doing.

A: Ajax calls are asynchronous, you should be using a callback function to select loaded data, for example:
$('div').load(url, data, function(data, status) {
   $(someDiv:last).dosomething();
}

A: Probably the new div is not being inserted where you think it is.  $(someDiv : last) is returning the wrong result because the new div isn't in someDiv, or it isn't at the end. This seems like the kind of thing that Firebug would make easy to debug.
Rather than using the "last" metaclass to select the div, here's a better idea: give the new div an ID and refer to it directly.  Or give it a class when you create it, use the class to select it $(".newdiv"), and then clear the class when you're done.  Or simply return the new div to the calling function, so it doesn't need to use a selector at all.  Sorry, I didn't entirely understand your situation, but I think at least one of these solutions will work.

A: Did you notice that the first time the value gets added to the first item, and after that it gets added to the previously last item? That might be a clue.
Oh, and I got stuck in a loop which added my message 10 times. Looks like your code has timing issues.
Edit: bringing it back to its basics would look something like this: http://kruisit.nl/so/841982/
Hope that helps.


text:
Q: Preventing a Fn from being invoked again while it's already running I am using inputbot to write a program that provides some global macros for my computer. For example, when I press the h key, it should execute the macro typing

Hello World

into the current application. I tried to implement it like this:
extern crate inputbot;

fn main() {
    let mut callback = || {
        inputbot::KeySequence("Hello World").send();
    };

    inputbot::KeybdKey::HKey.bind(callback);

    inputbot::handle_input_events();
}

However, when I pressed the h key what I actually got was:

hHHHHHHHHHHHHHHHHHHHHHHHHHEHEHhEhEEHHhEhEhEHhEHHEHHEEHhEHlhEHEHHEHLEHLHeeleleelelelllelelleelehlhehlleeheehelheelleeleelhllllllellelolelellelleoleloloelellololol olollollelllolllol lloo ol o oo l lo lolooloooloo loo LOWOLO  O  L  OLW  WOWO L WLLOLOW L O O  O O   o WOWW low o oOow WWW  WOW wowooWWWO oOWRWOoor W RoW oOWorororWRRWLR rLROwoRWLWOworo  WorrrRWl ow o   WRLR OLw  o OWLDol rollWWLDWowDLlroWWo r oWDWOL dorRrwrolrdrrorlrLWDRdodRLowdllrllolrdlrddolrdlrldowldorowlrdlrorloLDLWDLoddlrddlrdldldldrrdordldrlrddrodlrrldoldlrlddldlrdlldlrdlddrlddldddlddlddd

The macro was triggering itself each time it sent the h key event.
How can I prevent a Fn from being invoked again while another instance of it is still running? This is the main functionality of a small application, so there's nothing else to really worry about compatibility with.

My naive attempt to fix

this was to add a mut running variable in main, which callback would set to true while it was running, or immediately return if it was already true:
extern crate inputbot;

use std::time::Duration;
use std::thread::sleep;

fn main() {
    let mut running = false;
    let mut callback = || {
        if running { return };
        running = true;

        inputbot::KeySequence("Hello World").send();

        // wait to make sure keyboard events are done.
        sleep(Duration::from_millis(125));

        running = false;
    };

    inputbot::KeybdKey::HKey.bind(callback);
    inputbot::handle_input_events();
}

However, this doesn't compile:

error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnMut`

After some reading, my understanding is now that a Fn closure (required by inputbot's .bind() methods) can't own any mutable data, like a captured mut variable.
Maybe it's possible to wrap the variable in some kind of non-mut value? Perhaps some kind-of lock, to make the potential concurrency safe, like this pseudocde?
fn main() {
    let mut running = false;
    let lockedRunning = example::Lock(&running);
    let mut callback = || {
        {
            let mut running = lockedRunning.acquire();
            if running { return };
            running = true;
        }

        inputbot::KeySequence("Hello World").send();

        // wait to make sure keyboard events are done.
        sleep(Duration::from_millis(125));

        {
            let mut running = lockedRunning.acquire();
            running = false;
        }
    };
}

A: What you want here is that the function is mutually exclusive to itself.
Rust allows you to do this with the Mutex struct. It allows you to hold a lock that when acquired stops anyone else from taking it until you release it.
Specifically the functionality you want is the try_lock method which would allow you to check if the lock has already been acquired and would allow you to handle that case.
let lock = mutex.try_lock();

match lock {
    Ok(_) => {
       // We are the sole owners here
    }
    Err(TryLockError::WouldBlock) => return,
    Err(TryLockError::Poisoned(_)) => {
        println!("The mutex is poisoned");
        return
    }
}

A: Using an atomic value is a bit simpler than a Mutex as you don't need to worry about failure cases and it can easily be made into a static variable without using lazy-static:
use std::sync::atomic::{AtomicBool, Ordering};

fn main() {
    let is_being_called = AtomicBool::new(false);

    bind(move || {
        if !is_being_called.compare_and_swap(false, true, Ordering::SeqCst) {
            print!("I'm doing work");
            is_being_called.store(false, Ordering::SeqCst);
        }
    });
}

I have a hunch that this is also more efficient than using a Mutex as no heap allocations need to be made, but I didn't benchmark it.
If you are in a single-threaded context and your callback is somehow (accidentally?) recursive (which closures cannot be) you can also use a Cell:
use std::cell::Cell;

fn main() {
    let is_being_called = Cell::new(false);

    bind(move || {
        if !is_being_called.get() {
            is_being_called.set(true);
            print!("doing work");
            is_being_called.set(false);
        }
    })
}

If you happen to have a FnMut closure, you don't even need the Cell and can just use a boolean:
fn main() {
    let mut is_being_called = false;

    bind(move || {
        if !is_being_called {
            is_being_called = true;
            print!("doing work");
            is_being_called = false;
        }
    })
}


text:
Q: Module not found: Can't resolve 'firebase' in 'D:\gmail-react\src' I am installed firebase logged in as well.
I am getting a completely white screen on importing it.
This is the firebase.js file
import firebase from 'firebase'

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
const firebaseConfig = {
    apiKey: "AIzaSyBb9O35r_N--vwBZNfpxY3vZHzi4wH1oII",
    authDomain: "fir-237a1.firebaseapp.com",
    projectId: " fir-237a1",
    storageBucket: "fir-237a1.appspot.com",
    messagingSenderId: "1055799909510",
    appId: "1:1055799909510:web:c90fad7d5113500585c507"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = app.firestore();
const auth = firebase.auth();
const provider = new firebase.auth.GoogleAuthProvider();

export { db, auth, provider };

This is where I am importing firebase, SendMail.js file
import { db } from "./firebase.js"
import firebase from 'firebase';

function SendMail() {
    const { register, handleSubmit, watch, formState: { errors } } = useForm();
    const dispatch = useDispatch();

    const onSubmit = (formData) => {
        console.log(formData);
        db.collection('emails').add({
            to: formData.to,
            subject: formData.subject,
            message: formData.message,
            timestamp: firebase.firestore.FieldValue.serverTimestamp(),
        });

        dispatch(closeSendMessage());
    };

A: If the files are one by another the import here:
import { db } from "./firebase.js"

Should be like this:
import { db } from "/firebase.js"

without the ".". If you use the "." the file will be searched in the folder above and that is how it looks like. It wen to the src folder witch is probable above the one where your file is.
Also update your firebase.js file to this:
import { getFirestore } from "firebase/firestore";
import { getAuth, GoogleAuthProvider } from "firebase/auth";
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "AIzaSyBb9O35r_N--vwBZNfpxY3vZHzi4wH1oII",
  authDomain: "fir-237a1.firebaseapp.com",
  projectId: " fir-237a1",
  storageBucket: "fir-237a1.appspot.com",
  messagingSenderId: "1055799909510",
  appId: "1:1055799909510:web:c90fad7d5113500585c507",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore();
const auth = getAuth();
const provider = new GoogleAuthProvider();

export { db, auth, provider };

and make sure you use the latest Firebase JS SDK Version 9.x
A just saw that a lot of your code has the old SKD 8 in the repo. You can either stay with that syntax by using the compad version in the new SDK or refactor your code to use the new syntax of SDK version 9. Here is a migration guid.
You need to pick one of those two options. I would recommend to migrate to the new version.
With the new SDK version you don't even need the firebase.js file. Your code would look like this:
import { getFirestore, addDoc, collection } from "firebase/firestore";

function SendMail() {
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm();
  const dispatch = useDispatch();

  const onSubmit = (formData) => {
    console.log(formData);
    addDoc(collection(db, "emails"), {
      to: formData.to,
      subject: formData.subject,
      message: formData.message,
      timestamp: firebase.firestore.FieldValue.serverTimestamp(),
    });
  };

  dispatch(closeSendMessage());
}


text:
Q: Absolute paths within includes with localhost all.
My question is in regards to a problem I'm encountering when trying to add a universal php template for my DOCTYPE section. My DOCTYPE include (aptly entitled doctype.php) lies within the /template directory, and also includes calls pointing to my CSS and JS files that I want to be accessible to all pages.
So the problem is encountered when I try to write the absolute path to these files (the CSS and JS files). Currently, I am trying:
<script type="text/javascript" src="<?php echo $_SERVER['DOCUMENT_ROOT'] . '/file/extension/to/javascript/file.js'; ?>"></script>

and
<link rel="stylesheet" type="text/css" href="<?php echo $_SERVER['DOCUMENT_ROOT'] . 'file/extension/to/css/file.css'; ?>"

I am running the application through WAMP on my localhost.
Taking a look a look at the source code, it appears as though the links are pointing to the appropriate files (c:/wamp/www/examplesite/path/to/file/file.ext), and all should be well. BUT it is not...
The JavaScript is not accessible and the Stylesheet is not functioning. I'm at a loss for what to do.
I've also tried:
-writing the absolute path without the use of PHP
-creating PHP variables to hold the document root and then concatenating the appropriate directory path to access the files.
Any suggestions? And how will this change when I upload the directory structure to my online server vs. my current localhost?

A: You might want to try $_SERVER['HTTP_REFERER'] instead. It gives you the path you are looking for.
On my local machine, which uses WAMP, I used <?php print_r($_SERVER); ?> to see what values it gives.
Also, there may be some typos in the snippets. For example, you don't need the leading / in the first example you gave.
For example:
<script type="text/javascript" src="<?php echo $_SERVER['HTTP_REFERER'] . 'file/extension/to/javascript/file.js'; ?>"></script>
<link rel="stylesheet" type="text/css" href="<?php echo $_SERVER['HTTP_REFERER'] . 'file/extension/to/css/file.css'; ?>"></link>

Or since HTTP_REFERER can't be trusted in some case, you may want to create a function that builds the base part of the absolute path.
<?php
function getAddress() {
    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
    $filenamepattern = '/'.basename(__FILE__).'/';
    return $protocol.'://'.$_SERVER['HTTP_HOST'].preg_replace($filenamepattern,"",$_SERVER['REQUEST_URI']);
 }
?>

Then call it like so:
<script type="text/javascript" src="<?php echo getAddress() . 'file/extension/to/javascript/file.js'; ?>"></script>
<link rel="stylesheet" type="text/css" href="<?php echo getAddress() . 'file/extension/to/css/file.css'; ?>"></link>

A: You're pointing to files on your local machine using the file path (ex: C:\some\path\to\file) when you should be using a URL (ex: http://localhost/some/path/to/file).  The HTML is parsed by the client's browser so when it attempts to access a path that isn't a URL it can't.
Instead of using $_SERVER['DOCUMENT_ROOT'] you can either use absolute URLs such as
<script type="text/javascript" src="/path/to/my/file.js"></script>

where the "/path" folder is your base web directory, or you can use relative URLs based on whatever the current directory the file is in to which you're including the doctype.php file.  I'd recommend not doing the latter as it's a pain in the butt to keep track of.
If you use relative URLs you should have no problems when moving your code to a new host, provided the directory structure remains the same.

A: Of course any kind of resource (JS, CSS, Images, etc.) has to be accessed via http(s) request and therefore it is impossible to directly access them with an absolute path. Think of the security implications of such an approach. So you always have to use web paths relative to your web root directory.
For example:
<script type="text/javascript" src="http://localhost/myproject/media/ja/file.js"></script>

A: You're going about the wrong way of including files in your page, you should be using HTTP URLS instead:
<script type="text/javascript" src="/file/extension/to/javascript/file.js"></script>

Or, if you prefer to use a variable with the host name:
<script type="text/javascript" src="http://<?php echo $_SERVER['HTTP_HOST']; ?>/file/extension/to/javascript/file.js"></script>


text:
Q: How can I return IQueryable object from a mock object? I am trying to tell a method GetAll() on a mocked object _portalUserRepositoryMock to return an object of type IQueryable<TEntity>. I know it is of this type because the method in the class to be tested returns this type.
I've not been able to come up with a solution.
I saw this post, but had errors trying to include the library into my project. Something about the version of Microsoft.EntityFrameworkCore - which led to more issues.
What I did to get this error was:
_portalUserRepositoryMock = Substitute.For<IPortalUserRepository>();
_portalUserRepositoryMock.GetAll().Returns(fakeQueryablePUser.AsQueryable());

The class under test uses the repository like this:
var portal = await _portalUserRepository.GetAll().Include(p =>
p.Portal).Where(p => p.UserId == user.Id && p.Portal.PortalType ==
dto.PortalType).FirstOrDefaultAsync();

and the GetAll() method is:
        public IQueryable<TEntity> GetAll()
    {
        try
        {
            return DbContext.Set<TEntity>().AsNoTracking();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

I get this error:

Message: System.InvalidOperationException : The provider for the source
      IQueryable doesn't implement IAsyncQueryProvider. Only providers that
      implement IEntityQueryProvider can be used for Entity Framework
      asynchronous operations.

I reckon I'm getting this error because of the FirstOrDefaultAsync() that is being used. Just have no idea on how to resolve it.
Edit:
I have now been able to add the MockQueryable library to my test project (by using version 1.0.4 and not the latest 1.1.0 ). I have followed the steps, as shown below:
        var fakePortalUser = new PortalUser()
        {
            PortalId = new Guid()
        };

        var fakeQueryablePUser = new List<PortalUser>
        {
            fakePortalUser
        }.AsQueryable().BuildMock();

Last step is now to use GetQueryable(). Which I try to use here:
_portalUserRepositoryMock.GetAll().GetQueryable().Returns(fakeQueryablePUser);

But I get the red squigly line under theGetQueryable() method call. So code won't compile.

A: The initial issue is as you suspected with FirstOrDefaultAsync. That extension expects the queryable to also have a IAsyncQueryProvider in order to match async EF which the mock wont be by default.
Remove .GetQueryable() as you do not need it. That member came from one of the  samples to demonstrate how to use the mock library.
Also make sure the fake data has data in it that will match the predicate in the Where.
.Where(p => p.UserId == user.Id && p.Portal.PortalType == dto.PortalType)

FirstOrDefault will return null if there are no elements to enumerate.
And if the data does not satisfy the filter you will get back null by default.

A: You dont, IQueryable<T> is an implementation detail handled by Entity Framework / Core. Unless your business logic actually creates an implementation of IQueryable<T> then you want to return a mock stub object.
i.e (Note that this uses the library Moq to mock the objects as im not sure what you're using and the implementation may vary.)
_mockedEntityQuery = new Mock<IQueryable<T>>();
_portalUserRepositoryMock = Substitute.For<IPortalUserRepository>();
_portalUserRepositoryMock.GetAll().Returns(_mockedEntityQuery.Object);

If you return an instance of IQueryable<T> you would also be testing that implementation which will have already been done by the EF unit tests. Unit tests should only test the code that is within the scope of the unit.