text:
Q: Text not fiting properly inside of div on smaller screen size I have a div with an image in it and next to it some text. I want the text to fit properly into the box, which works fine with my normal screen size. Unfortunatly the text overflows the box if I look at the webiste in 1280x720 (smaller screen size).
This is how my website look in 1440x2560
This is how it looks in 1280x720
This is the CSS:
.head-container {
    display: flex;
    flex-direction: row;
}

 .container {
    background-color: #F6E9DA;
    position: relative;
    top: 200px;
    left:50px;
    display: flex;
    height: 450px;
    width: 1200px;
    justify-content: center;
    align-items: center;
    border-radius: 15px;
    transition: 250ms;
    scale: 0.9;
}

.container2 {
    background-color: #F6E9DA;
    position: relative;
    top: 200px;
    display: flex;
    height: 450px;
    width: 1200px;
    justify-content: center;
    align-items: center;
    border-radius: 15px;
    transition: 250ms;
    scale: 0.9;
    margin-left: 100px;
}

 .description p {
    font-family: "Poppins";
    font-size: 16px;
    margin-right: 20px;
    color: #617569;
}

 .description h2 {
    font-family: "Poppins";
    font-size: 26px;
    text-decoration: underline;
    text-decoration-thickness: 2px;
    color: #617569;
 }

HTML:

Lorem Ipsum

Lorem ipsum dolor sit amet, consetetur sadipscing elitr,

                        sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                        aliquyam erat, sed diam voluptua.

                        At vero eos et accusam et justo duo dolores et ea rebum.

                        Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod

                        tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.

                        At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,

                        no sea takimata sanctus est Lorem ipsum dolor sit amet.

Lorem Ipsum

Lorem ipsum dolor sit amet, consetetur sadipscing elitr,

                        sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                        aliquyam erat, sed diam voluptua.

                        At vero eos et accusam et justo duo dolores et ea rebum.

                        Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod

                        tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.

                        At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,

                        no sea takimata sanctus est Lorem ipsum dolor sit amet.

I tried setting a fixed height for the div that the text is in but that didnt work. I'm looking for a solution which works universally on any screen size.

A: You have 2 possibilities:

*

*you let the box grow to fit the text

*you cut the text which overflow

*you decrease text size
...
or a combination of the 3 depending of media query values

For the third one you can use clamp(), see here:
https://developer.mozilla.org/en-US/docs/Web/CSS/clamp
You can combine 1 and 2.
So you can cut the text which overflow with text-overflow (take care of the browser option compatibilities), see here:
https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow
You add an event on the ellipsis (button?), to let the box increase

A: Fixed example in action: https://codepen.io/sudhxnva/pen/RwJVjde
You don't need to use relative positioning to set the containers to where you want them to be, plus you need to add your align-items and justify-content styles to the element you're setting flex to i.e your head container. So your CSS can look something like this:
.head-container {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

 .container {
    background-color: #F6E9DA;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 1200px;
    border-radius: 15px;
    transition: 250ms;
    scale: 0.9;
    padding: 40px;
}

 .description p {
    font-family: "Poppins";
    font-size: 16px;
    margin-right: 20px;
    color: #617569;
}

 .description h2 {
    font-family: "Poppins";
    font-size: 26px;
    text-decoration: underline;
    text-decoration-thickness: 2px;
    color: #617569;
 }

As you'll notice, I've removed the container2 class because you don't need it. They can share the same classes as they aren't being positioned relatively to the parent element anymore. Just set both containers to the container class and you should be good to go

A: *

*use overflow:auto so both container will auto scroll show when something is overflow .

.head-container {
    display: flex;
    flex-direction: row;
}

 .container {
    background-color: #F6E9DA;
    position: relative;
    top: 200px;
    left:50px;
    height: 450px;
    width: 1200px;
    justify-content: center;
    align-items: center;
    border-radius: 15px;
    transition: 250ms;
    scale: 0.9;
    overflow: auto;
    padding: 2%;
}

.container2 {
    background-color: #F6E9DA;
    position: relative;
    top: 200px;
    height: 450px;
    width: 1200px;
    justify-content: center;
    align-items: center;
    border-radius: 15px;
    transition: 250ms;
    scale: 0.9;
    margin-left: 100px;
    overflow: auto;
    padding: 2%;
}

.description p {
    font-family: "Poppins";
    font-size: 16px;
    margin-right: 20px;
    color: #617569;
}

 .description h2 {
    font-family: "Poppins";
    font-size: 26px;
    text-decoration: underline;
    text-decoration-thickness: 2px;
    color: #617569;
 }
<meta name="viewport" content="width=device-width, initial-scale=1">

test

Lorem ipsum dolor sit amet, consetetur sadipscing elitr,

          sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

          aliquyam erat, sed diam voluptua.

          At vero eos et accusam et justo duo dolores et ea rebum.

          Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

          Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod

          tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.

          At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,

          no sea takimata sanctus est Lorem ipsum dolor sit amet.

test

Lorem ipsum dolor sit amet, consetetur sadipscing elitr,

          sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

          aliquyam erat, sed diam voluptua.

          At vero eos et accusam et justo duo dolores et ea rebum.

          Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

          Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod

          tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.

          At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,

          no sea takimata sanctus est Lorem ipsum dolor sit amet.

*use @media css for container display:block when they are comes to small screen.

.head-container {
    display: flex;
    flex-direction: row;
}

 .container {
    background-color: #F6E9DA;
    position: relative;
    top: 200px;
    left:50px;
    height: 450px;
    width: 1200px;
    justify-content: center;
    align-items: center;
    border-radius: 15px;
    transition: 250ms;
    scale: 0.9;
    overflow: auto;
    padding: 2%;
}

.container2 {
    background-color: #F6E9DA;
    position: relative;
    top: 200px;
    height: 450px;
    width: 1200px;
    justify-content: center;
    align-items: center;
    border-radius: 15px;
    transition: 250ms;
    scale: 0.9;
    margin-left: 100px;
    overflow: auto;
    padding: 2%;
}

.description p {
    font-family: "Poppins";
    font-size: 16px;
    margin-right: 20px;
    color: #617569;
}

 .description h2 {
    font-family: "Poppins";
    font-size: 26px;
    text-decoration: underline;
    text-decoration-thickness: 2px;
    color: #617569;
 }

 @media screen and (max-width:1200px)
 {
  .head-container {
    display: block;
  }
  .container
  {
    width:80vw;
  }
  .container2
  {
    width: 80vw;
    margin-left: 50px;
  }
 }
<meta name="viewport" content="width=device-width, initial-scale=1">

test

Lorem ipsum dolor sit amet, consetetur sadipscing elitr,

          sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

          aliquyam erat, sed diam voluptua.

          At vero eos et accusam et justo duo dolores et ea rebum.

          Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

          Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod

          tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.

          At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,

          no sea takimata sanctus est Lorem ipsum dolor sit amet.

test

Lorem ipsum dolor sit amet, consetetur sadipscing elitr,

          sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

          aliquyam erat, sed diam voluptua.

          At vero eos et accusam et justo duo dolores et ea rebum.

          Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

          Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod

          tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.

          At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,

          no sea takimata sanctus est Lorem ipsum dolor sit amet.

comment if any query


text:
Q: terminfo disable XON/XOFF I can disable XON/XOFF flow control:
stty -ixon

So I put this in my "~/.profile". However I have started making my own terminal
with "terminfo" and "tic", and I noticed these options:
xon_xoff          xon       xo     terminal uses xon/xoff handshaking

exit_xon_mode     rmxon     RX     turn off xon/xoff handshaking

xon_character     xonc      XN     XON character

Could I compile my terminal with some of these options and avoid having to put
the "stty" command in my startup file?

A: short: no
long:
terminfo describes the features of a terminal.  Those particular capabilities likely were added to AT&T's list of possible terminal capabilities in the late 1980s to describe some long-forgotten terminal that didn't use ^S and ^Q.
curses in general (ncurses specifically) doesn't pay any attention to these features (because no one uses them).  stty doesn't pay any attention for a different reason: it ignores the terminal database, being essentially a platform-dependent program with hard-coded knowledge to fill in the cases where a default initial value is needed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does "...crickity" mean? Good morning guys,
What does crickity mean? I was reading a basic English book for my little song and the phrase "crickity" showed up. I looked it up in the dictionary but could not find it. You can find this part of the book following this link.
Thanks

A: Your question says we can find "this part of the book" in the link your provide. I don't find crickity, so I am answering about the word clickity, which is what I think you are referring to.
The opening line of the story includes the compound word clickity clack.

Splat's bike went clickity clack.

The word is usually spelt 'clickety-clack'. But since the word refers to a sound, there are variations in spelling. Dictionary dot com provides this definition:

[the] rhythmic, swiftly paced succession of alternating clicks and clacks, as the sound produced by the wheels of a train moving over tracks

In the story, clickity clack refers to the sound of the bike's wheels as the bike goes over "the bumpy track." The word can also refer to the sound of one or more typewriters.
The word can be spelled different ways, including 'clickety clack' and 'clickity click'. All these are examples of onomatopoeia, or a word that sounds like what it means. A computer mouse button and the shutter of an SLR camera make a click when you press them. Other examples of words that sound like what they mean from the opening pages of the story include Splat, whack, smack and, later, quack.
Video of the story being read to a kid: Splat the Cat and the Duck with No Quack.
Another way to get a clickity click noise from bike wheels is to attach playing cards to the bike frame so that the spokes of the wheels hit the card. But this makes a much faster clickity noise then does the sound of the wheels on a bumpy track. For example, see this youtube video. This is not what is happening in the story, but it is something  that kids do.
Hope this is helpful!


text:
Q: JavaScript file not reloading in browser when modified on server So I have this ASP.Net 2.0 website that uses functions contained within a JS file. When a webpage loads the js file loads fine. But when I change something in that file on the server the changes are not propagated to user's browser. It keeps working according to the out dated file. How can I force the browser to reload the modified file from the server?

A: One rather common solution (that is also used here at SO I think) is to add a query string to the url of the javascript file, containing a version number. When you change the query string, the browser will treat it as a new file and download it rather than picking it from the cache.
<script type="text/javascript" src="http://example.com/file.js?v=2"></script>

In the above example, changing file.js?v=2 to file.js?v=3 would force the browser to download the file, instead of loading the cached file.js?v=2.

A: In general, the quickest way to force update is to press CTRL+F5 in the browser.
Otherwise you need to empty the browser's cache.
If you are using Firefox I'd recommend the plugin Web Developer Toolbar, where you easily can just click "Misc -> Clear Private Data -> Cache".


text:
Q: In angular2 I only want to add the addthis plugin to a specific route e.g. my /blog url but when I add a the script library it doesnt work In Angular2 I only want to add the addthis plugin to a specific route e.g. my /blog url but when I add a the script library it doesn't work.
It only seems to work on the index.html and not on a specific view like blog.html

A: Here you go:
I implemented it for my use case following ng-addthis but adding a few extra checks for Angular SSR.
/**
 * https://stackoverflow.com/questions/35538552/in-angular2-i-only-want-to-add-the-addthis-plugin-to-a-specific-route-e-g-my-b
 * Reinitiate add this.
 */

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';

@Injectable()
export class AddThisService {
    constructor(){}
    private removeScript(){
        let element     = null;
        let divElements = null;
        let divElement  = null;

        element = document.getElementById('addthis-js');
        if (element) {
            element.parentNode.removeChild(element);
        }

        divElement = document.getElementById('_atssh');
        if (divElement) {
            divElement.style.display = "none";
        }

        divElements = document.getElementsByClassName('addthis-smartlayers');
        while (divElements.length > 0) {
            divElements[0].parentNode.removeChild(divElements[0]);
        }

        divElements = document.getElementsByClassName('addthis-smartlayers-desktop');
        while (divElements.length > 0) {
            divElements[0].parentNode.removeChild(divElements[0]);
        }

        divElements = document.getElementsByClassName('addthis-smartlayers-mobile');
        while (divElements.length > 0) {
            divElements[0].parentNode.removeChild(divElements[0]);
        }

        return true;
    }
    showLayers() {
        var divElements = null;
        var divElement  = null;
        console.log('what here..');

        divElement = document.getElementById('_atssh');
        if (divElement) {
            divElement.style.display = "block";
        }

        divElements = document.getElementsByClassName('addthis-smartlayers');
        for (var i = 0; i < divElements.length; i++) {
            divElements[0].style.display = "block";
        }

        divElements = document.getElementsByClassName('addthis-smartlayers-desktop');
        for (var i = 0; i < divElements.length; i++) {
            divElements[0].style.display = "block";
        }

        divElements = document.getElementsByClassName('addthis-smartlayers-mobile');
        for (var i = 0; i < divElements.length; i++) {
            divElements[0].style.display = "block";
        }

        return true;
    }

    hideLayers () {
            var divElements = null;
            var divElement  = null;

            divElement = document.getElementById('_atssh');
            if (divElement) {
                divElement.style.display = "none";
            }

            divElements = document.getElementsByClassName('addthis-smartlayers');
            for (var i = 0; i < divElements.length; i++) {
                divElements[0].style.display = "none";
            }

            divElements = document.getElementsByClassName('addthis-smartlayers-desktop');
            for (var i = 0; i < divElements.length; i++) {
                divElements[0].style.display = "none";
            }

            divElements = document.getElementsByClassName('addthis-smartlayers-mobile');
            for (var i = 0; i < divElements.length; i++) {
                divElements[0].style.display = "none";
            }

        return true;
    }

    private loadProject(key: string, hideLayers:boolean) {
        return Observable.create((observer: Subscriber<any>) => {
            switch (true) {
                case (!document || !window):
                /**
                 * For Angular Universal
                 */
                    observer.error('Cannot render it on Server');
                    observer.complete();
                case ((document.getElementById('addthis-js') != null)):

                    if (hideLayers) {
                        this.hideLayers();
                    } else {
                        this.showLayers();
                    }
                    if ((<any>window).addthis.layers && (<any>window).addthis.layers.refresh) {
                        (<any>window).addthis.layers.refresh();
                    }
                    observer.next(true);
                    observer.complete();
                    break;

                case (!key):
                    observer.error('no-project');
                    observer.complete();
                    break;

                default :
                    var script    = document.createElement('script');
                    script.type   = 'text/javascript';
                    script.id     = 'addthis-js';
                    script.async  = true;
                    script.src    = 'https://s7.addthis.com/js/300/addthis_widget.js#pubid=' + key;
                    script.onload = (ev: Event) =>{
                        if (hideLayers) {
                            this.hideLayers();
                        } else {
                            this.showLayers();
                        }
                        (<any>window).addthis.init();
                        observer.next(true);
                        observer.complete();
                    };

                    var first = document.getElementsByTagName('script')[0];
                    first.parentNode.insertBefore(script, first);
            }
        });
    }
    /**
     *
     * @param accountKey eg. ra-13245612346
     * @param hideLayers eg. true for hiding in a particular state and true for showing in another.
     */
    initAddThis(accountKey:string, hideLayers:boolean):Observable<any> {
        return this.loadProject(accountKey, hideLayers);
    };
}

Then inject the service in your providers section of the main module and use it in ngAfterViewInit hook, like below:
ngAfterViewInit() {
    //Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
    //Add 'implements AfterViewInit' to the class.
    this._addThis.initAddThis('ra-123456asdf', false).subscribe();
}

You can also use isPlatformBrowser method for checking platform before calling initAddThis method if you are using Angular Universal.


text:
Q: How to find reports for sobject via soql? I have 300 reports in my organization, and i want to see reports for sobject say xyz__c.
I tried to retrieve it using soql but there is no relationship between sObject and Report.
Any pointers/suggestions would greatly appreciated.

A: As far as I know it can't be done with SOQL.
You probably could try with Analytics API but it has some limitations.
The "old school" way would be to download all report types and report definitions to Eclipse IDE (or with any other tool of your choice). If you'd have > 5,000  reports the retrieval would have to be split into chunks - for example fetch few folders at a time.
Report definitions will be shown as XML files (sample is at the bottom of Metadata API page for Report object).
You'll then be able to run text searches on the XML files (Ctrl+H in Eclipse but you could also use Windows "Find in files" or anything really). Search for your custom object's API name (Xyz__ - ideally without the c at the end because you might see Xyz__r sometimes).
Personally I like Notepad++ "find in files" - easy to select the search results and paste to text file or Excel...
If that's too much work - go to the object's definition, clear the "allow reports" checkbox and soon your users will tell you which reports are related to that object ;)


text:
Q: Where and AutoGenerateWhere in EntityDataSource I keep getting this error and I think it's a Bug but I would like your opinions.
WhereParameters cannot be specified unless AutoGenerateWhere==true or Where is specified.
this is my entitydatasource control.
<asp:EntityDataSource ID="MtrlEntityDataSource" runat="server"
    ConnectionString="name=AitisiEntities" DefaultContainerName="AitisiEntities"
    EnableDelete="True" EnableFlattening="False" EnableInsert="True" Select="" AutoGenerateWhereClause="false"
    EnableUpdate="True" EntitySetName="MTRL" Where="it.SODTYPE = @sodTypeParam">
    <WhereParameters>
        <asp:Parameter DbType="Int32" DefaultValue="51" Name="@sodTypeParam" />
    </WhereParameters>
</asp:EntityDataSource>

Now do you see something wrong here? Tried in some projects and always keep failing.
Thank you.

A: Problem was so typical...long time to use parameters...
Name="@sodTypeParam"

should be...
Name="sodTypeParam"

For anyone looking for something similar and his mind is full....


text:
Q: Persist BLE connection and access service after closing app I am working on app with BLE device. All is working fine except the fact that I have problems maintaining the BLE connection after app closure.
I am using Bind Service + Start sticky with foreground service and notification. When I open the app, I call bindService().
The problem is that if I don't call disconnect() and gatt.close(), the second time I open the app, I cannot access the BLE device because of onAutoConnectionStatusCb()status =10
Since I have the service already running, I don't need to call bindService() again but in this case I no longer have instance of the service hence my BroadcastReceivers are not called.
How do I get around this?
This is how I start my service:
private final Runnable mStartGattRunnable = new Runnable() {
    @Override
    public void run() {
        Intent gattServiceIntent = new Intent(mContext, BluetoothLeService.class);
        gattServiceIntent.putExtra(Consts.DEVICE_ADDRESS, mDeviceAddress);
        gattServiceIntent.setAction(Consts.STARTFOREGROUND_ACTION);

        mContext.startService(gattServiceIntent);

        if (mContext.bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE))
            CONNECTED = true;
    }
};

This is how I get my service instance:
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder service) {
        Log.d(TAG, "onServiceConnected()");
        mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
        if (!mBluetoothLeService.initialize()) {
            Log.e(TAG, "Unable to initialize Bluetooth");

        }
        // Automatically connects to the device upon successful start-up initialization.
        mBluetoothLeService.connect(mDeviceAddress);

        swipeContainer.setRefreshing(true);
    }

When I close my app, I don't disconnect or close any connection.
On a second start of the app, if I call bindService() again, BLE gets stuck. No way I can access mBluetoothLeService again ...

A: Apparently the issue was with how I was connection to GATT service. I had false for auto connect. I changed it and it works now:
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        mBluetoothGatt = device.connectGatt(this, true, mGattCallback, 2);
    else
        mBluetoothGatt = device.connectGatt(this, true, mGattCallback);


text:
Q: $S$ and $T$ are two sets. Prove that if $|S-T|=|T-S|$, then $|S|=|T|$. Here is the problem that I am currently working on:
$S$ and $T$ are two sets. Prove that if $|S-T|=|T-S|$, then $|S|=|T|$.
I have access to the answer for this proof, and wanted help with the first assumption. Here is the answer I have been given to the proof:

Since $|S-T|=|T-S|$, there exists a bijective function $g\colon S-T\to T-S$. Let $i\colon S\cap T\to S\cap T$ be the identity function on $S\cap T$.
Then we know that the function $f\colon S\to T$ defined by
  $$
f(x)=
\begin{cases}
g(x) &\text{if $x\in S-T$}\\
i(x) &\text{if $x\in S\cap T$}
\end{cases}
$$
  is bijective. Now using the fact of cardinality $\Rightarrow |S|=|T|$.

My first question is: how would I have known to make the leap into assuming that a bijective function exists? Would I need to consider that I am performing an operation on two sets, and that since I have that equal to another set (with operations), that I can allow this to exist as a bijective function? Or should I come to this assumption because I am showing that the cardinalities of two different groups of sets are the same, meaning that I am trying to show numerical equivalence (which requires a bijective function)?
Assuming that I need the bijection to show numerical eq., my next question is regarding the identity function step. I'm not sure where or why we jump to that assumption...
Thanks. I am studying for my final in proofs on Wednesday, and while I have a pretty good piecemeal understanding of each topic we've learned, I sometimes have a hard time piecing together multiple proof topic\techniques.

A: \begin{align}
|S| & = |S-T| + |S\cap T| \\[8pt]
|T| & = |T-S| + |S\cap T|
\end{align}
If $|S-T|=|T-S|$, then the two right sides are the same, so the two left sides are the same.
We can also write a proof explicitly dealing with bijections.
You ask why one would "assume" a bijection exists.  The bijection $g$ that you write about is not simply "assumed" to exist.  Rather, you have $|S-T|=|T-S|$ and equality of cardinalities by definition means there is a bijection.
You need a bijection from $S$ to $T$.  You have a bijection $g$ from part of $S$ to part of $T$.  The other part of $S$ is the same as the other part of $T$: it is $S\cap T$.  You need a bijection from that set to itself.  The simplest bijection from a set to itself is the identity.
You can split the union of two sets into three parts:
$$
\begin{array}{cccccccccccc}
& \underbrace{a \quad b \quad c}_{S\,-\,T} \qquad \underbrace{p \quad q \quad r \quad s}_{S\,\cap\, T} \qquad \underbrace{x \quad y \quad z}_{T\,-\,S} \\[10pt]
\text{or two parts, thus:} & \underbrace{a \quad b \quad c \qquad p \quad q \quad r \quad s}_S \qquad \underbrace{x \quad y \quad z}_{T\,-\,S} \\[10pt]
\text{or two parts, thus:} & \underbrace{a \quad b \quad c}_{S\,-\,T} \qquad \underbrace{p \quad q \quad r \quad s \qquad x \quad y \quad z}_T
\end{array}
$$
Here's a bijection:
$$
\begin{array}{cccccccccccc}
S: & & a & b & c & \qquad & p & q & r & s \\
& & \updownarrow & \updownarrow & \updownarrow & & \updownarrow & \updownarrow & \updownarrow & \updownarrow &  \\
T: & \quad & x & y & z & \qquad & p & q & r & s
\end{array}
$$
The last four arrows are the identity function on $S\cap T$.  The first three are the bijection between $S-T$ and $T-S$ that must exist because $|S-T|=|T-S|$.

A: The big key to this realization is that
 $$(S\setminus T)\cup (S\cap T)=S$$
$$(S\setminus T)\cap (S\cap T)=\emptyset$$

A: Hint. So we have $|S-T| = |T-S|$.
Then there is a bijection $g: (S-T) \to (T-S)$.
The identity function on $S \cap T$, which I denote $i_{S \cap T}$, is a bijection [I leave this as an exercise].
Define $f: S \to T$ by $$f(s) = \begin{cases}
i_{S \cap T}(s), & s \in S \cap T \\
g(s), & s \notin S - T\text{.}
\end{cases}$$
Note that $f$ is indeed a bijection $S \to T$, since $(S \cap T) \cup (S-T) = S$ is a union of the disjoint sets $S \cap T$ and $S - T$ and when restricted to both of these disjoint sets, it is a bijection.
Edit. In case you're new to this idea of showing that the piecewise function $f: S \to T$ defined by $$f(s) = \begin{cases}
i_{S \cap T}(s), & s \in S \cap T \\
g(s), & s \notin S - T\text{.}
\end{cases}$$
is a bijection, split it into cases.
Injectivity. Suppose $f(s_1) = f(s_2)$, $s_1, s_2 \in S$.
Without loss of generality, suppose $s_1 \in S \cap T$ and $s_2 \in S - T$. Then $f(s_1) = i_{S \cap T}(s_1) \in S \cap T$ and $f(s_2) = g(s_2) \in S - T$ since $i_{S \cap T}$ and $g$ are bijections on $S \cap T$ and $S-T$ respectively. But $S \cap T$ and $S-T$ are disjoint (and hence $f(s_1) \neq f(s_2)$ since $f(s_1)$ and $f(s_2)$ are of disjoint sets, a contradiction).
Hence $s_1$ and $s_2$ must be both of either $S \cap T$ and $S-T$. If both of them are of $S \cap T$, we then have $s_1 = s_2$. If they are both of $S-T$, we then have $g(s_1) = g(s_2)$. But $g$ is a bijection, hence injective. So $s_1 = s_2$ and $f$ is an injection.
I leave proof of $f$ being surjective to you.

A: Two sets have the same cardinality if and only if there exists a bijection between them, so the first step follows from definition.
Given this definition, since the question asks you to show that $S$ and $T$ have the same cardinality, you know that your goal is to find a bijection between $S$ and $T$ (this bijection is $f$).
The reason for using the inclusion function $i$ in the definition of $f$ is that the domain of $g$ is the set $S\setminus T$, so $g$ doesn't know where to send the elements in in $S\cap T$. (As Thomas Andrews noted, $S = (S \cap T) \cup (S \setminus T)$, so this proof defines a bijection on all of $S$ by defining bijections on its disjoint components)
A good way to understand this proof would be to check that $f$ is a bijection.

*

*For surjectivity, let $t$ be an element of $T$. Can you find an element of $S$ that gets mapped to $T$? (Hint: this depends on whether $t$ is also an element of $S$, so you'll have to look at two different cases.)

*For injectivity, suppose $f(t_1)=f(t_2)$. What does that tell you about $t_1$ and $t_2$? Is it possible for one to be in $S\setminus T$ while the other one is in $S\cap T$?


text:
Q: Can two request be mapped to a single stateless EJB instance concurrently Can two request be mapped to a single stateless EJB instance concurrently?
Or must the container map the requests to different instances or serialize the requests?
The EJB 3.1 specification states:

This means, for example, that [...] the
  container may interleave requests from multiple transactions to the same instance.

Which sounds like concurrency would be allowed..

A: Requests to stateful and stateless session beans must be serialized by the container.
This is from Section 4.3.14 of the EJB 3.1 specification:

The container serializes calls to each stateful and stateless session bean instance. Most containers will
  support many instances of a session bean executing concurrently; however, each instance sees only a
  serialized sequence of method calls. Therefore, a stateful or stateless session bean does not have to be
  coded as reentrant.


text:
Q: Is it possible to extract a UUID from a response in Jmeter so I can use for a subsequent request My Scenario:

*

*I am doing a POSt request that generates a rateID( UUID)

*Doing another POST request that uses this rateID

*I am also using 2 other fields in the body that is getting extracted by JSON Extractor but somehow this rateID is just getting passed as is

Sample Response body from 1st POST request
{
        "source": "USD",
        "target": "MXN",
        "RateId": "0f4a78a2d2b34849882f0154b9249345",
        "exchangeRate": 21.3909440000,
        "rateExpiry": "2020-09-14 20:30:20",
        "providerId": 2,
        "providerNm": "ZIGA-STATIC",
        "rawRate": 21.3376000000,
        "markupValue": 0.00250
 }

Sample request body from 2nd POST request
[{

  "source":"${source}",
  "target":"${target}",
  "RateId":"${RateId}",
  "buyAmount":100,
  "transactionSettlementDate":"2020-07-28",
  "transactionId":"${GUID}",
  "transactionTimestamp":"2020-07-28T17:35:17.866Z"

}]

Getting error
{"errorMessages":["Transaction #0: [invalid RateId ${RateId}]"]}

IS it not possible to use UUID like that?? I even tried using a Regex for extracting UUID
([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}) but still no luck
Asking help from Jmeter experts in the community, please help

A: From what you show, it looks like extraction of the 4 fields did not work.
You need to add to the first HTTP request 3 JSON extractors:
First one with for source variable with json path expression :

Second for target variable :

Last one for RateId

For Guid, it's not clear if it's just the value of RateId (why did you create a variable Guid and not just used ${RateId} and how is it filled in this case ?).
If it's just a random uuid, you can use function UUID:

${__UUID()}

Otherwise clarify where it comes from.
See:

*

*https://jmeter.apache.org/usermanual/functions.html#__UUID

A: You can extract 3 values in a single shot using JSR223 PostProcessor and the following Groovy code:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())

vars.put('source', response.source)
vars.put('target', response.target)
vars.put('RateId', response.RateId)

Demo:

More information:

*

*JsonSlurper

*Apache Groovy - Parsing and producing JSON

*Apache Groovy - Why and How You Should Use It


text:
Q: In a Rails helper method, is it possible to specify a column name as a helper method variable and then use it? I want to create a helper method that can turn the results of a Rails find into a sentence, where I specify the the results, and the column to use for making the sentence. For example:
  def items_to_sentence(items, label_column)
    items.map { |u| u.(label_column) }.to_sentence
  end

I'm just not sure how to tell Rails to use my specified column.
Thanks for looking.

A: If items contains ActiveRecord objects (or any other objects that have accessor methods that match up with your column names), then you could use send:
def items_to_sentence(items, label_column)
  items.map { |u| u.send(label_column) }.to_sentence
end

Or equivalently:
def items_to_sentence(items, label_column)
  items.map(&(label_column.to_sym)).to_sentence
end

Or, if that's too noisy:
def items_to_sentence(items, label_column)
  sym = label_column.to_sym
  items.map(&sym).to_sentence
end


text:
Q: Display data at index between two models or more in rails Currently, I have two tables countries and users
schema for countries something like this,

*

*id

*country_code

*name

and for users table,

*

*id

*name

*born_country_id

*live_at_country_id

so for users/index.html.erb instead showing born_at_id or live_at_id that I've got from country table id, I wanna show the name for that country.
I have try and search quite lot articles regarding this matter, but none of it works for me.
For my table do I need to put references during migrations for users table or is it enough just using has_one, many and belongs_to and how to display the data in index.

A: Add following associations in you models,
user.rb
class User < ActiveRecord::Base
  belongs_to :born_country, foreign_key: :born_country_id, class_name: 'Country'
  belongs_to :live_at_country, foreign_key: :live_at_country_id, class_name: 'Country'

  delegate :name, to: :born_country, prefix: true
  delegate :name, to: :lived_at_country, prefix: true
end

country.rb
class Country < ActiveRecord::Base
  has_many :born_users, foreign_key: :born_country_id, class_name: 'User'
  has_many :live_at_users, foreign_key: :live_at_country_id, class_name: 'User'
end

You can check it in below manner,
@users = User.includes(:born_country, :lived_at_country).each do |user|
  puts user.born_at_country_name
  puts user.lived_at_country_name
end


text:
Q: Why ZonedDateTime.now() throws NoSuchMethodException while running test cases(using mockito) Lately I am writing junit test cases and I came across ZonedDateTime.now() works partially expected where the method which we try to write test case uses DozerBeanMapper for copying common fields. Please go through below to have better understanding btw I am using @Spy for DozerBeanMapper not @Mock because @Mock provides me dummy Object which troubles while I assert at the end.
class A {
  @Autowired
  DozerBeanMapper mapper;

  Entity method(Request req) {

      Entity ent = new Entity();

      req.setCreatedOn(ZonedDateTime.now());
      dozerMapper.map(req,ent);

      return ent;

  }
}

Throws exception for above code :
org.dozer.MappingException: java.lang.NoSuchMethodException: java.time.LocalDateTime.<init>()
at org.dozer.util.MappingUtils.throwMappingException(MappingUtils.java:82) ~[dozer-5.4.0.jar:na]
at org.dozer.factory.ConstructionStrategies$ByConstructor.newInstance(ConstructionStrategies.java:261) ~[dozer-5.4.0.jar:na]
at org.dozer.factory.ConstructionStrategies$ByConstructor.create(ConstructionStrategies.java:245) ~[dozer-5.4.0.jar:na]
at org.dozer.factory.DestBeanCreator.create(DestBeanCreator.java:65) ~[dozer-5.4.0.jar:na]
at org.dozer.MappingProcessor.mapCustomObject(MappingProcessor.java:489) [dozer-5.4.0.jar:na]
at org.dozer.MappingProcessor.mapOrRecurseObject(MappingProcessor.java:446) [dozer-5.4.0.jar:na]
at org.dozer.MappingProcessor.mapFromFieldMap(MappingProcessor.java:342) [dozer-5.4.0.jar:na]
at org.dozer.MappingProcessor.mapField(MappingProcessor.java:288) [dozer-5.4.0.jar:na]

But It works absolute fine when I alter and add setCreatedOn after dozerMapper maps like below and I know this one is the correct way.
Class A {
    @Autowired
    DozerBeanMapper mapper;

    Entity method(Request req){

      Entity ent = new Entity();

      dozerMapper.map(req,ent);
      ent.setCreatedOn(ZonedDateTime.now());

      return ent;
  }
}

My whole point is why it does not work for first method code?
Here is the sudo test method
Class ATest {
    @InjectMocks
    A aService;

    @Spy
    DozerBeanMapper mapper;

    @Test
    void methodTest(){
      aService.method(req);
  }
}

I want an brief explanation why first code does not work?

A: Because dozer is attempting to create an instance of ZonedDateTime without knowing how, so it applies the usual strategy:

*

*Call the no-args constructor, find set methods to invoke.

*Call the no-args constructor, set the fields directly.

*Find a constructor that takes 1 of each arg in turn.

And ZonedDateTime has none of those - the 'formula' to make one is to call .of(...) or now() or parse(...) - hence, failure.
That exception means: "I tried to invoke new ZonedDateTime() but this did not work, as that constructor does not exist". At the bytecode/JVM level, constructors are, effectively, public static OwnType <init>(args) {} - they are 'methods' whose name is <init>. Hence, java.lang.NoSuchMethodException: java.time.LocalDateTime.<init>().
This is thrown by dozer's mapper infrastructure: It is trying to take some data from some source and 'map that' into an instance of ZonedDateTime.
Check the dozer documentation on how to provide to provide it the functions it needs to do this mapping. Perhaps this gist is what you need.


text:
Q: List all reports that use my report as sub report in SSRS 2012 I have a SSRS 2012 report server. I am trying to list all reports that use MyReport as a subreport. Following query gives me result.
USE ReportServer
GO

SELECT Path, CONVERT(XML, CONVERT(VARBINARY(MAX), Content))
FROM Catalog
WHERE Type=2
AND CONVERT(VARBINARY(MAX), Content) LIKE '%MyReport%'

Is there a better standard way for SSRS 2012 like the one mentioned in Subreport Usage for SSRS 2008?
Note: The SSRS 2008 approach didn't work for me in SSRS 2012

A: I just tried the SSRS2008 approach and it worked for me. It is the exact same code except I reference a different report server database.


text:
Q: import from "library" vs "library/part" This might have been asked before, but I don't know exactly what to search for.
Is there any differences/benefits to use either?
import { myModule } from "myLibrary";

or
import { myModule } from "myLibrary/myLibraryPart";

And when typescript compiles code, does it include entire library or only the parts of the library that's being used?

A: Module loading is a little bit tricky and can be configured through your config file.
You can find more about how typescript loads modules here: https://www.typescriptlang.org/docs/handbook/modules.html#import-a-module-for-side-effects-only
And here: https://www.typescriptlang.org/docs/handbook/module-resolution.html
Basically the compiler depending on your configuration will walk up looking for your module to import.


text:
Q: Sencha Touch : invalid item defined Here I am trying to add a simple toolbar with an embedded button and following these is a list of some items. I want this list to get sorted once i click on sort button.

The following is the view code :

Ext.define('UtilApp.view.Main', {
    extend: 'Ext.Container',
    xtype: 'main',

 initialize: function(){
  this.callParent(arguments);
  var Arr = new Array("Banana", "Apple", "Orange", "Peach", "Guava", "Pine", "Dates");
  var sortButton = {
   xtype: 'button',
   text: 'sort',
   handler: this.sorter(Arr)
  };

  var toolbar = {
   xtype: 'toolbar',
   title: Ext.Date.DAY,
   docked: 'top',
   items : [sortButton]
  };

  var list = Ext.create('Ext.List', {
   fullscreen: true,
   itemTpl: '{title}',
   data: [
   {title: Arr[0]},
   {title: Arr[1]},
   {title: Arr[2]},
   {title: Arr[3]},
   {title: Arr[4]},
   {title: Arr[5]},
   {title: Arr[6]}
   ]
  });

  console.log("List Created!");

  this.add([toolbar, list]);
 },

 sorter: function(Arr, toolbar, list){
  console.log("Starting sort");
  var sortedArray = Ext.Array.sort(Arr);
  console.log(sortedArray);
  console.log("Sorted");
  this.add([this.toolbar, this.list]);
  console.log("added");
 }
});

extend: 'Ext.Container',
xtype: 'main',

initialize: function(){
    this.callParent(arguments);
    var Arr = new Array("Banana", "Apple", "Orange", "Peach", "Guava", "Pine", "Dates");
    var sortButton = {
        xtype: 'button',
        text: 'sort',
        handler: this.sorter(Arr)
    };

    var toolbar = {
        xtype: 'toolbar',
        title: Ext.Date.DAY,
        docked: 'top',
        items : [sortButton]
    };

    var list = Ext.create('Ext.List', {
        fullscreen: true,
        itemTpl: '{title}',
        data: [
        {title: Arr[0]},
        {title: Arr[1]},
        {title: Arr[2]},
        {title: Arr[3]},
        {title: Arr[4]},
        {title: Arr[5]},
        {title: Arr[6]}
        ]
    });

    console.log("List Created!");

    this.add([toolbar, list]);
},

sorter: function(Arr, toolbar, list){
    console.log("Starting sort");
    var sortedArray = Ext.Array.sort(Arr);
    console.log(sortedArray);
    console.log("Sorted");
    this.add([this.toolbar, this.list]);
    console.log("added");
}

});

I am getting an error as follows :

Uncaught Error: [ERROR][Ext.Container#add] Invalid item given: undefined, must be either the config object to factory a new item, or an existing component instance

The list is not appearing in the screen if i remove this handler.
I could not figure out what the error means as I am new to sencha touch and also Ext.js . Please help.

A: First of all the way that i am defining a handler for the button is wrong. It is actually making a call to the sorter function. So the proper handler definition should be as follows :
handler: this.sorter.bind(this, Arr, true)

This way the sorter function is defined for the button handler and also we can pass parameters to the function.
The second and major problem with this code is that i cannot write js code inside the value for a config property as i've done for the xtype toolbar. So the value for the title should be either replaced by a string or it can be updated using a setter function.


text:
Q: function from a module not imported in python Good evenning guys,
I ve got that weird behavior. Any help would be appreciated.
Here is a function from a module called tankython, calling a function from a module called usual. However, it looks like Python refuses to recognize the function. Here is the code
#tankython.py

from usual import *
from get_data import *
from settings import *
from actif_class import *

def tanking(list_spreads,settings):
####    Tanking    ####
    fenetre = settings.fenetre
    list_spread_exit,list_spread_temp= [],[]

    ii= 0
    for spread in list_spreads :
        avc = ii * 100/float(len(list_spreads))
        print "Be patient. Tanking in progress..." , avc,"%"
        info = tankython (list_spreads,fenetre,ii)
        list_spread_temp.append(info)
        ii = ii + 1
    list_spread_exit = check_list(list_spread_temp)

    return list_spread_exit

#usual.py

def check_list(list_entry):
    i = 0
    while i < len(list_entry):
        if list_entry[i] == 0 :
            list_entry.pop(i)
        else :
            i = i+ 1
    return list_entry

Here is the error message which I found really weird as I asked Py to import everything from usual.py:
File "tankython.py", line 77, in tanking
  list_spread_exit = check_list(list_spread_temp)

NameError: global name 'check_list' is not defined

One last thing: eventually, if I put the function in tankython module, then Py accepts to goes through the entire process. However I really would like to know if there is anything I am doing wrong here.
Cheers guys

A: Try to put file tankython.py and usual.py in the same folder and use the
from usual import check_list

instead of
from usual import *

May help.
Or you can try:
import usual

Then change code like:
usual.check_list()

And
from module import *

is not a good way to import something if two packages have the same name functions.

A: I find another solution, although it is not the most elegan one, especially because it did not explain what went wrong. However, I renamed the entire module usual by f_usual and it is working perfectly fine.
Thanks for your help


text:
Q: Error from server (BadRequest): container "mariadb" in pod is waiting to start: CreateContainerConfigError This Helm chart (https://github.com/helm/charts/tree/master/stable/wordpress ) should install WordPress on Kubernetes with:
helm install stable/wordpress
However, I get:
kubectl get pods
NAME                             READY   STATUS                       RESTARTS   AGE
wp-1-mariadb-0                   0/1     CreateContainerConfigError   0          30m
wp-1-wordpress-7bff96d46-4bss6   0/1     CrashLoopBackOff             8          30m

and
k logs wp-1-mariadb-0
Error from server (BadRequest): container "mariadb" in pod "wp-1-mariadb-0" is waiting to start: CreateContainerConfigError

and
kubectl describe pod wp-1-mariadb-0
Normal   Pulled                 5s (x5 over 48s)  kubelet, minikube  Container image "docker.io/bitnami/mariadb:10.1.36-debian-9" already present on machine
Warning  Failed                 5s (x5 over 48s)  kubelet, minikube  Error: failed to prepare subPath for volumeMount "config" of container "mariadb"

Any suggestions what the problem might be?


text:
Q: The "ValidateAppxPackage" task failed unexpectedly While creating my export for Windows Store I am having this issue.
Simple export works fine but when I try to create a build for windows store I am having this error:
The "ValidateAppxPackage" task failed unexpectedly.
System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Build.AppxPackage.ValidateAppxPackage.<>c.<CheckThatLanguagesAreSupported>b__85_0(XElement resource)
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
   at Microsoft.Build.AppxPackage.ValidateAppxPackage.CheckThatLanguagesAreSupported()
   at Microsoft.Build.AppxPackage.ValidateAppxPackage.ExecuteImplementation()
   at Microsoft.Build.AppxPackage.AppxPackagingTaskHelper.Execute()
   at Microsoft.Build.AppxPackage.ValidateAppxPackage.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() SeedRateCalculator

I don't know what to do. I am using VS 2015 and creating build of my Universal Windows App.

A: On msdn some people solved the problem in this way:

*

*I fixed the problem by deleting the StoreAssociation file, making it
rebuild it. Thanks!

*I decided to move the app folder to another location, and ran Visual
Studio in admin mode (with admin privileges) and it started working
Let me know!

A: I normally delete my obj and bin folder before try to pack things up, I used to run into all sorts of trouble, also do a "Clean solution" just for good measure (Right click solution => Clean solution).
If the problem still persists then delete the Package.StoreAssociation.xml and [your_app_name]_StoreKey.pfx then associate with store again (Right click on project => Store => Associate ...) and then try to package it.
Should be straight forward.

A: I'm getting the same problem on an App that has been in the store for years, I just fixed a bug, built new packages, run verification on VS2017 and I get this on the Bytecode generation tests, and so all subsequent tests also fail.  So I deleted Package.StoreAssociation.xml and tried to re-associate the app with the store, but when I did that it did not create a new Package.StoreAssociation.xml.  So I had to restore the old Package.StoreAssociation.xml, then re-associate the app with the store, and I see a bunch of updates, so clearly this needs to happen - seems broken that this didn't happen automatically when I created my store packages the first time.  But this also didn't solve the problem, I still get this when trying to verify the app:
Bytecode generation

Error Found: The bytecode generation test detected the following errors:
System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.Windows.SoftwareLogo.Tests.Utility.IsPackageWWA(AppXPackage package) at Microsoft.Windows.SoftwareLogo.Tests.BytecodeGenerationCheck.BytecodeGenerationCheck.ExecuteSharedValidation(String manifestFilePath, String packageFullName) at Microsoft.Windows.SoftwareLogo.TestBase.TestBase.ExecuteTest()


text:
Q: Collection.AsQueryable() returns NullReferenceException when mapping with AutoMapper I am still a bit new to programming. I have the following method in my LessonsService:
public async Task<IEnumerable<T>> GetUserLessonsTableDataAsync<T>(string userId, string sortColumn, string sortColumnDirection, string searchValue)
{
    var user = await this.usersRepository
        .AllAsNoTracking()
        .Include(x => x.Trainer)
        .ThenInclude(t => t.Lessons)
        .Include(x => x.Member)
        .ThenInclude(m => m.Lessons)
        .ThenInclude(lm => lm.Lesson)
        .FirstOrDefaultAsync(x => x.Id == userId);

    IQueryable<Lesson> lessons;

    if (user.Trainer != null)
    {
        lessons = user.Trainer.Lessons.AsQueryable();
    }
    else
    {
        var lessonsMembers = user.Member.Lessons.Where(x => x.MemberId == user.MemberId);
        var lessonsList = new List<Lesson>();

        foreach (var lessonMember in lessonsMembers)
        {
            lessonsList.Add(lessonMember.Lesson);
        }

        lessons = lessonsList.AsQueryable();
    }

    var lessonData = from lesson in lessons select lesson;

    if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDirection)))
    {
        lessonData = lessonData.OrderBy(sortColumn + " " + sortColumnDirection);
    }

    if (!string.IsNullOrEmpty(searchValue))
    {
        lessonData = lessonData.Where(l => l.Topic.Contains(searchValue)
                            || l.StartingTime.Equals(searchValue)
                            || l.Group.Name.Contains(searchValue)
                            || l.Trainer.User.FirstName.Contains(searchValue)
                            || l.Trainer.User.LastName.Contains(searchValue));
    }

    return lessonData.To<T>().ToList();
}

For some reason this code throws System.NullReferenceException with message "Object reference not set to an instance of an object". I debugged and noticed that lessonData is not null, it is full with data from the database. Apparently, the mapping method .To< T >() is not working properly as it returns the following:

My controller is:
[HttpPost]
public async Task<IActionResult> GetUserLessons()
{
    try
    {
        var userId = this.HttpContext.Session.GetString("userId");
        var draw = this.Request.Form["draw"].FirstOrDefault();
        var start = this.Request.Form["start"].FirstOrDefault();
        var length = this.Request.Form["length"].FirstOrDefault();
        var sortColumn = this.Request.Form["columns[" + this.Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
        var sortColumnDirection = this.Request.Form["order[0][dir]"].FirstOrDefault();
        var searchValue = this.Request.Form["search[value]"].FirstOrDefault();
        int pageSize = length != null ? Convert.ToInt32(length) : 0;
        int skip = start != null ? Convert.ToInt32(start) : 0;
        int recordsTotal = 0;

        var lessonData = await this.lessonsService.GetUserLessonsTableDataAsync<LessonViewModel>(userId, sortColumn, sortColumnDirection, searchValue);

        recordsTotal = lessonData.Count();

        var data = lessonData.Skip(skip).Take(pageSize).ToList();
        var jsonData = new { draw, recordsFiltered = recordsTotal, recordsTotal, data };

        return this.Ok(jsonData);
    }
    catch (Exception e)
    {
        throw;
    }
}

The exception message in the stack trace is the following:
   at System.Linq.Enumerable.SelectIPartitionIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at ChessBurgas64.Services.Data.LessonsService.<GetUserLessonsTableDataAsync>d__15`1.MoveNext() in F:\ChessclubBurgas64WebApp\ChessBurgas64\Services\ChessBurgas64.Services.Data\LessonsService.cs:line 211
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at ChessBurgas64.Web.Controllers.UsersController.<GetUserLessons>d__17.MoveNext() in F:\ChessclubBurgas64WebApp\ChessBurgas64\Web\ChessBurgas64.Web\Controllers\UsersController.cs:line 171

I have a static class (where the method .To< T >() is positioned) that is referenced in the lessonsService:
public static class QueryableMappingExtensions
{
    public static IQueryable<TDestination> To<TDestination>(
        this IQueryable source,
        params Expression<Func<TDestination, object>>[] membersToExpand)
    {
        if (source == null)
        {
            throw new ArgumentNullException(nameof(source));
        }

        return source.ProjectTo(AutoMapperConfig.MapperInstance.ConfigurationProvider, null, membersToExpand);
    }

    public static IQueryable<TDestination> To<TDestination>(
        this IQueryable source,
        object parameters)
    {
        if (source == null)
        {
            throw new ArgumentNullException(nameof(source));
        }

        return source.ProjectTo<TDestination>(AutoMapperConfig.MapperInstance.ConfigurationProvider, parameters);
    }
}

Inoticed that this happens only to navigational properties (in this case it's user.Trainer.Lessons). If I get the lessons directly from the repository with
lessons = this.lessonsRepository.All().Where(...);, there will be no problem and everything will work fine, because the collection will be then a Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable instead of System.Collections.Generic.HashSet`1[Lesson]. So I guess the problem is that the method .AsQueryable() is not really converting the lessons to Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable, which is needed for the mapping method .To< T >() to work properly? What is the best way to fix this?


text:
Q: How to properly create an object from two existing objects i have collected two diferents objects form an api and i want to combine them into a single one before passing it to a child component.
I tried to loop one of them to create the third one into ComponentDidUpdate (maybe not the correct approach), and this pops up an error: "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops."
export default class Router extends Component {

    state = {
        posts : [],
        secciones : [],
        postSeccion : [],
    }

    componentWillMount() {
        this.obtenerPublicaciones(); //calling api
        this.obtenerSecciones(); //calling api
    }

    componentDidUpdate(prevProps, prevState) {

      this.createPostSeccionArray();

    }

    createPostSeccionArray() {
      const posts = [...this.state.posts];
      const secciones = [...this.state.secciones];

      //check if the two objects were fetched (sometimes didn't finish fetching one of them)
      if(posts.length !== 0 && secciones.length !== 0 ) {

        let postSeccionArray = [];

        posts.forEach(element => {

          const postSeccionElement = {};
          const actualPost = element;
          const actualSeccion = secciones.find(el => el.id == actualPost.id);
          postSeccionElement.post = actualPost;
          postSeccionElement.seccion = actualSeccion;
          postSeccionArray = [...postSeccionArray, postSeccionElement];
        });

        this.setState({
          postSeccion: postSeccionArray,
        })
      }

    }
}

This is the output array of objects im expecting:
[{
  "post": {
    "id": 1,
    "titulo": "Publicación 1",
    "cuerpo": "
test asdasd
",
    "seccion": 1,
    "fecha_creacion": "2019-04-16T15:16:36.181618Z",
    "fecha_edicion": "2019-04-16T15:16:36.181651Z",
    "autor": 1
  },
  "seccion": {
    "id": 1,
    "nombre": "Deportes",
    "descripcion": "test"
  }
}]

A: Based on what you have right now, the following will fix it.
  componentDidUpdate(prevProps, prevState) {
    if(!prevState.postSeccion.length > 0){
      this.createPostSeccionArray();
    }
  }

However, I will wait for more clarity from your side, after which I will edit this answer.

A: To merge 2 object (or more) you can use the spread operator

const a = {
  prop1 : "value1",
  prop2 : 23455,
  prop3 : "Hello"
}

const b = {
  prop2 : 67899,
  prop4 : "Workl"
}

const c = {...a, ...b}
console.log(c)

if you want the content of an object other you can do something like
const secciones = { // stuff };

const newObj = {
  prop1 : ...
  prop2 : ...
  secciones : {...secciones}
}

A: Firstly you can use the map function to refactoring your createPostSeccionArray method :
export default class Router extends Component {
  state = {
    posts: [],
    secciones: [],
    postSeccion: []
  }

  componentWillMount() {
    Promise.all(this.obtenerPublicaciones(), this.obtenerSecciones()).then(_ =>
      this.createPostSeccionArray()
    )
  }

  createPostSeccionArray() {
    const posts = [...this.state.posts]
    const secciones = [...this.state.secciones]

    // check if the two objects were fetched (sometimes didn't finish fetching one of them)
    if (posts.length !== 0 && secciones.length !== 0) {
      const postSeccionArray = posts.map(element => {
        const actualSeccion = secciones.find(el => el.id == element.id)
        return {
          post: element,
          seccion: actualSeccion
        }
      })

      this.setState({
        postSeccion: postSeccionArray
      })
    }
  }
}

I guess you want to create your post section array only when you are mounting the component. so can you use promise like I suggested to call createPostSeccionArray once ?


text:
Q: Sqlite : ORDER BY the MAX value of each group, but returning all rows I'm stuck with this one.
I would like to order a table by the max value of each group. (but returning all rows).
As it is always easier with an example :
Team | Player | Score
---
red  | Bob  | 32
red  | Jill | 34
red  | Shawn| 42
blue | Jake | 29
blue | Paul | 26
blue | Mike | 35

The desired result set :
blue | Jake | 35
blue | Paul | 35
blue | Mike | 35
red  | Bob  | 42
red  | Jill | 42
red  | Shawn| 42

A: You can use a correlated subquery:
select t.team, t.player,
       (select max(t2.score) from t t2 where t2.team = t.team) as max_score
from t;

You can do something similar with a group by and join.

A: You could use  a inner join on select table
  select t.team, a.player, t.score
  from my_table
  inner join (
      select team, max(score)
      from my_table
      group by team
  ) t on t.team = a.team
  order by t.team


text:
Q: Adding custom local fonts to QGIS I have some fonts that I want to add to QGIS but not globally to my operating system. So "installing" them e. g. via right-click in Windows or copying them to /usr/share/fonts/ on Linux is no option for me.
How can I make just QGIS aware of additional fonts?

A: One approach would be using Qt's QFontDatabase object which QGIS uses and add fonts to it via Python:
from qgis.PyQt.QtGui import QFontDatabase
qfontdatabase = QFontDatabase()
qfontdatabase.addApplicationFont("/tmp/ChivoMono-SemiBold.ttf")
qfontdatabase.addApplicationFont("/tmp/ComicSans.otf")

The font will be available immediately after running the addApplicationFont method.
You can use this for example in a plugin or in a startup.py script.


text:
Q: How can I run dart code in the background in flutter? I want to run a method in my main.dart file from the android(Kotlin) part of my app. For this I am using methodChannels and it works perfectly fine when the app is in foreground. However, the moment the app is killed, the flutterView is destroyed and therefore I am unable to run any methods in my main.dart file.
I read that using FlutterNativeView would allow me to do what I want but I am unable to find small code snippets to help me with it.
It would be great if you could help me with this
Thanks!!

A: In Flutter, you can execute Dart code in the background.
The mechanism for this feature involves setting up an isolate. Isolates are Dart's model for multithreading, though an isolate differs from a conventional thread in that it doesn't share memory with the main program. You'll set up your isolate for background execution using callbacks and a callback dispatcher.
For more information and a geofencing example that uses background execution of Dart code, see the Medium article by Ben Konyi, Executing Dart in the Background with Flutter Plugins and Geofencing. At the end of this article, you'll find links to example code, and relevant documentation for Dart, iOS, and Android.

A: You can write the native code for Firebase realtime database. You can check this.
You should create a custom plugin and put the native code in that plugin as writing the files directly in the Flutter android folder will make the project unmanageable in the future and you can face multiple unexpected issues.


text:
Q: how to use ZAP to scan HTTP security header? We want to integrate python/ZAPv2 into our SDLC, sometimes we only want to use ZAP to validate the security header, such as HttpOnly flag in Set-Cookie, CSP header, etc...
I google a lot, and find maybe ZAP policy could help us... but there is very limited document about how to self-define a zap policy, and how to call the API to call self-defined policy in ZAPv2 library
Is there any document/advices/ ideas could help me ...? thanks !

A: Security header checks are generally implemented as passive scan rules (so if you spider or proxy traffic you can get results for them). Here's some info on setting a Passive Scan "policy" programmatically.
Re-using my answer from over here: Export/Import OWASP ZAP Passive Scan Rules

There's an existing ticket open to unify Active/Passive Scan handling in a singular policy type interface: https://github.com/zaproxy/zaproxy/issues/3870.
If you're really interested in that you could support it on BountySource (https://www.bountysource.com/issues/49047644-improved-active-passive-rules-management) and see if that draws some attention/action.

Another option you could go with is to create a quick script that uses ZAP's web API to apply a Passive Scan rule "policy". Relevant endpoints include: pscan/view/scanners/, pscan/action/disableAllScanners/, pscan/action/enableScanners/. Here's a python example:
from zapv2 import ZAPv2 as zap
import time

apikey = "apikey12345" #Your apikey
z = zap(apikey=apikey, proxies={"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"})
time.sleep(2) #Might need to be longer depending on your machine and if ZAP is already running or not

print "Disabling all passive scan rules.."

z.pscan.disable_all_scanners()

scanners = z.pscan.scanners

for scanner in scanners:
    print scanner.get("id") + " : " + scanner.get("enabled") + " : " + scanner.get("name")

to_enable = "10020,10021,10062" #Customize as you see fit
print "\nEnabling specific passive scan rules..[" + to_enable +"]"

z.pscan.enable_scanners(to_enable)

print "\nListing enabled passive scan rules.."

scanners2 = z.pscan.scanners

for scanner in scanners2:
    if (scanner.get("enabled") == "true"):
        print scanner.get("id") + " : " + scanner.get("enabled") + " : " + scanner.get("name")

Finally you could configure ZAP on one system, then copy that config.xml to other systems as needed.


text:
Q: Link Clicking Before Javascript Loads (Problem) I'm using shadowbox for some html/iframe links, which effectively opens up the page in a lightbox. Everything works great - except when someone clicks before the javascript is done loading.
Now, the obvious answer is to not use links as the targets of loading the shadowbox. But this poses usability problems if javascript is disabled. Does anyone have any ideas on how else to solve the problem? I'm considering loading javascript inline that would deactivate the links until the page is done loading, although I'm not exactly sure how I'd approach that.
All ideas are welcome!

A: In general, I'd consider this to be a non-issue, but can't you just call the shadowbox processor inline directly after the links?
i.e.:
.link, .link, .link
script
$(".link").shadowbox();
/script

A: You could define your links as
...

and then reassign the click event handler once your javascript is loaded.  Or, if your links have non-JavaScript alternatives:
...

Again, when your JavaScript loads you can add a click event handler and override the default action.
If it takes a while for all of your scripts to load, you might reconsider if you need to load all of them right away.  If you do, then you could implement a loading screen (below example uses jQuery, but it doesn't have to):

    Loading...

  // Site content...

// Load your scripts here...

This way your site content isn't visible until all of your scripts are loaded.


text:
Q: Access QT Designer Objects Programmatically Disclaimer: New to both python and qt designer
QT Designer 4.8.7
Python 3.4
PyCharm 5.0.3
Question - How do I add controls to the main form or a scroll area widget on the main form (created in QT Designer) programmatically?
I have created a MainWindow in qt designer and added my widgets. The following is the entire test program in PyCharm:
import sys
from PyQt4 import QtGui, QtCore,  uic

from PyQt4.QtGui import *

from PyQt4.QtCore import *

qtCreatorFile = "programLauncher.ui"

Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)

class MyApp(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self):
    QtGui.QMainWindow.__init__(self)
    Ui_MainWindow.__init__(self)
    self.setupUi(self)

    # Cannot resize or maximize
    self.setFixedSize(1045, 770)

    # Add button test
    self.dateLabel = QtGui.QLabel("Test")
    self.pushButton = QtGui.QPushButton('Test button')

    # self.scrollArea_programs.addWidget()

    grid = QtGui.QGridLayout()
    # self.scrollArea_programs.addWidget(self.pushButton)
    grid.addWidget(self.dateLabel,0,0)
    grid.addWidget(self.pushButton,0,1)
    self.setLayout(grid)

    self.pushButton_exit.clicked.connect(self.closeEvent)

def closeEvent(self):
    QtGui.QApplication.quit()

if __name__ == "__main__":
  app = QtGui.QApplication(sys.argv)
  window = MyApp()
  window.show()
  sys.exit(app.exec_())

As you can see I tried to add controls to a grid but nothing shows up when the program runs - I have also tried to add a control to the scroll area. Can someone help me to just add 1 control to the scroll area at run time - so then I can know the proper way to do it or "a" proper way to do this.
Thanks in advance

A: Without having access to your programLauncher.ui and making minimal changes to your posted code, you can add your UI elements to the window like so:
from PyQt4 import QtGui
import sys

class MyApp(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        # Cannot resize or maximize
        self.setFixedSize(1045, 770)
        widget = QtGui.QWidget(self)
        self.setCentralWidget(widget)
        # Add button test
        self.dateLabel = QtGui.QLabel("Test")
        self.pushButton = QtGui.QPushButton('Test button')

        grid = QtGui.QGridLayout()
        grid.addWidget(self.dateLabel, 0, 0)
        grid.addWidget(self.pushButton, 0, 1)
        widget.setLayout(grid)

        self.pushButton.clicked.connect(self.closeEvent)

    def closeEvent(self, event):
        QtGui.QApplication.quit()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = MyApp()
    window.show()
    sys.exit(app.exec_())

This will get the controls on the screen, although the layout leaves a lot to be desired. You may have to make modifications to this based on what's in your .ui file. One thing that you'll want to note in this example is that the QMainWindow needs a central widget (widget in the example above). You then set the layout on that widget.

A: You can use the designer to create your .ui file
The you can load it in your .py using something like:
from PyQt4 import QtCore, QtGui, uic
class my_win(QtGui.QMainWindow):

    def __init__(self):
        self.ui = uic.loadUi('my_ui.ui',self)

then you can access all your widgets with something like
self.ui.actionQuit.triggered.connect(QtGui.qApp.quit)

or
self.ui.my_button.triggered.connect(self.do_someting)

A: Thanks to JCVanHamme (the programLauncher.ui hint) and also outside help I now learned most of what I need to know to access MainWindow at run time. So for anyone interested in this beginner tip:

*

*Take a blank form in QT Designer

*Add a control

*Run pyuic4 batch file

*Take a look at the generated .py file to learn EVERYTHING about how to add controls.

Don't let the power go to your head - cheers


text:
Q: Jackson JSON : Subclass fields not seralized if implements java.util.Set I have following inheritance
interface ResultSet extends java.util.Set<CustomResult> {
    public int getCount();
}

@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "CustomResultSet")
class CustomResultSet extends LinkedHashSet<CustomResult> implements ResultSet {

    @XmlElement(name = "count")
    private int count;

    public void setCount(int count) {
       this.count = count
    }

}
.
.
public static void main() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
CustomResultSet customResultSet = new CustomResultSet();
CustomResult customResult = new CustomResult(55, "abc");
customResultSet.setCount(11);
customResultSet.add(CustomResult);
System.out.println(objectMapper.writeValueAsString(customResultSet));

}

With above code serializes values in collection CustomResultSet but not field count in CustomResultSet .

A: Anything that implements the Set interface is treated as a Set by Jackson and it will result in a JSON array, even if you put annotations on your custom class. Your best shot is to have a custom serializer for your class.


text:
Q: Drop down does not populate with API data in Angular I want to retrive data to dropdown from api and I don't know what is wrong in my code.
Result of API:
[{"projectId":2,"projectName":"test","gates":[]},{"projectId":3,"projectName":"project1","gates":[]}]

Model of service(project.ts) :
export class Project{
    projectName: string;
    projectId :number;
}

Dropdown in my sidebar.component.html:
<div class="dropdown  ml-auto">
    <select (change)=selectedHandlerProjectName($event) class="btn btn-secondary dropdown-toggle" style="margin-left: -10px;border-left-width:15px;padding-left:11px;padding-right: 14px;margin-right: 12px;border-right-width: 12px">
        <option value = "default">Select project</option>
        <option *ngFor = "let projectName of selectProject?.projectName" value = {{projectName}}>{{projectName}}</option>
    </select>
</div>

Sidebar.component.ts
import { Component, OnInit } from '@angular/core';
import { Project } from '../models/Project';
import {ProjectService} from '../services/project.service';

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent implements OnInit {

  selectProject : Project;
  constructor(private projectService: ProjectService) { }

  getSelectedProject(): void{
    this.projectService.getProjects()
      .subscribe(selectProject => this.selectProject= selectProject);
  }
  //methods to get dropdown values
  dropDownProjectName: string = '';
  selectedHandlerProjectName(event : any)
  {
    if(event.target.value != 'default') { this.dropDownProjectName = event.target.value;}
    else {this.dropDownProjectName = null;}
  }

  ngOnInit() {
    this.getSelectedProject();

  }
}

Project.service.ts
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import {catchError,map,tap} from 'rxjs/operators';
import { Project } from '../models/Project';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class ProjectService {

  private urlProject = environment.baseUrl + environment.urlProject ;

  constructor(private http: HttpClient) { }

  getProjects(): Observable<any>{
    return this.http.get<Project>(this.urlProject)
    .pipe(
    catchError(this.handleError('getProject',[]))
  );
  }
}

If i look in Network when app running , appear data from API, but in dropdown not.

A: just try to replace it with your html dropdown code. it will works. because you don't need to check productName in *ngFor, *ngFor = "let projectName of selectProject?.projectName"
<select class="btn btn-secondary dropdown-toggle" >
    <option value="default">Select project</option>
    <option *ngFor="let project of selectProject" [value]="project.projectName">{{project.projectName}}</option>
</select>


text:
Q: For loop not returning back to the first forloop I am having issues with my script returning back to the first for loop in this program, right now it only returns to the second one. I am trying to figure out how to force it to through all the step.
Thanks in advance
import copy

test = {'AEP': {'days': [1]}, 'AES': {'days': [32]},'AIS': {'days': [7]},'TWO': {'days': [35]}}

print (test)
for stock in test:
    a = stock
    print ("step one")
    for stock in test.itervalues():
        print ("step two")
        for days in stock.itervalues():
            print ("step three")
            for i in days:
                print ("step four")
                if i <= 30:
                    days[days.index(i)] = i + 1
                else:
                    test_2 = copy.deepcopy(test)
                    test_2.pop(a)
                    print (str(a) + " Has been removed")
                    test = copy.deepcopy(test_2)

print (test)

Current flow/logs:
{'AEP': {'days': [1]}, 'AES': {'days': [32]}, 'TWO': {'days': [35]}, 'AIS': {'days': [7]}}
step one
step two
step three
step four
step two
step three
step four
AEP Has been removed
step two
step three
step four
Traceback (most recent call last):
  File "fortest.py", line 19, in <module>
    test_2.pop(a)

Here is what I would like to see as a end result
test = {'AEP': {'days': [1]},'AIS': {'days': [7]}}

A: So I went ahead and combined the first for loop with the second one so that the variable will still be the same one it reaches the if and else statements.
import copy

test = {'AEP': {'days': [1]}, 'AES': {'days': [32]},'AIS': {'days': [7]},'TWO': {'days': [35]}}

print (test)
for stock,stock_name in zip(test.itervalues(),test):
    a = stock_name
    print ('step one')
    for days in stock.itervalues():
        print ("step two")
        for i in days:
            print ("step three")
            if i <= 30:
                days[days.index(i)] = i + 1
            else:
                test_2 = copy.deepcopy(test)
                test_2.pop(a)
                print (str(a) + " Has been removed")
                test = copy.deepcopy(test_2)

print (test)

Current flow/logs:
{'AEP': {'days': [1]}, 'AES': {'days': [32]}, 'TWO': {'days': [35]}, 'AIS': {'days': [7]}}
step one
step two
step three
step one
step two
step three
AES Has been removed
step one
step two
step three
TWO Has been removed
step one
step two
step three
{'AEP': {'days': [2]}, 'AIS': {'days': [7]}}


text:
Q: Adding dates for unique EIDs row-wise to get Years of Service I have the following dataset:

EID
Company
Start_Date
End_Date
T_F

A111
ABC
2015-07-20
NaT
True

B111
DEF
1983-06-01
NaT
False

B111
ABC
2017-01-01
NaT
True

C111
GHI
1980-10-01
1981-08-31
True

D111
JKL
1973-05-01
1977-11-30
True

E111
ABC
2006-04-24
NaT
True

F111
ABC
1991-06-10
1994-12-15
False

F111
MNO
1994-12-01
2002-08-31
False

F111
ABC
2002-08-01
NaT
True

G111
ABC
1979-01-01
NaT
True

H111
ABC
2002-02-01
NaT
True

The expected output is as follows:

EID
Company
Start_Date
End_Date
T_F
YoS

A111
ABC
2015-07-20
NaT
True
NaN

B111
DEF
1983-06-01
NaT
False
(2017-01-01) - (1983-06-01)

B111
ABC
2017-01-01
NaT
True
NaN

C111
GHI
1980-10-01
1981-08-31
True
(1981-08-31) - (1980-10-01)

D111
JKL
1973-05-01
1977-11-30
True
(1977-11-30) - (1973-05-01)

E111
ABC
2006-04-24
NaT
True
NaN

F111
ABC
1991-06-10
1994-12-15
False
(2002-08-01) - (1991-06-10)

F111
MNO
1994-12-01
2002-08-31
False
NaN

F111
ABC
2002-08-01
NaT
True
NaN

G111
ABC
1979-01-01
NaT
True
NaN

H111
ABC
2002-02-01
NaT
True
NaN

This is what I am trying to do:

*

*Where an EID has only one record and company is ABC YoS column should be NULL. End_Date is always blank in these cases.

*Where an EID has multiple records and his/her last record is company ABC then YoS column will be Start date of first company - Start date of ABC company.

*Where an EID has only one record and company is not ABC then YoS will be calculated as End_Date - Start_Date

*Only the first record will have YoS value other records will contain NaN value.

*If an employee has multiple records 99% of the times employees last records will be ABC company.

I tried the following code but this is only half part (or incorrect) I believe:
 result.loc[~(result.CLEAN_NAME == 'HONEYWELL / HON') & (result.T_F == False),'Hon_StartDate'] = result['Start_Date']

Any leads would be appreciated. Thanks.!

A: Not the best solution, but it gets the job done. Considering the input is a CSV file stored in company.csv and using groupby on EID:
from itertools import chain
import pandas as pd

def compute_yos(record):
    if len(record) == 1 and record.iloc[0]["Company"] == "ABC":
        return [pd.NaT]
    elif len(record) > 1 and record.iloc[-1]["Company"] == "ABC":
        yos = [record.iloc[-1]["Start_Date"] - record.iloc[0]["Start_Date"]]
        return yos + [pd.NaT] * (len(record) - 1)
    elif len(record) == 1 and record.iloc[0]["Company"] != "ABC":
        return [record.iloc[0]["End_Date"] - record.iloc[0]["Start_Date"]]
    else:
        return [pd.NaT] * len(record)

input_df = pd.read_csv("company.csv")
print(input_df)
input_df[["Start_Date", "End_Date"]] = input_df[["Start_Date", "End_Date"]].apply(
    pd.to_datetime
)

grouping = input_df.groupby(["EID"]).apply(compute_yos)
concat_grouping = chain.from_iterable(grouping)
input_df["YoS"] = list(concat_grouping)
print(input_df)

input:
     EID Company Start_Date   End_Date    T_F
0   A111     ABC 2015-07-20        NaT   True
1   B111     DEF 1983-06-01        NaT  False
2   B111     ABC 2017-01-01        NaT   True
3   C111     GHI 1980-10-01 1981-08-31   True
4   D111     JKL 1973-05-01 1977-11-30   True
5   E111     ABC 2006-04-24        NaT   True
6   F111     ABC 1991-06-10 1994-12-15  False
7   F111     MNO 1994-12-01 2002-08-31  False
8   F111     ABC 2002-08-01        NaT   True
9   G111     ABC 1979-01-01        NaT   True
10  H111     ABC 2002-02-01        NaT   True

output:
     EID Company Start_Date   End_Date    T_F        YoS
0   A111     ABC 2015-07-20        NaT   True        NaT
1   B111     DEF 1983-06-01        NaT  False 12268 days
2   B111     ABC 2017-01-01        NaT   True        NaT
3   C111     GHI 1980-10-01 1981-08-31   True   334 days
4   D111     JKL 1973-05-01 1977-11-30   True  1674 days
5   E111     ABC 2006-04-24        NaT   True        NaT
6   F111     ABC 1991-06-10 1994-12-15  False  4070 days
7   F111     MNO 1994-12-01 2002-08-31  False        NaT
8   F111     ABC 2002-08-01        NaT   True        NaT
9   G111     ABC 1979-01-01        NaT   True        NaT
10  H111     ABC 2002-02-01        NaT   True        NaT


text:
Q: how to set max value in quantity update in codeigniter cart <?php echo form_input('cart[' . $item['id'] . '][qty]', $item['qty'], max=> $item['price'] ' type="number"  min="1" value="1" )'; ?>

how to set max value it shows me syntax error, unexpected '=>' (T_DOUBLE_ARROW)

A: Easiest way is to pass associative array,
<?php
      echo form_input(
             array(
               'name'=> 'cart[' . $item['id'] . '][qty]',
               'type'=>"number",
               'min'=>1,
               'max'=> $item['price'],
               'value'=> $item['qty'],
              )
      );
?>

You still can correct your existing one like below
<?php
    echo form_input(
              /*name*/
             'cart[' . $item['id'] . '][qty]',

             /* value */
             $item['qty'],

             /* other attributes as string */
             'max="'.$item['price'].'" type="number" min="1"'
     );
?>

From : https://www.codeigniter.com/userguide3/helpers/form_helper.html

form_input([$data = ''[, $value = ''[, $extra = '']]])
Parameters:
$data (array)   – Field attributes data
$value (string) – Field value
$extra (mixed)  – Extra attributes to be added to the tag
                  either as an array or a literal string


text:
Q: Why does `asyncio.run()` never return in Python 3.8? My application has the following top-level code (slightly abbreviated):
def main():
    # Some setup code ...
    try:
        asyncio.run(my_coroutine())
    except Exception as e:
        print("Exiting due to exception {}: {}".format(type(e).__name__, e))
    print("Coroutine finished")
    # Some cleanup code ...
    print("Shutdown complete")

In Python 3.8 asyncio.run never finishes, so the cleanup code does not run (and the shutdown text isn't printed). When the application is supposed to be exiting, it just hangs forever. In Python 3.7 it worked fine. Python 3.6 didn't have asyncio.run, but fairly similar code with loop.run_until_complete() and loop.close() also worked.
Some extra context: The setup and cleanup code starts and gracefully exits a worker thread created with threading.Thread. It's this thread that actually stops the main coroutine: it cancels the coroutine (technically, it cancels another coroutine which is called within my_coroutine()) using loop.call_soon_threadsafe

A: The premise of the question is wrong. (I knew that when I wrote it but not when I originally had the problem, so I left it in this form for others with the same problem.) asyncio.run() is finishing, but jumping over all the exception handling and shutdown code:
def main():
    # Some setup code ...
    try:
        asyncio.run(my_coroutine())
    except Exception as e:
        # <---- In Python 3.7, control passed to here when asyncio.run() finshed
        print("Exiting due to exception {}: {}".format(type(e).__name__, e))
    print("Coroutine finished")
    # Some cleanup code ...
    print("Shutdown complete")
    # <---- In Python 3.8 it directly dropped out of here!

This is because, in Python 3.8, the base class of asyncio.CancelledError changed from Exception to BaseException (which is the base class of Exception). This was done to avoid mistakes within async code where people were catching Exception thinking that it meant some operation had failed (e.g. network error) but accidentally preventing cancellation; see Python issue 32528.
The application then failed to exit because Python waits for all threads to finish unless they are started with daemon=False passed to the Thread constructor (see the discussion a few paragraphs into Thread objects docs). In my case, the thread is not a daemon thread (because I do want it to finish gracefully) but it will not exit unless I have requested it to, which is done in code where I put the comment "Some cleanup code...".
The solution is either to catch asyncio.CancelledError explicitly in addition to Exception, or use a finally: block instead. The finally: block is probably better since it really guarantees the code will be run, even in the face of other exceptions derived from BaseException such as KeyboardInterrupt:
def main():
    # Some setup code ...
    try:
        asyncio.run(my_coroutine())
    finally:
        print("Coroutine finished")
        # Some cleanup code ...
        print("Shutdown complete")


text:
Q: Image follows the cursor I need help trying to do following:
One: Click once to begin the image to follow
Two: Click again to stop the image
Three: It will notify which of the two states the user is in
My jfiddle code example is below.
$(document).mousemove(function (e) {
    $("#giraffeImg").stop().animate({
        left: e.pageX,
        top: e.pageY
    });
});

http://jsfiddle.net/sure1thing/5q8zH/4/
Thanks

A: Try this code:-
Fiddle link
$(document).ready(function(){
        var count = 0,
        anim = function(e){
        $("#giraffeImg").stop().animate({left:e.pageX,      top:e.pageY});
    }

    $(this).click(function(e){
        count += 1;

        if(count % 2){
        console.log('Animation started')

        $(this).on('mousemove',anim);

        }else{
         $(this).off('mousemove', anim);

         console.log('Animation finished')
        }
})

})

A: What about this:
var follow = false;
$(document).on('mousemove', function(e)
{
    //console.log(e.pageX);
    if(follow)
    {
        //alert('follow true');
        $('#image').animate({
            left: e.pageX,
            top: e.pageY
        }, 0)
    }
})

$(document).click(function()
{
    if(follow)
    {
        follow = false;
    }
    else
    {
        follow = true;
    }
})

jsFiddle
I just use a "flag" to start and stop the animation.


text:
Q: system agnostic url encoding I have a web application that performs GET requests to another web application. In one of my pages, I have a web form where I can search by name, and that might include special chars like áéíóú, etc.
The problem is, if I build my URI by concatenation of the different params, the result is wrongly encoded. If I use URLEncoder.encode(value) then the result is correctly encoded, but this method is deprecated.
If I specify the encoding, like URLEncoder.encode(value, "iso 9809-1") then it works, but to my understanding this is very system dependent.
How can I work out a URL encoding solution that works on all systems?

A: The deprecated version without encoding uses the platform specific encoding.
"ISO-8859-1" (Latin-1) is the default encoding of the HTTP protocols. That is more of less a subset of "Windows-1252" (Windows Latin-1). And covers some of the Western European languages like English and German.
"UTF-8" would be best, but maybe not supported by you server. Try it.


text:
Q: Client for Custom OpenId provider in Asp.Net web application I am relatively new to asp.net so sorry if the question sounds silly.
I have to build an Asp.net web application able to login on a OpenId custom server (i.e. not included in the DotNetOpenAuth library). I am using vs2010 and .net framework 4.0.
After many searches I found these posts where it is explained.
http://blogs.msdn.com/b/webdev/archive/2012/08/23/plugging-custom-oauth-openid-providers.aspx
How to use OpenID providers with unique identifier URLs in ASP.NET MVC4
http://blogs.msdn.com/b/webdev/archive/2012/08/15/oauth-openid-support-for-webforms-mvc-and-webpages.aspx
All of them refer to MVC and to a directory/file called /App_Start/AuthConfig.cs where you have to register your new provider in order to be able to use the client that comes built-in with the library.
From other searching I have understood this directory is not available in Asp.net web application.
Does exist a way/workaround for achieving the same results in Asp.net web application?
Do you have any suggestion/link on how to implements such custom client in my server?
Thank you
stmod

thanks for your help.
After your comment I was back to the provider for asking clarification, but so far, they cannot help me more than providing that link.
So I tried to manage it working in Java and I did it using openid4java library and the following code:
URL u = new URL("https://logint2.idm.toon.sul.t-online.de/gcp-web/login/10000112/");

Identifier i = new MyIdentifier();
*//myIdentifier is my implementation of interface openid4java.discovery.Identifier and returns* "http://specs.openid.net/auth/2.0/identifier_select"

DiscoveryInformation discovered = new DiscoveryInformation(u,i);

AuthRequest authReq = manager.authenticate(discovered, returnToUrl);

With this code (and others for managing the response) I have it working.
I am trying now to apply the same to my dot.net solution.
Can you help me in writing the code for having the DotnethOpenauth working with this endpoint?
I think I have to override the Identifier class as I did in Java, but I am stuck.
Thanks stmod

A: Adding OpenID Relying Party support to your ASP.NET web application is actually quite easy, and does not require an AuthConfig.cs file. If you are using web forms, the easiest way to go is just drop an OpenIdLogin control onto your web form. If you are using MVC, it's just a few lines of code to write, and you can check out the OpenIdRelyingPartyMvc sample that is included in the dotnetopenauth .zip download from SourceForge to see how it can be done.


text:
Q: How to insert a date that is 1 month prior to an existing date? I have been asked to fill a field with date that is 1 month prior to a date in a another field in our database.
This would be like if the date is 1/16/13 I would then input into the new field the date of 12/16/12.
The issue that I ran into is that some functions that are normal to native SQL databases do not exist in the same capacity in the Sybase Advantage Database I am using.
DATEADD for instance is not available from what I have experienced thus far.
So I have used the semi equivalent TIMESTAMPADD function. I started getting an error right when I thought I had it figured out so here is where I feel the issue is, but I do not know what the issue is:
INSERT INTO
  Normalization
(
  memotext
)
SELECT
  TIMESTAMPADD(SQL_TSI_MONTH, -1, memotext)
FROM
  eqanswer
WHERE
      entityrole = 'MTG_PROP_FIGS'
  AND fieldnum   = 22

I keep getting this error:
ERROR IN SCRIPT: poQuery: Error 7200:  AQE Error:  State = S0000;   NativeError = 2124;  [iAnywhere Solutions][Advantage SQL Engine]Invalid operand for operator: <assignment>

A: The ideal solution would be to have a TIMESTAMP column instead of a CHAR (or MEMO, etc.) column in your database.
You have to convert from your character field to a timestamp field in order to use the TIMESTAMPADD function.
For example this will output 2012-12-16:
SELECT
  LEFT(CONVERT(TIMESTAMPADD(SQL_TSI_MONTH, -1, CONVERT('2013-01-16 00:00:00', SQL_TIMESTAMP)), SQL_CHAR), 10)
FROM
  system.iota

If your date format is not in ISO 8601 you have to reformat the date string in input and output.
If it contains 01/16/13 (leading zeros) you can just use SUBSTRING to reformat the string:
DECLARE
  @Input CHAR(20);

SET
  @Input = '01/16/13';

SET
  @Input =
     '20'
    + SUBSTRING(@Input, 7, 2)
    + '-'
    + SUBSTRING(@Input, 1, 2)
    + '-'
    + SUBSTRING(@Input, 4, 2)
    + ' 00:00:00';

SELECT
  LEFT(CONVERT(TIMESTAMPADD(SQL_TSI_MONTH, -1, CONVERT(@Input, SQL_TIMESTAMP)), SQL_CHAR), 10)
FROM
  system.iota

If the database contains 1/16/13 (no leading zeros) you have to use a split string algorithm which is out of the scope of this question.
To reformat the output you can use MONTH, DAY and YEAR:
DECLARE
  @Input CHAR(20);

DECLARE
  @Temp TIMESTAMP;

SET
  @Input = '01/16/13';

SET
  @Input =
     '20'
    + SUBSTRING(@Input, 7, 2)
    + '-'
    + SUBSTRING(@Input, 1, 2)
    + '-'
    + SUBSTRING(@Input, 4, 2)
    + ' 00:00:00';

SET
  @Temp = TIMESTAMPADD(SQL_TSI_MONTH, -1, CONVERT(@Input, SQL_TIMESTAMP))
;

SELECT
  TRIM(CONVERT(MONTH(@Temp), SQL_CHAR)) + '/' + TRIM(CONVERT(DAY(@Temp), SQL_CHAR)) + '/' + TRIM(CONVERT(YEAR(@Temp), SQL_CHAR))
FROM
  system.iota

I'd suggest you first figure out how to do this with variables like in my examples. You can then combine this with your INSERT INTO .. SELECT statement.
You should be aware that anything that isn't a valid date format may cause trouble (the whole statement not executing due to CONVERT errors and so on).
If anything is unclear you can comment or ask another question on specific problems you're still having.


text:
Q: What kind of model should I use: dependent variable is proportion and test variables are dummy variables? My dependent variable is percentage (0%~100%). My tests variables are two dummy variables. It seems that I cannot use regression directly. I read several materials, but they have different suggestions.
Some suggest GLS, because the dependent variable is proportion (percentage between 0%~100%). Some suggest Tobit model, because the dependent variable is truncated (between 1 and 0) and with many zeros. Some suggest Beta regression.
How do I choice? Thanks in advance.

A: I would like to suggest you to try a GLM (Generalized Linear Model). Here is the link (http://data.princeton.edu/R/glms.html) for some details.


text:
Q: IIS7: How to block access with a web.config file? I know that IIS7 allows me to have a per directory configuration with the web.config xml file. I have a directory with some configuration files that don't want to be web accessible. A local web.config file forbidding read access to it would be a nice solution.
What should be the contents of a web.config file to forbid web access to the files?
Edit: I'm trying to put a web.config file with these contents in a file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
            <system.web>
                    <authorization>
                            <deny users="*" /> <!-- Denies all users -->
                    </authorization>
            </system.web>
</configuration>

But I can still directly access a file inside the directory. What's wrong with it? How do I debug what's happening?

A: i think this can solve your problem.
place this web.config in directory that contain target directory :
<configuration>
 <system.webServer>
  <security>
   <requestFiltering>
    <hiddenSegments>
     <add segment="target directory name"/>
    </hiddenSegments>
   </requestFiltering>
  </security>
 </system.webServer>
</configuration>

A: You can use the Location nodes on the Web.config. Here is a detailed explanation on msdn ; in a nutshell:
<location path="Subdirectory">
    <system.web>
        <authorization>
            <deny users="*"/> <!-- Denies all users -->
        </authorization>
    </system.web>
</location>
<location path="Public_Directory">
    <system.web>
        <authorization>
            <allow users="*"/> <!-- Allows all users -->
        </authorization>
    </system.web>
</location>

You can also use the ? wildcard to specify that you should (allow/deny) anonymous users

A: You're using system.web.  In IIS7, you should use system.webServer instead.  This will block all types of files, not just ASP.NET files.  For example, you can password protect jpg, gif, txt and all types of files.
It would look something like this:
  <system.webServer>
      <security>
          <authorization>
              <remove users="*" roles="" verbs="" />
              <add accessType="Allow" roles="Administrators" />
          </authorization>
      </security>
  </system.webServer>

And if you want to set it for just 1 file:
 <location path="dontlook.jpg">
     <system.webServer>
         <security>
             <authorization>
                 <remove users="*" roles="" verbs="" />
                 <add accessType="Allow" roles="Administrators" />
             </authorization>
         </security>
     </system.webServer>
 </location>

A: *

** means every logged in user.

*? means anonymous users.

You must use ?.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.web>
        <authorization>
            <deny users="?" />
        </authorization>
    </system.web>
</configuration>