text:
Q: SpringBoot: how to run tests twice, with two different config files I am writing a SpringBoot application using a JMS MOM. My application supports two kinds of JMS: EMS and AMQ
My application has many Junit Tests. Of course, whether I use EMS or AMQ the tests are exactly the same and the expected results are also exactly the same. The only difference is the configuration file used.
@RunWith(SpringRunner.class)
@TestPropertySource(locations="classpath:application.yaml")
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
public class MyTest {

    @SpringBootApplication
    @ComponentScan("com.mytest")
    static class Application {
    }

    @Test
    public void test() {
        ...
    }

}

What I would like to be able to do is to run my tests twice, one time with an EMS config and one time with and AMQ config: How should I do?

FYI, I am using Maven to build my application. A solution based on a maven trick would be  perfectly acceptable for me

Thank you for help

A: It sounds like a task for a building tool that you using.
For example, for Maven you can write specific test tasks with different active profiles, something like this:
mvn clean test -Dspring.profiles.active=kafka
mvn clean test -Dspring.profiles.active=rabbitmq
mvn clean test -Dspring.profiles.active=activemq

and collect necessary properties in files: application-{profile}.properties

This articles can help you:

*

*how to bind a property file to a current active profile: spring-boot-profile-based-properties

*mvn profiles:
introduction-to-profiles

*mvn different environments:
building-for-different-environments


text:
Q: trigger cursor move event upon page load I'm working on a portfolio website that is a full browser sized container which swaps images when moving the cursor from left to right.
the header and captions are involved in the jquery script in order to change their color according to the image that is shown.
this seems to work great but the only downside is that the header & caption are not visible until the cursor is moved across the browser when you just loaded the site.
Is there a way to make the text appear upon site load? like triggering a mouseover event when it loads so the text is already there? or maybe some less complicated fix...
In any case thanks so much for the help!

$.fn.swinger = function () {
    return this.each(function () {
        var $container = $(this);
        $container.css({
            "position": "relative"
        });
        var $images = $container.find("img");
        $images.css({

        });
        var $middleImage = $($images[Math.floor($images.length / 2)]);
        $middleImage.css({
            "z-index": "2",
            "position": "relative"
        });
        var columnsCount = $images.length;
        $images.each((i, img) => {
            var left = `${100 / columnsCount * i}%`;
            var width = `${100 / columnsCount}%`;
            var $column = $(`<span style="z-index:999;position:absolute;top:0;bottom:0;left:${left};width:${width}"></span>`);
            $(img).after($column);
            $column.hover(() => {
                $images.css({
                    "z-index": "1",
                    "position": "absolute"
                });
                $(img).css({
                    "z-index": "2",
                    "position": "relative"
                });
                // just added one line
                $(".caption").text($(img).attr("alt"));

                $(".caption")
                .text($(img).attr("alt"))
                .css('color', $(img).data('color'));

                $('header').css('color', $(img).data('color'))

            });
        })
    });
}
*{
    margin: 0px;
    padding: 0px;
    box-sizing: border-box;
}

body {

}

.left-holder {
    text-align: left;
    float: left;
    margin-right: 55px;
    width: 250px; }

div.swinger-container {
    text-align: center; /* ensures the image is always in the h-middle */
    overflow: hidden;
    width: 100vw;
height: calc(100vh);

}

div.swinger-container img {
    object-fit: cover;
-o-object-position: center center;
object-position: center center;
width: 100%;
height: 100% !important;
  }

  header {
    width: 100%;
    -webkit-box-align: center;
        -ms-flex-align: center;
            align-items: center;
    position: absolute;
    top: 0;
    left: 0;
    -webkit-box-pack: justify;
        -ms-flex-pack: justify;
            justify-content: space-between;
    padding: 10px 10px;
    -webkit-box-sizing: border-box;
            box-sizing: border-box;
    margin-top: -2px;
    text-align: center;
    z-index: 100;
    -webkit-transition: all .2s;
    transition: all .2s; }
    header.header-about {
      color: white !important;
      background-color: white; }
    header h1, header h2, header .about {
      font-size: 1em;
      font-weight: 400;
      display: block;
      line-height: 1.2em;
      margin-bottom: 0;
      padding-bottom: 0; }
    header h1 {
      text-align: left; }
    header a {
      text-decoration: none;
      color: white;
      line-height: 1; }
    header .about {
      text-align: left;
      padding-bottom: 2px; }

        .caption {

            z-index: 100;
            position: fixed;
            left: 0;
            right: 0;
            bottom: 20px;
            max-width: 500px;
            text-align: center;
            margin-left: auto;
            margin-right: auto;
            width: 50vw;

        }

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="Style.css">
    <title>website title</title>

my name

what I do

A: Is this okay for you?
I have just used the first image as a default one. Then the mouse events will do the rest.
Added this in init:
let defaultImage = $("#default-image");
$(".caption").text(defaultImage.attr("alt")).css('color', $(defaultImage).data('color'));
$('header').css('color', $(defaultImage).data('color'));

$.fn.swinger = function() {
  return this.each(function() {
    var $container = $(this);
    $container.css({
      "position": "relative"
    });
    var $images = $container.find("img");
    $images.css({

    });
    var $middleImage = $($images[Math.floor($images.length / 2)]);
    $middleImage.css({
      "z-index": "2",
      "position": "relative"
    });
    var columnsCount = $images.length;
    $images.each((i, img) => {
      var left = `${100 / columnsCount * i}%`;
      var width = `${100 / columnsCount}%`;
      var $column = $(`<span style="z-index:999;position:absolute;top:0;bottom:0;left:${left};width:${width}"></span>`);
      $(img).after($column);
      $column.hover(() => {
        $images.css({
          "z-index": "1",
          "position": "absolute"
        });
        $(img).css({
          "z-index": "2",
          "position": "relative"
        });
        // just added one line
        $(".caption").text($(img).attr("alt"));

        $(".caption")
          .text($(img).attr("alt"))
          .css('color', $(img).data('color'));

        $('header').css('color', $(img).data('color'))

      });
    })
  });
}
* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

body {}

.left-holder {
  text-align: left;
  float: left;
  margin-right: 55px;
  width: 250px;
}

div.swinger-container {
  text-align: center;
  /* ensures the image is always in the h-middle */
  overflow: hidden;
  width: 100vw;
  height: calc(100vh);
}

div.swinger-container img {
  object-fit: cover;
  -o-object-position: center center;
  object-position: center center;
  width: 100%;
  height: 100% !important;
}

header {
  width: 100%;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  position: absolute;
  top: 0;
  left: 0;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
  padding: 10px 10px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  margin-top: -2px;
  text-align: center;
  z-index: 100;
  -webkit-transition: all .2s;
  transition: all .2s;
}

header.header-about {
  color: white !important;
  background-color: white;
}

header h1,
header h2,
header .about {
  font-size: 1em;
  font-weight: 400;
  display: block;
  line-height: 1.2em;
  margin-bottom: 0;
  padding-bottom: 0;
}

header h1 {
  text-align: left;
}

header a {
  text-decoration: none;
  color: white;
  line-height: 1;
}

header .about {
  text-align: left;
  padding-bottom: 2px;
}

.caption {
  z-index: 100;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 20px;
  max-width: 500px;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  width: 50vw;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="Style.css">
  <title>website title</title>

my name

what I do

redpajama_set_name: RedPajamaStackExchange


text:
Q: The type arguments for method 'SelectExtensions.DropDownListFor(HtmlHelper, Expression>, IEnumerable, string, object)' cannot be inferred Getting this error, not sure what's causing it:
@model DelegatePortal.ViewModels.ImpersonateVendorViewModel
     @Html.DropDownListFor(model => model.Id, new SelectList(Model.Vendors, "Id", "Name"), "Choose a vendor", new { @class = "form-control form-control-sm " })

The type arguments for method
  'SelectExtensions.DropDownListFor(HtmlHelper, Expression>,
  IEnumerable, string, object)' cannot be inferred from the usage.

A: Check if you added all the properties in the View Model.
Mine was missing Id property:
 public class ImpersonateVendorViewModel
    {
        public int Id { get; set; }
        public List<Vendor> Vendors { get; set; }
    }


text:
Q: How to replace subset of string from pandas? Below is my input string
df =   text                   codes
       anesthesia code        99921
       aretic closure         75454
       nyopia                 75633
       right atrial           89732

string =  However, when performed anesthesia code with a formal report, this service may be considered a significant, separately identifiable, and if nyopia, a separately reportable service.

In input string if we get any text from text column then we can replace with that perticular code from code column.
I want output like
output =  However, when performed 99921 with a formal report, this service may be considered a significant, separately identifiable, and if 75633, a separately reportable service.

So how I can do this.

A: Using a single regular expression that matches all of the texts should be quite efficient:
import re
import pandas as pd

df = pd.DataFrame(
    {
        "text": ["anesthesia code", "aretic closure", "nyopia", "right atrial"],
        "codes": [99921, 75454, 75633, 89732],
    }
)

# Generate a mapping of text to code
text_to_codes = {text: str(code) for text, code in zip(df["text"], df["codes"])}
# Generate a regexp that will match any `text`s
match_re = re.compile("|".join(re.escape(t) for t in text_to_codes))

string = """
However, when performed anesthesia code with a formal report,
this service may be considered a significant, separately identifiable,
and if nyopia, a separately reportable service.
"""

# Run the regexp on the string, replacing texts with what we find in the mapping
output = match_re.sub(lambda m: text_to_codes[m.group(0)], string)

print(output)

This outputs
However, when performed 99921 with a formal report,
this service may be considered a significant, separately identifiable,
and if 75633, a separately reportable service.

If you add flags=re.I to the compile call, this becomes case-insensitive too.

A: Do you have to use pandas? If not, just put the data in a dictionary.
string =  'However, when performed anesthesia code with a formal report, this service may be considered a significant, separately identifiable, and if nyopia, a separately reportable service.'

dict = {
    'anesthesia code': '99921',
    'aretic closure': '75454',
    'nyopia' : '75633',
    'right atrial' : '89732'
}

for key in dict:
    if key in string:
        string = string.replace(key, dict[key])

print(string)

A: Try
d = {
    'anesthesia code': '99921',
    'aretic closure': '75454',
    'nyopia' : '75633',
    'right atrial' : '89732'
}

print(f"However, when performed {d['anesthesia code']} with a formal report, this service may be considered a significant, separately identifiable, and if {d['nyopia']}, a separately reportable service.")


text:
Q: Capture the same pixel rectangle at different resolutions I'm trying to capture the same pixel rectangle area no matter what the resolution of the currently selected monitor is. I have some code that captures the areas I need at (1920x1080, 2560x1440) but I am currently hard coding the start/end points of the area I need. I know there's a much better way of doing this as my current way is sloppy and works for only two resolutions. Any recommendations on a approach?
If Screen.AllScreens(intMonitorSelected).Bounds.Height = "1080" Then
    StartX = Screen.AllScreens(intMonitorSelected).Bounds.Left + TenStartX
    EndX = Screen.AllScreens(intMonitorSelected).Bounds.Left - StartX + TenEndX
    StartY = Screen.AllScreens(intMonitorSelected).Bounds.Bottom - TenStartY
    EndY = Screen.AllScreens(intMonitorSelected).Bounds.Bottom - StartY - TenEndY
ElseIf Screen.AllScreens(intMonitorSelected).Bounds.Height = "1440" Then
    StartX = Screen.AllScreens(intMonitorSelected).Bounds.Left + FourteenStartX
    EndX = Screen.AllScreens(intMonitorSelected).Bounds.Left - StartX + FourteenEndX
    StartY = Screen.AllScreens(intMonitorSelected).Bounds.Bottom - FourteenStartY
    EndY = Screen.AllScreens(intMonitorSelected).Bounds.Bottom - StartY - FourteenEndY
End If
        Dim screenshot As System.Drawing.Bitmap
        Dim graph As Graphics
        Dim bounds As New Rectangle(StartX, StartY, EndX, EndY)

        screenshot = New System.Drawing.Bitmap(bounds.Width, bounds.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb)
        graph = Graphics.FromImage(screenshot)
        graph.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy)

        Return New Bitmap(screenshot)

Called with:
Test.Image = GetImage(48, 210, 53, 35, 63, 220, 70, 47)

As you can see the correct pixel start and end points vary slightly depending on the resolution. I also need to expand this to be able to work on any resolution. I'm stumped ;/

A: Figured it out, now just need to figure out the math to adjusting the rectangle to shrink/grow also.
        Dim OCoordx = "65"
        Dim OCoordy = "1369"

        Dim posX As Long = OCoordx / 2560 * Screen.AllScreens(intMonitorSelected).Bounds.Width
        Dim posY As Long = OCoordy / 1440 * Screen.AllScreens(intMonitorSelected).Bounds.Height

        posX = Screen.AllScreens(intMonitorSelected).Bounds.Left + posX
        posY = Screen.AllScreens(intMonitorSelected).Bounds.Top + posY


text:
Q: How to detect a web page blocker and then act on it? I have a website here and being a student in my school they block some website like Facebook but on my site I have a Facebook iframe.
So when I load the site in school I get the web blocker screen where the Facebook like button should be.
So is there anyway of detecting any web blocker and then if there is a web blocker disabling the iframe or the div it is in?
I don't know this is even possible but if anyone knows how it would be greatly appreciated.
Thank you so much.

A: You could try to load any image or script from facebook.com and see if it gets an error.
(just make sure to change your code if Facebook changes their URLs)


text:
Q: Excel Show Data Based on user Choice Excel 2007: I get my data from Access tables the Excel sheet is called "Data". My Excel report cells are populated by linking to those data cells(=Data!A1) and some report cells have simple code.  But my question is this; my report needs to specify one record. Example: Data record 1: Name=Joe, Birth=7/29/62, Country=USA: record 2: Name=Sam, Birth=4/13/74, Country=China...  How do we control the report display to a specific record?  If I add a DropDown or ListBox, how do we make only the records for the name picked show in the report. Is there a way to put the code behind the listbox, or should I scrap the list and create a macro, what is the best way for a user to pick the data to be displayed on the report?  Suggestions please...

A: There are two approaches I would use.
When you embed a query object in Excel (which is, I assume, how you are fetching the data from Access) you have the ability to edit that query in the little Query Editor tool.
You can add criteria to that query in this tool - there's a filter icon, you select let's say the Name column, and then type "Sam" in the box below, and that will produce a SQL statement that now includes "Where Name = 'Same'" at the end.
However, that's not that helpful for reporting, since most likely we want the name to be a parameter passed in from the Excel sheet itself. If in the criteria box, you type "[enter name]" instead of "Sam", the square brackets tell the Query tool that this is a user supplied parameter. When you run the query from the tool now you get a pop up box asking you each time for the name.
Now when you exit the query tool and return to Excel, you can edit the Query Parameters for that embedded query object. The parameter you made (name) is there, and it can either take on a static value, prompt the user, or take the contents of a cell. You can even set a flag to refresh the query when the cell contents change.
The other approach goes a little further and manipulates the query object in some VBA code. If you need to do some heavier lifting, or other logic, for example, and you don't want to deal with writing it all out as spreadsheet formulas. An easy way to do that is to drop in a button on the report sheet and have the VBA code start on that button's click event.


text:
Q: Filter Placeholders with Yii2 Does anyone know how to implement a placeholder or tooltip on the Gridview filter of the Yii2 Framework? I need something that stands out to the user to let them know that textbox is in fact a search filter.
Look forward to hearing responses.

A: yon can also use the tooltip/title with filterOptions
 [
            'attribute' => 'name',
            'label' => 'labelname',
            ...
            ....
            'filterOptions' => [ 'title' => 'prova'],
        ],

A: Placeholder could be realized with this:
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel'  => $searchModel,
    'columns'      => [
        [
            'attribute' => 'name',
            'filterInputOptions' => [
                'class'       => 'form-control',
                'placeholder' => 'Type in some characters...'
             ]
        ],
        ['class' => 'yii\grid\ActionColumn' ],
    ],
]); ?>

class should be provided, though it is not a must - it is just the default styling class.
Setting this globally
The only way that I found is in config/web.php that is used for the application configuration:
$config = [
    ...
    'on beforeRequest'          => function ($event) {
        Yii::$container->set('yii\grid\DataColumn', [
            'filterInputOptions' => [
                'class'       => 'form-control',
                'placeholder' => 'Type in some characters...'
            ]
        ]);
    },
    ...
];

This is an event handler. On each request DataColumn will be configured to use the placeholder. Some detail information can be found here. Now you don't need to adjust any GridView configuration in order to have the placeholder. In the handler you can change other configurations as well, of course.


text:
Q: File Upload is not working I'm using file upload in my site. I'm uploading word Document(Doc,Docx). Suddenly, it's not working. It is not getting the filename. It is showing empty!!! My Code is as follows:
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="ContentPlaceHolder1">

            <asp:UpdatePanel ID="UpdatePanel2" runat="server">
                <ContentTemplate>
                    <asp:Button ID="btnResumedload" Text="Download Resume" runat="server" BackColor="Maroon"
                        ForeColor="White" Font-Bold="true" OnClick="btnResumedload_Click" Height="27px"
                        Width="195px" />
                </ContentTemplate>
            </asp:UpdatePanel>

            <asp:UpdatePanel ID="UpdatePanel4" runat="server">
                <ContentTemplate>
                    <asp:Button ID="btnUploadnew" Text="Upload New" runat="server" BackColor="Maroon"
                        ForeColor="White" Font-Bold="true" OnClick="btnUploadnew_Click" Height="30px"
                        Width="198px" />
                </ContentTemplate>
            </asp:UpdatePanel>

            <asp:UpdatePanel ID="UpdatePanel3" runat="server">
                <ContentTemplate>
                    <asp:Button ID="btnDel" Height="30px" Width="198px" OnClientClick="return confirm('Are you sure?');"
                        BackColor="Maroon" ForeColor="White" Font-Bold="true" Text="Delete Resume" runat="server"
                        OnClick="btnDel_Click"></asp:Button>
                </ContentTemplate>
            </asp:UpdatePanel>

            <asp:Label ID="lblmsg" runat="server" Font-Bold="True" ForeColor="Red" Visible="False"
                Height="17px" Width="855px"></asp:Label>

                <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                    <ContentTemplate>
                        <%--<ajaxToolkit:AsyncFileUpload ID="fpResumenew" runat="server" Visible="false" />--%>
                        <asp:FileUpload ID="fpResumenew" runat="server" Visible="false" Width="226px" />
                    </ContentTemplate>
                    <Triggers>
                        <asp:PostBackTrigger ControlID="btnUpload" />
                    </Triggers>
                </asp:UpdatePanel>

            <%--<asp:Button ID="btnUpload" Font-Bold="true" DisabledText="Processing..." Visible="false"
                        Text="Upload" BackColor="Maroon" ForeColor="White" runat="server" OnClick="btnUpload_Click" />--%>
            <cc1:ClickOnceButton ID="btnUpload" Font-Bold="true" DisabledText="Processing..."
                Visible="false" Text="Upload" BackColor="Maroon" ForeColor="White" runat="server"
                OnClick="btnUpload_Click" DisableAfterClick="True" />

protected void btn_Click(object sender, EventArgs e)
{

    string strfilename = fp.FileName.ToString();

    if (fp.PostedFile.FileName.Trim().Length != 0)

    {

        binary = new byte[fp.PostedFile.ContentLength];

        binary = fp.FileBytes;

        doc = fp.FileName;

        contenttype = fp.PostedFile.ContentType;

    }

}
Just a sample!!!

Nothing works for me.. Problem is that I'm using three more buttons in the same page. The other buttons initializing the file upload control. So, when clicking the upload button, the file name is empty. So, I used another page for uploading the word document. Now, it is working.. !! Anyhow, I need the solution for this!! Anyone give me idea!!

A: Hai vaishu
FileUpload controls are not compatible with UpdatePanel when they are used to upload files as part of an asynchronous postback.
Just check the AJAX documentation. The FileUpload control is not supported inside an UpdatePanel (http://ajax.asp.net/docs/overview/UpdatePanelOverview.aspx):
or
use asp:postbacktrigger instead of asyncpostbacktrigger
<asp:updatepanel runat="server" id="UpdatePanel1">
    <contenttemplate>
        <asp:FileUpload runat="server" id="FileUpload1" />
        <asp:button runat="server" id="ButtonSubmit" text="Postback" />
    </contenttemplate>
    <triggers>
        <asp:postbacktrigger controlid="ButtonSubmit" />
    </triggers>

</asp:updatepanel>

or
use ajax for asynchronous file upload:
http://www.asp.net/(S(fu2l2uzphr2u3u45q2dnez55))/ajax/AjaxControlToolkit/Samples/AsyncFileUpload/AsyncFileUpload.aspx

A: The reason that the postback trigger is not working in your case is because the FileUpload Control is set to visible=false.  If you use display:none instead, the postback trigger will work.

A: This works just fine, I finally solved the issue... the ButtonSubmit is reload by the trigger so the page got the info from the control.
 <asp:updatepanel runat="server" id="UpdatePanel1">
     <contenttemplate>
         <asp:FileUpload runat="server" id="FileUpload1" />
         <asp:button runat="server" id="ButtonSubmit" text="Postback" />
     </contenttemplate>
     <triggers>
         <asp:postbacktrigger controlid="ButtonSubmit" />
     </triggers>

 </asp:updatepanel>


text:
Q: Compare trends in time series I have two time series that represent yearly population estimates from different sources, for some species. In the first species ('Forc') the two series are definetly not consistent despite the overall trend is similar, in the second ('Cot') both trend and fluctuations are somewhat consistent.

Data should be autocorrelated since they represent population abundance, but fitting an ARIMA model (with auto.arima from forecast package) results in some 0 in the AR(p) parameters.
 Series: Forc_Abb
 ARIMA(0,1,0)

 Series: Forc_ntot_est
 ARIMA(0,0,0) with zero mean

 Series: Cot_Abb
 ARIMA(1,0,0) with zero mean

 Series: Cot_ntot_est
 ARIMA(2,0,0) with zero mean

The question is how to assess consistency of the two proxies for each species.
That is, not only a test for difference of the slopes but something that accounts also for the yearly consistency (e.g. in 'Forc' species, slope is similar but definitely the proxies are not consistent).
Some species (not shown here) show an evident negative or positive trend.
I'm not interested in forecasting.
Are any of these ideas suitable?

*

*GLS with autocorrelation at lag 1 with proxy and year as indipendent variables, plus the interaction term? Do I need to add some polynomial term in 'Cot' species in this case to better fit the peak in 2006-2007?

*remove the trend by differencing and compare the differenced series (how?)

*adding a changepoint analysis? (e.g. cpt.meanvar from changepoint package)? Do I need apply some smoothing function (e.g. LOESS, moving average etc.)?


text:
Q: How can I move a value out of the argument to Drop::drop()? I'm using gfx-hal, which requires me to create resources which need to be explicitly destroyed using functions specific to their type. I'd like to store instances of these types in structs, and I'd also like to tie cleaning them up to the lifetime of the owning struct, instead of managing their lifetimes manually and potentially having objects on the GPU/in the driver live forever.
However, all the functions in the destroy family of functions take the type directly, rather than a reference, so when I try to pass them from my structs, I get errors like the following:
error[E0509]: cannot move out of type `S`, which implements the `Drop` trait
 --> src/lib.rs:9:18
  |
9 |         destroyT(self.member)
  |                  ^^^^^^^^^^^ cannot move out of here

It seems like there should be some way around this issue, as I'm currently in the Drop::drop function itself, so self is already "consumed." How do I get the instances of these types out of self as T, and not &T?
struct T;

struct S {
    member: T,
}

impl Drop for S {
    fn drop(&mut self) {
        destroyT(self.member)
    }
}

// elsewhere, in a library

fn destroyT(t: T) {
    //...
}

A: The safest, easiest way to do this is to use an Option:
struct T;

impl Drop for T {
    fn drop(&mut self) {
        println!("dropping T");
    }
}

struct S {
    member: Option<T>,
}

impl Drop for S {
    fn drop(&mut self) {
        if let Some(t) = self.member.take() {
            destroy_t(t);
        }
    }
}

fn destroy_t(_t: T) {
    println!("destroy T");
}

fn main() {
    let _x = S { member: Some(T) };
}

You could choose to use unsafe code with MaybeUninit and swap out the current value for an uninitialized one:
use std::mem::{self, MaybeUninit};

struct T;

impl Drop for T {
    fn drop(&mut self) {
        println!("dropping T");
    }
}

struct S {
    member: MaybeUninit<T>,
}

impl Drop for S {
    fn drop(&mut self) {
        let invalid_t = MaybeUninit::uninit();
        let valid_t = mem::replace(&mut self.member, invalid_t);
        let valid_t = unsafe { valid_t.assume_init() };
        destroy_t(valid_t);
        // Dropping MaybeUninit does nothing
    }
}

fn destroy_t(_t: T) {
    println!("destroy T");
}

fn main() {
    let _x = S {
        member: MaybeUninit::new(T),
    };
}

See also:

*

*How to move one field out of a struct that implements Drop trait?

A: You can use ManuallyDrop. It has no overhead and a clear API. It is less of a pain to use than MaybeUninit since it doesn't require unsafe to use elsewhere (access to the inner value is available by simple Deref) and it only requires unsafe to actually move the value out.
use std::mem::ManuallyDrop;

struct T;

impl Drop for T {
    fn drop(&mut self) {
        println!("dropping T");
    }
}

struct S {
    member: ManuallyDrop<T>,
}

impl Drop for S {
    fn drop(&mut self) {
        // SAFETY: this is safe because we do not access `self.member` any more
        let member = unsafe { ManuallyDrop::take(&mut self.member) };
        destroy_t(member);

        // dropping a `ManuallyDrop` does nothing
    }
}

fn destroy_t(_t: T) {
    println!("destroy T");
}

fn main() {
    let _x = S {
        member: ManuallyDrop::new(T),
    };
}

destroy T
dropping T

Keep in mind, as evidenced by the name, ManuallyDrop will prevent the inner value from being dropped unless ManuallyDrop::take or ManuallyDrop::into_inner is called (thereby removing it from protections and normal drop rules will apply) or if ManuallyDrop::drop is used.


text:
Q: How to make dynamic (variable) content with angularjs? My first problem, i don't know make a dynamic template in twig with AngularJs.
The purpose of my project, then making a page editor app.
So, first of all:
- I get a JSON file in the following structure
- I started processing the content of JSON file, but I'm getting stuck in processing.
Can I ask for a nice solution?
Many thanks!
/* Json file */

$scope.form={
'content':
    [{
        "name"  : "text_right",
        "img"   : "nope.jpg",
        "text"  : "text text text"
    },
    {
        "name"  : "text_left",
        "text"  : "text text text",
        "img"   : "nope.jpg"
    },
    {
        "name"  : "text_both",
        "textL"  : "text text text",
        "textR"  : "text text text"
    },
    {
        "name"  : "special",
        "text"  : "
text text text
"
    }]
};

/* HTML content */

    [[ initTemp(key) ]]

/* AngularJs */
$scope.initTemp = function($key){
    let html;

    if(form.content[$key].name ==  "text_both"){
        html = textBoth();
    }
    if(form.content[$key].name == "text_left"){
        html = textLeft();
    }
    return $compile(html)($scope);
}
function textBoth($key){
    return `

<input ng-model="form.content.${$key}.textL">

<input ng-model="form.content.${$key}.textR">

    `;
}
function textLeft($key){
    return `

<input ng-model="form.content.${$key}.text">

<input ng-model="form.content.${$key}.img">

    `;
}

A: Code that assembles DOM from data is best done in a custom directive:

     ̶[̶[̶ ̶i̶n̶i̶t̶T̶e̶m̶p̶(̶k̶e̶y̶)̶ ̶]̶]̶
     <custom-directive item="item"></custom-directive>

app.directive("customDirective", function($compile) {
    return {
        link: postLink,
    };
    function postLink (scope,elem,attrs) {
        var item=scope.$eval(attrs.item);
        var html = `

        `;
        var linkfn = $compile(html);
        elem.append(linkfn(scope));
    }
})

For more information, see

*

*AngularJS Developer Guide - Creating Custom Directives


text:
Q: Closed form for $\sum_{k=1}^\infty \frac{B_{2k}}{(2k)!}$ What do you think about the closed form I found for this series?
$$\sum_{k=1}^\infty \frac{B_{2k}}{(2k)!} = \frac{e+1}{2(e-1)}$$
I found it this way:
Take the Ramanujan's summation $C(0)$ for divergent series:
$$C(0) = -\frac{1}{2}f(0) - \sum_{k=1}^\infty \frac{ B_{2k}}{(2k)!}f^{(2k-1)}(0)$$
Let $f(x)=e^x$ so that $f^{(2k-1)}(0)=f(0)=1$.
Now we have:
$$C(0) = -\frac{1}{2} - \sum_{k=1}^\infty \frac{B_{2k}}{(2k)!}$$
Lets now assign some value to $C(0)$, by manipulating $\sum_{k=1}^\infty e^k$ one arrives to:
$$S = \sum_{k=1}^\infty e^k = e^1+e^2+e^3+...$$
$$\frac{1}{e}S=1+S$$
$$S=\frac{e}{1-e}$$
Now we have:
$$\frac{e}{1-e} = -\frac{1}{2} - \sum_{k=1}^\infty \frac{B_{2k}}{(2k)!}$$
$$\frac{e}{1-e} + \frac{1}{2} = - \sum_{k=1}^\infty \frac{B_{2k}}{(2k)!}$$
$$\frac{e+1}{2(1-e)} = -\sum_{k=1}^\infty \frac{B_{2k}}{(2k)!}$$
$$\frac{e+1}{2(e-1)} = \sum_{k=1}^\infty \frac{B_{2k}}{(2k)!}$$

A: It seems that the identity follows immediately from the definition  of Bernoulli number. It si known that for $|x|<2\pi$,
$$\frac{x}{e^x-1}+\frac{x}{2}-1 = \sum_{k=1}^\infty \frac{B_{2k}x^{2k}}{(2k)!}$$
so by taking $x=1$ we get the result (different from OP's)
$$\frac{3-e}{2(e-1)}=\frac{1}{e-1}+\frac{1}{2}-1 = \sum_{k=1}^\infty \frac{B_{2k}}{(2k)!}.$$
Am I missing something?
P.S.By the way the
$$\frac{e+1}{2\left(e-1\right)}=\sum_{k=0}^\infty \frac{B_{2k}x^{2k}}{(2k)!}.$$

A: What do I think? That you should take care when using Ramanujan Summation this way.
Note that:
$$\frac{e+1}{2\left(e-1\right)} =\color{red}{1}.08197670687\ldots\neq \sum_{k=1}^\infty \frac{B_{2k}}{(2k)!} = \color{red}{0}.08197670687\ldots$$
Without using numerics we can already see that
$$\frac{e+1}{2\left(e-1\right)} \gt \frac{e+1}{2\left(e+1\right)} = 1/2$$
While we have
$$\sum_{k=1}^\infty\frac{B_{2k}}{(2k)!} < \sum_{k=1}^2\frac{B_{2k}}{(2k)!} = \frac{59}{720}<1/2$$
Proving that the two are not equal.

A: According to this page, a Taylor series is $$\coth x=\dfrac{1}{x}+\sum\limits_{n=1}^\infty\dfrac{4^nB_{2n}}{(2n)!}x^{2n-1}\qquad \text{for} \qquad 0<|x|< \pi$$  where $B_n$ is the $n$th Bernoulli number.
We can rewrite it as $$\coth x=\dfrac{1}{x}+\dfrac{1}{x}\sum\limits_{n=1}^\infty\dfrac{B_{2n}}{(2n)!}(2x)^{2n}$$ So, making $x=\frac 12$ we have $$\coth\left(\frac 12\right)=\frac{e^{1/2}+e^{-1/2}}{e^{1/2}-e^{-1/2}}=\frac{e+1}{e-1}=2+2\sum\limits_{n=1}^\infty\dfrac{B_{2n}}{(2n)!}$$ and then $$\sum\limits_{n=1}^\infty\dfrac{B_{2n}}{(2n)!}=\frac{3-e}{2 (e-1)}$$


text:
Q: Start/stop button not working correctly iOS I got into a very noob problem which I can not seem to solve in any way, I am sure I am overlooking something, but cannot figure it out for gods sake!!
Okay, so I have a start/stop button in my app, it should resume the action if the action is paused and pause the action if it is already running. Here is my code:
- (IBAction)pause:(id)sender {

    if(paused){
        [self.progressBar resumeLayer];
        paused = false;
        NSLog(@"resume");
    }

    if(!paused){
        [self.progressBar pauseLayer];
        paused = true;
        NSLog(@"pause");

    }

}

The problem is: When i run the app and press on the button to pause, it works fine however after that it won't resume at all. After NSLogging to the console, I found that pause is called right after resume.... Why is this?? First: the button is clicked only once, how can it call two opposite methods? Second: Why isn't my BOOL check working?
EDIT: If I swap out one of the if statements to an else if, it works fine... Why is that?
Thank you!

A: Please Take Paused variable as BOOL & set with YES & NO

A: What is "paused"? A global variable? An instance variable? I don't know.
Convention is that instance variables should start with an underscore character, which they will do automatically if you just define a property. That way people have at least some idea what is happening.
Convention for BOOL values is YES or NO. Not true or false.
The real bummer is of course a stupid bug in your code. If paused == YES then the first if is executed, paused is set to NO, and then in the next test you check that paused == NO - which it is at this point.
You would have found that easily by stepping through the code in the debugger, line by line.

A: - (IBAction)pause:(id)sender {

    if(paused){
        [self.progressBar resumeLayer];
        NSLog(@"resume");
    }

    if(!paused){
        [self.progressBar pauseLayer];
        NSLog(@"pause");
    }

    paused = !paused;

}

A: You should check for the other state in an else block instead of having two if statements.
The reason why this fails for you now is that, you change the state  of paused to false and immediately after the first if statement is done you check for !paused. That will be true as you just changed it to false.
To fix it, you either can use an else if (!paused) statement or just a plain else if the paused variable is a boolean.
Something like this:
- (IBAction)pause:(id)sender {

    if(paused){
        [self.progressBar resumeLayer];
        paused = false;
        NSLog(@"resume");
    } else {
        [self.progressBar pauseLayer];
        paused = true;
        NSLog(@"pause");
    }
}

A: 1) Declare first BOOL variable in @interface ViewController ()
Ex. bool start;
2) Initialize BOOL variable in viewDidLoad method Like this start = YES;
3) now write code in button Action Like this

- (IBAction)btnPause:(UIButton *)btn {
    if (start == YES)
    {
        btn.backgroundColor = [UIColor blackColor];
        start = NO;
    }
    else
    {
        btn.backgroundColor = [UIColor whiteColor];
        start = YES;
    }
}

// Its change button background color but you can use your Logic.


text:
Q: How to prevent the java process icon display in mac When I start the java process, it will always display the java icon in dock under mac. I have added the following line to .profile, but still not working
export JAVA_TOOL_OPTIONS=-Dapple.awt.UIElement="true"
anyone could help ?

A: Either in your Java code, add this:
System.setProperty("java.awt.headless", "true");

Or at the command-line, add this:
java -Djava.awt.headless=true -jar myProg.jar


text:
Q: AWS - Cannot find a Cloudfront stack I'm facing a pretty weird problem using AWS CLI. I created a new IAM user from my main profile and I gave this user AdministratorAccess in order to allow this user to create AWS resources using a CloudFormation script.
I just created a new stack containing a VPC resource. The stack should have been created in eu-west-2 since I got the following message:
{
    "StackId": "arn:aws:cloudformation:eu-west-2:350027292717:stack/emajarstack/a3b07fd0-8d1e-11ea-9ac5-060e4e394d84"
}

If I log in with my main AWS profile I cannot see any stack created in the eu-west-2 region.
I even tried to run a couple of CLI commands to list or describe my stacks but apparently no stack has been created:
$ aws cloudformation list-stacks
{
    "StackSummaries": []
}

$ aws cloudformation describe-stacks --stack-name emajarstack
An error occurred (ValidationError) when calling the DescribeStacks operation: Stack with id emajarstack does not exist

Fun fact is that I cannot create the same stack because I get the following message:
An error occurred (AlreadyExistsException) when calling the CreateStack operation: Stack [emajarstack] already exists

Questions are:

*

*do you know how can I find my stack or if I'm doing something wrong?

*is there a way to search a stack by id?

A: This message does NOT guarantee the stack will be created successfully:
"StackId": "arn:aws:cloudformation:eu-west-2:350027292717:stack/emajarstack/a3b07fd0-8d1e-11ea-9ac5-060e4e394d84"

Two possibilities here:
1 - 99% sure your stack failed creation because of some issues with the template or other (e.g. limits, dependencies) and that's why it's not showing up, check in the console for more details. It might be in roll_back complete state, so if you can't look at the console, use this flag:
aws cloudformation list-stacks --stack-status-filter ROLLBACK_COMPLETE

2 - Specify the correct region with your list command as your CLI will be looking in the default region which could be different from the one your stack is in.
Edit: also, run aws sts get-caller-identity to ensure you are using the right user with enough permissions.


text:
Q: Admin logging in as a User without knowing user password? I am trying to provide an admin functionality where an admin is able to login as another user without knowing their password. All the site content is permission controlled. My questions are -

*

*Should I logout the admin user before switching to the user account?
Does that mean admin have to re-login?

*If I need to switch back to admin account - how do I go about this as the "User" don't have admin permissions but I previously logged in as an admin?

*Any other thing I need to keep in mind?

What do you suggest?

A: I'm not familiar with CI, but here's a generic solution:
When choosing to impersonate a user, you:

*

*Store the user id in the session as admin user id.

*Replace the user id in the session with the target user id (i.e. do whatever would happen during a successful login)

If an admin user id is present in the session, display an "end impersonation" link somewhere. When clicking that link, you:

*

*Replace the user id in the session with the admin user id.

*Remove the admin user id from the session.

A: *

*Dont destroy the admin session

*check if admin session is set
if(isset($_SESSION['admin']))
{
      //authenticate the user without checking the password,only check the uname
}
else
{
    //authenticate the user by checking both username and password
}

*Remember to keep two separate session for a user and admin.
I hope that will do


text:
Q: How can I convert this Python mutable function into immutable? I have a mutable Fibonacci function that mutates a list in order to return that list as a fib sequence. I want to do the same thing... but the list (or tuple in this case) should not be able to change. The return still has to send the whole list, how can I implement this, without using recursion.
Ex) if x = 6... list should return {1,1,2,3,5,8}
I'm running in python 3.5
Here is my code:
def mutableFib(x):
result = []
for y in range(0,x):
    if y < 2:
        result.append(1)
    else:
        last = result[y - 1]
        previous = result[y - 2]
        result.append(last + previous) //result is being changed
return result

A: You could create a new list for every new element.
def fibonacci(x):
    list_of_fibonaccis = []
    for y in range(0,x):
        if y < 2:
            temp_fibonacci = [1] * (y + 1)
        else:
            last = list_of_fibonaccis[y-1][-1]
            previous = list_of_fibonaccis[y-1][-2]
            temp_fibonacci = list_of_fibonaccis[y-1] + [last + previous]
        list_of_fibonaccis.append(temp_fibonacci)
    return list_of_fibonaccis[-1]

A: If I understand what you mean by "a functional approach that doesn't use recursion," it seems like the input parameter should be a list of the first n Fibonacci numbers and the output should be a list of the first n+1 Fibonacci numbers.  If this is correct, then you could use
def fibonacci(fib):
    if not fib: return [1]
    if len(fib) == 1: return [1,1]
    return fib + [fib[-1]+fib[-2]]


text:
Q: Javascript alert is not called in callback I am facing one problem in my javascript code.I am calling one url that is returning one partialview and loading it in a div.After that i have tablesorter method for pagination.But after loading that url paging is not working properly.
My code is below:
CODE SECTION:
function FileMastergridpage(text) {
    var url = encodeURI("Setpagesize_allrulesgrid?pagesize=" + text + "");
    jQuery("#ruledetailsgrid").load(url, paging_function() );
}

function paging_function (){
    alert('hello');
    jQuery("#StandardGridid").tablesorter();
    jQuery("#StandardGridid").tablesorterPager({ container: jQuery("#pagerOne"), positionFixed: false });
}

I am not able to get the 'hello' alert also.So any help will be highly appreciated..

A: It should be:
jQuery("#ruledetailsgrid").load(url, paging_function);

You're calling the function immediately, not passing it as a callback.

A: Your code will either be like this :
function FileMastergridpage(text) {
var url = encodeURI("Setpagesize_allrulesgrid?pagesize=" + text + "");
jQuery("#ruledetailsgrid").load(url,function() {

alert('hello');
jQuery("#StandardGridid").tablesorter();
jQuery("#StandardGridid").tablesorterPager({ container: jQuery("#pagerOne"),     positionFixed: false });
 });

or :
 function FileMastergridpage(text) {
var url = encodeURI("Setpagesize_allrulesgrid?pagesize=" + text + "");
jQuery("#ruledetailsgrid").load(url, paging_function );
 }

function paging_function (){
alert('hello');
jQuery("#StandardGridid").tablesorter();
jQuery("#StandardGridid").tablesorterPager({ container: jQuery("#pagerOne"), positionFixed: false });
}


text:
Q: Show that this processes are martingales I have to show that the following two processes are martingales

*

*$M_t=g(t)B_t-\int_0^tg'(s)B_sds$

*$X_t=\exp\left(e^tB_t-\int^t_0e^sB_sds-\frac{e^{2t}}{4}+\frac{1}{4}\right)$
Where $g(t)$ is a real valued continuously differentiable function and $B_t$ is a brownian motion.
I tried the first part straight forward but without success. I guess I can not simply use Fubini here to switch expectation and integration. So I believe it has something to do with Ito. But i really don't know how to apply it here to show that 1. is a martingale.
For the second process: I know that the first two terms in the exponent are 1. with $g(t)=e^t$ so this is a martingale. I assume I also have to apply Ito here aswell, but like in 1., I'm not sure how.


text:
Q: How to add h4 tag to refinerycms editor? I'm trying to add an h4 tag to the refinerycms wysiwyg editor. How do i do this? Not finding any documentation on this.
I'm assuming i have to do something with this config var:
config.wymeditor_whitelist_tags = {}

A: The following instructions apply to versions 2.x.x and 3.x.x of Refinery CMS.
However, in version 3.x.x you will need to use custom_visual_editor_boot_options instead of custom_wymeditor_boot_options.
Using this file: https://github.com/refinery/refinerycms/blob/master/core/app/assets/javascripts/admin.js you can specify custom options for WYMeditor in Refinery.
First, you need to override the file:
bundle exec rake refinery:override javascript=admin

Now, open app/assets/javascripts/admin.js and edit it to be like the following:
// Use this to customize the wymeditor boot process
// Just mirror the options specified in boot_wym.js with the new options here.
// This will completely override anything specified in boot_wym.js for that key.
// e.g. skin: 'something_else'
if (typeof(custom_wymeditor_boot_options) == "undefined") {
  custom_wymeditor_boot_options = {
    containersItems: [
      {'name': 'h1', 'title':'Heading_1', 'css':'wym_containers_h1'}
      , {'name': 'h2', 'title':'Heading_2', 'css':'wym_containers_h2'}
      , {'name': 'h3', 'title':'Heading_3', 'css':'wym_containers_h3'}
      , {'name': 'h4', 'title':'Heading_4', 'css':'wym_containers_h4'}
      , {'name': 'p', 'title':'Paragraph', 'css':'wym_containers_p'}
    ]
  };
}

Note that what you are doing is overriding boot_wym.js.erb which only specifies h1, h2, h3 and p as container tags. See: https://github.com/refinery/refinerycms/blob/2-0-stable/core/app/assets/javascripts/refinery/boot_wym.js.erb#L49-L54
Any options that you specify inside custom_wymeditor_boot_options override anything inside wymeditor_boot_options in boot_wym.js.erb so make sure that it's valid Javascript or else the editors won't load at all.
Hope that helps; let me know if you need anything clarified.
Phil


text:
Q: How to recover the Windows 7 partition in Ubuntu 12.04 I had Windows 7 and Ubuntu 12.04 in my machine, and after trying to mount and unmount a SD card, my Windows 7 "has hidden him self",
When i power on the computer,i can enter the Grub and choose
Windows 7 (loader) (on /dev/sda1)

but, it says
error: no such device: B6606771606736F1.
error: invalid signature.

How can I recover my Windows 7?
when i do sudo fdisk -l it appearsthis
Disk /dev/sda: 750.2 GB, 750156374016 bytes
255 heads, 63 sectors/track, 91201 cylinders, total 1465149168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0xfeff8cfd

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048   523655167   261826560    7  HPFS/NTFS/exFAT
/dev/sda2       523655168  1359239167   417792000    7  HPFS/NTFS/exFAT
/dev/sda3      1359241214  1465147391    52953089    5  Extended
Partition 3 does not start on physical sector boundary.
/dev/sda5      1359241216  1448818687    44788736   83  Linux
/dev/sda6      1448820736  1465147391     8163328   82  Linux swap / Solaris

Disk /dev/sdb: 24.0 GB, 24015495168 bytes
255 heads, 63 sectors/track, 2919 cylinders, total 46905264 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x74f02dea

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1   *        2048    46901247    23449600    7  HPFS/NTFS/exFAT

Help please...


text:
Q: How to reduce text in terminal on Visual Studio Code 2? I'm not even sure how to effectively ask this question, but I'm new to Visual Studio Code 2 and every time I run anything, let's say a simple print function, the output shows me all the directories and unnecessary text that to me just seems like clutter. How can I remove the directories for a simple and clean output on terminal?

A: The commands you provided are the description of the debugging. It can help users to clearly know what the VSCode doing through the commands.
It has no way to remove it, and it's helpful in fact. If you really want to reduce the outputs, you can click the green triangle on the top right. It will run the python file only without debugging.


text:
Q: Is T-SQL Stored Procedure Execution 'atomic'? Let's say I have a simple stored procedure that looks like this (note: this is just an example, not a practical procedure):
CREATE PROCEDURE incrementCounter AS

DECLARE @current int
SET @current = (select CounterColumn from MyTable) + 1

UPDATE
    MyTable
SET
    CounterColumn = current
GO

We're assuming I have a table called 'myTable' that contains one row, with the 'CounterColumn' containing our current count.
Can this stored procedure be executed multiple times, at the same time?
i.e. is this possible:
I call 'incrementCounter' twice.  Call A gets to the point where it sets the 'current' variable (let's say it is 5).  Call B gets to the point where it sets the 'current' variable (which would also be 5).  Call A finishes executing, then Call B finishes.  In the end, the table should contain the value of 6, but instead contains 5 due to the overlap of execution

A: This is for SQL Server.
Each statement is atomic, but if you want the stored procedure to be atomic (or any sequence of statements in general), you need to explicitly surround the statements with
BEGIN TRANSACTION
Statement ...
Statement ...
COMMIT TRANSACTION
(It's common to use BEGIN TRAN and END TRAN for short.)
Of course there are lots of ways to get into lock trouble depending what else is going on at the same time, so you may need a strategy for dealing with failed transactions. (A complete discussion of all the circumstances that might result in locks, no matter how you contrive this particular SP, is beyond the scope of the question.) But they will still be resubmittable because of the atomicity. And in my experience you'll probably be fine, without knowing about your transaction volumes and the other activities on the database. Excuse me for stating the obvious.
Contrary to a popular misconception, this will work in your case with default transaction level settings.

A: In addition to placing the code between a BEGIN TRANSACTION and END TRANSACTION, you'd need to ensure that your transaction isolation level is set correctly.
For example, SERIALIZABLE isolation level will prevent lost updates when the code runs concurrently, but READ COMMITTED (the default in SQL Server Management Studio) will not.
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

As others have already mentioned, whilst ensuring consistency, this can cause blocking and deadlocks and so may not be the best solution in practice.

A: I use this method
CREATE PROCEDURE incrementCounter
AS

DECLARE @current int

UPDATE MyTable
SET
  @current = CounterColumn = CounterColumn + 1

Return @current

this procedure do all two command at one time and it is isolate from other transaction.

A: Maybe I'm reading too much into your example (and your real situation may be significantly more complicated), but why wouldn't you just do this in a single statement?
CREATE PROCEDURE incrementCounter AS

UPDATE
    MyTable
SET
    CounterColumn = CounterColumn + 1

GO

That way, it's automatically atomic and if two updates are executued at the same time, they'll always be ordered by SQL Server so as to avoid the conflict you describe. If, however, your real situation is much more complicated, then wrapping it in a transaction is the best way to do this.
However, if another process has enabled a "less safe" isolation level (like one that allows dirty reads or non-repeatable reads), then I don't think a transaction will protect against this, as another process can see into the partially updated data if it's elected to allow unsafe reads.

A: Short answer to your question is YES it can and will come up short.  If you want to block concurrent execution of stored procedures start a transaction and update the same data in every execution of the stored procedure before continuing to do any work within the procedure.
CREATE PROCEDURE ..
BEGIN TRANSACTION
UPDATE mylock SET ref = ref + 1
...

This will force other concurrent executions to wait their turn since they will not be able to change 'ref' value until the other transaction(s) complete and associated update lock is lifted.
In general it is a good idea to assume result of any and all SELECT queries are stale before they are ever even executed.  Using "heavy" isolation levels to workaround this unfortunate reality severely limits scalability.  Much better to structure changes in a way which make optimistic assumptions about state of system you expect to exist during the update so when your assumption fail you can try again later and hope for a better outcome.  For example:
UPDATE
    MyTable
SET
    CounterColumn = current
WHERE CounterColumn = current - 1

Using your example with added WHERE clause this update does not affect any rows if assumption about its current state fails.  Check @@ROWCOUNT to test number of rows and rollback or some other action as appropriate while it differs from expected outcome.


text:
Q: Какой парсер может парсить только  игнорируя body(не скачивая body) Уже долго выискиваю быстрые html парсеры для парсинга большого количества сайтов(очень) и пока что знаю только 2 хороших варианта - zombie.js и scrapy. Оба достаточно быстрые но у них обоих есть минус - если парсится страница то скачивается тоже вся страница, нельзя к примеру собрать только значения тайтлов или скриптов(<script>) в <head> без скачивания <body> а это очень напрягает сервер при больших страницах.
Кто знает, напишите быстрые аналоги этих парсеров с схожей функцией(если такие есть). Буду очень благодарен


text:
Q: degrees of freedom for t-statistic comparing two networks I'm reading the following paper on non-parametric standard errors and tests for network statistics - https://www.stats.ox.ac.uk/~snijders/Snijders_Borgatti.pdf  by Snijders & Borgatti.
When comparing e.g. the density of two networks, we can calculate a t-statistic using the formula:

Where Z1 and Z2 are the observed densities of each network, and SE1 and SE2 are the standard errors derived from bootstrapped samples of each network.
My question is, to generate a p-value for this t-statistic, what degrees of freedom should we be using (in the example they cite, network 1 has an N of 16 vertices, and network 2 an N of 15 vertices)?  Is it analogous to the Student's t-test, so df = N1+N2-2 ?

A: If you believe that the number of edges coming from a vertex is reasonably approximated as normal, and the networks share maximum cardinality, then the $Z$s can be viewed as means of Gaussian random samples scaled by a constant. This constant, the total number of possible edges in the graph, is also implicitly present in the standard error estimates in the denominator and cancels out. Then the statistic is reduced to the same conditions as Student's t, and $t \sim T_{N_1 + N_2 -2}$ if you're willing to also willing to ignore the effect of dependence between observations (an edge correlates the counts for two vertices).
However, the laundry list assumptions above raises an eyebrow. Seeing as you're already comfortable with bootstrapping, I would advise considering a randomization test, which provides similar inference without the listed assumptions, at the cost of some power.


text:
Q: Unable to stop a windows service with net stop command I have created a windows service which is running fine by doing the following.
 SC_HANDLE hService = ::CreateService(*m_ServiceConfig,         // SCM database
                                                name.c_str(),               // name of service
                                                displayname.c_str(),        // service name to display
                                                SERVICE_ALL_ACCESS,         // desired access

                                                SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,    // service type (interactive for debug)

                                                SERVICE_AUTO_START,         // start type
                                                SERVICE_ERROR_NORMAL,       // error control type
                                                path.c_str(),               // path to service's binary
                                                nullptr,                    // no load ordering group
                                                nullptr,                    // no tag identifier
                                                dependencies,               // dependencies
                                                nullptr,                    // LocalSystem account
                                                nullptr);                   // no password

As you can see i specified the access to be  SERVICE_ALL_ACCESS and online this constant states that you have access to pause continue and stop the service,
However when i run the command net stop <service-name> i get the following ouput

the requested pause continue or stop is not valid for this service

my question is is there anything wrong with the way im creating the service?
Service Control Handler function
DWORD WINAPI ServiceControlHandler(DWORD dwControl, DWORD dwEventType, LPVOID /*lpEventData*/, LPVOID /*lpContext*/)
{
    // Handle the requested control code.

    switch (dwControl)
    {
    case SERVICE_CONTROL_STOP:
    TVLOG_INFO(L"SERVICE_CONTROL_STOP");
    {
        MessageBoxA(NULL, "Please stop the service", "Uninstall service error!", MB_OK | MB_ICONERROR);

    }

A: The access rights you specify in the dwDesiredAccess parameter of CreateService() have no effect on the net stop command.  The access rights only apply to the returned SC_HANDLE and effect how that handle interacts with subsequent API calls.
The error you are seeing is most likely being caused by your calls to SetServiceStatus() not including the SERVICE_ACCEPT_STOP flag in the SERVICE_STATUS::dwControlsAccepted field.
SERVICE_STATUS structure

dwControlsAccepted
  The control codes the service accepts and processes in its handler function (see Handler and HandlerEx). A user interface process can control a service by specifying a control command in the ControlService or ControlServiceEx function. By default, all services accept the SERVICE_CONTROL_INTERROGATE value. To accept the SERVICE_CONTROL_DEVICEEVENT value, the service must register to receive device events by using the RegisterDeviceNotification function.
The following are the control codes.
...
SERVICE_ACCEPT_STOP
  0x00000001
The service can be stopped.
This control code allows the service to receive SERVICE_CONTROL_STOP notifications.


text:
Q: Linux command for moving, merging and renaming duplicates I am trying to move directories (with sub-directories and files) to another directory. With mv some folders are not merging because the same directory exists with files. This is no good because even if the files are more recent in the source directories they are being deleted upon the move.
I need a command that will:

*

*move directories that do not exist in the destination directory, and;

*merge directories that already exists in the destination directory, and;

*rename any duplicate files (eg: file.txt already exists, renames the source file to file(1).txt)

I have not been able to find anything that can handle all of this.
Edit
I have tried using the following command:
mv -u [source] [destination]

It only moves the directories that do not exist in the destination, and I believe discards any that are duplicated with content. So, any newer files from the source directory are lost upon moving. Instead, these directories should merge and rename any duplicate files. Hope I have explained this well enough.
P.S. This would work best if written in a terminal command, I am not experienced with creating scripts.
Thanks for any help!

A: The files may not be going where you think. I recommend using the -t or -T option of mv.

A: Here's what I eventually used just to accomplish what I needed. It's not perfect but with moving that many directories this took care of 99% of the move/merge.
First, I used 'mv' to move all the directories to the new destination that didn't exist there. Each of the destination folders are labeled as follows, "a, b, c...". I wanted each source directory starting with an "A" to move to its respective destination directory ("a").
mv -u /[source directory]/A* /[destination directory]/a && mv -u /[source directory]/B* /[destination directory]/b && so on and so on...

This did not move all of the directories because a % of them already existed in the destination. So next, I ran rsync very similarly to the above command:
rsync --progress --remove-source-files -arvu /[source directory]/A* /[destination directory]/a && rsync --progress --remove-source-files -arvu /[source directory]/B* /[destination directory]/b && and so on and so on...

I had destination directories from A-Z and 0-9 so I just ran these commands over and over changing the letters and numbers and combining these commands with &&. It did the job but it's a lengthy commands as I am sure you can imagine.
To finish it off I ran the following command:
find . -type d -empty -print -delete

This took care of the empty directories left behind by rsync. Could this have all been done with just rsync? I don't know. I'm a rookie and learning something new here.
Like I said, not perfect but it worked for me and I hope this helps someone else.


text:
Q: Two questions around the $abc$-conjecture Let $d(a,b) = 1-\frac{2 \gcd(a,b)}{a+b}$, $d_{ABC}(a,b) = 1-\frac{2\gcd(a,b)^3}{ab(a+b)}$ be two metrics on natural numbers.
The abc-conjecture can be formulated using these two metrics as:
For every $\epsilon >0 $ there exists a $K_{\epsilon}$ such that:
$$d(a,b) < D_{\epsilon}(a,b):=1-\frac{2}{K_{\epsilon}\text{rad}(\frac{2}{1-d_{ABC}(a,b)})^{1+\epsilon}}$$
Trying make $D$ to a metric on natural numbers, leads to $K_{\epsilon} = \frac{1}{2^\epsilon}$.
One can prove that with this choice of $K_{\epsilon}$, $D$ is a metric on natural numbers.
Now this is a very explicit version of the abc-conjecture, and for example for $\epsilon = 1/2$ this version is wrong but my conjecture is that for $\epsilon \ge 1$ this is true.
My question is:
1) There are various results which build upon the abc-conjecture. Is there $0 < \epsilon < 1$ needed, or is it enough to have $\epsilon \ge 1$?
I have tested this with the Schoenberg-Criterion for some $\epsilon$ and some numbers $n$:
2) Is the metric $D_{\epsilon}$ for every $\epsilon>0$ embeddable in Euclidean Space? (Maybe this is too much to ask.)
(This seems very counterintuitive, because of the radical function one would not expect the $D$ to be so nice to behave as to embedd in Euclidean Space.)
Thanks for your help!
Edit:
Making the following Ansatz:
Suppose that $\phi(a)$ is the vector which embedds the natural number $a$.
Then $ D_1(a,b)^2 = |\phi(a)|^2+|\phi(b)|^2 - 2 \left< \phi(a), \phi(b) \right>$
If we assume that:
$$\left< \phi(a), \phi(b) \right> = \frac{-2}{R(a,b)^2}(\frac{4}{R(a,b)^2}-2)$$
where $R(a,b) = \text{ rad }(\frac{ab(a+b)}{\gcd(a,b)^3})$
then we get, substituting $a=b$ that $|\phi(a)| = \frac{1}{\sqrt{2}}$
So this is of course no proof, but if $\phi$ existed, then the matrix
$$G_n = (\frac{-2}{R(a,b)^2}(\frac{4}{R(a,b)^2}-2))_{1 \le a,b \le n}$$
should be positive definite, which I have checked for $n$ up to $20$ in Sagemath, and it is so.
So to be more precise about the question 2):
3) Is the matrix $G_n$ as defined above, positive definite?
Related question:
The abc-conjecture as an inequality for inner-products?


text:
Q: Python Antlr4 Brackets I'm in the middle of writing my grammar, but I can't tackle bracket problem and operations priority. 1 + 3 gives 4, but I need grammar to deal with
(1 + 3) * 3 = 12 problem and
1 + 3 * 3 = 12.
My grammar has only odd numbers, but it doesn't matter.
Here is my grammar code:
grammar PolishNotation;

fragment SINGLE_SPACE   : '\u0020'; // ' '
fragment TABULATION     : '\u0009'; // '\t'
fragment LINE_FEED      : '\u000A'; // '\n'
fragment CARRAIGE_RETURN: '\u000D'; // '\r'
fragment DECEVEN        : '0' | '2' | '4' | '6' | '8';
fragment DECODD         : '1' | '3' | '5' | '7' | '9';
fragment HEXEVEN        : '0' | '2' | '4' | '6' | '8' | 'A' | 'C' | 'E';
fragment HEXODD         : '1' | '3' | '5' | '7' | '9' | 'B' | 'D' | 'F';
fragment OCTEVEN        : '0' | '2' | '4' | '6';
fragment OCTODD         : '1' | '3' | '5' | '7';

Add           : '+';
Subtract      : '-';
Multiply      : '*';
Divide        : '/';
Colon         : ':' -> type(Divide);
Power         : '^';
DoubleMultiply: '**' -> type(Power);
Max           : 'max';
Min           : 'min';

Int           : (DECODD)
              | ([1-9]+ (DECODD | DECEVEN)* (DECODD))
              ;
Hex           : ('0x' (HEXODD))
              | ('0x' [1-F]+ (HEXODD | HEXEVEN)* (HEXODD))
              ;
Oct           : ('0o' (OCTODD))
              | ('0o' [1-7]+ (OCTODD | OCTEVEN)* (OCTODD))
              ;

WhiteSpace    : ( SINGLE_SPACE | TABULATION )+ -> skip;
NewLine       : ( CARRAIGE_RETURN | LINE_FEED )+ -> skip;

number        : Int | Hex | Oct
              ;
operation     : ( number )
                op=( Add
                | Subtract
                | Multiply
                | Divide
                | Power
                | Max
                | Min )
                ( number | operation )
                | '(' operation ')'
              ;
expression    : operation
              | number
              ;

A: Your grammar is missing two things here; precedence rules and recursive sub expressions (i.e. brackets).  A typical expression grammar will achieve this by breaking the expression down into a series of terms & factors as follows:
expression    : term ( ( Add | Subtract )  term )* ;
term          : factor ( ( Multiply | Divide ) factor )* ;
factor        : number | '(' expression ')' ;

There are numerous tutorials and books available on the theory and practice behind this so I won't duplicate that detail here (try this one or this one).

I need grammar to deal with (1 + 3) * 3 = 12 problem and 1 + 3 * 3 = 12

Here you are implying that Plus should have a higher precedence than Multiply (so not the typical BODMAS precedence rules), are you sure that is what you want?  If so I hope you'll be able to see how to rework the above in your grammar to give you the precedence you want.

A: Thank you very much, I appreciate your answer. I did something like this, but it doesnt work for every option:
number        : Int | Hex | Oct
              ;
operation     : ( ('(') ( number ) (op=(Add|Subtract|Multiply|Divide|Power|Max|Min)) ( number ) (')') )
              | number
              ;
muldiv        : ( ( operation ) (op=(Multiply|Divide)) ( operation ) )
              |operation
              ;
addsub        : ( ( muldiv ) (op=(Add|Subtract)) ( muldiv ) )
              | muldiv
              ;
expression    : ( (addsub) (op=(Add|Subtract|Multiply|Divide|Power|Max|Min) (addsub)) )
              | addsub
              | number
              ;


text:
Q: Proof of exponential inequality Claim: For any $c \in \mathbb{R}$ and any constant $\lambda > 0$ we have that $$\frac{e^{-\lambda c} + e^{\lambda c}}{2} \leq e^{(\lambda c)^2/2}$$
The place I observed the inequality proves it by taking the Taylor expansion on both sides of the equation but it seems to me that there should be a simpler way of proving it.
My initial idea was to apply the natural logarithm to both sides:
$$\ln(e^{-\lambda c} + e^{\lambda c}) - \ln(2) \leq \frac{1}{2}\lambda^2c^2$$
However, I got stuck here. Any ideas?


text:
Q: Change a homepage based on theme wordpress I have 2 themes in my WP installation: Theme, Theme2, and separately I have 2 Homepages, one for each theme.
Is it any way for me to change a homepage based on active theme dynamically?
So, Example if i'll activate Theme2, Homepage2 becomes a main homepage?
Ideally, i want something like:
if ( current_user_can( 'manage_options' ) ) {
    switch_theme('twentytwelve');
    /* Activate Homepage_1 */
  } else {
    switch_theme('twentythirteen');
    /* Activate Homepage_2 */
  }
}

A: Change a homepage based on theme wordpress
You can follow this steps and set the homepage page as you have activated the theme.

*

*Click on "Pages" from your dashboard.

*Click the "Add New" button on the top and create a new page called, "Homepage."

*Go to "Settings" from the dashboard, and click on "Reading."

*The first option available is called "Front Page Displays." Change it to "A static page."

*In the "Front Page" drop down, you should see your new homepage. Select it and save your changes.

*Go back into "Pages" and click on your homepage.

*Add the shortcodes you want to display.

*Update your homepage.


text:
Q: Limited number of geoms in ggforce? Trying to plot several circles in one dataset, seems that 10 is the max number of circles. How can I plot more than 10 circles?
library(tidyverse)
library(ggforce)

circles <- data.frame(
  x0 = rep(1:3, 10),
  y0 = rep(1:3, each = 10),
  r = seq(0.1, 1, length.out = 30)
)

ggplot() +
  geom_circle(aes(x0 = x0, y0 = y0, r = r, fill = r), data = circles) +
  coord_fixed()


text:
Q: WickedPdf and Rails 5.1.4: can't instantiate I want to generate a PDF in a ruby service used by a Rails 5.1.4 app. It fails kind of quickly.
class PdfRenderer
  require 'wicked_pdf'

  def self.generate
    WickedPdf.new.pdf_from_string('
Hello There!
')
  end
end

When I call PdfRenderer.generate in my rspec tests, I get that error:
NoMethodError Exception: undefined method `pdf_from_string' for nil:NilClass

I can't instantiate the WickedPdf class. When I call WickedPdf.new in byebug, I get nil.
The stacktrace:
NoMethodError:
   undefined method `pdf_from_string' for nil:NilClass
 # ./app/services/pdf_renderer.rb:25:in `generate'
 # ./spec/services/pdf_renderer_spec.rb:40:in `block (2 levels) in <top (required)>'
 # /usr/local/bundle/gems/spring-commands-rspec-1.0.4/lib/spring/commands/rspec.rb:18:in `call'
 # /usr/local/bundle/gems/spring-2.0.2/lib/spring/command_wrapper.rb:38:in `call'
 # /usr/local/bundle/gems/spring-2.0.2/lib/spring/application.rb:201:in `block in serve'
 # /usr/local/bundle/gems/spring-2.0.2/lib/spring/application.rb:171:in `fork'
 # /usr/local/bundle/gems/spring-2.0.2/lib/spring/application.rb:171:in `serve'
 # /usr/local/bundle/gems/spring-2.0.2/lib/spring/application.rb:141:in `block in run'
 # /usr/local/bundle/gems/spring-2.0.2/lib/spring/application.rb:135:in `loop'
 # /usr/local/bundle/gems/spring-2.0.2/lib/spring/application.rb:135:in `run'
 # /usr/local/bundle/gems/spring-2.0.2/lib/spring/application/boot.rb:19:in `<top (required)>'
 # -e:1:in `'


text:
Q: What would be the exact procedure to add new nodes to a Cassandra cluster so that the cluster remains balanced? I've read the relevant documentation I could find, but I still have doubts.
What I read
From http://wiki.apache.org/cassandra/Operations#Moving_nodes

If you add nodes to your cluster your ring will be unbalanced and only way to get perfect balance is to compute new tokens for every node and assign them to each node manually by using nodetool move command.

and from http://www.datastax.com/docs/1.1/operations/cluster_management#adding-capacity-to-an-existing-cluster

If you need to increase capacity by a non-uniform number of nodes, you must recalculate tokens for the entire cluster, and then use nodetool move to assign the new tokens to the existing nodes. After all nodes are restarted with their new token assignments, run a nodetool cleanup to remove unused keys on all nodes

But I'm not clear on the order of these things.
Could you explain how to do it in the following scenario?

*

*I'm using cassandra 1.1.9, so no virtual nodes are in use.

*I have a cluster ring with 5 nodes, and each owns 20%

*Their tokens are

*

*0

*34028236692093846346337460743176821145

*68056473384187692692674921486353642291

*102084710076281539039012382229530463436

*136112946768375385385349842972707284582

I want to add 2 additional nodes.
What steps do I have to follow? I know I should install and configure cassandra, use the original 5 as seeds, and calculate their new tokens, but in what order should I move the data using nodetool move? Is it one at a time?
What happens with the data when I move the first one? Is it available at all times?
Should I start the two new nodes before moving the original 5 to their new tokens?
A step by step guide would be ideal.
Please note that I need to do it pre version 1.2

A: The new tokens should be

*

*0

*24305883351495604533098186245126300818

*48611766702991209066196372490252601636

*72917650054486813599294558735378902454

*97223533405982418132392744980505203272

*121529416757478022665490931225631504090

*145835300108973627198589117470757804908

calculated using 2^127/7 * {0-7}.

What steps do I have to follow?
  in what order should I move the data using nodetool move?

You should

*

*Bootstrap in one node at 48611766702991209066196372490252601636

*Bootstrap the other node at 121529416757478022665490931225631504090

*Move 34028236692093846346337460743176821145 to 24305883351495604533098186245126300818

*Move 68056473384187692692674921486353642291 to 72917650054486813599294558735378902454

*Move 102084710076281539039012382229530463436 to 97223533405982418132392744980505203272

*Move 136112946768375385385349842972707284582 to 145835300108973627198589117470757804908

(I tried to minimise the amount of data transferred - might not be optimal but is close enough to not make much difference given the inbalance of data you probably have already.)

Is it one at a time?

You should bootstrap one node and once and move one token at once.  This avoids placing excess load on the cluster while streaming data.

What happens with the data when I move the first one? Is it available at all times?

Data is fully available during the move. The node participates in reads and writes for the old and new range so you can read and write during the move.

Should I start the two new nodes before moving the original 5 to their new tokens?

Always better to have more nodes in the cluster - if you moved first, you'd have some nodes with twice as much data as the others.

A: From Cassandra 1.2, keeping a cluster balanced when adding nodes is very easy, because of the new vnodes (multiple seeds per node) feature. Cassandra now automatically balances the cluster for you. If you upgrade from an earlier version you will have to activate the vnode feature yourself


text:
Q: Configuring VCS of Teamcity for code checkout I am trying to specify rather complicated labeling rule in VCS of Teamcity. Not sure if what I am trying to do is possible or not.
This is my directory structure I have inherited.
mysvn/abc/repos
    |
    -TestDomain
    -TestSystem
     |
      -MyFrameWork
      -MySoftware
         |
          -MySoftwareDevices
          -MySoftwareFiles
                       |
                       -branches
                       -tags
                       -trunk1
     -MySoftwareDriver
         |
          - branches
          - tags
          - trunk2

I want to specify such a rule that in the working directory of the checkout directory of Teamcity has structure like this:
 Teamcity checkout directory
  |
   -FolderA
   -FolderB

Where FolderA has contents of trunk1 and FolderB has contents of trunk2.
Is it possible to be done?
SVN URL like:
mysvn/abc/repos/TestSystem/MySoftware/MySoftwareFiles/trunk1
does give me trunk1. But I need contents of trunk1 and trunk2 under two different folders in the same build checkout directory.
Labeling I have been using: trunk=>tags

A: Ok got the thing working. Its kind of hit and trial. Hoping someone comes up with proper explanations.
Labeling rules still has:
 trunk=>tags

The SVN URL : mysvn/abc/repos/TestSystem
It is the checkout rules which I added:
-:.
+:MySoftware/MySoftwareFiles/trunk1=>MyDir/FolderA
+:MySoftware/MySoftwareDriver/trunk2=>MyDir/FolderB


text:
Q: allow user to download dynamic csv file asp.net I want to allow my user to click on a button that says "download" and then will build a dynamic csv file on the fly and will prompt the user to download.   I know how to build the file using a HTTPHandler, but not quite sure the mechanism for delivering the content via download.

A: I usually create a Generic Handler (.ashx) and do something like this:
public void ProcessRequest(HttpContext context)
{
   StringBuilder myCsv = new StringBuilder();
   foreach(myRow r in myRows) {
     myCsv.AppendFormat("\"{0}\",{1}", r.MyCol1, r.MyCol2);
   }

   context.Response.ContentType = "application/csv";
   context.Response.AddHeader("content-disposition", "attachment; filename=myfile.csv");
   context.Response.Write(myCsv.ToString());
}

Now if the CSV you're building is REALLY big, you might want to write out each row as you create it, rather than stuffing it into a StringBuilder.

A: Just emit a Content-Disposition HTTP header in your HTTP Handler code. Most browsers will interpret that as a download request. Replace yourfile.csv by the filename you want the user to see.
context.Response.ContentType = "text/csv";
context.Response.AddHeader("Content-Disposition", "attachment; filename=yourfile.csv");


text:
Q: Convert Enum into underlying type I have an enum as follows
type Suit =
    |Clubs = 'C'
    |Spades = 'S'
    |Hearts = 'H'
    |Diamonds = 'D'

How do I get the underlying char value if given enum value?
eg I have Suit.Clubs and want to get 'C'

A: You can use functions from the LanguagePrimitives module:
// Convert enum value to the underlying char value
let ch = LanguagePrimitives.EnumToValue Suit.Clubs

// Convert the char value back to enum
let suit = LanguagePrimitives.EnumOfValue ch

EDIT: I didn't see these functions in my first answer attempt, so I first suggested using:
unbox<char> Suit.Clubs

This is shorter than what ildjarn suggests in a comment, but it has the same problem - there is no checking that you're actually converting to the right type. With EnumToValue, you cannot make this mistake, because it always returns the value of the right underlying type.

A: as another option
type Suit =
    |Clubs = 'C'
    |Spades = 'S'
    |Hearts = 'H'
    |Diamonds = 'D'

let c = Suit.Clubs
let v : char = LanguagePrimitives.EnumToValue c

EDITED:
Comparison of different approaches:
type Suit =
    |Clubs = 'C'
    |Spades = 'S'
    |Hearts = 'H'
    |Diamonds = 'D'

let valueOf1 (e : Suit) = LanguagePrimitives.EnumToValue e
let valueOf2 (e : Suit) = unbox<char> e
let valueOf3 (e : Suit) = (box e) :?> char

And under the hood:
.method public static
    char valueOf1 (
        valuetype Program/Suit e
    ) cil managed
{
    // Method begins at RVA 0x2050
    // Code size 3 (0x3)
    .maxstack 8

    IL_0000: nop
    IL_0001: ldarg.0
    IL_0002: ret
} // end of method Program::valueOf1

.method public static
    char valueOf2 (
        valuetype Program/Suit e
    ) cil managed
{
    // Method begins at RVA 0x2054
    // Code size 13 (0xd)
    .maxstack 8

    IL_0000: nop
    IL_0001: ldarg.0
    IL_0002: box Program/Suit
    IL_0007: unbox.any [mscorlib]System.Char
    IL_000c: ret
} // end of method Program::valueOf2

.method public static
    char valueOf3 (
        valuetype Program/Suit e
    ) cil managed
{
    // Method begins at RVA 0x2064
    // Code size 13 (0xd)
    .maxstack 8

    IL_0000: nop
    IL_0001: ldarg.0
    IL_0002: box Program/Suit
    IL_0007: unbox.any [mscorlib]System.Char
    IL_000c: ret
} // end of method Program::valueOf3


text:
Q: error while node-gyp build I want to use c/c++ language in javascript(node.js), so I use addon, node-gyp.
And I make spi.cc(source file), this file make in /home/pi
  GNU nano 2.2.6               File: spi.cc

#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<wiringPi.h>
#include<wiringPiSPI.h>
#include<node.h>
#include<v8.h>

#define CS_MCP3208 10
#define SPI_CHANNEL 0
#define SPI_SPEED 1000000

using namespace v8;

int read_mcp3208_adc(unsigned char adcChannel)
{
        unsigned char buff[3];
        int adcValue = 0 ;
        buff[0] = 0x06 |((adcChannel & 0x07 ) >>2);
        buff[1] = ((adcChannel & 0x07) << 6);
        buff[2] = 0x00;

        digitalWrite(CS_MCP3208,0);
        wiringPiSPIDataRW(SPI_CHANNEL,buff,3);
        buff[1] = 0x0F & buff[1];
        adcValue = (buff[1] << 8)| buff[2];
        digitalWrite(CS_MCP3208,1);

        return adcValue;
}
Handle<Valude> GetValue(const Arguments& args)
{
        HandleScope scope;
        int adcValue = 0;
        float temp = 0.0;

        wiringPiSetup();
        wiringPiSPISetup(SPI_CHANNEL,SPI_SPEED);

        temp = (read_mcp3208_adc(0)/24.818)-40;

        return scope.Close(Number::New(temp);
}
void Init(Handel<Object> exports)
{
        exports->Set(String::NewSymbol("getValue"),FunctionTemplate::New(GetVal$
}

NODE_MODULE(myaddon, Init)

And I make binding.gyp, this file make in /home/pi,too.
  GNU nano 2.2.6             File: binding.gyp

{
        "targets":[
        {
                "target_name": "spi",
                "sources": ["./spi.cc"]
        }
        ]
}

I use node-gyp build after I finish node-gyp configure
Then I watch the this error.
root@raspberrypi:/home/pi# node-gyp build
gyp info it worked if it ends with ok
gyp info using node-gyp@1.0.2
gyp info using node@0.10.32 | linux | arm
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
make: Entering directory '/home/pi/build'
  CXX(target) Release/obj.target/spi/spi.o
../spi.cc:31:8: error: 'Valude' was not declared in this scope
../spi.cc:31:14: error: template argument 1 is invalid
../spi.cc: In function 'int GetValue(const v8::Arguments&)':
../spi.cc:42:38: error: expected ')' before ';' token
../spi.cc:34:6: warning: unused variable 'adcValue' [-Wunused-variable]
../spi.cc: At global scope:
../spi.cc:44:11: error: variable or field 'Init' declared void
../spi.cc:44:11: error: 'Handel' was not declared in this scope
../spi.cc:44:24: error: expected primary-expression before '>' token
../spi.cc:44:26: error: 'exports' was not declared in this scope
../spi.cc:49:1: error: 'Init' was not declared in this scope
../spi.cc:49:1: note: suggested alternative:
/root/.node-gyp/0.10.32/src/node.h:93:8: note:   'node::Init'
../spi.cc: In function 'int GetValue(const v8::Arguments&)':
../spi.cc:43:1: warning: control reaches end of non-void function [-Wreturn-type]
spi.target.mk:82: recipe for target 'Release/obj.target/spi/spi.o' failed
make: *** [Release/obj.target/spi/spi.o] Error 1
make: Leaving directory '/home/pi/build'
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/local/lib/node_modules/node-gyp/lib/build.js:267:23)
gyp ERR! stack     at ChildProcess.emit (events.js:98:17)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:810:12)
gyp ERR! System Linux 3.12.28+
gyp ERR! command "node" "/usr/local/bin/node-gyp" "build"
gyp ERR! cwd /home/pi
gyp ERR! node -v v0.10.32
gyp ERR! node-gyp -v v1.0.2
gyp ERR! not ok

I think, my spi.cc file don't find v8.h and node.h.
I use raspberry pi. I have never used c/c++ language in linux.

A: First of all, look at the error descriptions... you have some typos, notably Valude instead of Value and Handel instead of Handle.
Secondly, you might wrap your Init() function and NODE_MODULE() like this:
extern "C" {
  void Init(Handle<Object> exports)
  {
    exports->Set(String::NewSymbol("getValue"),FunctionTemplate::New(GetVal...
    NODE_MODULE(myaddon, Init)
  }

Lastly, the value you supply as the first argument to NODE_MODULE() must match what you have for target_name in your binding.gyp.


text:
Q: Multiple fact tables for each grain level Following up from this earlier question. How do you best model a set of facts that don't aggregate? For example a "score" for each city, each state, and each electorate. However the city scores don't add up equal the state scores, so they're independent.
Would this be an appropriate way to organise them in a data warehouse? Should I look to combine them in some other way?
Business questions being asked are:

*

*How does X city's score compare with Y city's score?

*Give me all the city's that score a 3 and tell me some other facts about them (e.g. population, gender)

*Show me the overall state score and how the cities within that state score


text:
Q: Pitfalls of deviating from the {controller}/{action}/{id} REST URL format for ASP.NET MVC? I will be launching a new site soon. One section of the site contains products.
I am currently trying to decide between different URLS for the ASP.NET routing :
**Products: **
 /products/1001
 /products/sku/1001
 /products/product/1001
 /products/view/1001

**Categories: **
 /products/category/cats
 /products/category/clothing

 /products/cats         - this is pretty nasty
 /products/clothing

I am primarily trying to decide which of the following I should adopt.
I am currently doing the first.
  routes.MapRoute(
    "product-route-short",
    "products/{sku}",
    new { controller = "Products", action = "ViewProduct", sku = "1001"}
  );

or
  routes.MapRoute(
    "product-route-short",
    "products/sku/{sku}",
    new { controller = "Products", action = "ViewProduct", sku = "1001"}
  );

or one of the following
 * call the action 'sku' , 'details' , 'item'
 * use an [ActionName] attribute and leave the action method name as 'ViewProduct'

I really like the simplicity of /products/1001 so the user can see it and change it - but there is quickly a danger of it conflicting with other actions if I'm not careful. I also have to be sure to use 'product-route-short' when creating my URLS which is a very minor pain.
What does anyone think? What have you found a best practice to be? This example is pretty simple, but I want to be consistent across the site of course and don't want to have to retrofit everything once Google has already indexed everything for me.
If there are any especially good podcasts or articles on the subject (general or specific to ASP.NET) I'd appreciate links to them. I found a good podcast where one thing they specifically said was that 'this podcast is NOT about how to create good REST links'

A: I would gear my URLs towards these goals...
1) Usability. It's really nice if you can tell what kind of page you'll get if you look at the URL. If it's short enough to type and/or guess, all the better.
2) Search Engines. You really want to get your keywords into those URLs. I know you want to use the ID to look up the product, but human beings and search engines want to see the product name there. Also, the closer a key word is to the start of the URL, the more importance is placed on it.
This is really just a skimming. If you want the best URLs you'll need to ensure the categories and product names are unique so you can look them up rather than using IDs in the address.
My suggested convention would be...
/products/
/products/clothing/
/products/clothing/blue-suede-shoes/

A: Note that SO itself lists this question on stackoverflow.com/questions/625213 (the / afterwards is ignored). So you at least have precedent :).

A: I think the shorter URLs you are making are fine. The beauty of the asp.net mvc routing engine is that, assuming you have made your links correctly in the views, you can make changes to the routes as you develop. So feel free to play around as you go.
Another thing to keep in mind is the constraints argument in the MapRoute method. You can always try something like this:
routes.MapRoute(
"product-route-short",
"products/{sku}",
new { controller = "Products", action = "ViewProduct", sku = "1001" } ,
new { sku = @"[0-9]" }
);

routes.MapRoute(
"product-route-other",
"products/{action}/id",
new { controller = "Products", action = "ViewProduct" }
);

That filter will make it so only skus between 0-9 will work. Obviously you would want to use a regex to fit your particular scenario, but that would help you avoid conflicts with actions. In this situation, if the value for sku was not between 0-9 then the routing engine would go to the next route and try to match that. It will do this until it finds a match.
With the combination of routes and constraints you should be able to have very clean url that make sense to the user.


text:
Q: how add tag model (ActsAsTaggableOn) in rails_admin? I install rails admin and include all model in active record in rails admin,
first time, when install rails admin display me this error
NoMethodError in RailsAdmin::MainController#index

undefined method `per_page_kaminari' for #<ActiveRecord::Relation:0x00000006713e18>

and fixed it by added this configure
Kaminari.configure do |config|
    config.page_method_name = :per_page_kaminari
end

when install acts_as_taggable_on gem in project, rails admin did't add tag model in it ( i added field tags_list in other model), but i want to add tag model in rails admin to manage tags (index,create,edit and destroy)..
I added this line
config.included_models = ['ActsAsTaggableOn::Tag']

in rails_admin.rb and it display me tag model in dashboard, but when open list tags, it display me again this error
NoMethodError in RailsAdmin::MainController#index

undefined method `per_page_kaminari' for #<ActiveRecord::Relation:0x00000006713e18>

what should i do to add tag model in rails admin and manage tags ?!

A: I had to solve the same issue here.
I used the gem 'rails_admin_tag_list' but latest version from rubygem is not updated for rails 4 (doesnt support RailsAdmin Property).
So you need to get the one from master that include the fix.
gem 'rails_admin_tag_list', git: 'https://github.com/kryzhovnik/rails_admin_tag_list.git', branch: 'master'

Indeed add:
config.included_models = ['YourModel', 'ActsAsTaggableOn::Tag']

and
class YourModel < ActiveRecord::Base
  acts_as_taggable # dont add attr_accessible stuff since we're in rails 4
end

then choose the config for tag list:
config.model 'YourModel' do
  configure :tag_list  do
    partial 'tag_list_with_autocomplete'
  end
  exclude_fields :body, :locale, :base_tags, :tags
end

A: The exact same issue occurs with ActiveAdmin: Manage acts_as_taggable tags with activeadmin. I solved it with the same solution:
Add an initializer to config/initializers with the custom Kaminari code:
Kaminari.configure do |config|
    config.page_method_name = :per_page_kaminari
end

Create a new class in app/models called tag.rb:
# This class fixes a bug between Kaminari, RailsAdmin, and ActsAsTaggableOn.
class Tag < ActiveRecord::Base
end

Use the Tag model instead of ActsAsTaggableOn::Tag in RailsAdmin config:
config.included_models = [Tag]

A: Here's my solution with rails 4 and fields configuration (must be before the congig.included_models call):
config.model ActsAsTaggableOn::Tag do
    edit do
      exclude_fields :taggings_count
      exclude_fields :taggings
    end
  end

  config.model ActsAsTaggableOn::Tagging do
    edit do
      exclude_fields :context
    end
  end

  admin_models = ActiveRecord::Base.descendants.map(&:name)
  admin_models.delete("PgSearch::Document") #if you use it
  admin_models.delete("PaperTrail::Version") #if you use it
  #add other models to exclude here
  config.included_models = admin_models


text:
Q: Is it possible to synchronously invoke an AWS Lambda function from Python Boto? This page shows only a method for asynchronous invocation.  I imagined there would be a synchronous invocation option.
http://boto.readthedocs.org/en/latest/ref/awslamba.html?highlight=invoke
Apparently it is possible with .NET:
How can I invoke an AWS Lambda function from my EC2 instance?

A: The documentation says to specify InvocationType as  RequestResponse for synchronous invocation
response = client.invoke(
    FunctionName='string',
    InvocationType= 'RequestResponse',
    LogType='None'|'Tail',
    ClientContext='string',
    Payload=b'bytes'|file,
    Qualifier='string'
)

A: You can certainly do this.
response = client.invoke(
    FunctionName='string',
    InvocationType='Event'|'RequestResponse'|'DryRun',
    LogType='None'|'Tail',
    ClientContext='string',
    Payload=b'bytes',
    Qualifier='string'
)

http://boto3.readthedocs.org/en/latest/reference/services/lambda.html#Lambda.Client.invoke


text:
Q: NPS Policy doesn't to respect the "Control access through NPS Policy" user attribute I have a Win2K8 server with NPS.  I am trying to set my VPN authentication on a FortiGate firewall to authorize users via Radius from my Windows server.
I have two policies configured

*

*a Connection Policy defining the client and the Radius secret

*a Network Policy defining the required AD group membership and the required requesting access server (ie the Firewall)

The Network Policy has the checkbox "Ignore user account dial-in properties" selected.
If the user account has "Control access through NPS Policy" selected on their dial-in properties page, access is denied.  If I change it to "Allow access", access is permitted.
If I leave it at "Allow access" and remove the user from the AD group required, then access is granted, which confuses me.
So what is required to get the NPS policy to determine if access is granted regardless of the Dial-In properties selected?
I found the other question on Server Fault which describes this problem, but the suggested solution of reordering the policies does not help.

A: The solution is: check your policies carefully.
In my case, I didn't read the critieria carefully enough, and both the Connection and Network policies defined referred to "Client IPv4 Address" instead of "Access Client IPv4 Address".

A: I know this is old, but I was having the same exact problem on one computer when trying to connect to our wireless network.  I went into my NPS network policy and selected to ignore dial-in properties, and I still could not connect to the network on this computer. I kept on getting an error 65 "The Network Access Permission setting in the dial-in properties of the user account in Active Directory is set to Deny access to the user. To change the Network Access Permission setting to either Allow access or Control access through NPS Network Policy, obtain the properties of the user account in Active Directory Users and Computers, click the Dial-in tab, and change Network Access Permission." in the event log on the NPS server security log.  Eventually, the solution was to remove my computer from AD, delete the AD account, uninstall my network adapters and restart the computer to allow them to re-install automatically.  After this I was able to connect to the network and authenticate successfully through the NPS.

A: I ran into this issue today... Make sure you are using AD CA and take the computer off the domain and re-join.


text: Q: Sending product attributes/variations to client with WooCommerce API I have a product that is a variable product with multiple different sizes: Small, Medium, Large, X-Large, XX-Large. I'm confused as to how WooCommerce stores these attributes in the database and links them to a product. Could someone explain the WooCommerce taxonomy to me as to how it knows that these product variations/attributes belong to a specific product? I've got a product ID with the ID of 370, and can't figure out how it links the sizes to that product. Thanks.