text:
Q: Components with large datasets runs slow on IE11/Edge only Consider the code below. <GridBody Rows={rows} /> and imagine that rows.length would amount to any value 2000 or more with each array has about 8 columns in this example. I use a more expanded version of this code to render a part of a table that has been bottle necking my web application.
var GridBody = React.createClass({
    render: function () {
        return

            {this.props.Rows.map((row, rowKey) => {
                    return this.renderRow(row, rowKey);
            })}

;
    },
    renderRow: function (row, rowKey) {
        return

            {row.map((col, colKey) => {
                return this.renderColumn(col, colKey);
            })}

;
    },
    renderColumn: function (col, colKey) {
        return 	;
    }
});

Now onto the actual problem. It would seem that computation (even with my own code) seems to be suprisingly fast and even ReactJS's work with the virtualDOM has no issues.
But then there are these two events in reactJS.
componentWillUpdate up until where everything is still okay.
And then there is componentDidUpdate which seems to be fine and all on chrome.
The problem
But then there is IE11/Edge with about 4-6 SECONDS slower than any other browser and with the F12-Inspector this seems to be p to 8 SECONDS slower than Chrome.
The steps I have done to try and fix this issue:

*

*Strip unnecessary code.

*Shave off a handful of milliseconds in computation time.

*Split the grid in loose components so that the virtualDOM doesn't try
to update the entire component at once.

*Attempt to concaternate everything as a string and allow react to
only set innerhtml once. This actually seems to be a bug in IE here a
large string takes about 25-30 seconds on IE11. And only 30 ms on
chrome.
I have not found a proper solution yet. The actions I have done above seemed to make things less bad in IE but the problem still persists that a "modern" or "recent" browser is still 3-4 seconds slower.
Even worse, this seems to nearly freeze the entire browser and it's rendering.
tl;dr How to improve overal performance in IE and if possible other browsers?
I apologize if my question is unclear, I am burned out on this matter.
edit: Specifically DOM access is slow on IE as set innerHTML gets called more than 10.000 times. Can this be prevented in ReactJS?

A: Things to try improve IE performance:

*

*check you are running in production mode (which removes things like prop validation) and make Webpack / Babel optimisations where applicable

*Render the page server side so IE has no issues (if you can support SS rendering in your setup)

*Make sure render isnt called alot of times, tools like this are helpful: https://github.com/garbles/why-did-you-update

*Any reason why you are using dangerouslySetInnerHTML? If you take out the dangerouslySetInnerHTML does it speed things up dramatically?
Why not just automatically generate the rows and cols based on a array of objects (or multidimensional array passed), im pretty sure then React will make less DOM interaction this way (makes use of the VDOM). The
 and 's will be virtual dom nodes.

*Use something like https://github.com/bvaughn/react-virtualized to efficiently render large lists

A: Shot in the dark: try not rendering, or not displaying, until everything is completely done.

*

*make the table element display:none until it's done

*render it offscreen

*in a tiny DIV with hidden overflow

*or even output to a giant HTML string and then insert that into the DOM upon completion.

A: In addition to @Marty's excellent points, run a dynaTrace session to pinpoint the problematic code. It should give you a better insight into where the bottleneck is. It's results are often more useful than the IE developer tools.
Disclaimer - I am not linked with the dynaTrace team in any way.


text:
Q: winform: binding problem with DropDownList I  have a table in access database file. I would like to show that table in DataGridView, i have a bindingsource which bind to the table. then DataGridView bind to bindingsource. I also have other controls(textboxs, comboboxs) which are bind to 'dataMember' of table through the same bindingsource. Everything work well. But when i changed 'DropDownStyle' of the combobox from 'DropDown' to 'DropDownList'. The binding is broken. The data in the combobox is not changed when i selected different row in the datagridview. However, when i changed the data in combobox, the data in the cell in DataGridView changed. Anyone has idea? Thank you very much!
The following is my code:

combobox1.Items.AddRange( new Object[]{
"Monday",
"Tuesday",
.....
.....
"Sunday"
});

bindingsource1.DataSource = dt; // dt is a instance of DataTable
combobox1.DataBindings.Add("Text", bindingsource1,"Day");

A: combobox1.DataBindings.Add("SelectedValue", bindingsource1,"Day");

[EDIT]
Add this:
comboBox1.DisplayMember = "Day";

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python: changing methods and attributes at runtime I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?
Oh, and please don't ask why.

A:
I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?

You can add and remove attributes and methods to any class, and they'll be available to all instances of the class:
>>> def method1(self):
       pass

>>> def method1(self):
       print "method1"

>>> def method2(self):
       print "method2"

>>> class C():
       pass

>>> c = C()
>>> c.method()

Traceback (most recent call last):
  File "<pyshell#62>", line 1, in <module>
    c.method()
AttributeError: C instance has no attribute 'method'

>>> C.method = method1
>>> c.method()
    method1
>>> C.method = method2
>>> c.method()
    method2
>>> del C.method
>>> c.method()

Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    c.method()
AttributeError: C instance has no attribute 'method'
>>> C.attribute = "foo"
>>> c.attribute
    'foo'
>>> c.attribute = "bar"
>>> c.attribute
    'bar'

A: you can just assign directly to the class (either by accessing the original class name or via __class__ ):
class a : pass
ob=a()
ob.__class__.blah=lambda self,k: (3, self,k)
ob.blah(5)
ob2=a()
ob2.blah(7)

will print
(3, <__main__.a instance at 0x7f18e3c345f0>, 5)
(3, <__main__.a instance at 0x7f18e3c344d0>, 7)

A:
I wish to create a class in Python that I can add and remove attributes and methods.

import types

class SpecialClass(object):
    @classmethod
    def removeVariable(cls, name):
        return delattr(cls, name)

    @classmethod
    def addMethod(cls, func):
        return setattr(cls, func.__name__, types.MethodType(func, cls))

def hello(self, n):
    print n

instance = SpecialClass()
SpecialClass.addMethod(hello)

>>> SpecialClass.hello(5)
5

>>> instance.hello(6)
6

>>> SpecialClass.removeVariable("hello")

>>> instance.hello(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'SpecialClass' object has no attribute 'hello'

>>> SpecialClass.hello(8)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'SpecialClass' has no attribute 'hello'

A: A possibly interesting alternative to using types.MethodType in:
>>> f = types.MethodType(talk, puppy, Dog)
>>> puppy.talk = f # add method to specific instance

would be to exploit the fact that functions are descriptors:
>>> puppy.talk = talk.__get__(puppy, Dog)

A: This example shows the differences between adding a method to a class and to an instance.
>>> class Dog():
...     def __init__(self, name):
...             self.name = name
...
>>> skip = Dog('Skip')
>>> spot = Dog('Spot')
>>> def talk(self):
...     print 'Hi, my name is ' + self.name
...
>>> Dog.talk = talk # add method to class
>>> skip.talk()
Hi, my name is Skip
>>> spot.talk()
Hi, my name is Spot
>>> del Dog.talk # remove method from class
>>> skip.talk() # won't work anymore
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Dog instance has no attribute 'talk'
>>> import types
>>> f = types.MethodType(talk, skip, Dog)
>>> skip.talk = f # add method to specific instance
>>> skip.talk()
Hi, my name is Skip
>>> spot.talk() # won't work, since we only modified skip
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Dog instance has no attribute 'talk'

A: Simply:
f1 = lambda:0                   #method for instances
f2 = lambda _:0                 #method for class
class C: pass                   #class

c1,c2 = C(),C()                 #instances

print dir(c1),dir(c2)

#add to the Instances
c1.func = f1
c1.any = 1.23

print dir(c1),dir(c2)
print c1.func(),c1.any

del c1.func,c1.any

#add to the Class
C.func = f2
C.any = 1.23

print dir(c1),dir(c2)
print c1.func(),c1.any
print c2.func(),c2.any

which results in:
['__doc__', '__module__'] ['__doc__', '__module__']
['__doc__', '__module__', 'any', 'func'] ['__doc__', '__module__']
0 1.23
['__doc__', '__module__', 'any', 'func'] ['__doc__', '__module__', 'any', 'func']
0 1.23
0 1.23

A: another alternative, if you need to replace the class wholesale is to modify the class attribute:
>>> class A(object):
...     def foo(self):
...         print 'A'
...
>>> class B(object):
...     def foo(self):
...         print 'Bar'
...
>>> a = A()
>>> a.foo()
A
>>> a.__class__ = B
>>> a.foo()
Bar

A: Does the class itself necessarily need to be modified? Or is the goal simply to replace what object.method() does at a particular point during runtime?
I ask because I sidestep the problem of actually modifying the class to monkey patch specific method calls in my framework with getattribute and a Runtime Decorator on my Base inheritance object.
Methods retrieved by a Base object in getattribute are wrapped in a Runtime_Decorator that parses the method calls keyword arguments for decorators/monkey patches to apply.
This enables you to utilize the syntax object.method(monkey_patch="mypatch"), object.method(decorator="mydecorator"), and even object.method(decorators=my_decorator_list).
This works for any individual method call (I leave out magic methods), does so without actually modifying any class/instance attributes, can utilize arbitrary, even foreign methods to patch, and will work transparently on sublcasses that inherit from Base (provided they don't override getattribute of course).
import trace

def monkey_patched(self, *args, **kwargs):
    print self, "Tried to call a method, but it was monkey patched instead"
    return "and now for something completely different"

class Base(object):

    def __init__(self):
        super(Base, self).__init__()

    def testmethod(self):
        print "%s test method" % self

    def __getattribute__(self, attribute):
        value = super(Base, self).__getattribute__(attribute)
        if "__" not in attribute and callable(value):
            value = Runtime_Decorator(value)
        return value

class Runtime_Decorator(object):

    def __init__(self, function):
        self.function = function

    def __call__(self, *args, **kwargs):

        if kwargs.has_key("monkey_patch"):
            module_name, patch_name = self._resolve_string(kwargs.pop("monkey_patch"))
            module = self._get_module(module_name)
            monkey_patch = getattr(module, patch_name)
            return monkey_patch(self.function.im_self, *args, **kwargs)

        if kwargs.has_key('decorator'):
            decorator_type = str(kwargs['decorator'])

            module_name, decorator_name = self._resolve_string(decorator_type)
            decorator = self._get_decorator(decorator_name, module_name)
            wrapped_function = decorator(self.function)
            del kwargs['decorator']
            return wrapped_function(*args, **kwargs)

        elif kwargs.has_key('decorators'):
            decorators = []

            for item in kwargs['decorators']:
                module_name, decorator_name = self._resolve_string(item)
                decorator = self._get_decorator(decorator_name, module_name)
                decorators.append(decorator)

            wrapped_function = self.function
            for item in reversed(decorators):
                wrapped_function = item(wrapped_function)
            del kwargs['decorators']
            return wrapped_function(*args, **kwargs)

        else:
            return self.function(*args, **kwargs)

    def _resolve_string(self, string):
        try: # attempt to split the string into a module and attribute
            module_name, decorator_name = string.split(".")
        except ValueError: # there was no ".", it's just a single attribute
            module_name = "__main__"
            decorator_name = string
        finally:
            return module_name, decorator_name

    def _get_module(self, module_name):
        try: # attempt to load the module if it exists already
            module = modules[module_name]
        except KeyError: # import it if it doesn't
            module = __import__(module_name)
        finally:
            return module

    def _get_decorator(self, decorator_name, module_name):
        module = self._get_module(module_name)
        try: # attempt to procure the decorator class
            decorator_wrap = getattr(module, decorator_name)
        except AttributeError: # decorator not found in module
            print("failed to locate decorators %s for function %s." %\
            (kwargs["decorator"], self.function))
        else:
            return decorator_wrap # instantiate the class with self.function

class Tracer(object):

    def __init__(self, function):
        self.function = function

    def __call__(self, *args, **kwargs):
        tracer = trace.Trace(trace=1)
        tracer.runfunc(self.function, *args, **kwargs)

b = Base()
b.testmethod(monkey_patch="monkey_patched")
b.testmethod(decorator="Tracer")
#b.testmethod(monkey_patch="external_module.my_patch")

The downside to this approach is getattribute hooks all access to attributes, so the checking of and potential wrapping of methods occurs even for attributes that are not methods + won't be utilizing the feature for the particular call in question. And using getattribute at all is inherently somewhat complicated.
The actual impact of this overhead in my experience/for my purposes has been negligible, and my machine runs a dual core Celeron. The previous implementation I used introspected methods upon object init and bound the Runtime_Decorator to methods then. Doing things that way eliminated the need to utilize getattribute and reduced the overhead mentioned previously... however, it also breaks pickle (maybe not dill) and is less dynamic then this approach.
The only use cases I have actually come across "in the wild" with this technique were with timing and tracing decorators. However, the possibilities it opens up are extremely wide ranging.
If you have a preexisting class that cannot be made to inherit from a different base (or utilize the technique it's own class definition or in it's base class'), then the whole thing simply does not apply to your issue at all unfortunately.
I don't think setting/removing non-callable attributes on a class at runtime is necessarily so challenging? unless you want classes that inherit from the modified class to automatically reflect the changes in themselves as well... That'd be a whole 'nother can o' worms by the sound of it though.


text:
Q: rails models for address books (company, person, address) I want to create address-book-like set of models to represent company, person, location, etc. This looks like very typical address book, I wonder if somebody did it already with ruby on rails 3. The question appeared not (only) because of my laziness, but also because "best practice" approach is usually well-developed, have fewer pitfalls, etc. Currently I think about following models/fields:
Company:

*

*name

*has_many :persons

*has_many :locations

*has_many :urls, :through => :urlcatalog
the reason to have URL catalog is a possibility to assign notes to URL
Person:

*

*name maybe split to first-middle-last

*phone

*has_one :location

*has_many :emails :through => :emailcatalog
the reason to have email catalog is the same as above: one can assign
"private", "office" labels to it.  many phones can be organized this way as well.
Location

*

*address optional

*has_one :city

*has_one :country
city or country should be present
City

*

*name

*has_one :country

Country

*

*name

any comments on this concept, thoughts, working examples, etc are welcome!

A: You should look up polymorphic associations. This means your location will be better organized and it will be easier to get parent etc...
Good example over at RailsWiki


text:
Q: Meteor Blaze display array I have collections like this:

I want to iterate over object.questions.teema for example.
I have helper:
Template.game.helpers({
    theGame: function() {
        var theGame = Game.findOne({_id:"LhQmaZKW8eJNenyX9"})
        console.log(theGame)
        return theGame
    }
});

and template:
<template name="game">

{{#with theGame}}
  {{#each theGame.questions}}
    {{teema}}
  {{/each}}
{{/with}}
</template>

But it doesnt work, what is wrong with the template?

A: theGame.questions is an array (that you iterate over) of array of objects which have the teema key. So you still need to iterate over the 2nd level array, or define a specific item in that array before you can eventually reach the object with teema property.
Maybe something like:
{{#with theGame}}
  {{#each questions}}
    {{#each this}}
      {{this.teema}}
    {{/each}}
  {{/each}}
{{/with}}

But it depends on why you have these 2-level arrays in the first place.

A: What is {{teema}} supposed to be?
Regardless, as you can see from your console.log statement, {{theGame.questions}} returns another array. But that array returns objects. This is really hard to query for with Blaze.
The better solution would be to flatten it out so that your data is shaped like this:
questions: [
   {
       a: 'asdfkjah',
       level: 'askdjfhal',
       q: 'asdkfh',
       teema: 'asdkfjh'
       vaartus: 100
   },
   {
      ...
   }
]

This way you don't have an array nested in an array. That will allow you to:
{{#with theGame}}
  {{#each theGame.questions}}
    {{this.teema}}
  {{/each}}
{{/with}}

A: '#each theGame.questions' Will not work inside the #with, because you can access the 'theGame' object directly.
The point is when you try to get theGame object inside the #with it will return you undefined, because 'theGame' object does not have theGame property, Which you want to access inside #with block.
<template name="game">
  {{#with theGame}}
    {{#each questions}}
       //Thie #each because you have nested array. As I can see in your console log.
       {{#each this}}
         {{teema}}
       {{/each}}
    {{/each}}
  {{/with}}
</template>


text:
Q: Static and public IP addresses for regular computers I want to do a messaging application on the browser using WebRTC, but I want to get rid of every third party like STUN and TURN servers (I also want to get rid of signaling servers but first things first). I want the users to keep their contacts in the browser localStorage in a key-value way: name of the person => IP address.
I don't really care how the users find their own public IP address (they can do an ipconfig as there is no web API to retrieve it) nor how they distribute it (they can use use a centralized service like Messenger to give their public IP address to their friends, or they can use a QR code on their business card).
But the main issue I have is that I want these public IP addresses to be static, because I don't want to notify all my friends to update their contact file every time my gateway changes my public IP address.
In IPv4, there are too few available addresses (only 4 billions), so the public static addresses are all reserved to website and residential gateways. Whenever I want to access the Internet, my gateway opens a specific port for my computer. For example, if my gateway has the public address 1.2.3.4, the "public address" of my computer would be temporarily 1.2.3.4:3000. This process is called NAT. To find one's "public address", one must send a request to a STUN server which would respond with what IPv4 address and what port it sees. But the gateway closes the connection of the port at some point, so that's not a public static address like I want.
But in IPv6 it's different, the number of possible addresses is ridiculously high (2^128), so we could theorically give one static public address to each computer in the world. NAT would basically be useless (I'm not talking about firewalls here). But again, there is a problem, in IPv6 you have one address that is static but not public, and you have one or more addresses that are public but not static. So nothing has really changed from IPv4, and it still doesn't solve my problem.
I have 2 questions:

*

*How to have a public and static address for regular computers? I don't want my users to meddle with their router/ISP or install anything on their computer.

*Why don't we all already have static and public IPv6 addresses? Is there a design choice behind this?

Thank you for your help.

A: Your question is not really a programming question, so I'm assuming you need to know this because you are developing software that uses IPv6. Looking at it from a application point of view:

*

*You don't need TURN to discover your own public address. Without NAT your address is not changed by the network and your local address is your public address. You just need to let your software ask the OS what the currently configured addresses are.

*With IPv6 it's usually not the gateway giving out addresses to connected devices. The gateway only communicates the network prefix (a /64) to the network, and all devices choose their own addresses (usually multiple addresses per device).
DHCPv6 does exist, but it is usually not used to configure IPv6 addresses on devices. It may be used in stateless mode to configure domain names, DNS resolvers etc, but that is not related to assigning addresses.
So the device chooses its own addresses within the prefix communicated by the gateway. How does it choose?
Originally devices used their interface MAC address for the suffix (using the modified EUI-64 algorithm). The problem with this was that if you had a lap for example, online services that you connect to could track your device. Because no matter what network you connect to, the last 64 bits of your address would contain your unique MAC address. That way it was possible to track your device from work to home to your favourite coffee place etc.
These days the OS uses privacy extensions to make your IPv6 address untraceable. Often there is a stable address that is linked to the network prefix, so that every time you connect to the same network you get the same address. That address is useful for peer-to-peer communication.
But they went further than that. There is often also a set of privacy addresses that (semi)randomly change over time. Your device might generate a new address every day, or maybe even every hour. That makes it even harden for online services to determine whether there is a single device that has changed it's privacy address, or whether there are multiple devices. Because this address changes over time it's good for short-lived outbound connections, but not so useful to accept inbound connections on. For that use the stable address I mentioned in the previous paragraph.
Probably the most difficult bit is how to ask the OS about the available addresses. Looking at my own macOS box I see:
en2: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
    ether c8:e0:eb:5c:af:61
    inet6 fe80::1074:8568:e447:d9e3%en2 prefixlen 64 secured scopeid 0x12
    inet6 2a02:xxxx:xxxx:xxxx:3e:873f:837:1417 prefixlen 64 autoconf secured
    inet6 2a02:xxxx:xxxx:xxxx:b19c:71c5:1de8:8fde prefixlen 64 autoconf temporary

You can see both the long-term secured address and the short-term temporary address.
Without knowing which OS you are developing for and in which programming language I can't help you further. Please adjust your question to include that information.


text:
Q: Find match pattern and delete the first occurrence I have a file1
NR2SKRD12BWP210H6P51CNODSVT-(.A1(n7),.A2(),.ZN(n8)); |2
MUX2D2BWP210H6P51CNODSVT-(.I0(n8),.I1(),.S(),.Z(n9)); |4
CKLHQD16BWP210H6P51CNODSVT-(.CPN(#),.E(1),.TE(n9),.Q(n10)); |5
LHCSNQD1BWP210H6P51CNODSVT-(.CDN(n10),.D(),.E(1),.SDN(),.Q(n11)); |6
OAI21D8BWP210H6P51CNODSVT-(.A1(n11),.A2(),.B(),.ZN(n12)); |9
DCCKND16BWP210H6P51CNODSVT-(.I(n12),.ZN(n13)); |10
INVSKFD14BWP210H6P51CNODSVT-(.I(n13),.ZN(n14)); |11
NR2SKRD12BWP210H6P51CNODSVT-(.A1(n7),.A2(n1),.ZN(n8)); |2
MUX2D2BWP210H6P51CNODSVT-(.I0(n8),.I1(n2),.S(),.Z(n9)); |4

I need to find matching lines in file1 i.e 1st field. Field are seperated by- and if match found , delete 1st match line.
I want output as
CKLHQD16BWP210H6P51CNODSVT-(.CPN(#),.E(1),.TE(n9),.Q(n10)); |5
LHCSNQD1BWP210H6P51CNODSVT-(.CDN(n10),.D(),.E(1),.SDN(),.Q(n11)); |6
OAI21D8BWP210H6P51CNODSVT-(.A1(n11),.A2(),.B(),.ZN(n12)); |9
DCCKND16BWP210H6P51CNODSVT-(.I(n12),.ZN(n13)); |10
INVSKFD14BWP210H6P51CNODSVT-(.I(n13),.ZN(n14)); |11
NR2SKRD12BWP210H6P51CNODSVT-(.A1(n7),.A2(n1),.ZN(n8)); |2
MUX2D2BWP210H6P51CNODSVT-(.I0(n8),.I1(n2),.S(),.Z(n9)); |4

Here NR2SKRD12BWP210H6P51CNODSVT andMUX2D2BWP210H6P51CNODSVT have same $1. So delete their 1st match line.
I tried the code
awk -F'-' 'FNR==NR{a[$1];next} !(($1) in a)' file1

But this code is to find match and delete lines between two files. How can I find match and delete for single file.
*delete the first match line only. Keep the second,third, fourth etc repeats.

A: Could you please try following, written and tested with shown samples in GNU awk.
awk '
BEGIN{ FS="-" }
FNR==NR{
  arr[$1]++
  next
}
arr[$1]>1 && ++arrAgain[$1]==1{ next }
1
' Input_file Input_file

Explanation: Adding detailed explanation for above.
awk '                             ##Starting awk program from here.
BEGIN{ FS="-" }                   ##Setting field separator as dash here.
FNR==NR{                          ##Checking FNR==NR condition which will be TRUE when 1st time Input_file is being read.
  arr[$1]++                       ##Creating array arr with 1st field index and keep increasing its value with 1 on each of its occurrence.
  next                            ##next will skip all further statements from here.
}
arr[$1]>1 && ++arrAgain[$1]==1{   ##Checking if arr value with 1st field index is greater than 1 and its first time occurring in arrAgain then skip that line.
  next                            ##next will skip all further statements from here.
}
1                                 ##1 will print current line.
' Input_file Input_file           ##Mentioning Input_file names here.

A: This might work for you (GNU sed):
sed -E 'H;x;s/^(\n[^-]*-)[^\n]*(.*\1)/\2/;x;$!d;x;s/.//' file

Make a copy of the current line in the hold space.
If the current key already exists in the hold space, remove the first line.
At the end of the file, swap to the hold space, remove the first newline that was introduced when making copies and print the results.

A: another awk
$ awk -F- 'NR==FNR{a[$1]++; next} !(--a[$1])' file{,}

CKLHQD16BWP210H6P51CNODSVT-(.CPN(#),.E(1),.TE(n9),.Q(n10)); |5
LHCSNQD1BWP210H6P51CNODSVT-(.CDN(n10),.D(),.E(1),.SDN(),.Q(n11)); |6
OAI21D8BWP210H6P51CNODSVT-(.A1(n11),.A2(),.B(),.ZN(n12)); |9
DCCKND16BWP210H6P51CNODSVT-(.I(n12),.ZN(n13)); |10
INVSKFD14BWP210H6P51CNODSVT-(.I(n13),.ZN(n14)); |11
NR2SKRD12BWP210H6P51CNODSVT-(.A1(n7),.A2(n1),.ZN(n8)); |2
MUX2D2BWP210H6P51CNODSVT-(.I0(n8),.I1(n2),.S(),.Z(n9)); |4

double scan file, first round count the occurrences of each key, second round print the last one only.

A: To delete first duplicate:
awk -F- 'NR==FNR {++a[$1]; next} a[$1]==1; {a[$1]=1}' file file

Read same file twice. Count $1 on the first read, decide what to do with the count on the next.


text:
Q: How to use ImmutableList<> instead of List<> in Entity Framework 6 In my project, we are using either Entity Framework 6 and the Microsoft's System.Collections.Immutable types nuget package.
We aim to be able to do a query into the Database with EF and the data returned be immutable by default.
Since we have one-to-many relations, in EF we use a List<> type to represent that in our structure. But since we want it to be immutable and with strong guarantees, we want to use ImmutableList<> instead.
Just changing the table class property from List<> to ImmutableList<> doesn't seems to work, since the new migration will ignore the ImmutableList<> and remove the one-to-many relation we had before.
So, my question is if there is some way to make EF work with the ImmutableList<> type and if not, what are other alternatives to make this EF table structure immutable?


text:
Q: underlying connection was closed using webclient from azure I am windows application developer currently am working in a tutorial based application.my application is built in framework 2.0,c#.net ,i have a task that i need to download zip files from azure cloud storage, i know i can simply done this using windows azure nuget package in higher framework but the problem is i can't upgrade the application framework i need to done the task with this framework. can anyone please help me how to solve this, i got a small hint and i tried on that time i got an error "underlying connection was closed". please help me
my code

 string spath = Application.StartupPath.ToString();
            string lPath = spath + "\\EncryptedFiles";
            string dTo = Path.Combine(lPath, File);
            if (System.IO.File.Exists(dTo))
            {
                System.IO.File.Delete(dTo);
            }
            NetworkCredential credential = new NetworkCredential("*****", "*****");
            CredentialCache cCache = new CredentialCache();
            cCache.Add(new Uri(fileName), "Basic", credential);

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(delegate { return true; });

            WebClient wClient = new WebClient();
            wClient.Credentials = cCache;
            wClient.DownloadFile(fileName, dTo);


text:
Q: PersistenceMode vs. Storing property in ViewState What is the difference in utility/performance between using PersistenceMode on a property and storing the value of said property in ViewState in an ASP.NET web page?
This:
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    [PersistenceMode(PersistenceMode.InnerProperty)]
    public int ClientUno { get; private set; }

versus this:
    public int ClientUno
    {
        get
        {
            if (ViewState["ClientUno"] == null) return 0;
            else return (int)(ViewState["ClientUno"]);
        }
        set { ViewState["ClientUno"] = value; }
    }

I have done some googling around the internets and can't figure this one out.  It seems like this would have come up before - I just can't find the answer.  Anyone?

A: PersistanceMode has nothing to do with storing data in a ViewState. It is used to create custom server controls and affects server code.
For example see: How do I make a control with a child control collection in ASP.Net


text:
Q: ColdFusion 11 seems to render definitions for superclass as well as class In a ColdFusion application, I have a class called ProjectBeanService that extends another class called AjaxBeanService.
In CF8, where the code seems to be working properly, when debugging the application in IE, I see this rendered JavaScript:

However, when I try to run the same application under CF11, both the class methods and the superclass methods are rendered:

In this block of code, notice how after the "set" function is defined, it is defined again (and according to the superclass definition). It seems to me that ColdFusion 11 is rendering this superclass, whereas CF 8 did not.
Any suggestions?
UPDATE:
Here is a stripped down version of the application, wherein I was able to reproduce the error.
/components/AbstractAjax.cfc:
<cfcomponent displayname="AbstractAjax">

    <cffunction name="sendError" access="private" returntype="void">
        <cfargument name="sErrCode" type="string" required="yes" />
        <cfargument name="sErrMsg" type="string" required="yes" />
        <cfif IsNumeric(arguments.sErrCode)>
            <cfscript>
                GetPageContext().getResponse().sendError(arguments.sErrCode,arguments.sErrMsg);
         </cfscript>
      <cfelse>
        <cfscript>
            GetPageContext().getResponse().sendError(555,arguments.sErrCode & ' - ' & arguments.sErrMsg);
         </cfscript>
      </cfif>
    </cffunction>

</cfcomponent>

/components/AjaxBeanService.cfc:
<cfcomponent displayname="AjaxBeanService" extends="com.AbstractAjax">

    <cffunction name="createSessionBean" access="remote" returntype="struct">
        <cfargument name="sBeanName" type="string" required="yes">
        <cfargument name="sBeanType" type="string" required="yes">
        <cfargument name="sDAOName" type="string" required="yes">
        <cfset var oBean = StructNew() />
        <cfset var oBeanArguments = ARGUMENTS />
        <cfset var oDAO = application[sDAOName] />

        <cftry>
            <cfset oBean = createObject("component","com." & sBeanType) />

            <cfset ArrayDeleteAt(oBeanArguments,1) />
            <cfset ArrayDeleteAt(oBeanArguments,1) />
            <cfset ArrayDeleteAt(oBeanArguments,1) />

            <cfset ArrayPrepend(oBeanArguments,oDAO) />

            <cfset oBean.init.apply(oBean,oBeanArguments) />
            <cfset SESSION.beans[sBeanName] = oBean />
            <cfreturn oBean.getAll() />
            <cfcatch type="any">
                <cfset sendError(cfcatch.ErrorCode,cfcatch.message) />
            </cfcatch>
        </cftry>
    </cffunction>

    <cffunction name="destroySessionBean" access="remote" returntype="struct">
        <cfargument name="sBeanName" type="string" required="yes">
        <cfset rc = StructDelete(SESSION.beans, "#sBeanName#", "True")>
    </cffunction>

    <cffunction name="reInitSessionBean" access="remote" returntype="struct">
        <cfargument name="sBeanName" type="string" required="yes">
        <cfargument name="argument1" type="any" required="no" default="">
        <cfargument name="argument2" type="any" required="no" default="">
        <cfargument name="argument3" type="any" required="no" default="">
        <cfargument name="argument4" type="any" required="no" default="">
       <cfset var oBean = StructNew() />
        <cftry>
            <cfset oBean = getSessionBean(sBeanName) />
            <cfset oBean.init(oBean.getDAO(),argument1,argument2,argument3,argument4) />
            <cfset SESSION.beans[sBeanName] = oBean />
            <cfreturn oBean.getAll() />
            <cfcatch type="any">
                <cfset sendError(cfcatch.ErrorCode,cfcatch.message) />
            </cfcatch>
        </cftry>
    </cffunction>

    <cffunction name="getSessionBean" access="remote" returntype="any">
        <cfargument name="sBeanName" type="string" required="yes">
        <cfset var oBean = StructNew() />
        <cfif StructKeyExists(SESSION.beans,sBeanName) >
            <cflock scope="session" type="readonly" timeout="5" throwontimeout="yes">
                <cfset oBean = Duplicate(SESSION.beans[sBeanName]) />
            </cflock>
        </cfif>
        <cfif StructIsEmpty(oBean)>
            <cfthrow errorcode="500" message="No bean found by the name '#sBeanname#'" />
        <cfelse>
            <cfreturn oBean />
        </cfif>
    </cffunction>

    <cffunction name="set" access="remote" returntype="void">
        <cfargument name="sBeanName" type="string" required="yes">
        <cfargument name="sPropertyName" type="string" required="yes">
        <cfargument name="oPropertyValue" type="string" required="yes">
        <cfset var oBean = StructNew() />
        <cftry>
            <cfset oBean = getSessionBean(sBeanName) />
            <cfset oBean.set(sPropertyName,oPropertyValue) />
            <cfcatch type="any">
                 <cfset sendError(cfcatch.ErrorCode,cfcatch.message) />
            </cfcatch>
        </cftry>
     </cffunction>

    <cffunction name="get" access="remote" returntype="any">
        <cfargument name="sBeanName" type="string" required="yes">
        <cfargument name="sPropertyName" type="string" required="yes">

        <cfset var value = "" />
        <cfset var oBean = StructNew() />

        <cftry>
            <cfset oBean = getSessionBean(sBeanName) />
            <cfset value = oBean.get(sPropertyName) />
            <cfreturn value />

            <cfcatch type="any">
                    <cfset sendError(cfcatch.ErrorCode,cfcatch.message) />
            </cfcatch>
        </cftry>
     </cffunction>

     <cffunction name="getAll" access="remote" returntype="struct">
        <cfargument name="sBeanName" type="string" required="yes">

        <cfset var oBean = StructNew() />
        <cfset var oStruct = structNew() />

        <cftry>
            <cfset oBean = getSessionBean(sBeanName) />
            <cfset oStruct = oBean.getAll() />
            <cfreturn oStruct />

            <cfcatch type="any">
                  <cfset sendError(cfcatch.ErrorCode,cfcatch.message) />
            </cfcatch>
        </cftry>
     </cffunction>

</cfcomponent>

/components/ProjectBeanService.cfc:
<cfcomponent displayname="ProjectBeanService" extends="com.AjaxBeanService">

    <cffunction name="getBean" access="private" returntype="any">
        <cfargument name="sBeanType" type="string" required="yes">
        <cfargument name="nID" type="numeric" required="yes" hint="ProjectID or ImpactID">
        <cfargument name="sSection" type="string" required="no" hint="ProjectSection or ImpactSection" default="">
        <cfargument name="nRevision" type="numeric" required="no" hint="Commitment Revision" default="0">

        <cfset var oBean = createObject("component","com." & sBeanType).init(nID,sSection,nRevision)  />

        <cfreturn oBean />

    </cffunction>

    <cffunction name="set" access="remote" returntype="void">
        <cfargument name="sPropertyName" type="string" required="yes">
        <cfargument name="oPropertyValue" type="string" required="yes">
        <cfargument name="sBeanType" type="string" required="yes">
        <cfargument name="nID" type="numeric" required="yes">
        <cfargument name="sSection" type="string" required="no" default="">
        <cfargument name="nRevision" type="numeric" required="no" default="0">
        <cfset var oBean = StructNew() />
        <cftry>

            <cfset oBean = getBean(sBeanType, nID, sSection,nRevision) />
            <cfset oBean.set(sPropertyName,oPropertyValue) />
            <cfcatch type="any">
                 <cfset sendError(cfcatch.ErrorCode,cfcatch.message) />
            </cfcatch>
        </cftry>
     </cffunction>

    <cffunction name="get" access="remote" returntype="any">
        <cfargument name="sPropertyName" type="string" required="yes">
        <cfargument name="sBeanType" type="string" required="yes">
        <cfargument name="nID" type="numeric" required="yes">
        <cfargument name="sSection" type="string" required="no" default="">
        <cfargument name="nRevision" type="numeric" required="no" default="0">

        <cfset var value = "" />
        <cfset var oBean = StructNew() />

        <cftry>
            <cfset oBean = getBean(sBeanType,nID,sSection,nRevision) />
            <cfset value = oBean.get(sPropertyName) />
            <cfreturn value />

            <cfcatch type="any">
                    <cfset sendError(cfcatch.ErrorCode,cfcatch.message) />
            </cfcatch>
        </cftry>
     </cffunction>

     <cffunction name="getAll" access="remote" returntype="struct">
        <cfargument name="sBeanType" type="string" required="no" default="ProjectBean">
        <cfargument name="nID" type="numeric" required="yes">
        <cfargument name="sSection" type="string" required="no" default="">
        <cfargument name="nRevision" type="numeric" required="no" default="0">

        <cfset var oBean = StructNew() />
        <cfset var oStruct = structNew() />

        <cftry>
            <cfset oBean = getBean(sBeanType,nID,sSection,nRevision) />
            <cfset oStruct = oBean.getAll() />
            <cfreturn oStruct />

            <cfcatch type="any">
                  <cfset sendError(cfcatch.ErrorCode,cfcatch.message) />
            </cfcatch>
        </cftry>
     </cffunction>

</cfcomponent>

/Application.cfc:
<cfcomponent>
    <cfscript>
        this.mappings["/com"] = getDirectoryFromPath(getCurrentTemplatePath()) & "\components\";
   </cfscript>
</cfcomponent>

/index.cfm:

<title></title>
   <cfajaxproxy cfc="com.ProjectBeanService" jsclassname="ProjectBeanService">

This is a test.

A: So far, the only answer I have come up with is that this must be a bug in CF11, so I was able to "fix" it by marking the methods in the parent class as having access "public" rather than "remote". I do not yet know what unintended consequences this could have, but it seems to have fixed my problem. If anyone has a better suggestion, please let me know, and I'll give the answer check to that person.


text:
Q: How to pass parameter into silverlight so that it is "behind the scenes" I'm brand new to learning Silverlight/XAML/C#.
I'm using an ASP.NET function to pass a string parameter to a Silverlight App. Currently I'm using the following code to simply verify that it works when the Silverlight App is loaded:
<Grid x:Name="LayoutRoot">
    <StackPanel>
        <TextBlock x:Name="txtIP" />
    </StackPanel>
</Grid>

How do I set up an element that's "behind the scenes" that doesn't necessarily display in the XAML?  I thought about simply hiding the TextBlock, but I imagine there's a better way.

A: You can pass parameters to a Silverlight application using the initParams option in the plugin.  Load that with some ASPNET code and you can dynamically set it at load time.

A: For further information on how to pass initParams into a Silverlight, check out Tim's video demonstration on InitParams here: Using Startup Parameters with Silverlight.
Also, check out my blog post where I cover several of the details in Tim's video and show what to do with the data once it's in the Silverlight App: Pass the IP Address of a User to Silverlight as a Parameter.


text:
Q: Get the position of a CGPoint( which is inside a subview), W.R.T the parentView - ObjectiveC I have a point inside a subUIView. I want to find the location of that CGPoint with respect to the subview's parent UIView. How do I get it?

A: CGPoint pointInSuperview = [superview convertPoint:pointInSubview fromView:subView];

Example:
UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
[self.view addSubview:subView];

CGPoint pointInSubview = CGPointMake(20, 20);
CGPoint pointInSuperview = [self.view convertPoint:pointInSubview fromView:subView];
NSLog(@"%@", NSStringFromCGPoint(pointInSuperview));

Prints out {70, 70} to the console


text:
Q: PDFlib - "leading" option of create_textflow I'm trying to figure out how to add line spacing without adding spacing above the very first line of textflow.
This code:
$text = 'For more information about the Giant Wing Paper Plane see ' .
    'our Web site <underline=true>www.kraxi-systems.com' .
    'the Giant Wing in a thunderstorm as soon as possible.';
$optlist = 'fontname=Helvetica fontsize=12 encoding=unicode leading=400%';
$tf = $p->create_textflow($text, $optlist);
$result = $p->fit_textflow($tf, 28.346, 28.346, 400, 700, 'fitmethod=nofit');
$p->delete_textflow($tf);

results in:

All is good.
Next, I'm increasing the leading option to 400% as:
$optlist = 'fontname=Helvetica fontsize=12 encoding=unicode leading=400%';

And that gives me this:

Question:
How do I keep first paragraph line at the original position and only increase line spacing AFTER it?

A: checkout the "firstlinedist" option. The default is leading, but you might set this to "ascender" or "capheigt" or any other value.
Please see PDFlib 9.2 API reference, chapter 5.2, table 5.12 for more details.


text:
Q: Output from multiple iterations of a loop to a single line This is my code:
Program Output_Format

Implicit none

Integer::k
Integer,parameter:: Br_nn_mre = 11
Character(56),parameter:: FMT_01 = '(1x,"NN_0",i0)'
Character(56),parameter:: FMT_02 = '(1x,"NN_",i0)'

Open( 15 , File = 'Output.txt' , Status = 'Unknown' , Action = 'Write' )

    Do k = 1 , Br_nn_mre

       If ( k < 10) Write( 15 , FMT_01 ) k
       If ( k > 9 ) Write( 15 , FMT_02 ) k

    End do

Close( 15 , Status = 'Keep' )

End Program Output_Format

The content of Output.txt is:
  NN_01
  NN_02
  ....
  NN_11

My intention is to get this content in Output.txt all in a single line:
NN_01 NN_02 ... NN_11

What kind of change to FMT_01 and FMT_02 must I make if I want to get that?


text:
Q: Можно ли использовать border-radius вместе с border-image с градиентом? Я задаю стиль для поля ввода с закругленной границей (border-radius) и пытаюсь добавить градиент к указанной границе. Я могу успешно сделать градиент и закругленную границу, но ни то, ни другое не работают вместе. Он либо закруглен без градиента, либо граница с градиентом, но без закругленных углов.
-webkit-border-radius: 5px;
-webkit-border-image: -webkit-gradient(linear, 0 0, 0 100%, from(#b0bbc4), to(#ced9de)) 1 100%;

Есть ли способ, чтобы оба свойства CSS работали вместе, или это невозможно?
Свободный перевод вопроса Possible to use border-radius together with a border-image which has a gradient? от участника  @paulwilde.

A: Работаем над той же проблемой. Наткнулся на решение без svg, которое более лаконично, чем другие здесь:

div{
  width: 300px;
  height: 80px;
  border: double 1em transparent;
  border-radius: 30px;
  background-image: linear-gradient(white, white),
                    linear-gradient(to right, green, gold);
  background-origin: border-box;
  background-clip: content-box, border-box;
}

Это не мое собственное решение, оно взято отсюда
Свободный перевод  ответа от участника  @alphazwest.

A: Теперь мы можем использовать маску, чтобы легко добиться этого, сохраняя при этом прозрачность и отзывчивость.

.box {
  position:relative;
  padding:20px 30px;
  margin:5px;
  display:inline-block;
  font-size:30px;
}
.box::before {
  content:"";
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  border-radius:50px;
  padding:10px;
  background:linear-gradient(45deg,red,blue);
  -webkit-mask:
     linear-gradient(#fff 0 0) content-box,
     linear-gradient(#fff 0 0);
  -webkit-mask-composite: destination-out;
  mask-composite: exclude;
}

  Hello World

  Hello World again

  Hello World
 two lines

Более подробно в этом ответе
Свободный перевод  ответа от участника  @Temani Afif.

A: Я бы использовал для этого SVG:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 220 220" width="50%" height="50%" preserveAspectRatio="none">
  <defs>
    <linearGradient id="gradient">
      <stop offset="0" style="stop-color:#0070d8" />
      <stop offset="0.5" style="stop-color:#2cdbf1" />
      <stop offset="1" style="stop-color:#83eb8a" />
    </linearGradient>
  </defs>
  <ellipse ry="100" rx="100" cy="110" cx="110" style="fill:none;stroke:url(#gradient);stroke-width:6;" />
</svg>

Чтобы это работало в MS Edge и Firefox, мы должны избегать нашей разметки после utf8, поэтому мы заменим двойные кавычки «одинарными кавычками», # => на %23 и
% => на %25:

div {
  width: 250px;
  height: 250px;
  background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 220 220' width='100%25' height='100%25' preserveAspectRatio='none'><defs><linearGradient id='gradient'><stop offset='0' style='stop-color:%230070d8' /><stop offset='0.5' style='stop-color:%232cdbf1' /><stop offset='1' style='stop-color:%2383eb8a' /></linearGradient></defs><ellipse ry='100' rx='100' cy='110' cx='110' style='fill:none;stroke:url(%23gradient);stroke-width:6;' /></svg>");
  background-size: 100% 100%; /* Fix for Fifefox image scaling */
}

Свободный перевод  ответа от участника  @Vadim Ovchinnikov.


text:
Q: Flask forms - Handle multiple identical form fields I have the following code to display information in a shopping-cart manner:
<form method="POST" action="/updateorder/{{item.idordre}}">
  {%for parts in viewParts %}

    <input class="form-control" id="idpart" name="idpart" value="{{parts.idpart}}">

    <input class="form-control" id="quantity" name="quantity" required type="number" value="{{parts.quantity}}">

  {%endfor%}

    <input class="btn btn-warning btn-md" id="submit" name="submit" type="submit"value="Update quantity">

   </form>

There might be several instances of the same formfields with idpart and quantity where the user can change the quantity and submit the update.
@app.route('/updateorder/<int:ident>',methods=['GET','POST'])
def updateorder(ident):
form = updateOrder()
if request.method =="POST":
    quantityChange = request.form.to_dict()
    dostuff()

When i receive the form in my route i only get the first form value.
Is it possible to receive data like this at all?

A: If you're saying you have multiple fields with same name in the same form, then submitting the form will only give you one instance of it (because they have the same names, they overwrite each other or you will get just the instance that has a value)
A possible solution is to make the names unique by appending an index to the name e.g. idpart_1, idpart_2 (you can even use the idpart number itself i.e. idpart_{{idpart}}. On submit, you then process the names via a pattern e.g.
for k,v in request.form.items():
    if k.startswith("idpart_"):
        # This field is an idpart number. You can then figure out which one it is
        idpart = k.split("idpart_")[1] # Tells you which one you're dealing with


text:
Q: Is the root of $x^5-x-1$ rational or irrational? I am wondering whether the unique real root of the polynomial $x^5-x-1$ ($1.1673\ldots$) is rational or irrational. Is it possible to show that it is either rational or irrational?
Also, can it be expressed in any other way than "the root of $x^5-x-1$"? For example, by $n^{th}$ roots?

A: If it is $p/q$, a reduced fraction, then $p^5-pq^4=q^5$, hence $p|q$, a contradiction to being in reduced form unless $p|1$. In that case, $q^5\pm q^4=1$ which is also impossible, since then $q|1$.

A: If it were rational then according to Rational Roots Theorem, the roots would be $\pm 1$ now when you substitute 1 or -1 in equation the equation doesn't give 0, so this equation has no rational roots.

A: By the rational roots theorem, it has no rational roots. In "Solving Solvable Quintics" by Dummit it is specifically given a case for polynomials $x^5 + ax + b$ to be solvable in radicals; to be solvable, the resolvent $f_{20}(x)$ must have a rational root, where
$$f_{20}(x) = x^6 + 8ax^5 + 40a^2x^4 + 160a^3x^3 + 400a^4x^2 +
(512a^5-3125b^4)x + (256a^6-9375ab^4) $$
If I have not tragically erred in calculation, this polynomial has no rational roots, so $x^5-x-1$ cannot be solved in radicals.


text:
Q: Self join a table I'm trying to join a table to itself to get all session_ids, from clientids that had a goal_completion at some (later) point.
Table:

clientid	sessionid	goalcompletion

1	a	0

1	b	0

1	c	1

2	x	0

2	y	0

2	z	0

Expected Output:

clientid	sessionid

1	a

1	b

1	c

I tried a couple of versions, but I can't seem to figure out how this works. This is my latest iteration:
SELECT a.clientid,
       a.session_id,
       a.goal1completions_funnel,
       a.goal2completions_funnel,
       a.goal3completions_funnel
FROM _demo.ga_conversions_test a
left JOIN _demo.ga_conversions_test b
  ON a.session_id = b.session_id
  AND (b.goal3completions_funnel = 1
     OR b.goal1completions_funnel = 1
     OR b.goal2completions_funnel = 1)

Can you lead me the right way please?

A: I think you do not need to use a join for this task. Please try:
select session_id
from _demo.ga_conversions_test
where goal1completions_funnel=1 OR goal2completions_funnel=1 OR goal3completions_funnel=1
group by session_id

EDIT: Based on the provided data, if I were you, I would find the clientids having more than two type of goalcompletion number and use an inner join like below:
with cte as (
   select clientid, count(distinct goalcompletion) as CountDifferentGoalCompletion
   from _demo.ga_conversions_test
   group by clientid
   having count(distinct goalcompletion) > 1
)
select a.clientid, a.sessionid
from _demo.ga_conversions_test a
inner join cte on cte.clientid = _demo.ga_conversions_test.clientid

EDIT2: If cte structure does not work (will not work if this is not in SQL Server), then:
select a.clientid, a.sessionid
from _demo.ga_conversions_test a
inner join (select clientid, count(distinct goalcompletion) as CountDifferentGoalCompletion
            from _demo.ga_conversions_test
            group by clientid
            having count(distinct goalcompletion) > 1) x
on x.clientid = a.clientid

A: it seems the reason you cant get the desired result is that you are joining the tables with the same session_id. Try this:
Select ....
From _demo.ga_conversions_test a
left join _demo.ga_conversions_test a on a.session_id < b.session_id (and other criteria)

See if it works. If not, postin a sample of your data structure would help us better understand. If gave you a solution, please mark my answer as accepted solution.

A: Is this what you want?
select ct.*
from _demo.ga_conversions_test ct
where exists (select 1
              from _demo.ga_conversions_test ct2
              where ct2.session_id = ct.session_id and
                    1 in (goal1completions_funnel, goal2completions_funnel, goal3completions_funnel) and
                    ct2.<timecol> > ct.<ctimecol>
             );


text:
Q: TypeError: can't convert np.ndarray of type numpy.datetime64 I want to test a particular code, and I wrote the following data loader as an experiment (for a larger project)
import pandas as pd
import datetime
from torch.utils.data import Dataset, DataLoader
from random import randint
import random

class TestLoader(Dataset):
    def __init__(self, num_profiles):
        self.num_profiles = num_profiles
        self.profiles = {}

    def __len__(self):
        return self.num_profiles

    def __getitem__(self, idx):
        symbol = random.sample(["A","B","C","D","E"], 1)[0]
        if symbol not in self.profiles.keys():
            country = random.sample(['China', 'UK', 'Germany', 'Fiji', 'Lichtenstein'], 1)[0]
            gender = random.sample(['Male', 'Female', 'Other'], 1)[0]
            self.profiles[symbol] = {"country": country, "gender": gender}

        timeSince = random.uniform(10,80)
        dt=datetime.date(randint(2005,2025), randint(1,12),randint(1,28))
        date = np.datetime64(dt)

        sample = {'value': float(idx), 'country': self.profiles[symbol]["country"],
                  'gender': self.profiles[symbol]["gender"],
                  "timeSince": timeSince, "symbol": symbol, "date": date}
        return sample

And I have a code like the following to try visualize the code:
user_profiles = TestLoader(2000)
batch_size = 40
dataloader = DataLoader(user_profiles, batch_size=batch_size, shuffle=True)

visualize = pd.DataFrame()

for i,data in enumerate(dataloader):
    if i < 10:
       visualize = pd.concat([visualize, pd.DataFrame(data)], axis = 0).copy()
visualize

But then, on the line of for i,data in enumerate(dataloader):, I get the following error:
TypeError                                 Traceback (most recent call last)
<ipython-input-91-584c34ba614b> in <module>
      2
      3
----> 4 for i,data in enumerate(dataloader):
      5     pass
      6 #     if i < 10:

C:\ProgramData\Anaconda3\lib\site-packages\torch\utils\data\dataloader.py in __next__(self)
    515             if self._sampler_iter is None:
    516                 self._reset()
--> 517             data = self._next_data()
    518             self._num_yielded += 1
    519             if self._dataset_kind == _DatasetKind.Iterable and \

C:\ProgramData\Anaconda3\lib\site-packages\torch\utils\data\dataloader.py in _next_data(self)
    555     def _next_data(self):
    556         index = self._next_index()  # may raise StopIteration
--> 557         data = self._dataset_fetcher.fetch(index)  # may raise StopIteration
    558         if self._pin_memory:
    559             data = _utils.pin_memory.pin_memory(data)

C:\ProgramData\Anaconda3\lib\site-packages\torch\utils\data\_utils\fetch.py in fetch(self, possibly_batched_index)
     45         else:
     46             data = self.dataset[possibly_batched_index]
---> 47         return self.collate_fn(data)

C:\ProgramData\Anaconda3\lib\site-packages\torch\utils\data\_utils\collate.py in default_collate(batch)
     71         return batch
     72     elif isinstance(elem, container_abcs.Mapping):
---> 73         return {key: default_collate([d[key] for d in batch]) for key in elem}
     74     elif isinstance(elem, tuple) and hasattr(elem, '_fields'):  # namedtuple
     75         return elem_type(*(default_collate(samples) for samples in zip(*batch)))

C:\ProgramData\Anaconda3\lib\site-packages\torch\utils\data\_utils\collate.py in <dictcomp>(.0)
     71         return batch
     72     elif isinstance(elem, container_abcs.Mapping):
---> 73         return {key: default_collate([d[key] for d in batch]) for key in elem}
     74     elif isinstance(elem, tuple) and hasattr(elem, '_fields'):  # namedtuple
     75         return elem_type(*(default_collate(samples) for samples in zip(*batch)))

C:\ProgramData\Anaconda3\lib\site-packages\torch\utils\data\_utils\collate.py in default_collate(batch)
     63             return default_collate([torch.as_tensor(b) for b in batch])
     64         elif elem.shape == ():  # scalars
---> 65             return torch.as_tensor(batch)
     66     elif isinstance(elem, float):
     67         return torch.tensor(batch, dtype=torch.float64)

TypeError: can't convert np.ndarray of type numpy.datetime64. The only supported types are: float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.

I have some parts later in the code, which really would benefit from using numpy.datetime64, so I prefer to not change the type I am using in the definition of the loader. How can I fix this?


text:
Q: Proving basic probability inequalities So the title is a bit vague, but I am trying to solve some basic probability inequality. Given that $P(B\cap C) > P(B)P(C)$, how can I show that $P(B|C) > P(B|W\setminus C)$?
I started by showing that $P(B|C) > P(B)$, but I am not sure if this helps. Thoughts?
Thanks.

A: $W$ must be the sample space, so that $W\setminus C = C^\complement$.
Indeed, stating $\mathbb P(B\cap C) >\mathbb P(B)\,\mathbb P(C)$ implies that $0<\mathbb P(C)<1$*, thus, from the definition of conditional probability,
$$\begin{align}
\mathbb P(B\,|\,C)\,\mathbb P(C) &> \mathbb P(B)\,\mathbb P(C)\\
\mathbb P(B|C) &> \mathbb P(B)\quad.
\end{align}$$
Also, adding the probability of $B\cap C^\complement$ to both sides of the inequality given, using that $\mathbb P(C^\complement)\neq0$,
$$\begin{align}
\mathbb P(B\cap C) + \mathbb P(B\cap C^\complement) &>\mathbb P(B)\,\mathbb P(C) + \mathbb P(B\cap C^\complement)\\
\mathbb P(B) &>\mathbb P(B)\,\mathbb P(C) + \mathbb P(B\cap C^\complement)\\
\mathbb P(B)[1 - \mathbb P(C)] &> \mathbb P(B\cap C^\complement)\\
\mathbb P(B)\,\mathbb P(C^\complement) &> \mathbb P(B\cap C^\complement)\\
\mathbb P(B) &> \mathbb P(B\,|\,C^\complement)\quad,
\end{align}$$
and we combine the two inequalities obtained to prove that $\mathbb P(B\,|\,C) > \mathbb P(B\,|\,C^\complement)$.
* If $\mathbb P(C)=0$, then $\mathbb P(B\cap C) > 0$, but since $B\cap C\subset C$, $\mathbb P(B\cap C)\le\mathbb P(C)$, so $\mathbb P(B\cap C) = 0$, a contradiction. On the other hand, if $\mathbb P(C)=1$, we would have $\mathbb P(B\cap C) > \mathbb P(C)$, which contradicts $\mathbb P(B\cap C)\le\mathbb P(C)$ as well.

A: By hypothesis, $P(B\cap C)>P(B)P(C)$, which is equivalent to $P(B\mid C)>P(B)$. The Law of Total Probability tells us that $P(B)=P(B\mid C)P(C)+P(B\mid C^c)P(C^c)<P(B\mid C)$, by hypothesis, yielding $P(B\mid C)>P(B\mid C^c)$.


text:
Q: Classification of isolated singularity /Laurent series I want to find out, what kind of singularties does
$ f(z)= \frac{1}{z^3-z^5}$ have.
I would do the following steps:
$ f(z)= \frac{1}{z^3-z^5} = \frac{1}{z^3(1-z)(1+z)}$ so I have $ z_1=1, z_2=-1 , z_3=0$
I can argue by the limit test, that $ z_i$ are poles.
For example $ \lim_{z\rightarrow 1} (1-z)f(z)=  \lim_{z\rightarrow 1} \frac{1}{z^3(1+z)}= \frac{1}{2} \ne 0 $
Am I right?
How can I find the Laurent series of f  and classify the singularties without using the Limit test.

A: You are right: they are all poles.
Now, consider the point $0$. Since$$f(z)=\frac1{z^3}\times\frac1{1-z^2}$$and since, near $0$, you have$$\frac1{1-z^2}=1+z^2+z^4+z^6+\cdots$$then (again, near $0$) you have$$f(z)=\frac1{z^3}+\frac1z+z+z^3+\cdots$$and this confirms that $0$ is a pole.
You can do a similar thing at $\pm1$.


text:
Q: jQuery: can't select link I'm trying to use wordpress' media upload popup in a custom plugin I'm working on.
So far everything worked, I was able to upload images and insert them into a field, but I have another field that requires a link to the uploaded pdf.
tb_show('', 'media-upload.php?type=image&TB_iframe=true;height=200');
window.send_to_editor = function(html) {
    console.log(html);

    console.log(jQuery('a', html));
    console.log(jQuery('a', html).attr('href'));

    console.log(jQuery('img', html));
    console.log(jQuery('img', html).attr('src'));

    imgurl = jQuery('a', html).attr('href');
    current_upload.prev().val(imgurl);

    tb_remove();
}

For an image this would be my output, which is right since it's able to select the image source
 to.js:54
[]
undefined
[

]
http://to.local/wp-content/uploads/2012/07/Screen-Shot-2012-06-20-at-12.15.52-PM-300x221.png

But when I select a PDF I get this:
01 Mobile Characteristics and Interaction Design Principles (Slides) to.js:54
[]
undefined
[]
undefined

So I can't figure out why jQuery('img', html) works fine while jQuery('a', html) doesn't, while in both cases there is a link in the returned html.

A: The html itself is an "a".
console.log(jQuery(html).attr('href'));

A: Assuming html = jQuery('');, html is the  element.
jQuery('a', html) tries to select  within the children of html, which returns no results as there are no  elements there.
Since  is a children of the  parent in html, jQuery('img', html) works.
In your case, to get the href attribute of html, do this:
jQuery(html).attr("href")

(Remove the jQuery() if html is already an jQuery object)


text:
Q: ValueError: invalid literal for int() with base 10: i am getting this value error, when i try to insert some data to django model. My python script is :
from task.employeeDetails.models import EmployeeDetails

def dumpdata():
    userName = "John"
    designation = 'Software Engineer'
    employeeID = 2312
    contactNumber = 9495321257
    project = 'AOL'
    dateOfJoin = '2009-10-10'
    EmployeeDetails(userName,designation,employeeID,contactNumber,project,dateOfJoin).save()
dumpdata()

My models.py is
class EmployeeDetails(models.Model):
    userName = models.CharField(max_length=200)
    designation = models.CharField(max_length=200)
    employeeID = models.IntegerField()
    contactNumber = models.CharField(max_length=200)
    project = models.CharField(max_length=200)
    dateOfJoin=models.TextField()

Please help me to solve this error as i am new to python programming. The error is "ValueError: invalid literal for int() with base 10: 'John'

A: Don't use positional arguments, use keywords to specify which field is being populated with what data.
EmployeeDetails(userName=userName, designation=designation) #etc

Also, if you are going to call save() anyways, you can use EmployeeDetails.objects.create(...)

A: I am no Django expert, but try replacing
EmployeeDetails(userName,designation,employeeID,contactNumber,project,dateOfJoin).save()

with
EmployeeDetails(userName=userName,designation=designation,employeeID=employeeID,contactNumber=contactNumber,project=project,dateOfJoin=dateOfJoin).save()


text:
Q: Save slurm job information automatically I am looking for a way to save job information provided by sacct automatically to some file. So far I have included an sacct call in my job batch script, but then the state is always "RUNNING".
Is there a way to automatically call sacct after the job ended/died?
The only thing that came to my mind was to submit a second job that depends on the first and then calls sacct, but this is obviously not a good option.

A: You can set a file to store job completion data with JobCompLoc in slurm.conf. (We parse that file to send extra information in the job completion emails, and it includes (I think) everything that you get from sacct).


text:
Q: How is the H11AA1 ic working with AC mains voltage? I am making an arduino controlled fan speed controller that would digitally control the speed of my ceiling fan working on 230 VAC and 50 Hz. I am using the following circuit which is designed for 110VAC and 60Hz

I took this circuit from this website:- http://playground.arduino.cc/Main/ACPhaseControl
Working:-
When the AC voltage goes from zero to peak, the optocoupler is active and activates the output side. The arduino pin connected to the output of the optocoupler senses a HIGH voltage. When the pin reads a low it means we are approaching at a zero crossing of the AC mains voltage and depending upon the timing, the arduino will activate the TRIAC driver that is optocoupler MOC3052 that will further activate the TRIAC providing the power to the ceiling fan.
My doubt is that, in the datasheet of H11AA1 optocoupler ic the absolute max forward voltage of the optocoupler is not mentioned. How is this ic working directly with AC. I understand that the current is low since there are two 15k Ohms resistors, but the voltage is still around 55VAC at the pins 1 and 2 of H11AA1. How is this IC not destroyed?? Also will the circuit work for 230VAC 50Hz??
Datasheet of H11AA1: - http://www.vishay.com/doc?83608

A: What makes you think that the voltage at pis 1 and 2 is 55VAC?  There are back-to-back diodes across pins 1 & 2, and as long as you don't exceed the current rating of the diodes you will never see more than the diode's forward voltage drop between pins 1 & 2.
The max forward diode voltage is specified as 1.5V at 10mA.  In your circuit the peak current will be the peak of the AC line, maybe 155V across 30K or around 5mA.  So pins 1 & 2 will have less than 1.5V across them.
If you limit the current to a safe value you could use the circuit at 230VAC as well.
There are safety issues with use and PCB layout of this kind of device that you have to understand, but the device itself should be fine for these applications.


text:
Q: Selecting Only Columns Within Range I am trying to write a macro which only calls a function for every third cell within a range.
Currently I have the following:
Sub CallFormula()
Dim rng As Range
Set rng = Range("startcell:end:cell")
With rng
For i = Range.Columns("G13") To Range.Columns("endcell")
Columns(i).SpecialCells(xlCellTypeFormulas).Select
Call formula()
Next i
End With
End Sub()

The range starts with startcell and ends with endcell and is basically a rectangle. I want to loop through every column starting from column G (which is the 2nd column after startcell).
The problem is that I only want to call the function on rows within this range. However, the function is executed on all cells that have a formula in every third column after column G. I thought using With would fix it, but it does not.
Any solutions?
Thank you!


text:
Q: BeagleBoard C5 Building u-boot I am trying to successfully build u-boot for my BeagleBoard C5 board. I am using Ubuntu 10.04 and the Crosstool-NG toolchain. I have working images for Xloader (MLO), u-boot.bin, and uImage that I found prebuilt from the AngstromBB project for which the boards boots Angstrom successfully.
I can successfully build the u-boot.bin file by doing the following:
git clone git://git.denx.de/u-boot.git u-boot/
make ARCH=arm CROSS_COMPILE=arm-none-linux-gnueabi- omap3_beagle_config
make ARCH=arm CROSS_COMPILE=arm-none-linux-gnueabi-

I then copy my just built u-boot.bin to replace the working version of u-boot.bin on the SD card and attempt to boot the board but it fails by hanging at:
Reading boot sector
Loading u-boot.bin from mmc

It will just sit there forever! I cannot seem to find any clear instructions on building u-boot for the C5 BeagleBoard other than that it is different then previous versions or requiring something called 'SPL' built with u-boot. Does anybody know how I might succeed in building my own u-boot.bin image for the BeagleBoard C5?

A: Your first step should be researching the boot sequence of the board. Some processors do not boot directly to u-boot. They launch an application that is stored in Flash or maybe an EEPROM on the board. In the case of your C5, this application is X-Loader (https://gitorious.org/x-loader). You are going to need to understand what this level 1 boot loader does and how exactly it launches u-boot. Generally they will do some basic PSC, DRAM, ... configuration before launching the full boot loader. But where does it look for u-boot? Does X-Loader copy u-boot to RAM and begin execution from there? Or does it it start execution from your MMC? Sometimes there are jumpers that can be set which will control the boot sequence. So X-Loader could boot from NAND, NOR or SD/MMC depending on the setting.
Where did you get your u-boot source code from? Did you download it directly from the denx website or was it provided with your Beagle board?
In general, it is very difficult to debug bringing up a board (even if it's a reference board) without tools. Was a debugger provided with the board or d you have a JTAG debugger of your own that you could use to set hardware breakpoints and step through the code?


text:
Q: Cache is building up with each load I am working on my portfolio website. It is a PWA and there is a service worker. I am caching the index page and all the required assets of the index page using the service worker. But when I actually test it the cache size is building up with each load. After some experiments I found out that the problem is with the Google analytics script though I am not sure. But I cannot find a way to fix it. I had copied directly the code from Google analytics. Then as it didn't work, I tried to set the crossorigin="anonymous". Then also it isn't working.
Source code
Thanks in advance!

A: Right now your service worker's fetch handler unconditionally applies a caching strategy to all requests, regardless of what server is invovled.
If you want to avoid applying that strategy to requests made to third-party servers, like Google Analytics, you can exit the fetch handler early, before you call event.respondWith(). If you do that, then the normal network behavior will still apply, and you won't get any of the caching.
Assuming all of the assets that you want to cache are served from the same-origin server, you can do this with:
self.addEventListener('fetch', (event) => {
  const url = new URL(event.request.url);
  if (url.origin !== location.origin) {
    return;
  }

  // event.respondWith() and the caching logic goes here.
});


text:
Q: Mysql function for zip radius crawls on our production server, but is fine on local and staging servers Production is 5.7.27 and local is 5.7.35 - hopefully that is not the issue.
Problem involves getting a list of IDs within a zip code and radius.
function "get_zip_point" takes the zip and returns long and lat:
BEGIN
  DECLARE _point POINT;
     SELECT POINT(zd_long, zd_lat) INTO _point
     FROM zipdata
     WHERE zd_zip = LEFT(_zip, 5);
  RETURN _point;
END

This is then sent into function distance_between:
BEGIN
  DECLARE _degree FLOAT DEFAULT pi()/180;
  DECLARE _lat_1   FLOAT DEFAULT st_x(_point_1) * _degree;
  DECLARE _lng_1   FLOAT DEFAULT st_y(_point_1) * _degree;
  DECLARE _lat_2   FLOAT DEFAULT st_x(_point_2) * _degree;
  DECLARE _lng_2   FLOAT DEFAULT st_y(_point_2) * _degree;
  DECLARE _lat_d   FLOAT DEFAULT _lat_2 - _lat_1;
  DECLARE _lng_d   FLOAT DEFAULT _lng_2 - _lng_1;
  DECLARE _ans     FLOAT;

  SET _ans = POWER(SIN(_lat_d / 2), 2) + COS(_lat_1) * COS(_lat_2) * POWER(SIN(_lng_d / 2), 2);
  SET _ans = 2 * ASIN(SQRT(_ans));

  RETURN _ans * 3956;
END

On my local desktop I can run that and pull up thousands of correct results in 1-2 seconds based on a table of IDs and zips of close to a million rows.
On production, it'll run forever and eventually timeout.


text:
Q: Bootstrap 4.5 code is not working as expected I am a beginner in Bootstrap and I'm following bootstrap documentation. Still, my code is not working. My folder contains only an index.html file.
Visual Studio Code screenshot.
<!doctype HTML>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
    integrity="sha384-9aIt2nRe3js3W69CrMinNGtLdWyYrnnKzHR26vu4tDT5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

<title>WeGo</title>

        WeGo

A: You had problems with the integrity attribute, and the files you were trying to use were blocked, when you use cdn links always make sure to use the liks provide in the official source bootstrap website or bootstrapcdn

<!doctype HTML>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title>WeGo</title>

        WeGo


text:
Q: Why do I get syntax error before: '{'? While playing with Erlang getting started section
I have met bizarre syntax error on trivial use case (simple map initialization). Are there any suggestion why does that happen?

1> #{ "key" => 42}.

*

*1: syntax error before: '{'

Details: Erlang R16B03 (erts-5.10.4), Eshell V5.10.4.

A: Because maps were introduced in Erlang 17.
You have to upgrade your installation or do not use maps.


text:
Q: mysql foreign keys Hello I have two mysql tables one that holds username and password second that holds user information. Here are the tables:
CREATE  TABLE IF NOT EXISTS `test`.`dbo.users` (
  `userId` INT(11) NOT NULL AUTO_INCREMENT ,
  `userUsername` VARCHAR(45) NULL ,
  `userPassword` VARCHAR(45) NULL ,
  `dbo.userProfiles_userProfileId` INT(11) NOT NULL ,
  PRIMARY KEY (`userId`, `dbo.userProfiles_userProfileId`) ,
  INDEX `fk_dbo.users_dbo.userProfiles` (`dbo.userProfiles_userProfileId` ASC) ,
  CONSTRAINT `fk_dbo.users_dbo.userProfiles`
    FOREIGN KEY (`dbo.userProfiles_userProfileId` )
    REFERENCES `test`.`dbo.userProfiles` (`userId` )
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;

CREATE  TABLE IF NOT EXISTS `test`.`dbo.userProfiles` (
  `userProfileId` INT(11) NOT NULL AUTO_INCREMENT ,
  `userId` INT(11) NOT NULL ,
  `userFirstName` VARCHAR(45) NULL ,
  `userMidleName` VARCHAR(45) NULL ,
  `userLastName` VARCHAR(45) NULL ,
  `userBirthDate` VARCHAR(45) NULL ,
  `userCountry` VARCHAR(45) NULL ,
  `userState` VARCHAR(45) NULL ,
  `userCity` VARCHAR(45) NULL ,
  `userZipCode` VARCHAR(45) NULL ,
  `userPrimaryAddress` VARCHAR(45) NULL ,
  `userSecondaryAddress` VARCHAR(45) NULL ,
  `userThirdAddress` VARCHAR(45) NULL ,
  `userFirstPhone` VARCHAR(45) NULL ,
  `userSecondaryPhone` VARCHAR(45) NULL ,
  `userThirdPhone` VARCHAR(45) NULL ,
  `userFirstEmail` VARCHAR(45) NULL ,
  `userSecondaryEmail` VARCHAR(45) NULL ,
  `userThirdEmail` VARCHAR(45) NULL ,
  `userDescription` VARCHAR(45) NULL ,
  PRIMARY KEY (`userProfileId`, `userId`) )
ENGINE = InnoDB;

My problem with this tables is that the fk key doesn't work and I'm not sure why I'm missing something here.. ( I haven't used foreign keys much).
Error:

Executing SQL script in server
ERROR: Error 1005: Can't create table 'test.dbo.users' (errno: 150)

Can you please help fixing this so I can use fk on this tables and others? and if you got some time to spare to explain me how fk keys work exactly (using mysql workbench to create them on a diagram then forward engineer). thank you for your help

A: You have to create the root tables first (userProfiles). You can temporarily bypass this restriction by disabling foreign key checks with set foreign_key_checks=0. This must be done if you're creating multiple tables with circular references.


text:
Q: PHP HTML email gets sent with tags $to = 'jay@mywhitecard.ph';
$subject = 'Coupon Claimed!';
$header  = 'From: info@mywhitecard.ph';
$claimed = '';
$claimed .= '
Hello, World!
';
$claimed .= '';

mail($to, $subject, $claimed, $header);

I have this simple html php email but when it is sent everything including tags gets included.

googled tutorials show similar examples like the code i did, would like to know how I can only send the div content.

A: You need to add the Content-type to your header like this:
$to = 'jay@mywhitecard.ph';
$subject = 'Coupon Claimed!';
$claimed = '';
$claimed .= '
Hello, World!
';
$claimed .= '';
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= 'From: info@mywhitecard.ph\r\n';

mail($to, $subject, $claimed, $headers);


text:
Q: How to use git locally and push to remote server I want to use git to manage my development, integration test and production environments.  I've looked around but can't seem to find a simple explanation of how (eg Git - pushing to remote repository doesn't quite do it).  A very brief explanation of what I want to do:

*

*I master my codebase on my laptop as that's where I do most of my work.

*I host my site on 1and1.  On there, I have two sites set up, the production site and an integration test site.

*I want to set up git so I can have two remotes on my laptop, say siteprod and siteint.

*Whenever I have a branch I want to test, I want to push it from my laptop, say using "git push siteprod newproductionversion" (I'm sure you get the idea).

I've achieved something close by creating a repository on 1and1 using git --init (note without --bare!) and setting up the remotes using ssh.  But I have to set receive.denyCurrentBranch to ignore and once I've pushed, I have to checkout the branch by logging onto the 1and1 server.  I have to repeat it all for the integration environment.
This seems very clumsy but I'm sure my use case is not at all unusual.  Is there a sensible way of doing this?

A: If you have ssh connection to the server, you can add a git remote directly to the repository on the server.  Something like:
git add remote production sshUser@example.com:/path/to/repo/.git

Then, to deploy,
git push production branch

That said, you probably shouldn't have your production code served from a git repository.  Much better is to set up a repository outside your web root and use a post-receive hook to copy the code to the web root.  This appears to be outlined here:
Deploy a project using Git push

A: Git is not (originally) meant for synchronizing working copies but repositories that is Git's commits/branches/refs/etc.
What your  want to do I would call a remote checkout. There is hundreds of other ways to do. I have two ideas: As you have setup an ssh-connection the big work is done:
1) use git and ssh
git push origin my_branch
ssh user@server "(cd remote-dir-where-your-repo-is; git checkout -f my_branch;)"

2) Use rsync
rsync -av . ssh://user@server/dir --exclude=.git


text:
Q: Get 2 results from 1 left join I have a table with Orders. Each order has a Sender and a Receiver. Both the sender and the receiver are in the customers table. Each customer may be at some time a sender or a receiver, so I have no option to split them into a Sender and Receiver table.
I'm now stuck in constructing (in one query) a JOIN which will get me two customers (one as the Sender, one as the Receiver) that I can recognize as the "right" kind of customer.
I can make a standard LEFT JOIN,
SELECT o.date,c.last_name,c.first_name,c.company,c.email
FROM orders o
LEFT JOIN customers c ON ( o.sender = c.id )
WHERE o.id = 2";

but this will only get me the info on the sender. I can change o.sender to o.receiver, but that will only get me info for the receiver.
How can I get both and distinguish which of the two is the sender and which the receiver?
Thanks in advance,
Ton

A: You could use an OR on the ON clause of the join:
SELECT o.date, c.last_name, c.first_name, c.company, c.email,
       case when o.sender=c.id then 'Sender'
            when o.receiver=c.id then 'Receiver' end as kind_of_customer
FROM orders o
      LEFT JOIN customers c ON o.sender = c.id or o.receiver = c.id
WHERE o.id = 2;

and using a CASE WHEN you can distinguish if it's a sender or if it's a receiver.

A: You can join on the customer table twice. Once will return the sender and the other will return the receiver.
SELECT o.date,
  c1.last_name,
  c1.first_name,
  c1.company,
  c1.email,
  c2.last_name,
  c2.first_name,
  c2.company,
  c2.email
FROM orders o
LEFT JOIN customers c1
  ON o.sender = c1.id
LEFT JOIN customers c2
  ON o.receiver = c2.id
WHERE o.id = 2";

If you want to use more descriptive aliases, then you would use:
SELECT o.date,
  sender.last_name,
  sender.first_name,
  sender.company,
  sender.email,
  receiver.last_name,
  receiver.first_name,
  receiver.company,
  receiver.email
FROM orders o
LEFT JOIN customers sender
  ON o.sender = sender.id
LEFT JOIN customers receiver
  ON o.receiver = receiver.id
WHERE o.id = 2";


text:
Q: Div class background color change I am trying to change the background color of div whose class = thisphotobox.
All should happen after pressing the image inside of this div.
What do i do wrong? And what should i add to these onclick brackets?
This is the image:
  echo '

';

And here goes the function:
   function clicked(thisphotobox){
     var div = document.getElementsByClassName("thisphotobox");
     elements.style.backgroundColor="red";
   }

I'm also thinking how to make it get "checked" as in checkbox.

A: look at your variable name.  You've set the result of the search to div but you're trying to set the background on elements.
Also, this question has nothing to do with PHP or MySQL.

A: 1) Instead of onclick="clicked()", write onclick=clicked();.
2) If there is only one div, you should try to give it an id, not a class. You can still use CSS to modify it if you want to. And, of course, getElementsByClassName becomes getElementById.
3) In clicked() you create a variable named div, but try to change the background color of an undeclared variable elements. Change it to div, or change div to elements.
+1 What do you mean with the "checked like a checkbox" part? If you want to store that you clicked on the image (and changed the background color), then you can declare a new variable (outside of the clicked() function, so you can access it from elsewhere), false by default, then you can change it from the function like this:
variableName = true;. This is the easiest method to achieve it.


text:
Q: How to write a huge table (>10GB) column by column (column-wise) in Python? Basically what I'm doing is calculating a vector and then writing the results.  Right now I'm writing it row by row then I have to transpose is after with datamash transpose which is kind of annoying.  It would be way more efficient if I could write a tab-delimited table column-by-column.
How can I do this in Python (can it be down w/ np.savetxt)?
Here's one of my attempts below:
In [12]: import numpy as np

In [13]: data = np.random.normal(size=(10,3))

In [14]: data
Out[14]:
array([[-0.50469426, -0.9710173 ,  0.43285955],
       [ 0.71702597, -0.99998294, -1.00353228],
       [ 0.77699465, -0.66542361, -0.04594868],
       [-0.71012566, -1.46451086, -0.95308903],
       [ 0.47470605, -0.56792278,  0.95818696],
       [ 1.20729071, -0.04735589, -0.11576503],
       [ 1.03686861,  0.72149358,  0.35908901],
       [ 0.09520535,  0.24437775, -0.59554944],
       [-0.13346795,  0.29530724,  0.17524018],
       [-0.16433609,  0.05261348, -0.57545287]])

In [15]: with open("example.tsv", "w") as f:
    ...:     for row in data:
    ...:         print(*row, sep="\t\n", file=f, end="")
    ...:

In [16]: %%bash
    ...: cat example.tsv
    ...:
    ...:
-0.5046942610111921
-0.9710173002083825
0.43285954686999120.7170259682395401
-0.9999829435149956
-1.003532284093560.7769946455220355
-0.6654236121150638
-0.04594868270526936-0.7101256559235657
-1.4645108615674511
-0.95308903163753660.4747060486691834
-0.5679227787239494
0.9581869616594761.207290709055818
-0.047355888296561795
-0.115765032633420781.036868614074581
0.7214935810053711
0.35908901158512140.09520535113648704
0.2443777544867152
-0.5955494427027563-0.1334679518044996
0.29530724431573385
0.1752401825058493-0.1643360874489238
0.052613481327433834
-0.5754528683216069

A: Having 10 GB of data: it's worth start with a few remarks first :
Unless you data processing pipelines are outside of your control and you have to use anyway the plain-text, GNU datamash text-file transformations, the numpy-side is an absolute master in smart vector/array processing, if one decides to harness all its powers:
Key factors are:

*

*in-RAM-layout: numpy can change this in a snap, as it tricks you by handling axes abstract

*on-disk-layout: numpy can read both F-like (FORTRAN, column ) C-like (row-wise) data-files

This said, your python side is thanks to numpy as flexible as the crowd of scientific computing developers was already used to design, develop and performance tune. Fortran has used the column-first ordering since ever due to performance advantages, so it has been put into numpy-tools right for performance reasons since ever either.

The numpy smart in-RAM-layout tricks:
|>>> from zmq import Stopwatch
|>>> aClk = Stopwatch()
|>>> aClk.start(); a = np.arange( 1E3 );aClk.stop() #_____ tiny arrays are cheapest
46                                                  #_____ ~ 46 [us]+may live in-cache
|>>> aClk.start(); _ = np.arange( 1E6 );aClk.stop() #_____ small arrays are "fast"
10131                                               #_____ ~ 10 [ms] to alloc. RAM
|
|
|>>> aClk.start(); _ = np.arange( 1E8 );aClk.stop() #_____ going 1E8+ SWAPs a lot
23970419                                            #_____ ~ 24 [s] + O/S SWAPs RAM
+0:00:34.974360
|
|>>> _.shape                      (100000000,)
|>>> _.size * _.itemsize           800000000
|>>> _.dtype                       dtype('float64')
|>>> _.flags
  C_CONTIGUOUS    : True  <--------+--- vectors are {C|F}-contiguous blocks
  F_CONTIGUOUS    : True  <--------+
  OWNDATA         : True  <------------ indeed owns own data + may have cheap "np.view"-s
  WRITEABLE       : True
  ALIGNED         : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY    : False

in-RAM-layout is a bit hidden issue and if you have never been into numpy-tricks and performance tweaking details, might be, this is the first place you hear about this.
|>>> aClk.start();_ = _.reshape( _.shape[0]/10, 10 );aClk.stop() # ___ make 1E8 array into [1E7,1E1] shape
24                                                               # ___ ~ 24 [us]
# i.e. NOTHING HAS MOVED in memory, just the hidden indexing tricks were adapted
#      not a single byte from all of the 0.8 GB, now array, has been moved
#      the same will happen with numpy.ndarray.T smart-tricked operations
|>>> _.flags
  C_CONTIGUOUS    : True  <--------- vector ceased be vector, matrix is C-row-wise
  F_CONTIGUOUS    : False            as not a single byte was moved in in-RAM-layout
  OWNDATA         : False <--------- now, view-alike manipulations on "foreign"-owned data
  WRITEABLE       : True
  ALIGNED         : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY    : False

The smart tools can "transpose" ( actually doing nothing but indexing tricks ) in almost zero-time:
|>>> aClk.start();_.shape;aClk.stop()
(10000000, 10)                              #             BLOB is [1E7,1E1] ~0.8 GB
25                                          # ... 23 [us] to tell us the .shape
|>>> aClk.start();_.T.shape;aClk.stop()     #             go TRANSPOSE !
(10, 10000000)                              #             ok BLOB is [1E1,1E7]
43                                          # ...~43 [us]
                                            #    -23 [us] to tell us the .shape
                                            # ==  20 [us] to TRANSPOSE BLOB ??????
                                            #             NO transpose is tricked by adapted indexing only

The transpose operation just changes the way, how indices get mapped-onto an already RAM-allocated memory-area, all without moving a single byte of the 0.8 GB sized BLOB-data in the RAM, just smart-indexing tricks - so the column-wise arrangement could be used as it comes at zero add-on costs ( not counting those ~ 20 microseconds ... )
|>>> _.T.flags
  C_CONTIGUOUS    : False
  F_CONTIGUOUS    : True <------------- now, F-column-wise arrangement gets set
  OWNDATA         : False <------------ and, again, on "foreign"-owned data
  WRITEABLE       : True                                               already
  ALIGNED         : True                                               put in-RAM
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY    : False

Anyway, doing any high-performance, smart and vectorised code for a bit larger datasets, one will always benefit from taking due care about in-RAM-layout and tuning the vectorised-code to "follow" ( not fight against ) the actual layout used. Best read about cache-memory hierarchies for your processor/computing-platform and for ultimate performance always test each ordering scenario for the target scales of vectors/n-dim-arrays, before making the vectorised-code into HPC-production (cache-lines, associativity of caches are very different and HPC-impacts are indeed immense if your code "violates" the best alignment possible and such code wastes a lot of time right due to such inefficiencies ).

One may spend a lot or smart-save in using on-disk-layout tricks :
as noted above, unless forbidden to do so, one may increase the performance of on-storage ops, by smart-compression first all the output the numpy is to store on-disk. Be it a numpy way or dill.dump() or similarly developed compression-library.
Starting from the exemplified code above:
In [15]: with open("example.tsv", "w") as f:
    ...:     for row in data:
    ...:         print(*row, sep="\t\n", file=f, end="")

is very expensive, as the for-loops are particularly slow ( expensive ) in python and the whole job could be done smarter using the "HPC"-grade numpy-tools.
Additionally added data-compression is both fast per-se and way cheaper than moving data onto storage and back. SSD-media are faster than conventional media, yet ( in 2019 ) the benefits from compression remains smaller data-footprint and faster I/O-data-flows, which in most if not all cases justifies the time spent in using numpy.savez_compressed() to move just the compressed ( .ZIP_DEFLATED ) blob, instead of always spending 8-bits-per-each-digit in ASCII-file plain number representations.
numpy.load() is an input-direction call for the numpy-case, dill can even save/restore the whole python-interpreter session, which may have a wider use in scientific workflow automation ( plus saving restore-able-snapshots )
python also provides zipfile tools for direct work with compressed-files, so a need to resort to GNU command-line tools may be limited to some indeed corner-cases.


text:
Q: Configurable product doesn't show simple product images After updating to Magento 2.2
Configurable product only shows images assigned to its' own gallery but nothing of the simple products associated with it.
Even when I choose a product via swatch the image doesn't change.
Swatch attribute settings are correct, and has worked in previous version of Magento 2.1


text:
Q: bash - using a command line argument (hostname) to run an external command First time post, please forgive any missing information.
I have a script that is supposed to work with icinga. I need icinga to log into my Linux box and run a command like "script ". The script will then run a command to that hostname like sudo /etc/init.d/apache2 status then report back "running or unused" and an exit status of 0 or 2.
I'm wondering how I could add another command and have it one or the other run depending on what hostname it's given. Half of them need apache2 to be running and the other half need to have a process called dss to be running. I'd rather not have two separate scripts. Here is the working script and sorry it's sloppy but I haven't done any clean up and I'm not real good at bash yet.
so the user would run the script ./chkdss2  or
#!/bin/bash
ec=0
ec1=2
var3=run
var4=unused

for host in "$@"
do
  var1=`ssh $host sudo /etc/init.d/dss status|awk '{print $6}'`
  var2="$( echo $var1 | cut -c 3-5 )"
if [[ "$var2" == "$var3" ]]; then
    echo "$host is running"
    echo $ec
  else
    echo "$host is not running"
    echo $ec1
fi
done

A: There are a  couple ways to test if a particular hostname is for apache or dss.  You only need to have a list of hostnames for each case, and check if the received hostnames are included in said lists.
Method 1: using arrays
#!/bin/bash

# Method 1, using array lists of hosts
apachehosts=('ap1' 'ap2' 'ap3')
dsshosts=('dss1' 'dss2' 'dss3')

for host in "$@"
do
    if printf '%s\n' "${apachehosts[@]}" | grep -Fxq "$host"
    then
        echo "$host: APACHE HOST"
    elif printf '%s\n' "${dsshosts[@]}" | grep -Fxq "$host"
    then
        echo "$host: DSS HOST"
    else
        echo "ERROR, $host: unknown host"
    fi
done

To modify the lists of hosts, simply add or remove values in the declaration of arrays apachehosts and dsshosts.

Method 2: using case
#!/bin/bash

# Method 2, using case
for host in "$@"
do
    case "$host" in
        'ap1'|'ap2'|'ap3')
            echo "CASE, $host: APACHE HOST"
            ;;
        'dss1'|'dss2'|'dss3')
            echo "CASE, $host: DSS HOST"
            ;;
        *)
            echo "ERROR CASE, $host: unknown host"
            ;;
    esac
done

Here, you edit the patterns in each case.

Method 3: using if
#!/bin/bash

# Method 3, using if
for host in "$@"
do
    if [[ "$host" == 'ap1' || "$host" == 'ap2' || "$host" == 'ap3' ]]
    then
        echo "IF, $host: APACHE HOST"
    elif [[ "$host" == 'dss1' || "$host" == 'dss2' || "$host" == 'dss3' ]]
    then
        echo "IF, $host: DSS HOST"
    else
        echo "IF, $host: unknown host"
    fi
done

Here you modify the if conditions.  I prefer the other methods, since this one is more complicated to edit, it is not as clear, especially if your list of hosts is long.

Method 4: condition on the hostnames
If you are lucky, there is some pattern to your hostnames.  Ex. all apache servers start with letters ap, all your dss servers include dss in the name, ...
You can then simply use 2 if statements to decide which is which.
#!/bin/bash

# Method 4, patterns
for host in "$@"
do
    if [[ $(echo "$host" | grep -c -e "^ap") -ne 0 ]]
    then
        echo "PATTERNS, $host: APACHE HOST"
    elif [[ $(echo "$host" | grep -c -e "dss") -ne 0 ]]
    then
        echo "PATTERNS, $host: DSS host"
    else
        echo "PATTERNS, $host: unknown host"
    fi
done

Note: hostname apdss1 would come out as an Apache server here.  Previous methods would respond "unknown host".  You patterns must be strict enough to avoid mismatches.

A: I had a similar task to get few report items using single ssh request.
I had to retrieve in singel ssh command:

*

*Full hostname (FQDN)

*Linux version

*IP address of its Docker host if exist, or "none"

I got my script to work in 3 stage.
1. Get multiple lines of information from remote host
ssh -q dudi-HP-Compaq-Elite-8300-MT  <<< '
date +%F:%T   # line 1: time stamp
hostname -f     # line 2: hostname
awk  "/DESCR/{print \$3}" /etc/lsb-release # line 3 : host linux distribution version
ip a | awk "/inet / && !/127.0.0.1/{sub(\"/.*\",\"\",\$2);printf(\"%s \", \$2)}"      # line 4: list IP address to the host
'

Results:
2022-03-05:22:22:21
dudi-HP-Compaq-Elite-8300-MT
20
192.168.2.111 192.168.122.1 172.17.0.1

2. Process multiple lines of information from remote host
Read lines of information from remote host, into an array sshResultsArr.
readarray -t sshResultsArr < <(ssh -q dudi-HP-Compaq-Elite-8300-MT  <<< '
date +%F:%T   # line 1: time stamp
hostname -f     # line 2: hostname
awk  "/DESCR/{print \$3}" /etc/lsb-release # line 3 : host linux distribution version
ip a | awk "/inet / && !/127.0.0.1/{sub(\"/.*\",\"\",\$2);printf(\"%s \", \$2)}"      # line 4: list IP address to the host
')
hostname=${sshResultsArr[1]}
osVersion=${sshResultsArr[2]}
hasDockerIp=$(grep -Eo "172(.[[:digit:]]{1,3}){3}" <<< "${sshResultsArr[3]}") # find IP starting with 172
hasDockerIp=${hasDockerIp:="none"} # if not found IP set to "NONE"

printf "%s \t OS version: %s \t has Docker IP: %s\n" "$hostname" "$osVersion" "$hasDockerIp"

Result:
dudi-HP-Compaq-Elite-8300-MT     OS version: 20          has Docker IP: 172.17.0.1

3. Process each remote host in a loop
#!/bin/bash
for host in "$@"; do
  readarray -t sshResultsArr < <(ssh -q $host  <<< '
  date +%F:%T   # line 1: time stamp
  hostname -f     # line 2: hostname
  awk  "/DESCR/{print \$3}" /etc/lsb-release # line 3 : host linux distribution version
  ip a | awk "/inet / && !/127.0.0.1/{sub(\"/.*\",\"\",\$2);printf(\"%s \", \$2)}"      # line 4: list IP address to the host
  ')
  hostname=${sshResultsArr[1]}
  osVersion=${sshResultsArr[2]}
  hasDockerIp=$(grep -Eo "172(.[[:digit:]]{1,3}){3}" <<< "${sshResultsArr[3]}") # find IP starting with 172
  hasDockerIp=${hasDockerIp:="none"} # if not found IP set to "NONE"

  printf "%s \t OS version: %s \t has Docker IP: %s\n" "$hostname" "$osVersion" "$hasDockerIp"
done

A: I was able to take a little bit from the answers I received and put together something that works well. Thank you all for your answers.
for host in "$@"
do
    case "$host" in
       ('vho1uc1-primary'|'vho1uc2-backup'|'vho2uc1-primary'|'vho2uc2-backup'|'vho3uc1-primary'|'vho3uc2-backup'|'vho10uc1-primary')
          var1=`ssh "$host" sudo /etc/init.d/apache2 status|awk '{print $4}'`
          var2="$( echo $var1 | cut -c 3-5 )"
            if [[ "$var2" == "$var3" ]]; then
          echo "Apache2 on $host is running"
          echo "0"
            else
          echo "Apache2 on $host is not running"
          echo "2"
          fi
          ;;
       *)
    esac
done