text:
Q: Why c:if is not working with primeface in this case? I try to use the code below to be the condition to show a link or just the text.
            <c:if test="#{c.condition eq 'EXAMPLE'}">
                <p:column sortBy="#{c.num}"
                    filterBy="#{c.num}" filterMatchMode="contains">
                    <h:outputText value="#{c.num}" />
                </p:column>
            </c:if>
            <c:if test=#{c.condition eq 'EXAMPLE'}">
                <p:column sortBy="#{c.num}"
                    filterBy="#{c.num}" filterMatchMode="contains">
                    <h:link value="#{c.num}" rendered="#{!c.other}"
                        onclick="clickLink('#{request.contextPath}', '#{c.id}', '#{c.id2}');return false;">
                    </h:link>
                </p:column>
            </c:if>

However, it is not work that it always show the link instead of text.
But if I use rendered="", it works, Why? And which way is better?
            <p:column sortBy="#{c.num}"
                rendered="#{c.condition eq 'EXAMPLE'}"
                filterBy="#{c.num}" filterMatchMode="contains">
                <h:outputText value="#{c.num}" />
            </p:column>

            <p:column sortBy="#{c.num}"
                rendered="#{c.condition eq 'EXAMPLE'}"
                filterBy="#{c.num}" filterMatchMode="contains">
                <h:link value="#{c.num}" rendered="#{!c.other}"
                    onclick="clickLink('#{request.contextPath}', '#{c.id}', '#{c.id2}');return false;">
                </h:link>
            </p:column>


text:
Q: What seems to be a correct regex doesn't work in replace function I am trying to match three consecutive dots (".") followed optionally by a space.
My idea was the following:
\.\.\.\s?

Tested it here and seems to do exactly as expected.
But then when I try to use it in the replace function with javascript it doesn't seem to work, it's quite weird unless I'm missing something silly:
replace("\.\.\.\s?", "")

Doesn't work, see live demo here.
What am I missing?

A: this should work $('div').text("... hi".replace(/\.\.\.\s?/, ""));
String.replace() takes either a string or a regular expression as the first argument. If it is a string then it is searched for verbatim. https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/String/replace

A: The regex shouldn't be in quotes.  Try...
mystr.replace(/\.\.\.\s?/, "")

jsfiddle

A: The first parameter of String.replace must be a RegExp object, not String. Change it to:
$('div').text("... hi".replace(/\.\.\.\s?/, ""));

Or,
$('div').text("... hi".replace(new RegExp("\\.\\.\\.\\s?"), ""));

A: $('div').text("... hi".replace(/\.{3}/gi, ""));

Slightly optimized regular expression.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Thing that goes in between two things In software, module A can call onto another module B to do stuff. Now I put a third module C in between A and B, whose job it is to catch calls from module A, possibly divert them, and otherwise pass them through to module B. What do you call this interposed C?
I'm pretty sure there is a term for this in mechanics/electronics/carpentry, and hence I'm not looking for a software-specific term. (Before anyone asks: a proxy is a hyponym of the hyperonym I'm looking for. An interface is also not the right term, since that denotes a thin layer.)
For some reason, my mind keeps going to "shunt" (an electrical term), but I don't think that's what I need. A "wedge" has no ability to pass things through, so that's not right.

A: Shim is a term borrowed from carpentry and related fields, and has the benefit of having already been borrowed in computing for exactly this purpose.

(computing) A small library that transparently intercepts and modifies calls to an API, usually for compatibility purposes.

The non-computing definition is basically

[a] wedge

or

[a] thin piece of material, sometimes tapered, used for alignment or support.

Wiktionary


text:
Q: What does the time evolution operator look like in Matrix representation? In Matrix representation of quantum mechanics, using an energy eigenbasis, we have the state vector:
$$|\psi(t)\rangle=\left(\begin{matrix}
\psi_0(t)\\
\psi_1(t)\\
\psi_2(t)\\
\vdots
\end{matrix}\right)$$
and
$$|\psi(t)\rangle=\left(\begin{matrix}
\psi_0(0)e^{iE_0t/\hbar}\\
\psi_1(0)e^{iE_1t/\hbar}\\
\psi_2(0)e^{iE_2t/\hbar}\\
\vdots
\end{matrix}\right)$$
This is often represented as the state vector at time $0$ operated on by the time evolution operator $\hat U$:
$$|\psi(t)\rangle=\hat U (t)|\psi(0)\rangle$$
And $\hat U (t)$ is usually represented as:
$$\hat U(t)=e^{i\hat Ht/\hbar}$$
Now I know that, in the energy eigenbasis, the Hamiltonian Operator is represented as:
$$\hat H=\left(\begin{matrix}
E_0&0&0&\cdots\\
0&E_1&0&\cdots\\
0&0&E_2&\cdots\\
\vdots&\vdots&\vdots&\ddots
\end{matrix}\right)$$
How do you represent an exponential to the power of a matrix? Or is the exponential just shorthand to show $U_{ij}(t)=e^{i H_{ij}t/\hbar}$, such that
$$\hat U=\left(\begin{matrix}
e^{iE_0t/\hbar}&0&0&\cdots\\
0&e^{iE_1t/\hbar}&0&\cdots\\
0&0&e^{iE_2t/\hbar}&\cdots\\
\vdots&\vdots&\vdots&\ddots
\end{matrix}\right)$$
And how does this generalize to other eigenbasis?

A: The exponential of an operator is generally defined via Taylor series as:
$$e^{\hat A} \equiv \sum_{n=0}^\infty \frac{\hat A^n}{n!}$$
Which is completely independent of the matrix representation of $\hat A$ in any basis. Now if $\hat A$ is diagonalizable, as in the case of the hamiltonian, one can show that the above Taylor series definition boils down to exponentiating the diagonal elements of the operator in its eigenbasis (in which it is diagonal), which is what you have written. For the general matrix elements of $e^{\hat A}$ in an arbitrary basis, one can first write the matrix elements in its own eigenbasis, and then use a basis transformation.Explicitly, the spectral decomposition of $e^{\hat A}$ is:
$$e^{\hat A} = \sum_k e^{A_k} |A_k \rangle\langle A_k|$$
 Now imagine you want the matrix elements in the basis $\{|e_i \rangle \}_i$, this can easily be calculated with the above relation:
$$\langle e_i|e^{\hat A}|e_j \rangle = \sum_k e^{A_k} \langle e_i|A_k \rangle\langle A_k|e_j \rangle$$
What the above sum actually is depends on the specific operator in question. However, note the important fact that in general, $\langle e_i|e^{\hat A}|e_j \rangle \neq  e^{\langle e_i|\hat A|e_j \rangle}= e^{A_{ij}}$. Matrix elements generally can not be exponentiated for non-diagonal matrices.


text:
Q: findoverlap region with some condition I try to use findOverlap to solve this problem but I'm only find overlap region with no condition, so If I have some conditon to select data. How should I do?
Let's assume I have two data frame  like below
dataframe a
Sample, start, stop, event, probe, length, length/probe, region
CNV1234,  2000,  3000,  CN gain,  23,  235, 9, intron
CNV1534,  1200,  1800,  CN loss,  60,  600  10, exon

dataframe b
Sample, start, stop, event, probe, length, length/probe, region
CNV234,  2500,  3500,  CN gain,  23,  235, 9, exon
CNV34,  1200,  1800,  CN loss,  60,  600  10, intron

I have two questions
First ,I want to find overlap  between this two dataframe which CNV is have more than 50% length overlap  and this overlap is in intron region
Second,  I want to know the length of overlap region.
I want my result have a dataframe look like this
Sample, start, stop, event, probe, length, length/probe, region, overlap, length of overlap
CNV1234,  2000,  3000,  CN gain,  23,  235, 9, intron, CNV234, 500

A: Here's your data
a <- read.csv(textConnection(
    "Sample, start, stop, event, probe, length, length/probe, region
     CNV1234,  2000,  3000,  CN gain,  23,  235, 9, intron
     CNV1534,  1200,  1800,  CN loss,  60,  600  10, exon"))

b <- read.csv(textConnection(
    "Sample, start, stop, event, probe, length, length/probe, region
     CNV234,  2500,  3500,  CN gain,  23,  235, 9, exon
     CNV34,  1200,  1800,  CN loss,  60,  600  10, intron"))

Load the GenomicRanges package (I'm assuming that your data actually come from several chromosomes, and you'd like to do this across all; "A" is a chromosome name)
library(GenomicRanges)
gr1 <- with(a, GRanges("A", IRanges(start, stop - 1L),
                       Sample=Sample, event=event))
gr2 <- with(b, GRanges("A", IRanges(start, stop - 1L, names=Sample),
                       Region=Sample))

Note how GRanges denotes ranges (1-based, including start and end coordinates). Find all overlaps between these objects (you could use min.overlaps to exclude some overlaps, e.g., those that are shorter than 1/2 the minimum width)
h <- findOverlaps(gr1, gr2)

It's not clear what "50%" of the width is -- width of a? b? -- so I calculate the width of all overlaps, then keep those whose width is greater than 1/2 the width of "a"
wd <- width(pintersect(gr1[queryHits(h)], gr2[subjectHits(h)]))
ok <- wd > width(gr1[queryHits(h)]) / 2
h <- h[ok]

Finally, I assemble the result by selecting the queries that satisfy the overlap criteria and adding the metadata columns (mcols) and width of overlap of the regions they overlap
result <- gr1[queryHits(h)]
mcols(result) <- cbind(mcols(result), mcols(gr2[subjectHits(h)]))
result$`width of overlap` <- wd[ok]

The result could be coerced back to a data frame with as.data.frame(result), or perhaps your downstream analysis is done naturally with the GRanges infrastructure?
It's better to ask questions about Bioconductor packages on the Bioconductor mailing list (no subscription required). There are likely more efficient ways to do this, and the people on that mailing list will provide these solutions.


text:
Q: Как отсортировать и вывести значение из масива обьектов в js? Нужно вытянуть все total из массива объектов в зависимости от флага true или false и суммировать все total исходя из этого флага.
const totals = [
    {
      total: 757565,
      income: true,
    },
    {
      total: 33,
      income: false,
    },
    {
      total: 75,
      income: true,
    },
    {
      total: 757565,
      income: true,
    },
  ];

A:

const totals = [{
    total: 757565,
    income: true,
  },
  {
    total: 33,
    income: false,
  },
  {
    total: 75,
    income: true,
  },
  {
    total: 757565,
    income: true,
  },
];

const INCOME = false;
console.log(totals.reduce((a, c) => a + (c.income === INCOME && c.total), 0));

A: const getSumByFlag = totals => {
  let trueSum;
  let falseSum;
  for (i=0; i<totals.length; i++) {
    const flag = totals[i].income;
    const total = totals[i].total;
    flag === true ? trueSum += total : falseSum += total;
  }
  let result = {
    incomeTrueSum: trueSum,
    incomeFalseSum: falseSum
  };
  return result;
};


text:
Q: Relay not permitted - Microsoft365 Direct Send I am building a C# application which has to send certain (no-reply) e-mails within my company.(Warnings, Notifications, etc. Internal addresses only)
As I have spoken to our IT manager, it is possible without any authentication, even without an existing sender address (I can give anything I want), through a protected SMTP Host, only for internal use.
He even tested it with some printer application to show me that it works.
This is also explained here (Option 2):
https://learn.microsoft.com/en-us/exchange/mail-flow-best-practices/how-to-set-up-a-multifunction-device-or-application-to-send-email-using-microsoft-365-or-office-365
In my code, I get a "Relay Not Permitted" exception :
public static void Email(string htmlString, string subject, string address)
        {
            MailMessage message = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            message.From = new MailAddress("sender@internal_domain.com");
            message.To.Add(new MailAddress(address));
            message.Subject = subject;
            message.IsBodyHtml = true;
            message.Body = htmlString;
            smtp.Port = 25;
            smtp.Host = "***.protection.outlook.com";
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            try
            {
                smtp.Send(message);
                Console.WriteLine("E-mail Sent!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception Message: " + ex.Message);
                if (ex.InnerException != null)
                    Console.WriteLine("Exception Inner:   " + ex.InnerException);
            }
        }

I have changed the SMTP Host and the sender address for security purposes. The host is otherwise reachable.
The receiver's address is my own work e-mail address, given as parameter.
What should I look into?
Thanks in advance!


text:
Q: Magento2: Mixin is undefined on deploying static content I have created several mixins in my custom theme within the file "_mixins.less", these work locally and are loaded properly from my other less files. However, when I want to deploy static content I get the following compilation error:
Compilation from source: /var/projects/**project**/magento2/vendor/magento/theme-frontend-blank/web/css/email-fonts.less

Compilation from source:
frontend/GetNoticed/**project**/en_US/css/email-fonts.less
.anim-fade is undefined in /var/projects/**project**/magento2/var/view_preprocessed/css/frontend/GetNoticed/**project**/en_US/css/source/_theme.less

This only happens when it tries to compile less files from parent themes ( Luma or Blank ). I also get the same error in my Firebug console on the product page, within the gallery.css file.
The function .anim-fade doesn't do more than adding a simple transition effect:
.anim-fade(@element; @duration) {
  transition: @element ease-in-out @duration;
  -webkit-transition: @element ease-in-out @duration;
  -moz-transition: @element ease-in-out @duration;
  -o-transition: @element ease-in-out @duration;
}

Which works fine on all elements that use this. My _sources.less file looks like this:
@import '_mixins.less';
@import '_variables.less';
@import (reference) '_extends.less';
@import '_theme';
@import '_typography.less';
@import '_layout.less';
@import '_tables.less';
@import '_messages.less';
@import '_navigation.less';
@import '_tooltips.less';
@import '_loaders.less';
@import '_forms.less';
@import '_icons.less';
@import '_buttons.less';
@import '_sections.less';
@import '_pages.less'; // Theme pager
@import '_actions-toolbar.less';
@import '_breadcrumbs.less';
@import '_popups.less';
@import '_price.less';
@import '_bootstrap.less';
@import '_fonts.less'; /* theme fonts */
@import '_header.less'; /* theme heading */
@import '_homepage.less'; /* page specific styling */
@import '_checkout.less'; /* custom checkout styling */
@import '_productgrid.less'; /* products-grid search results */
@import '_product.less'; /* products-grid search results */
@import '_sidebar.less'; /* sidebars pages */

I'm absolutely clueless why it's doing this, all my other mixins are compiling just fine. I've tried renaming the mixin from "fade-transition" to "lib-fade-transition" to "anim-fade", but this didn't help.
Hoping to find answers here, thanks in advance!


text:
Q: Design pattern for a context sensitive popup menu in a ListActivity I have a ListActivity with row defined as this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
 <TextView android:id="@+id/me_games_won"
     android:textSize="16sp"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>

<TextView android:id="@+id/gamesmate_username"
     android:textSize="16sp"
     android:textStyle="bold"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>
 <TextView android:id="@+id/him_games_won"
     android:textSize="16sp"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>
 <ImageView
    android:id="@+id/imageMenuGamesmate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_settings" />
</LinearLayout>

The image is used to popup or not a menu depending on some status of the row.
My ArrayAdapter has this piece of code to launch the popup menu:
public View getView(int position, View convertView, ViewGroup parent) {
...
myimage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(v.getContext(), v);
popupMenu.getMenuInflater().inflate(R.menu.popupmenu_gamesmate, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

@Override
public boolean onMenuItemClick(MenuItem item) {

return true;
}
});

popupMenu.show();
}
});

Now when the user clicks on the menu item, an action will be performed but the values of the row are required to format the request properly.
I am looking for the best design pattern to do this?
Maybe subclassing the row view of the ListView of the ListActivity, but how then?
Maybe subclassing the PopupMenu in order for it to keep a version of the data used to create the row?
etc...
Anyone with a good idea?
Cheers.
David.

A: Have you used the listview with an adapter? This will make it very easy to be handled, there are many examples on how to do this (ex. http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/)

A: One possible YAGNI-based approach.

*

*To popup or not? I believe you have no problem with this.  You have all the data handy in your getView(). So a simple if() seems to be sufficient there.

*Assuming your popup menu is always the same, only the action is varied depending on the data, you only need to make the menu data-aware. To achieve that, you need to have a reference to the corresponding data item in onMenuItemClick().  To get it there, you could:

*

*Subclass the popup menu

*Pass the position to the menu's custom constructor

*Use the position in onMenuItemClick() to retrieve the data item via adapter.getItem(int position) and apply any desired logic there
The benefit of this approach is minimalism.  You only pass an integer around.
PS. In addition, you can encapsulate stuff nicely if you wish.
PPS. If you need a variety of popup menus, you can create a factory that knows how to make the right subclass when called from getView().


text:
Q: Getting ~ to expand in .hgrc on Windows Is it possible to get the following to work?
[ui]
ssh = ~\bin\ssh -i ~\.ssh\my_key

Using the Googles implies it must work for some people (Linux users?), but it's definitely not working for me.
I'd also accept $HOME (or some variant), but I can't find the right syntax.

A: what if you replace ~ with %USERPROFILE% (which, I believe is the equivalent to $HOME in Windows)?


text:
Q: How to implement saveFragmentInstanceState? Could you anyone advice me how to implement saveFragmentInstanceState() or some other methods  to retrieving fragment instance when back button is pressed. I use own stack for fragment, viz code bellow:
public class stackA extends ActivityInTab {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.i("StackA", "onCreate");

        if(savedInstanceState == null){
            navigateTo(new fragmentA());
        }

    }
}

Next there is implementation of ActivityInTab class. I think for this class must be implemented methods for saving and retrieving fragment state but still I can't find the way how to do this.
abstract class ActivityInTab extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_in_tab);

        Log.i("ActivityInTab", "onCreate");
    }

    protected void navigateTo(Fragment newFragment) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();
        ft.replace(R.id.content, newFragment);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        ft.addToBackStack(null);
        ft.commit();
    }
    @Override
    public void onBackPressed() {

        Log.i("ActivityInTab", "onBackPressed");

        FragmentManager manager = getSupportFragmentManager();
        if (manager.getBackStackEntryCount() > 1) {
            super.onBackPressed();
        } else {
            // Otherwise, ask user if he wants to leave :)
            //showExitDialog();
            super.onBackPressed();
        }
    }
}

And finally, this is imlementation of Fragments:
public class fragmentA extends Fragment {

    private LinearLayout ll;
    private FragmentActivity fa;

    private String textViewText;

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

        Log.i("Fragment A", "onCreateView");

        fa = super.getActivity();
        ll = (LinearLayout) inflater.inflate(R.layout.fragmenta, container,
                false);
        Button next = (Button) ll.findViewById(R.id.button1);
        Button randomBtn = (Button) ll.findViewById(R.id.random_button);
        final TextView randomText = (TextView) ll
                .findViewById(R.id.random_textview);
        next.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View view) {

                            ((ActivityInTab) getActivity()).navigateTo(new
                            fragmentB());
            }
        });

        randomBtn.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                randomText.setText(String.valueOf(Math.random()));
                textViewText = randomText.getText().toString();
            }
        });

        if (savedInstanceState != null) {
            randomText.setText(savedInstanceState.getString("TextView"));
        }

        return ll;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // setRetainInstance(true);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("TextView", textViewText);
    }
}

I'm able to save instance state only for orientation changes using onSaveInstanceState(Bundle outState), but no for back button.
I would be very grateful for any advice, thanks.

A: In the onBackPressed Method you have access to the FragmentManager which can retrieve any fragment for you using the FragmentManager methods "findFragmentById" or "findFragmentByTag".
You can get direct access to any fragment whos state you want to save using either of those two methods depending on how you added the fragments.


text:
Q: How can I decorate desktop-windows from commandline (red frame?, linusmint-cinnamon) I am "streaming" some of my desktop-windows to a remote host via xwininfo and x11vnc -id $WINID, which is already working.
Now I'd like to mark the windows, which I am streaming to the remote host, on the server-side.
How can I decorate these streamed windows (draw a red frame around them?), where I started x11vnc?
Something like:
#!/bin/bash
WINID=$(xwininfo |awk '/Window id:/ {print $4}')
x11vnc -id $WINID
draw_red_frame $WINID

# and later on
draw_red_frame $WINID delete


text:
Q: Xamarin.iOS equivalent to Xamarin.Android's CookieManager.Instance I am working with Cookies in my Xamarin Forms App.
At some point, I need to get the stored Cookies as a string.
In Android, I can resolve this as CookieManager.Instance.GetCookie(url); which returns a string of all Cookies, seperated with a ;
I am looking for an equivalent for Xamarin.iOS, since I am developing a cross-platform application.
Looking forward to your answers.

A: In iOS if you are using NSUrlSession, your cookies are shared automatically with the UIWebView/WKWebView and NSUrlSession.
To access the Cookie Container, you just need to call upon by using DependencyService or Custom Renderer .
NSHttpCookieStorage shareStore = NSHttpCookieStorage.SharedStorage;
var cookies = shareStore.CookiesForUrl(url);

A: For iOS you need to use NSHttpCookieStorage  class. You need to create Dependecny Service class in your iOS project.
NSHttpCookieStorage CookieStorage = NSHttpCookieStorage.SharedStorage;
var cookie = CookieStorage.CookiesForUrl(url);

For more information how to implement it, you can visit this url.

A: Since iOS does not provide such a method, I have implemented it myself. For anyone interested, here is my code:
public string GetCookieString(string url)
    {
        NSHttpCookie[] cookieArray = NSHttpCookieStorage.SharedStorage.CookiesForUrl(new NSUrl(Constants.PROXY_URL));
        string cookieString = "";

        NSHttpCookie lastCookie = cookieArray.Last();
        foreach (NSHttpCookie cookie in cookieArray)
        {
            cookieString = cookieString + cookie.Name + "=" + cookie.Value;
            if (!(cookie==lastCookie))
            {
                cookieString = cookieString + "; ";
            }
        }
        return cookieString;
    }

I could not test it yet, but it should provide me with a string which looks this:
cookieString= "name=value; name=value; name=value"


text:
Q: Pull images from album & display them <?php
//access the directory
$dir = dir('pics');

//build array of files in the directory
while (($pic = @$dir->read()) !== FALSE){
    $pics [$pic]= filesize('pics/'.$pic);
}

asort ($pics);

$txtfile=@fopen('txtfile.txt', 'w');

if ($txtfile === NULL) {
    throw new FileOpenException('txtfile.txt');
    //loop though and print each file as a link
    foreach ($pics as $name => $filesize){
        if ($name !="." && $name !=".."){
            echo "$filesize bytes
";
            $result =@fwrite($txtfile, $name . "\r\n");
            if ($result === FALSE)
                throw new FileWriteException();
            }
    }
}

fclose($txtfile);

?>

This code snippet was given by a professor to use for a project we are working on but it is not working & prof doesn't seem to know much.
The codes is meant to pull images from an album and display them but nothing I do seems to work. The album is named pics and is in the same folder as everything else.
Any help is appreciated.


text:
Q: The trait `FromSql<'_>` is not implemented for `Uuid` in tokio-postgres in rust I am trying to use UUID as my primary key in Postgres.
I am getting the trait FromSql<'_> is not implemented for Uuid in tokio-postgres.
First I try to use tokio-pg-mapper but it is also showing the same compile error.
So, I try diff approach and try to implement the From on Struct to covert it directly from Row.
When I try to implements From to convert the Row type to my struct Shop.
impl From<Row> for Shop {
    fn from(row: Row) -> Self {
       Self {
            id: row.get("id"), // Id is UUID type
            name: row.get("name"),
            address: row.get("address")
       }
    }
}

Still getting the the trait FromSql<'_> is not implemented for Uuid in tokio-postgres

I know that it is asking me to implement the FromSql for the UUID type.
But I looked into the tokio-postgres docs and found that it is already implemented there.

Did I miss something ?
uuid=0.8
tokio-postgres=0.7.2

A: To activate the UUID support I need to declare it in my Cargo.toml file and it will start working with tokio-pg-mapper and with my custom solution too.
tokio-postgres = {version="0.7.2", features=["with-uuid-0_8"]}


text:
Q: How to Restrict MFC Application to run only from a known USB flash drive I want to make a MFC Application that can only run form a know USB flash drive. It should not be run if we copy to the other place.
I found question something like this at here
But i don't really understand. Please show me a hint.

A: In MFC:  GetFileInformationByHandle
 BY_HANDLE_FILE_INFORMATION info;
DWORD dwSerialNumber = 0;

if(GetFileInformationByHandle(FileHandle, &info) != 0)
{
    dwSerialNumber = info.dwVolumeSerialNumber;
    swprintf(szTemp, L"The Volume Serial Number = %d", info.dwVolumeSerialNumber);
    MessageBox(NULL, szTemp, L"Success", MB_OK);
}
else
{
    swprintf(szTemp, L"GetFileInformationByHandle Error = %d", GetLastError());
    MessageBox(NULL, szTemp, L"Success", MB_OK);
}

In C#/C++.NET:
Use WMI the internal serial number of a USB-drive.
Try ths code , if there is no serial number, it is becuse some USB flash drives do have them, some don't.
//import the System.Management namespace at the top in your "using" statement. Then in a method, or on a button click:

ManagementObjectSearch theSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'");
foreach (ManagementObject currentObject in theSearcher.Get())
{
   ManagementObject theSerialNumberObjectQuery = new ManagementObject("Win32_PhysicalMedia.Tag='" + currentObject["DeviceID"] + "'");
   MessageBox.Show(theSerialNumberObjectQuery["SerialNumber"].ToString());
}


text:
Q: Not able to call class member function in a separate thread using C++11 thread class I am having a hard time to get the right syntax for calling a class member function in separate thread . Neither of the three options are working . Line 1 and 2 are throwing compile time error while the third one is showing run time error . Can anybody tell me please what is the correct way .
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
struct Complex
{
    mutex mx;
    int i;
    Complex(int q) : i(q) {}
    void mul(int x)
    {
        lock_guard<mutex> lock(mx);
        int z = i*x;
        cout<<z<<endl;
    }
    void div(int x)
    {
        lock_guard<mutex> lock(mx);
        int z = i/x;
        cout<<z<<endl;
    }
    void both(int x, int y)
    {
         mul(x);
         div(y);
    }
};
int main()
{
    //Complex complex(9);
    //thread t(&Complex::both,&Complex(9),32, 23);     --1
    //thread t(&Complex::both,complex,32,23);          --2
    //thread t(&Complex::both,&complex,32,23);         --3
    return 0;
}

A: (1) doesn't work because the expression &Complex(9) is ill-formed - you are trying to take the address of a temporary and that is disallowed.
(2) doesn't work because std::thread will copy all of its arguments internally. complex's copy constructor is defined as deleted because it contains a member of type std::mutex whose copy constructor is deleted.
(3) compiles fine but will fail at runtime because the created thread t will be destroyed before it is joined. You will want to join it first:
std::thread t(&Complex::both, &complex, 32, 32);
t.join();


text:
Q: Alternative for isDisplayed() as it is not available in/from safari 12 In one of test steps before clicking some element I use selenium
ExpectedConditions.elementToBeClickable(element)

This method checks visibility by verifying that element is displayed
element.isDisplayed()

Tests are run on browserstack.
Note, that with combination OS X High Sierra + Safari 11 this step pass.
But with Mojave + Safari 12 after element is found and request
/session/:sessionId/element/:id/displayed is sent I see in selenium log responce "unknown command":
{"value":{"error":"unknown command","message":"The command 'GET \/session\/CD43B950-D8D6-49A4-A0FF-3F459F1F6D86\/element\/node-E721541C-713B-4607-8041-C79138E08704\/displayed' was not found.","stacktrace":""}}

Here I see that such request ("displayed") is missing:
https://developer.apple.com/documentation/webkit/macos_webdriver_commands_for_safari_12_and_later?language=objc
So, the question: Is it possible use element.isDisplayed() with Safari 12? Am I miss something? If it's impossible, please share possible workarounds. Thanks
Update. From apple support:

Please know that our engineering team has determined that this issue
  behaves as intended based on the information provided.
If you need element.isDisplayed(), we recommend that you copy the atom
  into your repository and run it via Execute Script command. This is
  what later versions of Selenium libraries have started doing, because
  drivers do not necessarily ship it any more.

Clarification: In my tests selenium 2.52 is used


text:
Q: Is SharedPreferences a safe way of sharing settings between a service and the UI? Is SharedPreferences a safe way of sharing settings between a service and the UI?
I am calling commit() in a service and when I read the prefs in the UI 300ms later, the data is not there. This is on API 27.
I already use the Messenger for communicating between the service and the UI.
This is how I'm storing data on the services side:
  local e = context:getSharedPreferences("characters", context.MODE_PRIVATE):edit()
  e:putString("list", table.concat(names, "|"))
  log("saved these names in characters: %s", tstring(names))
  e:commit()
  local stuff = context:getSharedPreferences("characters", context.MODE_PRIVATE)

Retrieving it in the UI:
  charlist_settings = activity:getSharedPreferences("characters", activity.MODE_PRIVATE)
  log("refreshlist hit")
  if charlist_settings:contains("list") and charlist_settings:getString("list", "") ~= "" then
    [...]
  else
    log("no list in char_settings :(")
    log("all: %s", charlist_settings:getAll():toString())
  end

Service log, notice timestamp:
12-22 18:56:30.246 4142-4142/org.vadisystems.irehelper:Service I/IRE Helper: modified is: added
12-22 18:56:30.253 4142-4142/org.vadisystems.irehelper:Service I/IRE Helper: saved these names in characters: {"Vadimuses_Achaea"}

UI log, this is after a message is received from the service:
12-22 18:56:30.700 4120-4120/org.vadisystems.irehelper I/IRE Helper: refreshlist hit
12-22 18:56:30.701 4120-4120/org.vadisystems.irehelper I/IRE Helper: no list in char_settings :(
12-22 18:56:30.702 4120-4120/org.vadisystems.irehelper I/IRE Helper: all: {}

A: This should work, using either commit() or apply() based on the documentation. The change should be visible immediately between all in-process threads and components. However I have noted bugs in Android trying to do this between a Service and Activity in the past. Having you tried using getDefaultSharedPreferences() instead of a custom file. I have had no problems using the default file.

A: Not even restarting the activity worked to get the data after it has been commited. The only thing that did was restarting the application entirely. This was on API 27.

A: Use a local broadcast receiver, when the action is done, broadcast. On the listen side you have a class that takes care of persisting to SharedPreferences and also the UI can have a separate listener and update itself.
Sample Kotlin code
[EDIT] After suggesting using apply vs commit as a quick workaround relying on a in-memory cache layer that turned out not to be provided by SharedPreferences we are adjusting this answer to use a Local Broadcast receiver instead.


text:
Q: Conditional expectation of $X\sim U[0,2]$ given $\min(X,t)$, where $t\in [0,2]$. I want to determine the conditional expectation of $X\sim U[0,2]$ given $\min(X,t)$, where $t\in [0,2]$. Using the definition $$\mathbb E[X|\min(X,t)] = \frac{\mathbb E[X\chi_{\min(X,t)}]}{\mathbb P(\min(X,t))}$$
does not look that inviting to me. I am unsure if I should consider the probability for a specific value $\mathbb P(\min(X,t) = x)$ for $x\in [t,2]$ if the minimum is larger than $t$ or the probability that $\mathbb P(\min(X,t) \ne t)$
Intuitively I would say that since we know $t$ if $\min(X,t)$ is not $t$, it has to be $X$, and thus the conditional expectation has to be $\min(X,t) = X$ which seems tautological. If $\min(X,t)$ we know that $X>t$ and because $X\sim U[0,2]$ it follows that $X$ is uniformly distributed between $t$ and $2$. The conditional expectation, in that case, should be $\frac{2+t}{2}.$
Is this correct? If so, how does this follow from the definition given above?

A: Note that there is no such thing as $P[\min[X,t]]$ since $\min[X,t]$ is a random variable, not an event.

If we fix $t \in [0,2]$ and define $Y=\min[X,t]$ then $E[X|Y]$ is required to be a Borel measurable function of $Y$. One version of the conditional expectation is $$E[X|Y] = Y1_{\{Y<t\}} + \left(\frac{2+t}{2}\right)1_{\{Y\geq t\}} \quad \mbox{[Equation *]}$$ and any other version is the same as the above almost surely. Here I am using indicator functions of the type
$$ 1_{\{Y<t\}} = \left\{\begin{array}{cc}
1 & \mbox{if $Y<t$} \\
0 & \mbox{else}\end{array}\right.  $$
It is not formally correct to say
$$E[X|Y]=X1_{\{X\leq t\}} + \left(\frac{2+t}{2}\right)1_{\{X>t\}} \quad [\mbox{Incorrect equation}]$$
since, even though the right-hand-side is a random variable that is the same as the right-hand-side of equation (*) almost surely, it is not a function of $Y$ alone: What would be its value if $Y=t$?

Formal definitions of $E[X|Y]$ can be found in many places. The formal definition requires $E[X|Y]$ to be a Borel function of $Y$, and also some other requirements.
Informally, you can compute $E[X|Y]$ by using $E[X|Y]=g(Y)$ where $g(y)$ is a Borel measurable function that satisfies $g(y)=E[X|Y=y]$. This can usually be computed by considering either discrete or continuous cases for each relevant $y$.  In the above example, for $y=t$ we have $P[Y=t]>0$ so we compute $E[X|Y=t]$ using a standard conditional expectation given an event of positive probability:
$$ E[X|Y=t] = \frac{E[X1_{\{Y=t\}}]}{P[Y=t]}$$
which is consistent with the alternative computation $E[X|Y=t]=\int_0^2x f_{X|Y=t}(x)dx$.
If $y<t$ then $P[Y=y]=0$ and we use $f_{X|Y}(x|y)=\delta(x-y)$ to obtain $E[X|Y=y]=y$. You can verify the result (given in Equation (*)) is indeed a Borel measurable function of $Y$ and satisfies the other requirements for a conditional expectation given $Y$.

A: The conditional expectation is a random variable: essentially, $\mathbb{ E}[X|Y]$ is the random variable that takes the value "expectation of $X$ when $Y=y$" with probability $\mathbb{P}(Y=y)$. With probability $\frac{2-t}{2}$, $X$ is greater than $t$ so with this probability the random variable takes the value $\frac{2+t}{2}$ (your argument for the expectation in this stuation is correct). Then, from the case where $X$ is less than $t$, the random variable is equally likely to take every value in $[0, t]$ (is uniformly distributed on this interval), but with total probability $\frac{t}{2}$ (so with density $\frac{1}{2}$).


text:
Q: Adding a second trigger in task schedule Have a powershell script that will create a scheduled task, for deployment, by way of Octopus, to a Windows 2012 server.
Function Create-ScheduledTask($TaskName,$RunAsUser,$TaskRun,$Schedule,$StartTime,$StartDate,$Arguments,$RunWithElevatedPermissions,$Days,$Password){
    # set up
    $Command = "schtasks.exe /create /ru `"$RunAsUser`" /tn `"$TaskName`" /tr `"'$($TaskRun)' $Arguments`" $cmdSchedule $cmdDays $cmdStartDate $cmdStartTime /F $cmdInterval $cmdDuration $cmdRunLevel $cmdPassword"

    echo $Command
    Invoke-Expression $Command
 }

Attempting to add another trigger as part of the same taskname, on the command line, will not work with schtasks.exe which seemingly contradicts the GUI where it can be done.
This is the function that was used to create the event trigger, ideally, to attach that to the same scheduled task.
Function Create-ScheduledTaskEvent($TaskName,$RunAsUser,$TaskRun,$Arguments,$RunWithElevatedPermissions,$Password, $xPath, $channelName){

    $cmdRunLevel = if(-Not $RunWithElevatedPermissions){""}else{"/rl HIGHEST"}
    $cmdPassword = if([string]::IsNullOrEmpty($Password)){""}else{"/rp `"$Password`""}
    $cmdXPath = if([string]::IsNullOrEmpty($xPath)){""}else{"/sc ONEVENT /MO `"$xPath`" "}
    $cmdRunLevel = if(-Not $RunWithElevatedPermissions){""}else{"/rl HIGHEST"}

    $Command = "schtasks.exe /create $cmdRunLevel /ru `"$RunAsUser`" $cmdXPath /tn `"$TaskName`" /tr `"'$($TaskRun)' $Arguments`" /ec `"$channelName`" "

    echo $Command
    Invoke-Expression $Command
 }

Issue is, replacing the switch /create with /change only ends up clobbering the previous scheduled task's trigger/action.
Any idea how can this be done by way of schtasks.exe on the command-line, to combine the triggers into one.
It could be done by creating a separate task schedule with different taskname, it is not ideal though, nor is exporting out task as xml and then importing back in.

A: schtasks.exe won't allow you to do this via basic switches. In order to be able to do this with schtasks.exe you can use an XML import, of an existing task, as mentioned on SU.

Take an export of an existing task with the trigger set you want that you can import later. PowerShell can also natively understand xml files via the [xml] cast and Select-XML so you are not limited to static XML files but can also make changes on the fly to existing ones if you wanted.
Depending on what system you are working from you can also have access to the PowerShell task manipulation cmdlets like Register-ScheduledTask which does allow multiple tasks to be configured. These can be found on Windows Server 2012 R2 and Windows 8.1. To pull a small snippet from TechTarget

$triggers = @()
$triggers += New-ScheduledTaskTrigger -Daily -At 03:00
$triggers += New-ScheduledTaskTrigger -Daily -At 09:00
$triggers += New-ScheduledTaskTrigger -Daily -At 15:00
$triggers += New-ScheduledTaskTrigger -Daily -At 21:00

#..... code truncated to only show trigger portion

$action = New-ScheduledTaskAction -Execute $pstart -Argument $actionscript
Register-ScheduledTask -TaskName $taskname -Action $action -Trigger $triggers -RunLevel Highest -Description "Test job"

Since you tagged 2012 you might be able to run those cmdlets in a PSSession from your own system if it is not 8.1

A: I have similar task and most elegant solution that I found was to create the schedule task at test environment /local PC using the GUI and export it as XML. Then copy the XML formatted text and embedded it into the script, after execution the script save this string block as XML file locally and run schtasks.exe to create the new task.
schtasks.exe /create /RU "NT AUTHORITY\SYSTEM" /TN TaskName /XML "XMLFolder\TaskName.xml"


text:
Q: Function to delete selective row in dataframe I have a question.
I want to delete row in a dataframe but my function is deleting the wrong row. Sorry it is not the best code as I just start and the constant print are for my fault search.
#Reduce by a factor
    firstrow = int(in_csv.loc[in_csv.index[0]].name)
    lastrow = int(in_csv.loc[in_csv.index[-1]].name)

    for i in range (firstrow, lastrow+1):
        division = (i/reduce_factor)
        print (str(i) + " is " + str(division))
        print ("Division" + str(math.modf(division)))
        if ((math.modf(division)[0]) != 0):
            print (i)
            print (in_csv.iloc[i])
            i_drop = in_csv.loc[in_csv.index[i]].name
            print ("drop: " + str(i_drop))
            in_csv.drop([i], inplace=True)

The results is the following
5 is 2.5
Division(0.5, 2.0)
5
Time             5/11/20 12:01:32 AM
number                     1

Name: 7, dtype: object
drop: 7

For the calulation for row 5 it is dropping row 7, for row 7 it is 10, for row 3 it is row 4, for row 1 it is correct. So for every dropped row the fault is increasing by one row.
What is my fault?

A: I suppose that you should gather indices of rows to drop and perform the drop
after the loop.
But to be sure I have to know the content of your DataFrame, at least some
initial part of it, including the rows in question.


text:
Q: How to optimize calls to multiple APIs at once and return as one set? I have a web app that searches across 2 APIs right now.  I have my own Restful web service that I call, and it does all the work on the backend to asynchronously call the 2 APIs and concatenate them into one result set for my web app to use.
I want to scale this out and add as many other APIs as I can (currently looking at about 10 more).  But as I add APIs, the call to my service gets (potentially) slower and more complex.  How do I handle one API not responding ... and other issues that arise?
What would be the best way to approach this?  Should I create a service call for each API, that way each one is independent and not coupled to all the other calls?  Is there a way on the backend to handle the multiple API calls without all the extra complexity it adds?
If I go the route of a service call per API, now my client code gets more complex (and I have a lot of clients)?  And it's more work for the client, and since I have mobile apps, it will cost the client more data usage.
If I go one service call, is there a way to set up some sort of connection so I can return data as I get it, in case one service call hangs?

A: You need to look into threads and/or coroutines (Sometimes called fibers, goroutines, gevents, in different languages).
When a request comes in, you spawn off 10 threads/coroutines, then wait for them all to respond, or for a timeout. To the "web server", your request is simply sleeping for a few seconds. But other threads/coroutines are actively doing work.  If the work isn't done in N seconds, the threads/coroutines are killed off and only the results you have are returned.
Example in Go.
Threads are heavy weight (harder to scale), but generally better supported depending on the language. Coroutines are more efficient (less RAM, less CPU), but have problems on some languages/libraries.

A: How would you handle one of the API calls failing? If only some of the calls succeed is it still a valid response to the client?
Since websockets aren't widely supported and you are talking mobile platforms I think you have limited choices.
Long running requests
If the expected response is such that it may be processed in chunks before all requests complete, you may be able to stream the results in a single connection.
Ajax patterns provides some good information and examples for reading from a response stream before it has completed.
Using this approach, you would make a single request and handle the response as each API request completes.
Along with this, you will want to timeout individual API requests aggressively so that a hung service doesn't heavily impact your interface.
Yo don't want the client to timeout before done.
You could go as far as skipping calls for an expanding amount of time for any services which timeout or fail.
If it's an aggregated news feed or something this may make sense but you could poll and cache the feeds server side instead.
Long polling
Instead of a single request, you could make an initial request and then poll for additional data. This has the advantage of not holding the connection and appearance of being a push.
This would completely defeat your intent of limiting the number of connections.
In conclusion
With all this said, I still think you need to consider all the factors of your design.

*

*what is the upper limit of API calls that will be made behind this proxy? 10 may be ok but at 20 or 30 is this still the right design?

*do all clients need the data from all services? Are you saving a little at the expense of all?

*what is the quantifiable amount of bandwidth and processing time saved using the proxy for say 1000 requests? Is this worth it?

A: In systems like this, you always have to consider that as far as your code is powerful, at least a call will be delayed, and if your system is successful, that event will happen hundreds of times making your system slow, then maybe unstable.
I do not know the nature of the integration, maybe game providers, maybe social networks or anything else. But if your application is not academic, and it represents a real business requirements (in production) I think this is part of the things to do:
Before code

*

*if possible, all systems that are integrated, they must be aware of the timeouts that are demanded from you (anticipating this from a contractual point of view, it is a good idea mostly because no one guarantees 100% of up-time. It's myth).

*if point 1 is not possible, be objective and consider what we are willing to make our customers wait in front of the monitor (45 seconds, 10, 5, 2?). Found the value, we know how to set up the rest.

*Should be considered a constant calls/sub-calls prifile and logging;

*Should be planned for the possibility of suspending one or more services from the configuration (and not from code);

Technique
As for the technique, I think it is convenient to create a semaphore.

N functions will be called, the callback of each sub-function will be considered only if time set for each integration are respected.

So,

*

*A call is made to the main function,

*This considers what services are enabled to be contacted,

*The callback functions are configured,

*The sub-functions are called,

*While making calls, and while the general timer has not expired, all callbacks are considered to be unified in the response of the main function.


text:
Q: Greek characters in vectors, lists and data frames Under the specs listed below, data.frame objects convert greek characters to latin equivalents when the table is printed. For instance,
w<-data.frame(A=c("σ", "a", "b"))
print(w)
#    A
# 1: s
# 2: a
# 3: b

The same happens if "σ" is replaced by "\U03C3".
data.frame seems to treat "σ" and "s" interchangeably:
w<-data.frame(σ=1:4)
w$σ
# [1] 1 2 3 4
w$s
# [1] 1 2 3 4

But when it comes to printing, it favors the latin version.
However, vectors (together with lists) show a slightly different behaviour:
x=c("σ", "a", "b")
x
# [1] "s" "a" "b"
x=c("\U03C3", "a", "b")
x
# [1] "σ" "a" "b"

Is there a way, to force data.frame objects to print "σ" instead of "s"?

Output of
sessionInfo()
# R version 3.4.4 (2018-03-15)
# Platform: x86_64-w64-mingw32/x64 (64-bit)
# Running under: Windows >= 8 x64 (build 9200)

# Matrix products: default

# locale:
# [1] LC_COLLATE=German_Switzerland.1252LC_CTYPE=German_Switzerland.1252        LC_MONETARY=German_Switzerland.1252 LC_NUMERIC=C
# [5] LC_TIME=German_Switzerland.1252

# attached base packages:
# [1] stats     graphics  grDevices utils     datasets  methods   base

# other attached packages:
# [1] openxlsx_4.1.0    data.table_1.11.4

# loaded via a namespace (and not attached):
# [1] compiler_3.4.4 tools_3.4.4    Rcpp_0.12.19   zip_1.0.0


text:
Q: .NET DropDownList SelectedIndexChange Event Not Firing in IE 10 In IE 10, when a drop down list selected item is changed, nothing happens. It doesn't post back. All other controls work except for drop down lists.
It appears to work when I switch to IE 10 compatibility mode.

A: Scott Hanselman explains this on his blog.
http://www.hanselman.com/blog/BugAndFixASPNETFailsToDetectIE10CausingDoPostBackIsUndefinedJavaScriptErrorOrMaintainFF5ScrollbarPosition.aspx

A: Do you have the ASP.net Hotfix for IE10 installed?

A: Ok, this was a weird issue. The actual problem was that we had a web.config sitting in the very root of the application that had OLD, I'm talking ANCIENT browserCap definitions in there. I'm talking browserCap definitions for Windows TV kind of old.
We removed the browserCap definitions in this file, and all was fine.
If you run into this error, please check for any browser caps that are not in the immediate folder of your project (if you have that sort of setup).
The link in Michael's answer will most likely take care of you if you're experiencing this problem and do not have multiple web.config's in your project.


text:
Q: Lambda function to use in dataframe I have the following vector
3
5
6
7
4
6
7
8

And I would like to implement a lambda function that given a vector element i , computes the mean value of i-3 ,i-2 i-1 and ith element. But I do not know how can I access the i-3, i-2, i-1 elements in the lambda function.

A: You can use the rolling() method to access the elements of a Pandas series within a specified window. Then, you can use a lambda function to calculate the mean for the elements in that window. In order to include the three elements to the left of the current element, you use a window size of 4:
In [39]: import pandas as pd

In [40]: S = pd.Series([3, 5, 6, 7, 4, 6, 7, 8])

In [41]: S.rolling(4).apply(lambda x: pd.np.mean(x))
Out[41]:
0     NaN
1     NaN
2     NaN
3    5.25
4    5.50
5    5.75
6    6.00
7    6.25
dtype: float64

You'll note that there are missing values for the first three elements. This is so because you can only start to form a window of the size 4 from the fourth element onwards. However, if you want to calculate with smaller windows for the first elements, you can use the argument min_periods to specify the smallest valid window size:
In [42]: S.rolling(4, min_periods=1).apply(lambda x: pd.np.mean(x))
Out[42]:
0    3.000000
1    4.000000
2    4.666667
3    5.250000
4    5.500000
5    5.750000
6    6.000000
7    6.250000
dtype: float64

Having said that, you don't need the lambda in the first place – I included it only because you explicitly asked for lambdas. The method rolling() creates a Rolling object that has a built-in mean function that you can use, like so:
In [43]: S.rolling(4).mean()
Out[43]:
0     NaN
1     NaN
2     NaN
3    5.25
4    5.50
5    5.75
6    6.00
7    6.25
dtype: float64

A: if you want to do it on a pandas dataframe the easiest way is to use .loc, assuming you know the index position of i.
 import pandas as pd

 df = pd.DataFrame([3, 5, 6, 7, 4, 6, 7 ,8])
 setx = lambda x: df.loc[x:x-3:-1].mean()
 # x is the index position of your target value.
 > setx(4) # Without mean() gives values [4, 7, 6, 5]
 >> 5.5

Although if you want to stick with PEP8 standards it is best to define a function and avoid lambda in cases where (see python.org/dev/peps/pep-0008/#id50), assigning functions to an identifier by means of a lambda expression that is advised against in PEP8. Thank you @Schmuddi for the clarification.


text:
Q: Bulk update the product attributes using Magento 2 import tool - Product SKU / Custom Product Attribute Bulk update the product attributes using Magento import tool:

The Required fields(CSV) are:

1) Product SKU (required)
2) Custom Product Attribute (use the custom attribute that needs to be imported.)
Yes, we can import it easily, SKU is mandatory and other, you can use a custom attribute that needs to be imported.
NOTE: In M2, use the google spreadsheet product CSV to import the Products.
thanks!

Nithin Ninan
nithincninan@gmail.com
9895382293


text:
Q: Could not find Akavache GetObjectAsync method I've installed akavache Nuget package (tried v5.0 and v6.0.0-alpha and I am using .NET Standard), but don't have access to GetObjectAsync mentioned in many examples through the web. (Even on the official page).
I am considering this is rather not Akavache's methods but Rx extensions or something, but could not find if (and where) I can use it.
For instance, BlobCache.UserAccount just doesn't have it and I am shown syntax error.
Any clue?

A: GetObjectAsync was removed from Akavache because System.Reactive provides the means to convert an Observable in to a Task. In fact, an Observable can even be awaited.
GetObject returns an IObservable and can be used in place of GetObjectAsync, so long as the System.Reactive.Linq namespace is imported.
var obj = await BlobCache.UserAccount.GetObjectAsync("toaster"); // old style
var obj = await BlobCache.UserAccount.GetObject("toaster"); // new style

Note: An awaited Observable is expected to OnNext a single value only. If OnNext is invoked 2 or more times, or not at all, an exception will be thrown. OnError will also cause an exception to be thrown.
The documentation has been updated to exclude GetObjectAsync as of 2018.08.28.


text:
Q: How to parse Google Distance Matrix API JSON in IOS SWIFT 3 the correct way I have searched a lot to correctly parse a multi dimensional JSON arrays in swift. From the search results , what i could grasp was that it some what similar to retro-fit parsing in Android. i.e  creating a parsing class for each json response. Please excuse me if i am making a mistake. I am new to IOS swif.
This is the distance matrix api json output for my distance call
{
  "destination_addresses" : [ "My Destination" ],
  "origin_addresses" : [
     "My Source"
  ],
  "rows" : [
     {
        "elements" : [
           {
              "distance" : {
                 "text" : "23.3 km",
                 "value" : 23333  //lastly i take this
              },
              "duration" : {
                 "text" : "49 mins",
                 "value" : 2938
              },
              "status" : "OK"    //then i check this
           }
        ]
     }
  ],
  "status" : "OK"    //first i check this
}

This how i did it
This is my api call(works fine)
http://maps.googleapis.com/maps/api/distancematrix/json?origins=latitude,longitude&destinations=latitude,longitude&mode=driving&language=en-EN&sensor=false
func extract_Validate(jsonData:NSData)
    {
        var distInMeters = 0
        var chkVarOne = "notOK"
        let json1 = NSString(data: jsonData as Data, encoding: String.Encoding.utf8.rawValue)
        let data = json1!.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)
        print(data!)
        do{
            print("Inside do")
            let json = try JSONSerialization.jsonObject(with: jsonData as Data, options:.allowFragments) as! NSObject
            if let dictionary = json as? [String: Any] {
                print("inside dictionary ")
                if let detailsDict = dictionary as? NSDictionary {
                    print("Parse Data")

                    for (key, value) in detailsDict {

                        print("Property: \"\(key as! String)\"")
                        if key as! String == "status" && value as! String == "OK"{
                        chkVarOne = "OK"
                        }
                        if chkVarOne == "OK"
                        {
                        if key as! String == "rows"
                        {
                            if let elementsDict = value as? NSDictionary {
                            for(keyEle, valueEle) in elementsDict{
                            }
                        }
                            if let elementsDict = value as? NSArray
                            {
                                if let array = elementsDict as? [Any] {
                                    if let firstObject = array.first {

                                        if let distanceSet  = firstObject as? NSDictionary{

                                            for(keyDis, valueDis) in distanceSet{

                                                  // print("Property: \"\(keyDis as! String)\"")
                                                if keyDis as! String == "elements"
                                                {
                                                    if let DistDict = valueDis as? NSDictionary {

                                                        for(keyDict, valueDict) in DistDict{

                                                               print("Property: \"\(keyDict as! String)\"")
                                                        }
                                                    }

                                                    if let DistDict = valueDis as? NSArray {

                                                       // print(DistDict)

                                                        if let distArr = DistDict as?[Any]{

                                                            if let frst = distArr.first{
                                                                //print(frst)
                                                                if let distOne = frst as? NSDictionary{
                                                                    var checkvar = "notOK"
                                                                    for(ketOneDis, valOneDis) in distOne{

                                                                       // print("Property: \"\(ketOneDis as! String)\"", valOneDis)

                                                                        if ketOneDis as! String == "status" && valOneDis as! String == "OK"{

                                                                          checkvar = "OK"

                                                                        }

                                                                        if checkvar == "OK"
                                                                        {
                                                                            if ketOneDis as! String == "distance"
                                                                            {
                                                                               // print(valOneDis)

                                                                                if let valtwoDis = valOneDis as? NSDictionary{
                                                                                for(kDis, vDis) in valtwoDis{
                                                                                //  print("Property: \"\(kDis as! String)\"", vDis)

                                                                                if kDis as! String == "value"{

                                                                                distInMeters = vDis as! Int
                                                                                }
                                                                                }
                                                                                if let valTwoDis = valOneDis as? NSArray{
                                                                                print(valTwoDis)
                                                                                }
                                                                            }
                                                                        }

                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                         //print(distanceSet,"rttgtgtgtgtgtgtg")
                                        }
                                        if let distSet = firstObject as? NSArray{
                                            print(distSet,"dfdffddfdfdfd")
                                        }
                                    }

                                }
                            }
                        }

                        //let rows
                    }
                  }
                } //ending here
            }
          }
        }
        catch{
            print("error in JSONSerialization")
        }

        print(distInMeters," is the resulting value")

    }

This code is working fine fine. But i know this is not the way to do it.
So please help me
I think there might be some errors occur in this code later. Don't know for sure

A: The easiest and most effective way to do this is by using object mapping. Something like Gloss (https://github.com/hkellaway/Gloss) would do the trick. In your case you will have the following classes (objects):
Response
  import Foundation
import Gloss

//MARK: - Response
public struct Response: Glossy {

    public let destinationAddresses : [String]!
    public let originAddresses : [String]!
    public let rows : [Row]!
    public let status : String!

    //MARK: Decodable
    public init?(json: JSON){
        destinationAddresses = "destination_addresses" <~~ json
        originAddresses = "origin_addresses" <~~ json
        rows = "rows" <~~ json
        status = "status" <~~ json
    }

    //MARK: Encodable
    public func toJSON() -> JSON? {
        return jsonify([
        "destination_addresses" ~~> destinationAddresses,
        "origin_addresses" ~~> originAddresses,
        "rows" ~~> rows,
        "status" ~~> status,
        ])
    }

}

Element:
import Foundation
import Gloss

//MARK: - Element
public struct Element: Glossy {

    public let distance : Distance!
    public let duration : Distance!
    public let status : String!

    //MARK: Decodable
    public init?(json: JSON){
        distance = "distance" <~~ json
        duration = "duration" <~~ json
        status = "status" <~~ json
    }

    //MARK: Encodable
    public func toJSON() -> JSON? {
        return jsonify([
        "distance" ~~> distance,
        "duration" ~~> duration,
        "status" ~~> status,
        ])
    }

}

Row:
import Foundation
import Gloss

//MARK: - Row
public struct Row: Glossy {

    public let elements : [Element]!

    //MARK: Decodable
    public init?(json: JSON){
        elements = "elements" <~~ json
    }

    //MARK: Encodable
    public func toJSON() -> JSON? {
        return jsonify([
        "elements" ~~> elements,
        ])
    }

}

Distance:
import Foundation
import Gloss

//MARK: - Distance
public struct Distance: Glossy {

    public let text : String!
    public let value : Int!

    //MARK: Decodable
    public init?(json: JSON){
        text = "text" <~~ json
        value = "value" <~~ json
    }

    //MARK: Encodable
    public func toJSON() -> JSON? {
        return jsonify([
        "text" ~~> text,
        "value" ~~> value,
        ])
    }

}

After creating the classes, you map the JSON to the Object by doing the following:
let jsonResponse = ..//Your JSON response
guard let distanceResponse = Response(json: jsonResponse) else {
    // handle decoding failure here
}
//You can use the distanceResponse object here as an object and access it's values.

Learn more about object mapping in this tutorial: https://www.raywenderlich.com/150322/swift-json-tutorial-2


text:
Q: Multiple call to startService() If more calls to startService() are made simultaneously from various components how are they resolved? I mean the second call waits from the first call to finish executing onStartCommand(), the third for the second etc....or not?
I'm getting confused because of this declaration from the offical docs:

However, because you handle each call to onStartCommand() yourself, you can perform multiple requests simultaneously.


text:
Q: Custom URL with form I am working on codeigniter, and have a search bar that I want to map to a search class in a controller. The URL currently is search/searchterm. I want to build out a form that adheres to this and would esentially just take whatever is in the form and pass it to the URL. I've tried just doing a javascript relocation onsubmit like this:
document.location.href= "<?= base_url() ?>" + document.forms["searchbox"]["search"].value

but it doesn't seem to work. What do you guys recommend as the best for something like this? I'm sure tons of people require something similar to what I want in their projects.

A: Here is another sample. It is a valid xhtml document and searches in google whatever you type in the search box. It works in FF10, IE8, Chrome 17 and Opera 11.61.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Search</title>

    <form id="form1" method="post" action="">

            Search:
            <input type="text" id="searchText" name="searchText" />
            <input type="submit" value="Click" />

    </form>

A: That would work if it was not inside a form, to do that inside a form you need to set the onsubmit event to set the appropriate action to the form.
Here is a simple working example:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title></title>

    <form  id="searchbox" onsubmit="foo()" >
        <input type="text" id="search" />
        <input type="submit" />
    </form>


text:
Q: When No Active Bounties, the List is Redundant! Right now (at least as of two minutes ago) on Meta, there aren't any questions with active bounties. I clicked on the Featured tab, and this is what I see:

Looks normal, right? So I clicked on the "complete list" link, and now this is what I see:

It doesn't look "wrong", but how is "recent questions" different from "all questions" in terms of Featured questions, even with reputation?
UPDATE: Thanks to the first answer, I now realize that the Recent Questions Featured tab indicates bounties ending soon, while that of All Questions shows all of bounties. However, now I have a small feature/change request - wouldn't it be better to not have that link from Recent Questions if there aren't any bounties at all?
UPDATE #2: Also, Wim had a very good comment:

I think he means that, when both lists are empty, it's a little pointless to link to "All Questions". A "No Featured questions at this time" message would be more clear I guess.

Is that a good idea? I think so!

A: Look at Stack Overflow and you will understand. The featured list shows by default only one page with the questions where the bounty will end soon. If you want to see more than one page you have to click the "See All (featured) Questions" link (aka "complete list").
If the "pointless link" is bugging you, then I suggest: Don't bother! This is only an issue on Meta. I doubt that this will become visible on SO. There are always bounties.


text:
Q: Windows Authentication - Getting current user name In my MVC application I want to render a table in a cshtml file, if the current log in user is some x person. I am using windows authentication and I have made the following changes in web.config file.
<authentication mode="Windows">
      </authentication>

And in my controller when I am trying to access the current user name I am not getting any user name. I am trying the following:
ViewBag.LogInUserName = Request.RequestContext.HttpContext.User.Identity.Name;

This above line was working before. But I don't know whats wrong now. Also I have hosted my application on IIS now.

A: Take a look at the web project's properties, in particular:

*

*Anonymous Authentication - Set to "Disabled"

*Windows Authentication - Set to "Enabled"

By default these are set to the opposite of what you're probably looking for.

(Image sourced from MSDN)

A: You need to put the [Authorize] attribute on your controller.
You can use User.Identity.Name in your controllers.
[Authorize]
public class YourController : Controller
{

    public ActionResult SomeAction()
    {
        var userName = User.Identity.Name;
    }
}

A: A little bit late, but this may serve others in the future.
I had the same problem once after deploying my site to a new IIS server, and the anonymous authentication was enabled, so make sure that anonymous authentication is disabled and it should work.


text:
Q: Intellij IDEA Web Project deployment Created a new Java Web Project from a scratch in Intellij IDEA, changed nothing here, and found out that my project starts by default at localhost:8080/ in contrast to Eclipse, NetBeans, for example, where the project starts at localhost:8080/WEB_PROJECT_NAME.
The thing is that the default file index.jsp is always correctly displayed at localhost:8080/index.jsp
But I always got a 404 error, trying to access localhost:8080/WEB_PROJECT_NAME/index.jsp
Therefore, I have no opportunity to run any servlets or smth else.
Anything I try to access via localhost:8080/WEB_PROJECT_NAME/... gives me an error.
Here are my Run/Debug configurations:

A: Click on the Deployment tab shown on your screenshot, you can specify the context for your web application there, lile /WEB_PROJECT_NAME instead of the default / (ROOT).


text:
Q: How to add breadcrumbs in product category and product details page in Magento 2? I have added the following code to the following file.

app/design/frontend/Emthemes/everything/diamond/Magento_Catalog/layout/default.xml

<move element="breadcrumbs" destination="content" before="-" />

But it's not working for me.
Anyone can help me regarding this.

A: as @Suresh Chikani mentioned in the comment, breadcrumbs are displayed OOTB in those places(product page & category), if it's not then somebody removed it.
It could be removed in few ways
1) somebody removed the parent block in which the block containing your   functionality was, in this case just "move" the block containing your desired functionality to a different existing block/container
2) somebody removed the block, you need to find the code and change it or add a new block as you done in your answer.
3) Somebody could rewrite the block class (Magento\Theme\Block\Html\Breadcrumbs) itself and override the toHtml function or any other that is responsible for displaying content.
Look in
di.xml

for
Magento\Theme\Block\Html\Breadcrumbs

if nothing is found then no one rewritten it.
4) Somebody could rewritten
vendor/magento/module-theme/view/frontend/layout/default.xml

Where the setup of breadcrumbs originally takes place.
https://devdocs.magento.com/guides/v2.3/frontend-dev-guide/layouts/layout-override.html
And going back to your question, if you want only add it only category &  product page then you should add it to
catalog_product_view.xml
catalog_category_view.xml

not to default.xml

A: Try below code to display breadcrumbs on list or detail page
<move element="breadcrumbs" destination="page.top"  />

A: Added the following code to this path:

app/design/frontend/Emthemes/everything/diamond/Magento_Theme/layout/default.xml

<referenceContainer name="page.top">
                <block class="Magento\Theme\Block\Html\Breadcrumbs" name="breadcrumbs" as="breadcrumbs"/>
        </referenceContainer>


text:
Q: How do I create fixtures for ActiveStorage variants for Rspec? Summary
On a personal project, I have a view that references an ActiveStorage resource's variant, based on viewport size. I'm trying to ensure that the views use the correct variants in the specs as well, but am running into NoMethodError problems.
Breakdown
For example, with the following view partial:
<div>
  <%= image_tag @post.image.variant(:web).processed.url %>
</div>

And this spec:
feature 'Posts', type: :feature do
  fixtures :posts, :users

  scenario 'Accessing a public post via ID' do
    visit post_path(posts(:one).id)
    expect(page).to have_css("#post-#{posts(:one).id}")
  end
end

And these fixtures (defined as per the official guide):
posts.yml:
one:
  user: rafael
  filter: gotham
  private: false
  caption: This is a beautiful fixture

active_storage/attachments.yml:
one:
  name: image
  record: rafael (User)
  blob: one_blob

active_storage/blobs.yml:
one_blob:
  <%= ActiveStorage::FixtureSet.blob filename: 'storage/brighton-pier.jpg', service_name: 'test' %>

The views fail to render with:
NoMethodError:
  undefined method `processed' for nil:NilClass

This makes sense, because the fixtures do not have variants defined.
Edit #1
The Post model has a set of predefined variants:
class Post < ApplicationRecord
  belongs_to :user
  has_many :comments, dependent: :destroy
  has_one_attached :image, dependent: :destroy do |attachable|
    attachable.variant :web, resize_to_fill: [1200, 1200, { crop: :attention }]
    attachable.variant :opengraph, resize_to_fill: [200, 630, { crop: :attention }]
    attachable.variant :twitter, resize_to_fill: [1024, 512, { crop: :attention }]
    attachable.variant :mobile, resize_to_fill: [600, 600, { crop: :attention }]
    attachable.variant :thumb, resize_to_fill: [100, 100, { crop: :attention }]
  end

  ...
end

Question
How do I add variants to my ActiveStorage fixtures?


text:
Q: Postman changing line endings when exporting JSON collection file from CR LF (Windows) to LF (Unix) Issue
Postman is changing line endings when exporting a JSON collection file from CR LF (Windows) to LF (Unix) and this is a causing Warning when I try to commit the file to git.
Has anyone come across this before and is there a solution other than the work around that I outline below?
Specs

*

*Windows 10

*Postman version 8.0.3

*Notepad++ version 7.9.1

Steps to reproduce

*

*Ensure Postman collection JSON file has CR LF (Windows) line endings using Notepad++ as shown in screen grab 1

*Import Postman collection file to Scratchpad Workspace

*Make a small change like rename a Request (this is automatically saved)

*Export the collection and save/replace it back to the original file that was imported

*Go back to Notepad++ and you will be asked to reload the file, which you "yes" to

*Check that the Postman collection JSON file has now unexpectedly changed  CR LF (Windows) line endings to LF (Unix) line endings using Notepad++ as shown in screen grab 1

*Stage the file in git and you will see the Warning in screen grab 2. Note, I'm using Git Extensions here but you will see the same Warning on the command line.
.gitattributes
My .gitattributes file has the following entries:
* text=auto encoding=UTF-8
*.sh text eol=lf
*.service text eol=lf

*

*text=auto encoding=UTF-8 is setting the default behaviour of text/JSON files

Work around
To avoid the Warning, I have to do the following every time I want to change/export and git commit a Postman collection file, which I'm sure I shouldn't need to do. (A colleague of mine has the same behaviour when I checked on his machine).

*

*After Steps to reproduce above, un-stage the file in git

*Use Notepad++ to change the Postman file back from having LF (Unix) line endings to having CR LF (Windows) line endings using Notepad++

*Save the file in Notepad++

*Stage the file in git and the Warning will have gone
Screen grabs
Screen grab 1

Screen grab 2

Links
LF will be replaced by CRLF in git - What is that and is it important?
Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?
https://github.com/postmanlabs/postman-app-support/issues/190
https://github.com/postmanlabs/postman-app-support/issues/726
https://github.com/postmanlabs/postman-app-support/issues/4179


text:
Q: How to take and handle object from multiple threads in Java? How to create Multiple instances of Future I need to create bunch of JMX connections to different hosts. I'm trying to create these connections in parallel. In this performance is much better now.
I've method to which I'm passing Collection of "host and port" entries. For each entry one connection will be created.
Now I'm submitting this task of creating connections to Multiple threads. But I don't know how to take return and store the connection objects created by threads.
code goes like this,
ConnectionFactory.createConnections(collection of hostportEntries)

class ConnectionFactory{

public static CollectionOfConnections createConnections(ListOfHostPorts)
{

   ExecutorService exec = Executors.newFixedThreadPool(4);

   for(iterate over hostportEntries)
   {
     Future<Connection> future1 = exec.submit(new connCreator(HostPortEntry));

      //Now here, connCreator is implementing Callable Interface and creating connection. and returning it. I'm taking reference of that Returned connection.
//But how will I take              Multiple Connection objects returned by Multiple threads. I tried to create Future[] but OPTION like that doesn't seem to be there
      // Can anybody help here?????

   }

//if I succeed in getting the objects return then I'll store in one more collection and return those for further use of those connections.

}

A: Take a look at ThreadPool's invokeAll method - it takes a collection of Callables and returns a list of Futures.
Edit: the advantage of using invokeAll over simply submitting your tasks one at a time and putting the Futures in your own list is that invokeAll will return only after all of the tasks complete, so you don't have to keep checking all of the Futures to see if they have completed.

A: Once each thread (your ConnectionCreator) creates a connection, it needs to register the handle to the newly created connection with a singleton of some sort.  If you are running within an EJB container, this is easily accomplished with a session bean.  Essentially, this session bean could become the "connection pool".  Within the connection creator, you could do the following (For brevity, I am excluding exception handling and other things you should already be doing):
Inside of ConnectionCreator
============================

// Create your connection
Connection myConnection = doWhateverToCreateConnection();

// Presuming things went fine, get a handle to the session bean.  You could
// also potentially do this through resource injection using Spring or what not.
Context ctx = new InitialContext();
ConnectionPoolBean connectionPoolBean = ( ConnectionPoolBean )ctx.lookup( "java:module/ConnectionPoolBean" );

// Now, register the connection with the pool
connectionPoolBean.registerConnection( myConnection );

Then in your ConnectionPoolBean, you hold a collection of connection objects.  You should have register and unregister methods in those objects -- as well as possible getConnection... et cetera.  Hope that helps.

A: According to this javadoc Future<V> has .get() method that returns an object of type of V. You should invoke that method to receive the result of Future execution. It's safe to invoke it from callee thread.

A: You can use ExecutorCompletionService to run your connection openers and get them in order of the one who opens connection first :)
So, with your code, it would be something like
ExecutorService exec = Executors.newFixedThreadPool(4);
CompletionService<Result> ecs
       = new ExecutorCompletionService<Result>(exec);

for (HostPortEntry hpe : hostportEntries) { ecs.submit(new ConnCreator(hpe)); }

Collection<Connection> connections = new ArrayList<Connection>(hostportEntries.size());
for (int i = 0; i < hostportEntries.size(); i++) {
    // will add the created connections in order of what finish first.
    connections.add(ecs.take().get());
}
return connections;

Hope this helps :)
EDIT
IMPORTANT: you could not use CompletionService and Executor#submit. The thing is that your call to Future#get() must be done in another loop, or you will block your thread until the just submitted callable has finish. So:
Collection<Future> connCreatorsFuture = new ArrayList<Future<Connection>>(hostportEntries.size());
for (HostPortEntry hpe : hostportEntries) { connCreatorsFuture.add(exec.submit(new ConnCreator(hpe))); }

Collection<Connection> connections = new ArrayList<Connection>(hostportEntries.size());
for (Future<Connection> connection : connCreatorsFuture) {
    // will wait until this connCreator finishes.
    connections.add(connection.get());
}
return connections;


text:
Q: Group a json data into list based on key trailing number I got a json result as shown in image 1 but I need an output shown in image 2.

I took the following classes
public class NameDTO
        {
            public string Name;
        }

        public class ValDTO
        {
            public string Val;
        }

I got the list to the above classes as shown in figure 3 and 4 and combining them and converting to json.

var combined1 = _nameDetials1.Zip(_valDetials1, (name1, val1) => new { name1.Name, val1.Val })                                               .ToDictionary(k => k.Name, k => k.Val);

var jsonSerialiser1 = new JavaScriptSerializer();
var json1 = jsonSerialiser1.Serialize(combined1);

How can I do the grouping so that I can get he correct output as shown in image2
Thanks.

A: If it is possible you can use Json.NET.
Here an example to solve your problem.
const string JSON = @"{
    ""message-Code-1"": ""000"",
    ""msg-Number-Pos1-1"": ""0000"",
    ""msg-Number-Pos2-1"": ""1"",
    ""msg-Number-Pos3-1"": ""1"",
    ""message-Code-2"": ""1"",
    ""msg-Number-Pos1-2"": ""0001"",
    ""msg-Number-Pos2-2"": ""2"",
    ""msg-Number-Pos3-2"": ""1"",
    ""message-Code-3"": ""0002"",
    ""msg-Number-Pos1-3"": ""3"",
    ""msg-Number-Pos2-3"": ""1"",
    ""msg-Number-Pos3-3"": ""1"",
    ""message-Code-4"": ""0003"",
    ""msg-Number-Pos1-4"": ""3"",
    ""msg-Number-Pos2-4"": ""1"",
    ""msg-Number-Pos3-4"": ""1""
}";

JObject loMessages = JObject.Parse(JSON);
JArray loMessageArray = new JArray();
JObject loAddMessage;
foreach (var loMessageGroup in loMessages.Properties().GroupBy(item => Regex.Match(item.Name,@".*-(?<pos>\d+)").Groups["pos"].Value))
{
    loAddMessage = new JObject();
    foreach (var loMessage in loMessageGroup)
        loAddMessage[loMessage.Name] = loMessage.Value.ToString();
    loMessageArray.Add(loAddMessage);
}
Console.WriteLine(loMessageArray.ToString());

The Json Ouput is like this:
[
  {
    "message-Code-1": "000",
    "msg-Number-Pos1-1": "0000",
    "msg-Number-Pos2-1": "1",
    "msg-Number-Pos3-1": "1"
  },
  {
    "message-Code-2": "1",
    "msg-Number-Pos1-2": "0001",
    "msg-Number-Pos2-2": "2",
    "msg-Number-Pos3-2": "1"
  },
  {
    "message-Code-3": "0002",
    "msg-Number-Pos1-3": "3",
    "msg-Number-Pos2-3": "1",
    "msg-Number-Pos3-3": "1"
  },
  {
    "message-Code-4": "0003",
    "msg-Number-Pos1-4": "3",
    "msg-Number-Pos2-4": "1",
    "msg-Number-Pos3-4": "1"
  }
]


text:
Q: How to add different datasource to two different colums in c# I have a ListView in which I have added two columns. One column is simple and one column has the Free 3 of 9 Font as I want to convert the values of column one into BarCode and then show them into the second column. I want to fill the Datasource of the ListView with the help of a List.
Now my question is that how can I set the Datasources of a single column of ListView as I have to convert the values of that columns to BarCode and then show it in other column.
I am now only setting the Datasource of the whole of the ListView as I have added the columns after that.
My code is as follows what I am trying to do
      private void GenerateButton_Click(object sender, EventArgs e)
      {
         List<string> SerialNumberList = new List<string>();
         int SerialNumberStart = Convert.ToInt32(Regex.Replace(StartSerialBox.Text, "[^0-9]+", string.Empty));

         int SerialLimit = Convert.ToInt32(LimitBox.Text);
         for (int i = 0; i < SerialLimit;i++ )
         {
           SerialNumberStart++;
           SerialNumberList.Add("S" + SerialNumberStart);
         }
        for (int j = 0; j < SerialNumberList.Count;j++ )
        {

            Adapter.insertserialnumbers(SerialNumberList[j], DateTime.Now.ToString());

        }
         radListView1.DataSource = SerialNumberList;
       }

I want that both columns should have separate List as Datasource and only the Font of the second column should be changed.

A: Here's the sample with DataGridView:
    private void Form1_Load(object sender, EventArgs e)
    {
        var dataGridView = new DataGridView
        {
            AutoGenerateColumns = false,
            DataSource = new List<string>
            {
                "Red",
                "Green",
                "Blue"
            }
            .Select(s => Tuple.Create(s))
            .ToList()
        };

        var columnA = new DataGridViewTextBoxColumn
        {
            HeaderText = "Column A",
            DataPropertyName = "Item1"
        };

        var columnB = new DataGridViewTextBoxColumn
        {
            HeaderText = "Column B",
            DataPropertyName = "Item1",
        };

        columnB.DefaultCellStyle.Font = new System.Drawing.Font("Times New Roman", 14);

        dataGridView.Columns.Add(columnA);
        dataGridView.Columns.Add(columnB);

        Controls.Add(dataGridView);
    }

DGV can't be bound to the list of strings directly, because data binding for the particular column needs a data property name, which to bind to. So, I'm using a wrapper here (a Tuple<string>).
Is this what you want?
P.S. Of course, you can use designer as well. The sample creates DGV in code to show, what's happening.


text:
Q: Polymorphism in Laravel? for example I have model Message with these columns:
messages
- id
- body
- type
- created_at
- updated_at

And such a controller:
class MessageController extends Controller
{

    /**
     * Display the specified resource.
     *
     * @param  \App\Message  $message
     * @return \Illuminate\Http\Response
     */
    public function show(Message $message)
    {
        switch ($message->type) {
            case 'info':
                $color = 'blue';
                // updated - lots of code here!
                break;
            case 'warning':
                $color = 'yellow';
                // updated - lots of code here!
                break;

            .
            .
            .

            case 'danger':
                $color = 'red';
                // updated - lots of code here!
                break;
            default:
                $color = 'gray';
                // updated - lots of code here!
        }
        return view('messages.show',compact(['message','color']));
    }

}

and as you see my problem is this long switch. I tried searching and I found that Polymorphism could help me to avoid this long switch, but I did not find out how to implement it how much I went and all my searches ended in Polymorphic Relations in Laravel that was not my answer.
would you help me to do something like this:
class MessageController extends Controller
{

    /**
     * Display the specified resource.
     *
     * @param  \App\Message  $message
     * @return \Illuminate\Http\Response
     */
    public function show(Message $message)
    {
        $color = $message->[something?]->color();
        return view('messages.show',compact(['message','color']));
    }

}

Update: As I wrote at beginning, It's just an example and switch case block will contain more lines of code.

A: You can use some sort of 'strategy pattern' to improve your code, creating some services to handle the calculation of the color for each type on message (each strategy), and then one 'delegator' service that decides which service to call, based on the message type...
First you need an interface for all your calculators:
interface ColorCalculatorInterface
{
    public function calculateColor(Message $message);

    public function getSupportedMessageType();
}

Then one service for each strategy:
class InfoColorCalculator implements ColorCalculatorInterface
{
    public function getSupportedMessageType()
    {
        return 'info';
    }

    public function calculateColor(Message $message)
    {
        // lots of code here!
        return 'blue';
    }
}

class WarningColorCalculator implements ColorCalculatorInterface
{
    public function getSupportedMessageType()
    {
        return 'warning';
    }

    public function calculateColor(Message $message)
    {
        // lots of code here!
        return 'yellow';
    }
}

// More calculators...

class DefaultColorCalculator implements ColorCalculatorInterface
{
    public function getSupportedMessageType()
    {
        return 'default';
    }

    public function calculateColor(Message $message)
    {
        // lots of code here!
        return 'grey';
    }
}

And finally one service that decides which strategy to use based on the message type (this code could be directly into the controller, but it's cleaner as a separate service):
class ColorCalculator
{

    private $calculators = [];
    private $defaultCalculator;

    public function setDefaultColorCalculator(ColorCalculatorInterface $calculator)
    {
        $this->defaultCalculator = $calculator;
    }

    public function registerColorCalculator(ColorCalculatorInterface $calculator)
    {
        $this->calculators[$calculator->getSupportedMessageType()] = $calculator;
    }

    public function calculateColor(Message $message)
    {
        if (array_key_exists($message->getType(), $this->calculators)) {
            $calculator = $this->calculators[$message->getType()];
        } else {
            $calculator = $this->defaultCalculator;
        }

        return $calculator->calculateColor($message);
    }
}

Now your controller is much thiner!
class MessageController extends Controller
{
    /** @var ColorCalculator */
    private $calculator;

    public function show(Message $message)
    {
        $color = $this->calculator->calculateColor($message);

        // do what you want with your color...
    }
}

Note I'm not a Laravel developer, but a Symfony one! I'm assuming Laravel provides some way to define the delegator service and register all the calculators into it, and finally inject that service into the controller... (Symfony does)

A: I would create a class containing consts:
<?php

namespace App\Constants;

class TextColor
{
    const INFO = 'blue';
    ...
    const DANGER = 'red';
}

// usage
$color = TextColor::INFO; // 'blue'

However my second advise is to story these colors that correspond to a warning level in a new table (model) with a foreign key on messages.type to that table.

A: No need to Polymorphic just make an array like this in your model or config:
    $messageColors = [
        "info"=>"blue",
        .......
    ]

And then write this:
    $color = $messageColors[$message->type];

A: finally, I found my answer from the example on this post and it's working for my situation:
\app\Message.php
class Message extends Model {

  public static function color() {
    // lots of code here!
    return 'grey';
  }

}

\app\InfoMessage.php
class InfoMessage extends Message {

  public static function color() {
    // lots of code here!
    return 'blue';
  }

}

\app\Http\Controllers\MessageController.php
class MessageController extends Controller {

  public function show(Message $message) {
    $color = $message->type ? $message->type::color() : $message->color();
    // $message->type will be something like '\App\InfoMessage'
    // so $message->type::color() will be equal to \App\InfoMessage::color()
    return view('messages.show',compact(['message','color']));
  }

}

thanks for all answers.


text:
Q: Contour integral over a square $f(z) = \frac{z^2e^z}{2z+i}$, and the contour is the square with vertices at $1+i, -1+i, -1-i,$ and $1-i.$
The issue I'm having with this integral is that the singular point $z = -\frac{i}{2}$ is included in the domain, so $f(z)$ is not analytic everywhere inside and on $C$.
Regardless, using the $f(z(t))z'(t)$ method appears impractical here since $z(t)$ is four line segments and integrating all four would prove time consuming, so I'm trusting there's an easier method.
I decided to try the following, letting $f_1(z)= \frac{z^2e^z}{2}$: $\int_C f(z) = \int_C \frac{\frac{z^2e^z}{2}}{(z-(-\frac{i}{2}))^(0+1)} = 2\pi i f_1(-\frac{i}{2}) = \frac{\pi i}{4e^\frac{i}{2}}$
Again, that requires $f(z)$ to be analytic everywhere in the domain, and if it was, the integral would equal zero since the square is a simply connected domain and $C$ is a closed contour.
So I am obviously confused. Any advice would be greatly appreciated.


text:
Q: when choose CROSS APPLY and when EXISTS? I read, CROSS APPLY is just like JOIN.. and I think JOIN can be accomplished with EXISTS also (correlated sub query)
I am confused, what is the difference in using CROSS APPLY and EXISTS?
when should I go for CROSS APPLY against EXISTS?

A: CROSS APPLY isn't just like a JOIN. A JOIN finds matching (or not matching) rows between two sets of data. CROSS APPLY is a method to run a query against every row of the thing you're applying it against. This can act as a filtering mechanism, something like how a JOIN works, but it's applying something to each row, so it needs to be thought of that way.
EXISTS in a sub-query is a completely different mechanism of filtering. It's a method of quick identification because it immediately short-circuits it's search when it finds something. The place you'd want to use EXISTS in general is when you're likely to get a hit on the filter criteria, thereby making the searches as short as possible. But, EXISTS doesn't find all matches. It just finds the first match and then stops searching.
So while you can arrive at the same results from these three different methods, use them as defined and you'll usally be right. If you're literally JOINing two sets of data, use JOIN. If you want to run a process, frequently a filter, against every row in a data set, use CROSS APPLY. If you want a fast filter on a likely positive match, use EXISTS.

A: Grant's response is right on the money
But from a personal style perspective I use OUTER APPLY exclusively.
Here's a common pattern, all three of these do the same thing, but by using outer apply, when validating you can briefly comment out the "WHERE ca2.HasAddress = 'Yes'" and add ca2.HasAddress to the main select to verify that your filter is removing the records you want while the other two methods of filtering dont offer the same transparency at the row level.
SELECT c.CustomerID
FROM SalesLT.Customer c
OUTER APPLY (SELECT TOP 1 'Yes' HasAddress
             FROM SalesLT.CustomerAddress ca
             WHERE c.CustomerID = ca.CustomerID)
             ca2
WHERE ca2.HasAddress = 'Yes'

SELECT c.CustomerID
FROM SalesLT.Customer c
CROSS APPLY (SELECT TOP 1 'Yes' HasAddress
             FROM SalesLT.CustomerAddress ca
             WHERE c.CustomerID = ca.CustomerID)
             ca2

SELECT c.CustomerID
FROM SalesLT.Customer c
WHERE EXISTS (SELECT 1
             FROM SalesLT.CustomerAddress ca
             WHERE c.CustomerID = ca.CustomerID)


text:
Q: SMS over GSM/GPRS protocol In the GSM/GPRS world, how is SMS transmitted? In CDMA, SMS is encapsulated within a data burst signaling message (received/sent during idle mode) or if it's too long then a traffic channel is setup (with specific service option 6 or 14) and the SMS is carried in traffic. Is GSM/GPRS the same?

A: In GSM/GPRS, SMS is part of the non-access stratum (NAS) signalling protocol, and is always (as far as I know) sent over a control (signalling) channel.  UMTS is the same.  See 3GPP TS 24.007 for more details.
LTE is slightly different, because an IP connection is formed at network registration.  See Myth 2: SMS isn't supported over LTE (half way down the page) for an explanation of the standard way to send SMS.
The principle of being able to send an SMS without any connection other than being registered on the network holds.