text:
Q: Periodic Temporary ping timeouts from some WiFi clients I'm seeing some odd behavior that I'm trying to isolate on my home network. And if this post belongs in a more specific manufacturer section, please lmk.

*

*ASUS ZenWiFi AX XT8s

*one main router with two identical meshed APs

*dedicated wired Ethernet back-haul

*latest STABLE fw version 3.0.0.4.388_21617

Periodically (and often after a router fw upgrade), when I try to ping a numeric IP address from my WiFi iPhone targeting another local wireless client (in this case, a few Raspberry Pi Zero W's), I will get "Request timed out"s ... for a while, but, then it will eventually clear up and start pinging successfully (Note: numeric IP, not a host name resolution issue). It happens less from my hard-wired clients (i.e.: laptop, Pi server, etc.) but it still happens occasionally.
I am not using the "tri-band" setup on my router (called "SmartConnect" by ASUS, band-steering elsewhere, etc.). I am using each WiFi SID (2.4Ghz, 5-1Ghz, 5-2Ghz) separately, with their own auth creds... but, it should automatically route / switch between IP clients on those bands just fine... right? They are part of the DHCP IP range.
This seems to me like a stale ARP cache issue. But, I thought reboots typically resolved that? Am I wrong? (Note: I have rebooted everything, the issue seems to eventually return) Periodic manual pinging does seem to resolve it. If this is a corrupt ARP cache, where? On the client? On the main router or nearest AP mesh node? If rebooting doesn't permanently resolve it, should I maybe truly submit an ARP clear cache cmd on the clients, SSH into the routers and do the same?


text:
Q: Xpath2.0 selecting first and last occurance of string with iteration I have this tree:
<Events>
 <Properties>
   <Property Descriptor=100>1378314022</Property>
   <Property Descriptor=200>ABC1234</Property>
 </Properties>
 <Properties>
   <Property Descriptor=100>1378314023</Property>
   <Property Descriptor=200>ABC1234</Property>
 </Properties>
 <Properties>
   <Property Descriptor=100>1378314024</Property>
   <Property Descriptor=200>ABC1234</Property>
 </Properties>
 <Properties>
   <Property Descriptor=100>1378314022</Property>
   <Property Descriptor=200>123456</Property>
 </Properties>
 <Properties>
   <Property Descriptor=100>1378314023</Property>
   <Property Descriptor=200>123456</Property>
 </Properties>
 <Properties>
   <Property Descriptor=100>1378314024</Property>
   <Property Descriptor=200>123456</Property>
 </Properties>

</Events>

I'm iterating at this level: Events/Properties
How can I have only the FIRST and LAST occurrence of each Property Descriptor = 200 and its respective Property Descriptor = 100?
I've tried so far:

*

*Iteration: Events/Properties

*Select:
Property[@Descriptor=200])[last()] or
Property[@Descriptor=200])[first()]
but with no success.
OUTPUT should look like this [I'm showing it in HTML, iterating in the ROW level]:
P100        | P200
1378314022  | ABC1234
1378314024  | ABC1234
1378314022  | 123456
1378314024  | 123456

A: In XSLT 2.0 this would be easy with for-each-group, grouping by the 200 value and taking the first and last members of each group.  But in pure XPath (not XSLT) you need to think laterally.
If the groups are always contiguous as you've shown here (i.e. all the ABC1234 entries are adjacent to one another, and all the 123456 entries are adjacent to one another) then this boils down to wanting every Properties element P that does not have an immediately preceding and an immediately following sibling Properties element with the same 200 value as P.  I.e. you want to iterate over
Events/Properties[not(
  (
    Property[@Descriptor="200"] =
    preceding-sibling::Properties[1]/Property[@Descriptor="200"]
  ) and (
    Property[@Descriptor="200"] =
    following-sibling::Properties[1]/Property[@Descriptor="200"]
  )
)]

and then select the Property[@Descriptor="100"] and Property[@Descriptor="200"] from each of the resulting Properties elements.
You've tagged your question "xpath-2.0" but this expression is also valid in XPath 1.0.

A: I am not completely sure which answer you are looking for, but here I will give you two examples. One of them should probably fit your needs.
I used the following input XML:
<?xml version="1.0" encoding="UTF-8"?>
<Events>
    <Properties>
        <Property Descriptor="100">1378314022</Property>
        <Property Descriptor="200">ABC1234</Property>
        <Property Descriptor="100">MD2356</Property>
        <Property Descriptor="200">25689</Property>
        <Property Descriptor="100">MD75632</Property>
        <Property Descriptor="200">5632</Property>
    </Properties>
    <Properties>
        <Property Descriptor="100">1378314023</Property>
        <Property Descriptor="200">ABC1234</Property>
        <Property Descriptor="100">MD2356</Property>
        <Property Descriptor="200">25689</Property>
        <Property Descriptor="100">MD75632</Property>
        <Property Descriptor="200">5632</Property>
    </Properties>
    <Properties>
        <Property Descriptor="100">1378314024</Property>
        <Property Descriptor="200">ABC1234</Property>
        <Property Descriptor="100">MD2356</Property>
        <Property Descriptor="200">25689</Property>
        <Property Descriptor="100">MD75632</Property>
        <Property Descriptor="200">5632</Property>
    </Properties>
    <Properties>
        <Property Descriptor="100">1378314022</Property>
        <Property Descriptor="200">123456</Property>
        <Property Descriptor="100">MD2356</Property>
        <Property Descriptor="200">25689</Property>
        <Property Descriptor="100">MD75632</Property>
        <Property Descriptor="200">5632</Property>
    </Properties>
    <Properties>
        <Property Descriptor="100">1378314023</Property>
        <Property Descriptor="200">123456</Property>
        <Property Descriptor="100">MD2356</Property>
        <Property Descriptor="200">25689</Property>
        <Property Descriptor="100">MD75632</Property>
        <Property Descriptor="200">5632</Property>
    </Properties>
    <Properties>
        <Property Descriptor="100">1378314024</Property>
        <Property Descriptor="200">123456</Property>
        <Property Descriptor="100">MD2356</Property>
        <Property Descriptor="200">25689</Property>
        <Property Descriptor="100">MD75632</Property>
        <Property Descriptor="200">5632</Property>
    </Properties>
</Events>

When I use the next XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Properties">
        <xsl:copy>
            <xsl:apply-templates select="Property[@Descriptor = '100'][1]" />
            <xsl:apply-templates select="Property[@Descriptor = '100'][last()]" />
            <xsl:apply-templates select="Property[@Descriptor = '200'][1]" />
            <xsl:apply-templates select="Property[@Descriptor = '200'][last()]" />
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

This XSLT also has a iteration over the Properties element, within that Properties element it gets the first and the last occurence of each provided Descriptor. The result would be:
<?xml version="1.0" encoding="UTF-8"?>
<Events>
    <Properties>
        <Property Descriptor="100">1378314022</Property>
        <Property Descriptor="100">MD75632</Property>
        <Property Descriptor="200">ABC1234</Property>
        <Property Descriptor="200">5632</Property>
    </Properties>
    <Properties>
        <Property Descriptor="100">1378314023</Property>
        <Property Descriptor="100">MD75632</Property>
        <Property Descriptor="200">ABC1234</Property>
        <Property Descriptor="200">5632</Property>
    </Properties>
    <Properties>
        <Property Descriptor="100">1378314024</Property>
        <Property Descriptor="100">MD75632</Property>
        <Property Descriptor="200">ABC1234</Property>
        <Property Descriptor="200">5632</Property>
    </Properties>
    <Properties>
        <Property Descriptor="100">1378314022</Property>
        <Property Descriptor="100">MD75632</Property>
        <Property Descriptor="200">123456</Property>
        <Property Descriptor="200">5632</Property>
    </Properties>
    <Properties>
        <Property Descriptor="100">1378314023</Property>
        <Property Descriptor="100">MD75632</Property>
        <Property Descriptor="200">123456</Property>
        <Property Descriptor="200">5632</Property>
    </Properties>
    <Properties>
        <Property Descriptor="100">1378314024</Property>
        <Property Descriptor="100">MD75632</Property>
        <Property Descriptor="200">123456</Property>
        <Property Descriptor="200">5632</Property>
    </Properties>
</Events>

If you want to get the last en first occurence over all the Properties the XSLT should be slightly different:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Events">
        <xsl:copy>
            <Properties>
                <xsl:apply-templates select="(Properties/Property[@Descriptor = '100'])[1]" />
                <xsl:apply-templates select="(Properties/Property[@Descriptor = '100'])[last()]" />
                <xsl:apply-templates select="(Properties/Property[@Descriptor = '200'])[1]" />
                <xsl:apply-templates select="(Properties/Property[@Descriptor = '200'])[last()]" />
            </Properties>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

The result would then be:
<?xml version="1.0" encoding="UTF-8"?>
<Events>
    <Properties>
        <Property Descriptor="100">1378314022</Property>
        <Property Descriptor="100">MD75632</Property>
        <Property Descriptor="200">ABC1234</Property>
        <Property Descriptor="200">5632</Property>
    </Properties>
</Events>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any way, on Chrome DevTools, to see if a property's value was set as a result of author stylings, user-agent stylings or initial stylings Is there any way, on Chrome DevTools, to see if a property's value was set as a result of author stylings, user-agent stylings or initial stylings.
I'd like to learn about initial and user-agent stylings as I create. I know it's possible to look up initial on MDN. I don't actually know a document that lists all of, for example, Chrome's stylings.
I'm guessing, if there were a way, it'd lie in the 'Styles' & 'Computed' section.

A: On the Styles tab, you can see which CSS rules are being applied, and where the rules come from. On Stack Overflow, you can see:

On the top right of a rule set section, you can see the source of the rules listed on the left. If the top right says "user agent stylesheet", then the rules for that section which are not crossed out are being applied. (If the rules are crossed out, they're being overridden by later rules on the page)
If the top right says <style> or a filename like something.css, then the styles are being applied due to a style tag on the page.
The screenshot above is when the <body> is being selected. As you can see, there are 2 user agent stylesheet rules for the body: display: block and margin: 8px. But both rules are crossed out; they're being overridden by rules in <style> tags on the page.
There are also initial properties which are not set in the <style> of a page, or by the user agent stylesheet. These can be differentiated by going to the "Computed" tab and checking which properties are faded out. For example, on an empty page with just a <div>, you'll see:

The only rule (here) applied by the user agent stylesheet is display: block on the <div>. All the other faded-out rules are the initial ones. Rules applied by the user agent stylesheet or by a <style> tag will be dark red and black, not faded.


text:
Q: Number of functions from a set to another set We have two sets $A$ and $B$ . The first set has $m$ elements and the second set has $n$ elements . How many functions can we create using $A$ as domain and $B$ as range ? (with proof)

A: We can consider an example: let be $A=\{1,2,3,4\}$ and $B=\{a,b,c\}$, we want to build all the functions from $A$ to $B$.
To each element of A (domain) is associated to an element of B (only one), while an element of B can be associated with multiple elements of A, so we have:

*

*To the first element of $A$ we can associate one element of $B$ choosing it between three different ways $B=\{a,b,c\}$

*To the second element of $A$ we can associate one element of $B$ choosing it between three different ways $B=\{a,b,c\}$...and so on

We can understand that we have $3^4$ functions. In general if we have $m$ elements in $A$ and $n$ elements in $B$, then we get $n^m$ functions.


text:
Q: Why does return statement and print statement return different answers? The problem I am having is why does returning greatestProduct and printing greatestProduct output different results. The former answer is wrong and the latter is correct.
#include <iostream>
#include <string>
using namespace std;

int largestproduct();
int main() {
cout << largestproduct() << endl;
}

int largestproduct()
{
const int adjacentDigits = 13;
int n = 0;
unsigned long greatestProduct = 0;
signed char num[] = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";

while(n <= 1000-adjacentDigits)
{
    unsigned long product = 1;
    for(int i = n; i < n+adjacentDigits;i++)
    {
        product *= (num[i] - '0');
    }

    if(greatestProduct < product)
    {
        greatestProduct = product;
    }
    n++;

}
cout << greatestProduct << endl; //the problem is right here!!!
return greatestProduct;
}

A: You need to change int largestproduct() to: unsigned long largestproduct(). Since you are losing precision due to an implicit conversion.


text:
Q: GLSL: reuse shader object The OpenGL 4.3 Specification states on page 79 that

Multiple shader objects of the same type may be attached to a single program
  object, and a single shader object may be attached to more than one program object.

Attaching a shader object to different program objects worked fine on an old Nvidia card but fails on a Radeon HD 7850.
Here is a sort-of-minimal example which I used to reproduce the error when linking the same shaders to two different programs:
#!/bin/env python3
from OpenGL.GL import *
from OpenGL.GLUT import *

def compile_shader(source, shadertype):
    shader = glCreateShader(shadertype)
    glShaderSource(shader, source)
    glCompileShader(shader)
    if not glGetShaderiv(shader, GL_COMPILE_STATUS):
        print(glGetShaderInfoLog(shader).decode())
    return shader

def link_program(*shaders):
    prog = glCreateProgram()
    for shader in shaders:
        glAttachShader(prog, shader)
    glLinkProgram(prog)
    glValidateProgram(prog)
    print(glGetProgramInfoLog(prog).decode())
    return prog

glutInit('')
glutInitContextVersion(4, 3)
hwnd = glutCreateWindow(b'Shader Test')

print(glGetString(GL_VERSION).decode())

vtx_src = """#version 330 compatibility\nvoid main() { gl_Position = vec4(1, 1, 1, 1); }"""
frg_src = """#version 330 compatibility\nvoid main() { gl_FragColor = vec4(1, 1, 1, 1); }"""

v1 = compile_shader(vtx_src, GL_VERTEX_SHADER)
f1 = compile_shader(frg_src, GL_FRAGMENT_SHADER)
link_program(v1, f1)    # works
link_program(v1, f1)    # fails

Output:
4.3.12780 Core Profile Context 9.00.11
Validation successful.

Vertex shader(s) failed to link, fragment shader(s) failed to link.
Vertex link error: INVALID_OPERATION.
ERROR: 1:1: error(#132) Syntax error: "v" parse error
ERROR: error(#273) 1 compilation errors.  No code generated

fragment link error: INVALID_OPERATION.
ERROR: 1:1: error(#132) Syntax error: "v" parse error
ERROR: error(#273) 1 compilation errors.  No code generated

Am I doing something wrong here?
The error message that the shader's sources are parsed during linking, which seems strange to me. After all, the shaders were successfully compiled (and also linked) before.
I tagged the question with Python, since my code example is using that language and this might be as well the cause of the problem...


text:
Q: Is bounty 100% required to be given out? I have a question which has not been answered the way that I want it to and I am thinking of setting a bounty on it, but the problem is, according to all of the answers, what I want is not possible.
I am just afraid to lose 50 rep or so if all my answers simply say it can't be done.

A: Unfortunately, bounties don't come with a guarantee of an answer.
Be aware that bounties can be automatically awarded (for 50% of the value) even if you don't manually award it.

If you do not award the bounty during the period, half the reward will be automatically be awarded to the top voted answer posted after the bounty start provided it has a score of at least 2. If no new answer matches this requirement, no reputation is awarded at all.


text:
Q: Much Slower Build Times with SpringBoot 1.4.3 Anyone else seeing build performance issues with Spring Boot 1.4.3?  Our previous builds with SpringBoot 1.4.2 were taking about 48 seconds with the following gradle command:
gradlew clean build

After only migrating to Spring Boot 1.4.3 (and therefore pulling in all the associated libraries), they're taking about 3 minutes and 47 seconds.


text:
Q: Linux: w (who) command top-like monitor Is there a monitor like top but for the w (who) command? It's ok if it's a package that needs to be installed. Any Linux flavor. I'd like to have a simple CLI real-time monitor of users logged into the system along with what they're doing. TIA

A: You have several possibilities. Those that come to my mind immediately are all based in the idea to periodically execute the w command (hence, strictly speaking they are no real-time monitors, but top also refreshes the current processes only periodically):

*

*Shell based (bash syntax)
Infinite loop that executes w every second:
while true; do
   clear
   w
   sleep 1
done

*There's also a dedicated program for that purpose, called watch:
watch -n 1 "w"

*While possibility 1 and 2 usually work out-of-the-box on a standard GNU/Linux system, there is also a program called multitail. Although in the first place designed for another purpose,

The program MultiTail lets you view one or multiple files like the
  original tail program. The difference is that it creates multiple
  windows on your console (with ncurses). It can also monitor wildcards:
  if another file matching the wildcard has a more recent modification
  date, it will automatically switch to that file.

it can also execute a program periodically:
multitail -r 1 -l "w"

Both, watch and multitail can also highlight the differences compared to the previous run, please check the man pages for the corresponding (and much more) options.

A: The last command acts by reading /var/log/wtmp. You can set up a watch on it by means ofinotifywait(part of the package *inotify-tools) as follows:
   while inotifywait -e close_write /var/log/wtmp ; do /path/to/executable/script; done

where /path/to/executable/script is some a script (made executable by chmod 755 script) which will do some highly noticeable action to attract your attention, see here for some suggestions.


text:
Q: Possible to have a string that can bend but not twist? I am looking for a string that can bend and flex easily but not twist. I want it to be able to snake through pipes, around bends, but not allow rotation of the thing at the end of the string. The closest I have been able to come is a chain -- the links tend to retard the rotation. But retarding the rotation isn't enough for the project I'm wanting to build, and honestly, the chain is heavy. So that got me thinking... is it even possible to have a string that can bend but not twist? Is there some geometry of forces that would allow such a substance? Does it exist?

A: A variant on bicycle chain (which bends only in one plane) can be
made that has some links with the pivot axes perpendicular; such
a chain will drape into any curve, but will be stiff against
torsion applied to the ends.   This is the equivalent of
a chain linked with universal joints or constant-velocity joints.
Universal Joint wikipedia

A: It seems to me that any linkage that is long and thin enough to bend will be too long and too thin to be able to resist twisting.
That said, there are clever designs that come close.

There seem to be several different designs in circulation. One way, I suppose, would be to have two spiral wires, tightly wound, one inside the other, winding in opposite directions, and the inside wire tightly around a flexible but highly non-compressible core.
The fact that the flexible extension can be used to tighten bolts and nuts shows that it can transfer a high torque from the wrench to the part.

A: Any one-piece string made out of solid material will have the ability to twist. The torque needed to twist the material will depend on its geometry and the shear modulus of the material.

A: I would consider a different approach. Why should you care about the twist along the entire string if the only thing you need is to eliminate rotation at the end of the string? Maybe you should just measure the orientation of the thing at the end of the string (using accelerometers (measuring the direction of the gravity force)  or some kind of gyroscope) and correct the orientation using some actuators.


text:
Q: User Follower model in Django. To show username instead of email of the people users follow I have a custom user model and a follower system. Everything is working good, I have kind of an feed system, where it shows the actions of users which they follow.
Whenever a user follows another user, its showing like:
User A started following userb@gmail.com

I need it to be like
User A started following User B or User A started following username(user B)

How to change that in my code. Please take a look at the code and thanks in advance.
views
@login_required
def user_follow(request):
    user_id = request.POST.get('id')
    action = request.POST.get('action')
    if user_id and action:
        try:
            user = Account.objects.get(id=user_id)
            if action == 'follow':
                Contact.objects.get_or_create(user_from=request.user, user_to=user)
                create_action(request.user, 'started following', user) # TODO: change email to username
            else:
                Contact.objects.filter(user_from=request.user, user_to=user).delete()
            return JsonResponse({'status':'ok'})
        except User.DoesNotExist:
            return JsonResponse({'status':'error'})
    return JsonResponse({'status':'error'})

js for follow
  $('a.follow').click(function(e){
e.preventDefault();
$.post('{% url "posts:user_follow" %}',
  {
    id: $(this).data('id'),
    action: $(this).data('action')
  },
  function(data){
    if (data['status'] == 'ok') {
      var previous_action = $('a.follow').data('action');
      // toggle data-action
      $('a.follow').data('action',
        previous_action == 'follow' ? 'unfollow' : 'follow');
      // toggle link text
      $('a.follow').text(
        previous_action == 'follow' ? 'Unfollow' : 'Follow');
      // update total followers
      var previous_followers = parseInt(
        $('span.count .total').text());
      $('span.count .total').text(previous_action == 'follow' ?
      previous_followers + 1 : previous_followers - 1);
    }
  }
);

});
Model
    class Contact(models.Model):
    user_from = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_from_set', on_delete=models.CASCADE)
    user_to = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_to_set', on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True, db_index=True)

    #USER_FROM IS THE ONE WHO IS FOLLOWING AND USER_TO IS ONE BEING FOLLOWED
    class Meta:
        ordering = ('-created',)

    def __str__(self):
        return f'{self.user_from} follows {self.user_to}'

following = models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)

#adding the above field to User Model class
user_model = get_user_model()
user_model.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers',
                            symmetrical=False))

User model
class Account(AbstractBaseUser):
    email                   = models.EmailField(verbose_name="email", max_length=60, unique=True)
    username                = models.CharField(max_length=30, unique=True)
    first_name              = models.CharField(max_length=50)
    last_name               = models.CharField(max_length=50, blank=True)
    date_joined             = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
    last_login              = models.DateTimeField(verbose_name='last login', auto_now=True)
    is_admin                = models.BooleanField(default=False)
    is_active               = models.BooleanField(default=True)
    is_staff                = models.BooleanField(default=False)
    is_superuser            = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name']

    objects = MyAccountManager()

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

A: Replace:
def __str__(self):
        return self.email

with:
def __str__(self):
        return self.username

This is the default string which will be passed for displaying the model.
For more info see https://docs.djangoproject.com/en/3.0/ref/models/instances/#str


text:
Q: Split Single Image in Four Pices I want to Split Single Image in Four Pieces  and Display it Like Single Image. How can achieve it. I split image through bitmap but it is not fixing in like one single image.

A: I am trying to achieve the same thing. I think this can be done by Android APIs but I would need make more research before answering on that. All I know there is a Java way to that. It might help http://kalanir.blogspot.com/2010/02/how-to-split-image-into-chunks-java.html


text:
Q: Call C++ function from C# which gives value frequently I need to show a live data on text field in C#.basically whenever a value changes, below c++ function under LTscriptenginedll.dll
ConnectLiveData(void* pCallBack, const char** pszTagNames, const int** pnTagAddress,
        bool bdiscconectConnection, bool bPyRequest)

gives new value .
I need to create a C# function which will call and takes value from this C++ function everytime value changes in function.I tried but so for I am still struggling.
Below is my code.
     public unsafe float StartLiveInfo(string tagNameFromRequest)
    {
        string tagName = tagNameFromRequest;//"Motor_1.OutPut.VI";
        byte[] tagNameByte = Encoding.ASCII.GetBytes(tagName);
        IntPtr tagNamePtr = Marshal.UnsafeAddrOfPinnedArrayElement(tagNameByte, 0);

        IntPtr[] tagNameIntPtr = new IntPtr[2];
        tagNameIntPtr[0] = tagNamePtr;
        tagNameIntPtr[1] = IntPtr.Zero;

        int tagValueTemp = 0;
        int*[] tagValuePtr = new int*[2];
        tagValuePtr[0] = &tagValueTemp;
        tagValuePtr[1] = null;
        float test;

        fixed (int** tagValue1 = tagValuePtr)
        {

            fixed (IntPtr* tagName1 = tagNameIntPtr)
            {
                try
                {
                    myCallBackPtr obj = new myCallBackPtr(CallMethod);
                    int finalTagValue = ConnectLiveData(obj, tagName1, tagValue1,false,true);
                    test = Convert.ToSingle(*tagValue1[0]);
                    return test;
                }
                catch (Exception ex)
                {
                    return 0;
                }
            }
        }
    }

This is how I have called dll function and using delegate.
    public delegate void myCallBackPtr();
    [DllImport("LTscriptenginedll.dll")]
    public static extern unsafe int ConnectLiveData(myCallBackPtr ps,IntPtr* test, int** temp,bool bdiscconectConnection, bool bPyRequest);

Here is callMethod
        public static void CallMethod()
    {
        Console.WriteLine("callbackcalled");
    }

I am calling this StartLiveInfo function from main.aspx on buttonclick event and showing return value in text field.
below it the code:
        protected void Button1_Click(object sender, EventArgs e)
    {
        float retValue = oraDal.StartLiveInfo("M1.Speed");
        TextBox1.Text = Convert.ToString(retValue);
    }

A: You might need to apply the UnmanagedFunctionPointerAttribute to your myCallbackPtr delegate.

A: If your requirement is add C++ code into C# Code, you will need to do some steps:

*

*At solution explorer, right-click in your Project and go to Properties;

*In the Build menu, go to General sub-menu and check the option "Unsafe code" like this image bellow:

*If you end these steps above, good luck! You'll may add C++ code into your C# project without impediments.

A: Make sure you have the DLL located in the same directory that your executable is in, so that at runtime it can actually find and load the DLL containing your c++ function.


text:
Q: How to show records related to upper records too in a subgrid? How can I build a subgrid that displays related records both of the current record and records above it, and can it contain complex conditions ?
One of my requirements is this:
I want to put a subgrid in Account form showing the related Contacts of the current Account, and also include the Contacts related to Accounts above the current one if a Two Options attribute of the contact is set to Yes.
Specifically, I'm looking at the Company Name on Contact to establish it's related to an Account.
I'm at a loss and start to doubt it's doable.

A: Not an out of the box solution but if you don't mind losing the sub grid command bar functionality you can use the following concept that displays a fetchxml inside a sub-grid.
Step 1 - would be to get all related accounts ids using a fetch or odata
Step 2 - construct a fetchxml with OR filter to get all contacts


text:
Q: How to install mysql2 on Ubuntu 16.04 [ ERROR: Error installing mysql2: ERROR: Failed to build gem native extension.] I don't know install mysql2 on ubuntu :(
sudo gem install mysql2
Building native extensions.  This could take a while...
ERROR:  Error installing mysql2:
ERROR: Failed to build gem native extension.

current directory: /var/lib/gems/2.3.0/gems/mysql2-0.4.4/ext/mysql2
/usr/bin/ruby2.3 -r ./siteconf20160515-9715-1s2u1sj.rb extconf.rb
mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h

extconf failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.3.0/gems/mysql2-0.4.4 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/mysql2-0.4.4/gem_make.out

sudo apt-get install libmysqlclient-dev
Lendo listas de pacotes... Pronto
Construindo árvore de dependências
Lendo informação de estado... Pronto
libmysqlclient-dev is already the newest version (5.7.12-0ubuntu1).
0 pacotes atualizados, 0 pacotes novos instalados, 0 a serem removidos e 61 não atualizados.

but is not working

A: sudo apt-get install libnetcdf-dev libssl-dev libcrypto++-dev libgmp-dev

has resolved same issue for me

A: First, install libmysqlclient-dev using:
sudo apt-get install libmysqlclient-dev

Then:
bundle

A: sudo apt-get install ruby-mysql2


text:
Q: There she is, there he is, there you are, and there it is In a movie when a lady entered the room a man exclaimed: there she is! I think this means something like drawing people's attention, kind of introducing her to the rest of public.
If we replace she with he certainly the meaning won't change.
But if we use you the meaning changes completely according to Cambridge Dictionaries Online: used when giving something to someone or used to mean "I told you so".
When I replaced the personal pronouns with it I was surprised to find nothing (to explain the phrase), on the Internet, but Vietnam's references.
Would you please help me to understand the meaning of these phrases?

A:
There [he/she/it] is!

is an exclamation that you have found something you were looking for. The speaker was probably wondering where she was, or at the least talking about her, when she appeared.
The reason it's not listed in the dictionaries is that, although it's a common phrase, it's not a "special" phrase - it's just a normal grammatical construction and its meaning is derived from the meaning of the constituent parts:
There (location) he (subject) is (verb to be) !
The emphasis is usually on there because you're emphasizing that you didn't know the location of the person (or object) and now you've found it: he/she/it is there.

There you are!

can also be used in this way. It means, "I was looking for you and now I've found you" or "I wondered where you are, but now you've appeared." You wouldn't say it in the middle of a conversation; you'd say it at the start.
However, there is another meaning of There you are!, which is the one you found. It's not more common, it's just that the phrase itself has a particular meaning beyond the definition of the individual elements, and so it's more necessary to define it.

Here I am!

would be the equivalent for the first person. (You can't say "There" because the here/there distinction is relative to the speaker.)
It has a similar meaning: you are announcing your arrival because you believe everyone was expecting you somehow - either looking for you, or waiting for you, or something similar.

A: "There you are!" can be used "literally" (perhaps meaning something like "I didn't know where you were, but now I see you are there [in some specific location]"), it also has a peculiar idiomatic sense...

There you are! = You have arrived at [the metaphoric location of] the truth/solution/crucial point.

This same idiomatic usage can often occur with we and sometimes with I, but rarely with other personal pronouns (i.e. - native speakers wouldn't normally use "There he is!" to mean anything like "He's arrived at the answer!"). The reason for this is that it's usually used in contexts where two people are talking together in search of a solution (or one person who already knows it is leading the other to the answer).
Similar (often exactly synonymous) is...

There you go! = you've arrived at (or are accurately heading towards) the truth/your goal.

I suspect that second version may be less common in AmE. The eponymous star of the 70s American TV series McCloud often said "There ya' go" in contexts where he seemed puzzled by the syntax/meaning of his "catchphrase". As I recall, he often said it it what appeared to me to be inappropriate circumstances, but I can't say whether that reflected the fictional character's lack of familiarity, or that of the scriptwriters.

A: there it is definition
7) there it is - That is the state of affairs.
If you have seen the movie "Amadeus" (1984), Emperor Joseph II uses this phrase alot.
Maybe something like "That's the way it is."


text:
Q: How can I get a new Fedora 19 install to boot on Intel NUC I have a newly installed Fedora 19 on an Intel NUC computer.   During installation, I selected the "reclaim all space" option and took the default partitioning.
The install created an EFI boot partition, but the BIOS on the computer does not seem to recognize it.   I can boot Fedora Live from a USB stick and mount the partitions without issue.
If the UEFI boot and Legacy boot options are both selected, the BIOS displays
Reboot and Select proper Boot device
or Insert Boot Media in selected Boot device and press a key.

If either of the options are unchecked:
A bootable device has not been detected.
Please refer to the Product Guide at http://support.interl.com/support/motherboards/desktop

I did not find any helpful info at the URL above...
Here is the partition table:
Number  Start (sector)    End (sector)  Size       Code  Name
   1            2048          411647   200.0 MiB   EF00  EFI System Partition
   2          411648         1435647   500.0 MiB   0700
   3         1435648       234440703   111.1 GiB   8E00

And the details on partition 1:
Partition number (1-3): 1
Partition GUID code: C12A7328-F81F-11D2-BA4B-00A0C93EC93B (EFI System)
Partition unique GUID: C81832BE-6B66-474C-99B3-8C4DF9654B93
First sector: 2048 (at 1024.0 KiB)
Last sector: 411647 (at 201.0 MiB)
Partition size: 409600 sectors (200.0 MiB)
Attribute flags: 0000000000000000
Partition name: 'EFI System Partition'

I've been unsuccessful in finding details that match this particular scenario
Here is the output from efibootmgr after booting from the USB stick.
# efibootmgr
BootCurrent: 0004
Timeout: 1 seconds
BootOrder: 0001,0002,0003,0004,0000
Boot0000* Fedora
Boot0001* SATA : PORT 0 : Crucial_CT120M500SSD3 : PART 0 : Boot Drive
Boot0002* USB : Generic SD/MMC/MS/xD 1.07
Boot0003* USB : Generic MicroSD/M2 1.08 : PART 1 : Boot Drive
Boot0004* UEFI : USB : Generic MicroSD/M2 1.08 : PART 0 : OS Bootloader

Ideally, I'd like to be able to boot directly from the SATA drive, but at this point, I'd also be open to a solution that has a multi-stage boot using a USB stick -- as long as the root partition is on the SATA drive.

A: I resolved this by booting the Fedora 19 Live CD with UEFI disabled (i.e., only Legacy Boot enabled), and reinstalling F19, which created an MBR configuration.
I don't have UEFI, but I do have a bootable install.


text:
Q: K-theory formulation of the index theorem The Atiyah-Singer index theorem is one of the most important results in twentieth century's mathematics. It states that for an elliptic differential operator $D$ on a smooth, oriented compact manifold $M$ one has $\operatorname{Ind}D=\langle\operatorname{ch}(D) \cdot\operatorname{Td}(M), [M] \rangle$. This is the form of index theorem which I know: however, reading some expository texts I met the statement that it is nice to translate $K$-theoretic formulation of the index theorem into the "local" form where characteristic classes are involved. I wonder what does it mean:

Question What is the $K$-theoretic formulation of the index theorem?

I would be also very grateful for some historical explanation about the issues of $K$-theoretical formulation of index theorem and the one which I formulated (which one was earlier? all proofs are due to Atiyah and Singer? Which of them is seen to be more improtant? and so on...)

A: I disagree that index theorem is "one of the most important results in twentieth century's mathematics". This kind of superlatives usually does not mean anything, unless one can draw a fine line between "important", "more important", "most important", "of greatest importance", etc. I think it is better to be humble about it, even though my own research field is index theory and I wrote a thesis on it. Personally I think Atiyah-Singer is remarkable, but definitely not "one of the most important"results I know.
Having said that, I encourage you read an expository article on the K-theory proof of index theorem. The statement of theorem in K-theory setting is in page 17. The central part of the K-theory proof of index theorem is based on Thom isomorphism, and its proof in K-theory setting is not easy. So maybe a starting point is to go through Atiyah's book K-theory and Hatcher's book Vector bundles and K-theory, then going back to the proof itself.
You asked "I met the statement that it is nice to translate K-theoretic formulation of the index theorem into the "local" form where characteristic classes are involved. ". This is (in some sense) incorrect, and you should check the original source of this statement. The K-theory proof of the index theorem is global and not easily computable, what this statement is alluding to is the heat kernel proof of index theorem, which is usually called "the local index theorem" as it gives the topological side as an integral of differential forms in a local form:
$$
Ind(\mathcal{D})={\frac{1}{(4\pi i)^{m}}\int_{M}(\det)^{1/2}(\frac{\mathcal{R}/2}{\sinh(\mathcal{R}/2)})Tr(\tilde{Z}e^{\tilde{Q}})}
$$
But this statement has almost no characteristic class involved, what I mean is you can think of it purely in terms of differential forms without need to appeal to definition of Chern character or Todd class. The heat-kernel proof has the benefit of being computable, for example one can use it to show Atiyah-Singer implies Gauss-Bonnet and Riemann-Roch relatively easily. However, the statement is somehow uglier and which one you prefer is matter of aesthetic. Since the heat-kernel proof is local in nature, it is not clear to how translate it into an appropriate algebraic setting (like homogeneous spaces, loop spaces, etc) where one may expect a simplified version of Atiyah-Singer. And similarly K-theory proof does not work well when one wants to use it to make computation in an arbitrary given manifold.
There are also other proofs, using cobordism theory(the original proof), probability theory, and even path integral. But it is more or less outside of my expertise as I never read these proofs carefully. So I cannot comment on it.

A: From the Wikipedia page on the index theorem:

One can also define the topological index using only K theory (and this alternative definition is compatible in a certain sense with the Chern-character construction above). If $X$ is a compact submanifold of a manifold $Y$ then there is a pushforward (or "shriek") map from $K(TX)$ to $K(TY)$. The topological index of an element of $K(TX)$ is defined to be the image of this operation with $Y$ some Euclidean space, for which $K(TY)$ can be naturally identified with the integers $\mathbb Z$ (as a consequence of Bott-periodicity). This map is independent of the embedding of $X$ in Euclidean space. Now a differential operator as above naturally defines an element of $K(TX)$, and the image in $\mathbb Z$ under this map "is" the topological index.

The Wikipedia article is very detailed and answers pretty much all your question. The proof due to Atiyah--Singer and uses K-theory. The first proof used the Hirzebruch–Riemann–Roch theorem (I'm just quoting excerpts from Wikipedia at this point). Other proofs were given by other people...


text:
Q: Formatar numero de telefone como (00) 00000-0000 Tenho um problema com a formatação dos numeros de telefone em meu site escrito em PHP.
Neste formulário, o usuário digita seu numero de telefone:

        <?php _e('Whatsapp "Recomendado"',); ?> *

        <?php UserForm::mobile_text(osc_user()); ?>

depois de salvo todo processo,o telefone aparece no perfil do usuário:

Whatsapp

<?php printf('%s', osc_user_phone_mobile()); ?>

Eu estou procurando uma maneira de o numero aparecer formatado no seguinte padrão (xx) xxxxx-xxxx sem usar plugins ou JS. O formulário é Bootstrap.

A: Tem uma solução bem simples utilizando o plugin jquery.mask
Primeiro, você pode encontrar o jquery.mask nesse link: https://igorescobar.github.io/jQuery-Mask-Plugin/
Depois, no seu arquivo JS, basta colocar essa função:
$(document).ready(function() {
    $("#telefone").mask("(00) 00000-0000")
})

Com esse pequeno trecho de código todos os seus campos com id "telefone" já estarão com a máscara definida.
Veja esse exemplo funcionando aqui: http://natuqualy.com.br/seja-representante


text:
Q: Why is my pandas dataframe only showing results for one dataset? I have two datasets in CSV format that I want to loop through and show results for in one pandas dataframe. Right now my results in df are only showing for the B dataset but if I try to print "data" it shows my two CSV datasets that I have below.
The test CSV datasets are:

Date
fastMA
slowMA
Ticker

01/01/2021
1
5
A

02/01/2021
2
5
A

03/01/2021
4
5
A

04/01/2021
5
5
A

05/01/2021
6
5
A

06/01/2021
7
5
A

07/01/2021
4.5
5
A

08/01/2021
4
5
A

09/01/2021
3
5
A

Date
fastMA
slowMA
Ticker

01/01/2021
1
5
B

02/01/2021
2
5
B

03/01/2021
4
5
B

04/01/2021
5
5
B

05/01/2021
6
5
B

06/01/2021
7
5
B

07/01/2021
4.5
5
B

08/01/2021
4
5
B

09/01/2021
3
5
B

ticker = csv.reader(open('gdrive/My Drive/data/test/test_tickers/test_tickers.csv'))
for symbols in ticker:

  tickers = symbols
  data = pd.read_csv('gdrive/My Drive/data/test/test_data/{}.csv'.format(symbols))

  i = 1
  j = len(data)
  in_trade = 0
  dates = []
  symbol = []

  while i < j:
    long = data["fastMA"][i] > data["slowMA"][i]
    close = data["fastMA"][i] < data["slowMA"][i]

    if long and in_trade == 0:
      in_trade = 1
      symbol.append(data["Ticker"][i])
      dates.append(data["Date"][i])
      i += 1
    elif long and in_trade == 1:
      in_trade = 1
      i += 1
    elif close and in_trade == 1:
      in_trade = 0
      i += 1
    else:
      i += 1
d = {'Date':dates,'Ticker':symbol}
d
df = pd.DataFrame(d, columns=('Date','Ticker'))
df

Do I need to add in something else?
EDIT:
The output I'm getting now in df:

Date
Ticker

05/01/2021
B

My desired output in df:

Date
Ticker

05/01/2021
A

05/01/2021
B

A: For each ticker row that is read in, you were blanking dates and symbol, they need to be outside of your loop. If you restructure a bit, you should get your desired output:
import csv
import pandas as pd

with open('test_tickers.csv', newline='') as f_tickers:
    csv_tickers = csv.reader(f_tickers)
    dates = []
    symbols = []

    for symbol in csv_tickers:
        data = pd.read_csv(f'{symbol[0]}.csv')

        i = 1
        j = len(data)
        in_trade = 0

        while i < j:
            long = data["fastMA"][i] > data["slowMA"][i]
            close = data["fastMA"][i] < data["slowMA"][i]

            if long and in_trade == 0:
                in_trade = 1
                symbols.append(data["Ticker"][i])
                dates.append(data["Date"][i])
            elif long and in_trade == 1:
                in_trade = 1
            elif close and in_trade == 1:
              in_trade = 0

            i += 1

d = {'Date' : dates, 'Ticker' : symbols}
df = pd.DataFrame(d, columns=('Date','Ticker'))

print(df)

Giving:
         Date Ticker
0  05/01/2021      A
1  05/01/2021      B

(This assumes test_tickers.csv contains two lines containing A and B and the A.csv and B.csv contains the data in your question)


text:
Q: Magmi url_key slug - how to include sku? I'm trying to figure out the best course of action to change URL keys in the store to be name-sku.html
Currently MAGMI seems to be dictating the url key, which is fine.  Some of our products are not imported through MAGMI, so I think I'd probably have to also use the updateurl event to change the url on save -- I found this here for that -- https://magento.stackexchange.com/questions/24869/manufacturer-in-product-url-key
The question is, how is it best to do this within MAGMI?  I'm importing about 300,000 products currently.  The URL also needs to change, as it currently just uses the default settings.
I've looked into the wiki here -- http://wiki.magmi.org/index.php?title=Value_Replacer -- I guess the following code could work for the way it is currently working -- but what do I actually type into the value replacer box?
{{ Slugger::slug({item.name}) }}

Does anyone know how to add the sku to this as well?  Would I just do something like....
{{ Slugger::slug({item.name} ."-". {item.sku}) }}

Also, does anyone know if this automatically adds the dashes and the .html?
Any guidance would be extremely appreciated.
EDIT:
I have successfully tested this as working in my test environment, but it is not working as expected in my production environment.  I'll go over what happens, and what I did.
1) I purged the core_url_rewrite table
2) I deleted all cache
3) I set up MAGMI (updated it to the most current version as well, and triple checked all my settings)
4) MAGMI went through fine, and the url key on about 5 products that I checked for were how I would expect
5) During the catalog url rewrites reindex, all url keys disappeared.
6) After the reindex was done, they were now in the default magento format (using just the name, and not the sku)
Any ideas?
The only difference between production and development that I can think of at the moment that may have anything to do with this is the fact that I did create a module based on the linked manufacturer-in-product-url-key question on production.  Now that I think of it, maybe that's the main difference that I need to address..... I didn't think reindexing would have anything to do with that, but maybe I'm wrong.
Anyway, if anyone has any insight, I would still appreciate it.  I have a feeling maybe MAGMI should also be rewriting the url_path??  I think I read something about that somewhere.

A: Ok, I figured this out.  I think this is the best approach.
I was mistaken in my question.  I'm actually looking to add the mpn, not the sku.  Either way, that doesn't change the process.
So, the best thing to do is to use the Value Replacer in MAGMI, and to create a custom module that updates the url on the Magento catalog_product_save_before event.
Here's exactly what I did.....
MAGMI settings (Value Replacer)
Replaced attributes: url_key
New value for url_key: {{ Slugger::slug({item.name}.' '.{item.mpn}) }}

URLKeyChange (Magento Module)
app/code/local/My/URLKeyChange/etc/config.xml
<config>

    <global>

       <models>

           <LeathornURLRewrite>
                <class>Leathorn_URLKeyChange_Model</class>
           </LeathornURLRewrite>

       </models>

            <events>
                <catalog_product_save_before>
                    <observers>
                        <LeathornURLRewrite>
                            <type>singleton</type>
                            <class>LeathornURLRewrite/observer</class>
                            <method>updateurl</method>
                        </LeathornURLRewrite>
                    </observers>
                </catalog_product_save_before>
            </events>
    </global>

</config>

app/code/local/My/URLKeyChange/Model/Observer.php
class My_URLKeyChange_Model_Observer {
    public function updateurl($observer){
        Mage::log('My log entry', null, 'mylogfile.log');
        if($observer->getEvent()->getProduct()){
            $Product=$observer->getEvent()->getProduct();
            $Url='';
            if(!is_null($Product->getData('name'))):
            $Url=$Url.$Product->getData('name');
            endif;
            if(!is_null($Product->getData('mpn'))):
            $Url=$Url.$Product->getData('mpn').'-';
            endif;
            //Mage::log('My log entry'.$Url, null, 'mylogfile.log');
            $Product->setData('url_key',$Url);
        }
    }
}

app/etc/modules/My_URLKeyChange.xml
<config>
    <modules>
        <My_URLKeyChange>

            <!-- Whether our module is active: true or false -->
            <active>true</active>

            <!-- Which code pool to use: core, community or local -->
            <codePool>local</codePool>

        </My_URLKeyChange>
    </modules>
</config>

A: URL key will always be just dash separated strings. Don't worry, magento will add .html in it dynamically. You can see in magnento backend in any product configuration page, url key is without html.
Also magento will add dash in url key, Replace your "-" by space " ". Otherwise it will take last word of name and SKU as one word. :)


text:
Q: Windows 10, on my HP laptop I am unable to complete a back up to my external hard drive.
I have tried several times and the details screen said the following: "Windows back up failed to get an exclusive lock on the EFI system partition (ESP). This may happen if another application is using files on the ESP. Please retry the Operation."
Details: Access is denied.
error code Ox8078011E
Why has this happened, what caused it, and how do I rectify it?
Your help and advice would be appreciated.

A: You can try something that helped someone here:

Deleting or renaming the WindowsImageBackup folder in the target
  location and rerunning the backup


text:
Q: bind variables not allowed for data definition operations in oracle I'm trying to create a view in Oracle using the below Query, on executing it, throws error message

bind variables not allowed for data definition operations

When I run the same quer on Query window it executes. On trying to add to view it get this error.
SELECT Dept.Name || ' ' || Course.DeptCode AS CourseCode, 'Yes' AS IsActive
FROM Coursetab Course, Depttab dept
WHERE        Course.CODE = Depttab.CODE
UNION ALL
SELECT Dept.OldName || ' ' || Course.oldDeptCode AS CourseCode, 'No' AS IsNotActive
FROM Coursetab Course, Depttab dept
WHERE        Course.OldCODE = Depttab.oldCODE

A: Please see below how you can create a view:
/* Created Tables */
CREATE TABLE Coursetab
(
   DeptCode      NUMBER,
   oldDeptCode   NUMBER
);

CREATE TABLE Depttab
(
   name      VARCHAR2 (10),
   OldName   VARCHAR2 (10),
   CODE      NUMBER,
   oldCODE   NUMBER
);

/* Created Successfully view */
CREATE OR REPLACE VIEW XYX
AS
   (SELECT Dept.Name || ' ' || Course.DeptCode AS CourseCode,
           'Yes' AS IsActive
      FROM Coursetab Course, Depttab dept
     WHERE Course.DeptCode = Dept.CODE
    UNION ALL
    SELECT Dept.OldName || ' ' || Course.oldDeptCode AS CourseCode,
           'No' AS IsNotActive
      FROM Coursetab Course, Depttab dept
     WHERE Course.oldDeptCode = Dept.oldCODE);


text:
Q: VBA CPU usage during debug Is there a reason why CPU usage will jump when debugging in Word VBA?
I noticed that even when I "step into" a project, and nothing is actually being calculated except waiting for me to step to the next statement, the CPU goes up about 25-30% and stays there, across all 4 cores on a Core-i5 2400.
I can verify in Task Manager that WINWORD.EXE is the culprit. Memory use is consistent and expected. CPU usage up almost 30%, and it immediately drops off if I stop debugging.
This is in Office 2007.

A: Debugging requires tracking all related objects and variables in addition to actually using them as they would in non-debug mode.
This tracking is still happening even while sitting waiting for you to hit "Next step" or alike.


text:
Q: Xamarin Android System.ObjectDisposedException when scrolling through ListView of Images I am writing an Android app using Xamarin.Forms, and I've been seeing this System.ObjectDisposedException: 'Cannot access a closed Stream.' come up on one of my pages where I have a ListView with Images in it.  When scrolling down, the images load fine and all is well.  But when scrolling back up, that exception is thrown.  The images come from a database as a byte[], so I am using Memory Streams to assign the Image sources. The exception is coming from the streams closing, but I am not sure how to keep them open or find some other workaround for this issue.
Here is my xaml:
<ListView ItemsSource="{Binding imageGallery}" x:Name="imageList" RowHeight="100" VerticalScrollBarVisibility="Always">
                <ListView.ItemTemplate >
                    <DataTemplate>
                        <ViewCell>
                            <Grid >
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="0.5*" />
                                    <ColumnDefinition Width="0.5*" />
                                </Grid.ColumnDefinitions>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="100"/>
                                </Grid.RowDefinitions>
                                <Image Source="{Binding photo.Source}" x:Name="imageInGrid" Rotation="90" Grid.Column="0" MinimumHeightRequest="100" VerticalOptions="FillAndExpand"/>
                                <StackLayout Orientation="Vertical" Grid.Column="1" VerticalOptions="Center" >
                                    <Label Text="{Binding date}" FontSize="18" TextColor="Navy" HorizontalTextAlignment="Start" VerticalTextAlignment="Center" />
                                    <Label Text="{Binding manifestNum}" FontSize="18" TextColor="Navy" HorizontalTextAlignment="Start" VerticalTextAlignment="Center" FontAttributes="Bold" />
                                </StackLayout>
                            </Grid>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

Here is my C#:
static ObservableCollection<ImageViewer> imageGallery;
static List<Stream> streams;
        public ImagesPage()
        {
            InitializeComponent();
            imageGallery = new ObservableCollection<ImageViewer>();
            streams = new List<Stream>();

            //query string
            using (SqlConnection conn = new SqlConnection(queryString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(query, conn))
                {
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            ImageViewer viewer = new ImageViewer
                            {
                                imageData = (byte[]) reader[2],
                                photo = new Image(),
                                date = reader[1].ToString().Split(' ')[0],
                                manifestNum = reader[0].ToString().Substring(4)
                            };
                            Stream stream = new MemoryStream(viewer.imageData);
                            viewer.photo.Source = ImageSource.FromStream(() => { return stream; });
                            streams.Add(stream);
                            imageGallery.Add(viewer);
                        }
                    }
                }
            }
            imageList.ItemsSource = imageGallery;
        }


text:
Q: sfdx version cannot be updated I am using sfdx on mac.
I have tried:
sfdx update
npm update --global sfdx-cli
npm install --global sfdx-cli

And even:
npm uninstall --global sfdx-cli

and install back. But the version still remains 7.8.1.
How should I fix this?


text:
Q: How to view multiple reports in a crystal report viewer then print Assuming that I have two separate reports and I want to show it in a crystal report viewer then print it.
I have tried the number 1 solution in this link reference. I put 2 crystal report viewer in my Winforms.
then I use the code below but only one report is shown and printed.
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Public Class frmStPeter
    Private Sub frmStPeter_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim c As Integer
        Dim doctoprint As New System.Drawing.Printing.PrintDocument()
        doctoprint.PrinterSettings.PrinterName = "EPSON L120 Series on PC1"
        Dim Report As New ReportDocument
        Report.Load("C:\CRep\stPeter.rpt")
        Report.Load("C:\CRep\stAnthony.rpt")
        Dim rawKind As Integer
        For c = 0 To doctoprint.PrinterSettings.PaperSizes.Count - 1
            If doctoprint.PrinterSettings.PaperSizes(c).PaperName = "ClassSchedule" Then
                rawKind = CInt(doctoprint.PrinterSettings.PaperSizes(c).GetType().GetField("kind", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic).GetValue(doctoprint.PrinterSettings.PaperSizes(c)))
                Exit For
            End If
        Next

        Report.PrintOptions.PaperSize = CType(rawKind, CrystalDecisions.Shared.PaperSize)
        Report.PrintToPrinter(1, False, 1, 1)
        CR1.ReportSource = Report
        CR2.ReportSource = Report
        CR1.Refresh()
        CR2.Refresh()

    End Sub

End Class

Update. I did it this way. the print was successful but i only view the first report in the report viewer. I cannot find the settings to view my two reports at the same time
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Public Class frmStPeter
    Private Sub frmStPeter_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim c As Integer
        Dim doctoprint As New System.Drawing.Printing.PrintDocument()
        doctoprint.PrinterSettings.PrinterName = "EPSON L120 Series on PC1"

        Dim Report As New ReportDocument
        Dim Report1 As New ReportDocument
        Report.Load("C:\CRep\stPeter.rpt")
        Report1.Load("C:\CRep\stanthony.rpt")

        Dim rawKind As Integer
        For c = 0 To doctoprint.PrinterSettings.PaperSizes.Count - 1
            If doctoprint.PrinterSettings.PaperSizes(c).PaperName = "ClassSchedule" Then
                rawKind = CInt(doctoprint.PrinterSettings.PaperSizes(c).GetType().GetField("kind", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic).GetValue(doctoprint.PrinterSettings.PaperSizes(c)))
                Exit For
            End If
        Next
        Report1.PrintOptions.PaperSize = CType(rawKind, CrystalDecisions.Shared.PaperSize)
        Report1.PrintToPrinter(1, False, 1, 1)

        Report.PrintOptions.PaperSize = CType(rawKind, CrystalDecisions.Shared.PaperSize)
        Report.PrintToPrinter(1, False, 1, 1)

        CR1.ReportSource = Report
        CR2.ReportSource = Report1

        CR2.Refresh()
        CR1.Refresh()

    End Sub

End Class

Can anyone please help me to solve this. Thank you

A: Crystal Report 9 doesn't support multiple report view. For example you are using a form name frmView and this form having crviewer 9 and want this form to be used throughout the project. In this regard you print Jv and it has been viewed and again you open cash receipt voucher and click print button but viewer neither open another Tab nor any facility to show both print views in the same viewer. Sorry because its already too late.


text:
Q: Repeatedly creating new Vec vs reusing a mutable Vec I recently started working on a new Rust project which requires a lot of attention to performance stats. We are processing millions of rows and there is a code path that creates a small Vec for each row. I wanted to see whether it makes sense to have a mutable Vec instead of creating a new Vec for each row, so I did this test:
fn main() {
    understand_create_vec_cost();
    understand_mut_vec_cost();
}

fn understand_mut_vec_cost() {
    let timer = std::time::Instant::now();
    let mut v1 = Vec::<(usize, usize, usize, usize)>::new();
    let mut v2 = Vec::<(usize, usize, usize, usize)>::new();
    for _ in 0..100000000 {
        let random_val1 = rand::random::<usize>();
        let random_val2 = rand::random::<usize>();
        v1.clear();
        v1.push((random_val1, random_val2, random_val1, random_val2));
        v1.push((random_val2, random_val1, random_val2, random_val1));

        v2.clear();
        v2.push((random_val2, random_val1, random_val2, random_val1));
        v2.push((random_val1, random_val2, random_val1, random_val2));

        if v1.len() != 2 && v1[0].0 != random_val1 {
            println!("v1 is empty");
        }
        if v2.len() != 2 && v2[0].0 != random_val2 {
            println!("v2 is empty");
        }
    }
    println!("Mut Vec: Completed in {:?}", timer.elapsed().as_millis());
}

fn understand_create_vec_cost() {
    let timer = std::time::Instant::now();
    for _ in 0..100000000 {
        let random_val1 = rand::random::<usize>();
        let random_val2 = rand::random::<usize>();
        let v1 = vec![
            (random_val1, random_val2, random_val1, random_val2),
            (random_val2, random_val1, random_val2, random_val1),
        ];
        let v2 = vec![
            (random_val2, random_val1, random_val2, random_val1),
            (random_val1, random_val2, random_val1, random_val2),
        ];

        if v1.len() != 2 && v1[0].0 != random_val1 {
            println!("v1 is empty");
        }
        if v2.len() != 2 && v2[0].0 != random_val2 {
            println!("v2 is empty");
        }
    }
    println!("New Vec: Completed in {:?}", timer.elapsed().as_millis());
}

The results always showed that mutable version is around half a second slower. Below is a sample result, but all were mostly similar. These were measured using release build.

*

*New Vec: Completed in 1187 ms.

*Mut Vec: Completed in 1568 ms.

So my questions are

*

*Does this code make sense for the purpose? Are there any compiler optimizations that happen under the hood because the code was simple? (I added those if conditions thinking that might avoid any compiler optimizations that might favor one implementation)

*Do these results make sense? And why is that? Naive me thinks that each Vec creation means a lot of allocations, and that should cost more than calling clear on the mutable vector.

*I don't have industrial experience in Assembly/C++. What is the right way to start learning about performance-based coding in Rust? What are some starting points?

A: The flaw in your test lies in the way the vec! macro is constructed. when called with arguments, it pre-allocates the space the arguments take in memory immediately. As a hobbyist Rustacean, I would personally recommend using the new vectors so the data can still be borrowed again, since you'll be doing lots of borrowing in rust, but if you have a use case for a mutable vector, (would test myself, but have potato computer) try running it again with let mut let mut v1 = Vec::<usize,usize,usize,usize>::with_capacity(2); which will preallocate the space of two (usize,usize,usize,usize) tuples on the stack. By the way, if you want performance and are using the same sized thing every time with the same type (as in the example) you'll be best off using a fixed-size array- declared like [usize;4], i.e let v1 = Vec::<[usize;4]>::with_capacity(2); which will instead store it on the stack, making your memory much safer and your program much faster since the computer doesn't have to go searching for data.
Forgive me if you were already aware of this resource, but if you are new to rust I reccomend the book for quickly grasping the basics of rust in a manner oriented towards devs moving from other languages (like C)


text:
Q: Clustering trends across categories: which one to use? I have a dataset with daily temperatures for every country in 4 seasons: Spring, Summer, Fall, and Winter.
I wish to group(cluster) countries with similar temperature trends across the 4 seasons. I am aware of basic clustering techniques, but clustering across categories seems new. Is there a package or any previous work on the lines of clustering data trends? Any help is appreciated.


text:
Q: Placing letters under underlined text in XSL-FO using Apache FOP I have a project that requires me to place a ID string under some underlined text in a passage of text.
Here is an example using an inline SVG object with a gray border to show the layout:

I can get close using an inline element with a baseline-shift and then use SVG to render the text. However this has the disadvantage (I think) that I have to manually put in the width of the SVG in pixels, which seems very complicated for such a simple layout.
Here is the XSL-FO markup for this:
<fo:block>
Normal text
<fo:inline baseline-shift="-100%">
    <fo:instream-foreign-object text-align="center" display-align="center" border="solid silver 1px">
        <svg xmlns="http://www.w3.org/2000/svg" height="25" width="120" viewport="0 0 120 25">
            <text x="60" y="10" fill="black" text-anchor="middle" text-decoration="underline" font-size="12pt">underlined text with id</text>
            <text x="60" y="25" fill="black" text-anchor="middle" font-size="12pt">123</text>
        </svg>
    </fo:instream-foreign-object>
</fo:inline>
normal text.
</fo:block>

So my question is: Can I perform this layout in Apache FOP XSL-FO without using instream-foreign-object and SVG?  If I can not, is there some way to not have to put the width in the SVG in pixels?  Or is there some way to calculate how many pixels the SVG will take to render?
I should also note inline-container is not supported in Apache FOP.
https://xmlgraphics.apache.org/fop/compliance.html
Thanks in advance! - Dan

A: Here is a sample done as I suggested with RenderX using the formatting tree.
Format the desired fragments to the intermediate format ... something like this for a single one:
    <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
        <fo:layout-master-set>
            <fo:simple-page-master margin="0mm" master-name="MASTERsite1" page-width="214mm" page-height="29pt">
                <fo:region-body margin="0mm"/>
            </fo:simple-page-master>
        </fo:layout-master-set>
        <fo:page-sequence master-reference="MASTERsite1">
            <fo:flow flow-name="xsl-region-body">
                <fo:table>
                    <fo:table-body>
                        <fo:table-row>
                            <fo:table-cell><fo:block text-decoration="underline" text-align="center">This is Underlined Text with ID</fo:block></fo:table-cell>
                        </fo:table-row>
                        <fo:table-row>
                            <fo:table-cell><fo:block text-align="center">1234567</fo:block></fo:table-cell>
                        </fo:table-row>
                    </fo:table-body>
                </fo:table>
            </fo:flow>
        </fo:page-sequence>
    </fo:root>

The output of that would be this:
    <xep:document xmlns:xep="http://www.renderx.com/XEP/xep" producer="XEP 4.19 build 20110414" creator="Unknown" author="Unknown" title="Untitled">
        <xep:page width="162708" height="29000" page-number="1" page-id="1">
    <xep:word-spacing value="0"/>
    <xep:letter-spacing value="0"/>
    <xep:font-stretch value="1.0"/>
    <xep:font family="Helvetica" weight="400" style="normal" variant="normal" size="12000"/>
    <xep:gray-color gray="0.0"/>
    <xep:text value="This is Underlined Text with ID" x="0" y="18734" width="162708"/>
    <xep:line x-from="0" x-till="162708" y-from="17534" y-till="17534" thickness="600" style="solid"/>
    <xep:text value="1234567" x="58002" y="4334" width="46704"/>
    </xep:page>
    </xep:document>

Where you would modify the result to change the page width, but it's right in the text as the width of the text element of concern, that is change:
 <xep:page width="606614" height="29000" page-number="1" page-id="1">

so the width is from the text line of concern, programmatically pick up the x-till from xep:line or the xep:text line (changing as above). Note, this is exactly equivalent to your SVG example except you have the number programmatically to access right inside this file.
last, using this "file" as an image, one would then use:
 <fo:external-graphic src="test19.xep" content-type="application/xepout" alignment-baseline="central"/>

Now, while you say look at all those steps, this is a solution and all of the above could be automated into a single process chain. First loop through and format all of the objects of concern and make little files from them, then a second pass would instead of formatting those fragments, would use them as images.
Note: The line spacing shown in the attached image of the result cannot be done with FOP (I believe), I think that is a limitation of FOP.
Note #2: I am not a FOP expert and I know nothing of it's implementation, specifically using the area tree as an image in a document. If FOP is a must, I would suggest looking into it. You could just as easily convert the area tree to SVGs and use them as you would be able to use all their dimensions or better just read the area tree into the second transform and generate instream-foreign-object SVGs from it right inline.


text:
Q: Subract one aggregate value from another I'm writing a query to aggregate bookings for an event, and to then split the total figure into two categories: a count of those people with an application, and a count of those without an application.
Calculating the total booking figure and the number of applicants is no problem - the code I'm using is as follows:
SELECT [EVENTMODULE].[DESCRIPTION] as 'Event', cast([EVENTMODULE].[STARTDATE] as date) as 'Event Date',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') then 1 else 0 end) 'Total Bookings',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') AND [COURSEPLACE].[TYPE] = 'Application' then 1 else 0 end) 'Current Applicants' ...

However, I'm having problems with calculating the count of people that do not have an application (i.e. they have no application record associated with their account). I've tried using a NOT EXISTS statement, but discovered that this won't work within an aggregate statement.
So, what I'm instead trying to do is simply subtract the 'Number of Applicants' from the 'Total Bookings' figure, as this will leave me with a count of the number of non-applicants.
I've tried to simply subtract the above two outputs using the line of code below:
SUM ('Total Bookings' - 'Current Applicants') 'Non-Applicants'

But this gives me the error:
"Msg 8117, Level 16, State 1, Line 4
Operand data type varchar is invalid for subtract operator."

I'm presuming I need to get the earlier output to cast as an Integer - please can anyone help me with the syntax?

A: You can't use column aliases from your calculations directly in the same query, you could use your current SELECT as a derived table, or a CTE, or simply derive your new calculation. Also, you should avoid using single quotes for table aliases, instead use []:
SELECT  [EVENTMODULE].[DESCRIPTION] as [Event],
        CAST([EVENTMODULE].[STARTDATE] as DATE) as [Event Date],
        SUM(CASE WHEN [EVENTPLACE].[STATUS] IN ('Accepted','Attended') THEN 1 ELSE 0 END) [Total Bookings],
        SUM(CASE WHEN [EVENTPLACE].[STATUS] IN ('Accepted','Attended') AND [COURSEPLACE].[TYPE] = 'Application' THEN 1 ELSE 0 END) [Current Applicants],
        SUM(CASE WHEN [EVENTPLACE].[STATUS] IN ('Accepted','Attended') AND ISNULL([COURSEPLACE].[TYPE],'') <> 'Application' THEN 1 ELSE 0 END) [Non-Applicants]
        ...

A: Use Square Brackets to escape the space in column names. Single quotes will make it as string constant
select SUM ([Total Bookings] - [Current Applicants]) 'Non-Applicants'
from
(
SELECT [EVENTMODULE].[DESCRIPTION] as 'Event', cast([EVENTMODULE].[STARTDATE] as date) as 'Event Date',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') then 1 else 0 end) 'Total Bookings',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') AND [COURSEPLACE].[TYPE] = 'Application' then 1 else 0 end) 'Current Applicants'
..
)

Note : When you are using Single quotes to escape the space in alias name it will work but it will not work when using it as column names

A: Try this:
SELECT * , [Non-Applicants] = [Total Bookings] - [Current Applicants]
FROM
(
    SELECT [EVENTMODULE].[DESCRIPTION] as 'Event', cast([EVENTMODULE].[STARTDATE] as date) as 'Event Date',
    SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') then 1 else 0 end) 'Total Bookings',
    SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') AND [COURSEPLACE].[TYPE] = 'Application' then 1 else 0 end) 'Current Applicants' ...

) A

A: Hope this helps
with cte as
(
SELECT [EVENTMODULE].[DESCRIPTION] as 'Event', cast([EVENTMODULE].[STARTDATE] as date) as 'Event Date',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') then 1 else 0 end) 'Total Bookings',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') AND [COURSEPLACE].[TYPE] = 'Application' then 1 else 0 end)
)
select Event,Event Date,Total Bookings,[Total Bookings]-[EVENTPLACE].[STATUS] AS 'Non-Applicants'
from cte


text:
Q: Transfer trc20 usdt from one address to another I want to build a gateway for usdt payments and for this i'm using Tronweb tronWeb.utils.accounts.generateAccount() method
I have generated an address, transfered 1 usdt to it and now i want to transfer the funds to another address.
I get an error when sending the transaction:
  error: 'CONTRACT_VALIDATE_ERROR',
  message: 'contract validate error : account does not exist'

This is my code:

const TronWeb = require('tronweb');
const HttpProvider = TronWeb.providers.HttpProvider;
const fullNode = new HttpProvider("https://api.trongrid.io");
const solidityNode = new HttpProvider("https://api.trongrid.io");
const eventServer = new HttpProvider("https://api.trongrid.io");
const privateKey = "c83f36ae2e8661170e798ca73181693b76d75af016666e6f6baad92f69cfa1e2";
const tronWeb = new TronWeb(fullNode, solidityNode, eventServer, privateKey);
const trc20ContractAddress = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";//contract address
const addressTo = "TYcDSZor5ZgTsVMCZe1czfPEu8kzn6qe7L";
async function transfer() {
    try {
        const ownerAddress = tronWeb.address.fromPrivateKey(privateKey);
        const contractAddressHex = tronWeb.address.toHex(trc20ContractAddress);
        const contractInstance = await tronWeb.contract().at(contractAddressHex);
        const decimals = await contractInstance.decimals().call();
        const amount = 7 * Math.pow(10, decimals);
        const response = await contractInstance.transfer(addressTo, amount).send();
        console.log(response);
    } catch (e) {
        console.error(e);
        return null;`enter code here`
    }
}
transfer();

Is it something else i should do for getting this to work?

A: After generating new account, you need to activate it by transferring TRX/TRC-10 token to the address.

Transferring TRC20 will not activate an account. However, the balance can be inquired from Tronscan by the address.

TRON Account Documentation


text: Q: Clock on Stack Exchange Where do I set the Stack Exchange clock for my time zone? I live in the Eastern Time Zone (ET), Daylight Savings or Summer Time. At 11:00 each night (UTC 3:00, according to the notice at the top), the records for my reputation points switch over to a new day, as though my clock is set for a time zone further east. Is there a way for me to change this in my account settings? I think my time zone is UTC -5 by some standards. I am unable to find my primary account with settings, name, email, etc. I never log out. I guess I'm lost.


text:
Q: discord.py-rewrite Trying to blacklist certain terms only works when its only the blacklisted term My Goal and some Background Info
Hello, About a day ago, I tried to blacklist certain terms so if the user said something inappropriate, then it wont continue with the command (My stackoverflow question can be found here) And I tried mixing it with blacklisting certain people, (My stackoverflow question can be found here) But the blacklisting of the words only work if its nothing but the blacklisted term. The code command can be found
My Command's Code
@bot.command(pass_context=True)
async def order(ctx, *, orderItem):
    with open('blacklist.json', 'r') as file:
            blacklist = loads(file.read())
    with open('user_blacklist.json', 'r') as file:
        user_blacklist = loads(file.read())
    if ctx.author.id in user_blacklist:
        await ctx.send("You are blacklisted from ordering from Discord Chinese")
        return
    else:
        print(orderItem.lower() in blacklist)
        print(orderItem.lower())
        print(blacklist)
        if orderItem.lower() in blacklist:
            await ctx.send("Due to your order containing one of the blacklisted terms, your order will not be placed.")
        else:
            channel = bot.get_channel(724051586728460290)
            link = await ctx.channel.create_invite(max_age = 300)
            global baseNumberID
            baseNumberID += 1
            global orderIDdf
            global df
            df[str(baseNumberID)] = ctx.author.name
            embed=discord.Embed(title="New order", color=0xfc57ff)
            embed.add_field(name="Who and Where", value="{} in {} in the {} channel".format(ctx.message.author, ctx.message.guild.name, ctx.message.channel.mention), inline=False)
            embed.add_field(name="What", value="{}".format(orderItem), inline=False)
            embed.add_field(name="Invite", value="{}".format(link), inline=False)
            embed.add_field(name="Order ID", value="Order ID is {}".format(baseNumberID), inline=False)
            embed.add_field(name="Time", value="{} GM time".format(strftime("%Y-%m-%d %H:%M:%S", gmtime())), inline=True)
            embed.set_footer(text="End of this Order")
            #Second embed that will be used later.
            deliverIDInfo = str(baseNumberID)
            deliverInfoEmbed=discord.Embed(title="Order Info")
            deliverInfoEmbed.add_field(name="Who and Where", value="{} in {} in the {} channel".format(ctx.message.author, ctx.message.guild.name, ctx.message.channel.mention), inline=False)
            deliverInfoEmbed.add_field(name="What", value="{}".format(orderItem), inline=False)
            deliverInfoEmbed.add_field(name="Invite", value="{}".format(link), inline=False)
            deliverInfoEmbed.add_field(name="Order ID", value="Order ID is {}".format(baseNumberID), inline=False)
            deliverInfoEmbed.add_field(name="Time", value="{} GMT time".format(strftime("%Y-%m-%d %H:%M:%S", gmtime())), inline=True)
            deliverInfoEmbed.set_footer(text="End of this Order")
            orderIDdf[deliverIDInfo] = deliverInfoEmbed
            await ctx.author.send("Your order has been placed!")
            await ctx.author.send(embed=embed)
            await channel.send(embed=embed)

My Issue
The user blacklisting properly works, but the keywords doesn't. So say the blacklisted term is Ubisoft then it works if the args is Ubisoft/ubisoft But if its Words words Ubisoft then it doesn't work, it allows the order to come through.
My Guess of the Issue
I'm assuming its because when it either checks it, or takes the input, it doesn't check it properly, maybe it saves as an either array or weird form of string?

A: The problem right now is that string in blacklist only works if blacklist exactly contains string. Any variations and it won't work. Instead, you should loop through each blacklisted word and check if the word is in the message, like this:
if any(black_word in orderItem.lower() for black_word in blacklist):
    await ctx.send("Due to your order containing one of the blacklisted terms, your order will not be placed.")
    return

The any function will return True if any blacklisted words are in orderItem.lower()
As an example, if the blacklist is ['word1', 'word2'], and the message is 'word1 extra', the original code will not work because the exact string 'word1 extra' is not in blacklist. But the blacklisted word 'word1' is in 'word1 extra'.
Also, after you return you don't need to put an else statement. So for the user blacklist it should be:
if ctx.author.id in user_blacklist:
    await ctx.send("You are blacklisted from ordering from Discord Chinese")
    return

# rest of code, not in an else block


text:
Q: Maintain $ (dollar sign) when performing find and replace My script appends a block of text to the end of a file.
### Start My Block
$IPT -A INPUT -s 8.8.8.8 -j ACCEPT
$IPT -A INPUT -s 8.8.8.4 -j ACCEPT
### End My Block

If my text block doesn't exists, it successfully appends the file as shown above using the following:
HEAD="### Start My Block"
TAIL="### End My Block"
REPLACEMENT_CONTENT="
\$IPT -A INPUT -s 8.8.8.8 -j ACCEPT
\$IPT -A INPUT -s 8.8.8.4 -j ACCEPT"

echo -e "$HEAD" >> $FILE
echo -e "$REPLACEMENT_CONTENT" >> $FILE
echo -e "$TAIL" >> $FILE

If my text block exists, it attempts to replace the block's contents using the following:
HEAD="### Start My Block"
TAIL="### End My Block"
REPLACEMENT_CONTENT="
\$IPT -A INPUT -s 4.4.4.4 -j ACCEPT
\$IPT -A INPUT -s 4.4.2.2 -j ACCEPT"

perl -0777 -i -pe "s/($HEAD).*(\\n$TAIL)/\$1$REPLACEMENT_CONTENT\\$2/s" $FILE

The problem is I lose the "$IPT" and end up using the following:
### Start My Block
 -A INPUT -s 4.4.4.4 -j ACCEPT
 -A INPUT -s 4.4.2.2 -j ACCEPT
### End My Block

When I output the above via ">>", with the dollar sign escaped \$, the $IPT is included.  When I revisit the file to replace existing content between the $HEAD and $TAIL and use the perl function with an updated block, the escaped dollar sign doesn't seem to hold.  My guess is it's being interpreted and I'm not sure how to prevent that if escaping isn't enough.
Does anyone know how I can modify the command above to maintain the "$IPT"?

A: Yes, you are right your $IPT get interpreted in your regex inside perl.
So, using \$IPT this you are escaping $ for the shell. But you also need to escape $ for perl, so that it shouldn't interpret. For that you should do like this:
REPLACEMENT_CONTENT="
\\\$IPT -A INPUT -s 8.8.8.8 -j ACCEPT
\\\$IPT -A INPUT -s 8.8.8.4 -j ACCEPT"

This escapes \ once and then $ itself sending perl \$ and thus it did not get interpreted.
OR
Just wrap REPLACEMENT_CONTENT in single quotes.
REPLACEMENT_CONTENT='
\$IPT -A INPUT -s 8.8.8.8 -j ACCEPT
\$IPT -A INPUT -s 8.8.8.4 -j ACCEPT'

And after that perl part:
perl -0777 -i -pe "s/($HEAD).*($TAIL)/\$1$REPLACEMENT_CONTENT\n\$2/s" $FILE