text:
Q: Mailkit connect to Office365 programmatically I need to get emails from my Office365 account programmatically (C#).
I decided to use Mailkit and to create an application password on Azure portal.
I registered a new app, set its Redirect Uri and gave it some permissions:

I then created a client secret to access the account without user interaction.
Now, here is my code:
var opt = new ConfidentialClientApplicationOptions()
{
    ClientId = "xxx_clientid",
    TenantId = "xx_tenant_id",
    ClientSecret = "xxx_client_secret_value",
    RedirectUri = "http://localhost",
};

var scopes = new string[] {
    "email",
    "offline_access",
    "https://outlook.office.com/IMAP.AccessAsUser.All", // Only needed for IMAP
    //"https://outlook.office.com/POP.AccessAsUser.All",  // Only needed for POP
    //"https://outlook.office.com/SMTP.Send", // Only needed for SMTP
};

var app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(opt).Build();
var authToken = await app.AcquireTokenForClient(scopes).ExecuteAsync(); // <--- Exception
var oauth2 = new SaslMechanismOAuth2(authToken.Account.Username, authToken.AccessToken);

using (var client = new ImapClient(new ProtocolLogger("imapLog.txt")))
{
    client.Connect("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect);
    //client.AuthenticationMechanisms.Remove("XOAUTH2");
    client.Authenticate(oauth2);
    var inbox = client.Inbox;
    inbox.Open(MailKit.FolderAccess.ReadOnly);
    Console.WriteLine("Total messages: {0}", inbox.Count);
    Console.WriteLine("Recent messages: {0}", inbox.Recent);
    client.Disconnect(true);
}

Running the code I get this exception:
Microsoft.Identity.Client.MsalServiceException: 'AADSTS70011: The provided request must include a 'scope' input parameter. The provided value for the input parameter 'scope' is not valid. The scope email offline_access https://outlook.office.com/IMAP.AccessAsUser.All is not valid.
I tried following the guide found on GitHub:
Using OAuth2 With Exchange
The problem is that I need to use an app password instead.


text:
Q: Order Events in Fullcalendar by Start date and End Date How can I order events in fullCalendar first by start date?
Example:

*

*An event which starts first will show on top and then one which starts later will be later

*If two events have same the start date then, order them by end date
i.e
an event which ends earlier will be shown first, followed by an event which ends later.

Calendar Display
Events Order
var args = jQuery.parseJSON(emCalendarArgs);
var Jobj = args.events;

// Setup FullCalendar

(function() {
  //var language = jQuery('#pg_lang').val();
  //alert(language+ 'dsfsd');
  var date = new Date();
  var d = date.getDate();
  var m = date.getMonth();
  var y = date.getFullYear();
  var language = langg;
  var mn_text, week_text, day_text, list_text;

  //alert(mn_text);
  var args = jQuery.parseJSON(emCalendarArgs);
  var Jobj = args.events;
  console.log(Jobj);
  jQuery('#events-full-calendar').fullCalendar({

    allDaySlot: false,
    editable: true,
    lang: 'he',
    handleWindowResize: true,
    eventOrder: 'start,end',
    header: {
      left: 'today prev,next',
      center: 'title',
      right: 'month,basicWeek,basicDay'
    },
    buttonText: {
      month: mn_text,
      week: week_text,
      day: day_text
    },
    eventLimit: {
      'month': 3, // adjust to 4 only for months
      'default': false // display all events for other views
    },
    axisFormat: 'HH:mm',
    timeFormat: {
      agenda: 'H:mm{ - h:mm}'
    },
    slotEventOverlap: false,
    events: Jobj,
    timeFormat: 'H:mm',
  });
}());

A: I found a Solution to it. For any one else looking for the solution to this, I changed a function in fullcalendar.js:
compareSegs: function(seg1, seg2) { return seg1.eventStartMS - seg2.eventStartMS || // earlier events go first seg2.eventDurationMS - seg1.eventDurationMS || // tie? longer events go first seg2.event.allDay - seg1.event.allDay || // tie? put all-day events first (booleans cast to 0/1) compareByFieldSpecs(seg1.event, seg2.event, this.view.eventOrderSpecs); }

to :
compareSegs: function(seg1, seg2) {
        if(this.view.name=="basicWeek" || this.view.name=="month" || this.view.name=="basicDay"){ // ordering events by color in ListView
        return seg2.event.allDay - seg1.event.allDay || // tie? put all-day events first (booleans cast to 0/1)
            compareByFieldSpecs(seg1.event, seg2.event, this.view.eventOrderSpecs);
        }
        else{
            return seg1.eventStartMS - seg2.eventStartMS || // earlier events go first
                        seg2.eventDurationMS - seg1.eventDurationMS || // tie? longer events go first
                        seg2.event.allDay - seg1.event.allDay || // tie? put all-day events first (booleans cast to 0/1)
                        compareByFieldSpecs(seg1.event, seg2.event, this.view.eventOrderSpecs);
        }
    }

and used below code in fullcalendar function
eventOrder: 'start, end'

in my fullcalendar call

redpajama_set_name: RedPajamaStackExchange


text:
Q: Subsetting data from R data frame using incremental variable names I have an R data frame, df, with column names V1, V2, V3...V1000. I need to subset df by selecting every 20th column, that is, V1, V21, V41, V61 through end of columns.
I think this can be done using dplyr's select(df, num_range("V", val)), but am stumped how to iterate val through 1000 columns, stepping by 20.
Any suggestions?

A: Use the seq function with dplyr's select and num_range as below:
library(dplyr)

df <- as.data.frame(matrix(rnorm(3000), nrow = 3))
df %>% select(num_range("V", seq(1, 1000, by = 20)))

A: u can use some function like this.Here nskip=20 as u want to skip 20 columns
FOO <- function(data, nSubsets, nskip)
{
 outList <- vector("list", length = nSubsets)
 totcol <- ncol(data)
 for (i in seq_len(nSubsets))
 {
   colsToGrab<- seq(i, totcol, nSkip)
   outList[[i]] <- data[,colsToGrab ]
 }
return(outList)
}

A: You can try,
df[seq(1, ncol(df), 20)]


text:
Q: CollectionsUtils filter collections of objects using an object element collection I have a Collection of HOUSE objects and each HOUSE object has elements - ID, NAME. I get a another collection of IDs from another source. I want to remove the HOUSE objects with these IDs from the Original Collection of HOUSE objects. I am trying something like this..but I can not pass exclusionIDsList to inner class Predicate. Any alternate ideas?
List<HOUSE> originalHouses = ...//List of houses
List<ID> exclusionIDsList = ...//List of IDs to exclude

CollectionUtils.filter(originalHouses, new Predicate() {
    @Override
    public boolean evaluate(Object arg0) {
        if(exclusionIDsList.contains(((HOUSE)arg0).getID())
            return false;
        else return true;
    }
});

A: Declare exclusionIDsList final:
final List<ID> exclusionIDsList = ...


text:
Q: Mockito mocking with Enum parameter not working I can't figure out what is wrong with this, hopefully someone can help:
I have an enum, MyEnum that is used as a parameter to a method I am trying to mock. The mocking looks a bit like this:
when(myMockedObject.getMethod(MyEnum.XYZ)).thenReturn(myMockedValue);

and the actual code execution looks like this:
MyMockedValue theMockedValue = myMockedObject.getMethod(MyEnum.XYZ);

I'm expecting theMockedValue to equal myMockedValue. However, the mocking is not working and theMockedValue is always null. What is wrong with this?

A: This was down to my own dodgy code. I found a duplicated mock object, one instance was involved in the mocking and the other was being used in the code, resulting in null values being returned.
Just as I thought I was losing the battle with mockito and now I realise I do understand what is going on.


text:
Q: java.lang.IllegalStateException: Not a JSON Object I am trying to get a json response from SonarQube using the SonarQube web API.  While assigning the JsonElement into a JsonObject I am getting this error:
java.lang.IllegalStateException: Not a JSON Object

This is my Java class
@Controller
public class SonarController {

    @Autowired
    JenkinsDataService jenkinsService;
    @Autowired
    SonarDataService sonarService;
    HttpEntity<String> entity;

    @RequestMapping(value = { "/sonar" })
    public void test(HttpServletRequest request, HttpServletResponse response,ModelMap model ) throws ServletException, IOException{
        try{
            String url= "http://sbstpvmlx818:9000/api/resources?metrics=coverage,sonar&depth=1&metrics=ncloc";
            RestTemplate restTemplate = new RestTemplate();

            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            entity = new HttpEntity<String>("parameters", headers);
            ResponseEntity<String> sonarResponse = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

            JsonElement jelement = new JsonParser().parse(sonarResponse.getBody());
            JsonObject  jobject = jelement.getAsJsonObject();
        } catch(Exception e) {
            e.printStackTrace();
        }

    }
}

Here is my Json response
[{"id":2772,"uuid":"AVeKDMBLuPlc0jzh2Dos","key":"com.testgroup.sara:platform","name":"platform","scope":"PRJ","qualifier":"TRK","date":"2017-03-03T12:04:35+0530","creationDate":"2016-10-03T15:47:53+0530","lname":"platform","version":"1.0","msr":[{"key":"ncloc","val":590737.0,"frmt_val":"590,737"}]},{"id":1,"uuid":"AVeJ89Y3uPlc0jzh2Doq","key":"com.testgroup.tbms:tbms","name":"Tbms","scope":"PRJ","qualifier":"TRK","date":"2017-03-06T12:32:57+0530","creationDate":"2016-10-03T15:20:41+0530","lname":"Tbms","version":"5.0","msr":[{"key":"ncloc","val":427062.0,"frmt_val":"427,062"}]},{"id":6156,"uuid":"AVqJnkVdkCpBdZtQIlHD","key":"com.testgroup.sara.services.xdm:xdmf","name":"sara Services :: XDMF","scope":"PRJ","qualifier":"TRK","date":"2017-03-01T16:59:57+0530","creationDate":"2017-03-01T16:55:35+0530","lname":"sara Services :: XDMF","version":"0.9","description":"sara :: SERVICES","msr":[{"key":"ncloc","val":5798.0,"frmt_val":"5,798"}]}]

This is the error
java.lang.IllegalStateException: Not a JSON Object: [{"id":2772,"uuid":"AVeKDMBLuPlc0jzh2Dos","key":"com.testgroup.sara:platform","name":"platform","scope":"PRJ","qualifier":"TRK","date":"2017-03-03T12:04:35+0530","creationDate":"2016-10-03T15:47:53+0530","lname":"platform","version":"1.0","msr":[{"key":"ncloc","val":590737.0,"frmt_val":"590,737"}]},{"id":1,"uuid":"AVeJ89Y3uPlc0jzh2Doq","key":"com.testgroup.tbms:tbms","name":"Tbms","scope":"PRJ","qualifier":"TRK","date":"2017-03-06T12:32:57+0530","creationDate":"2016-10-03T15:20:41+0530","lname":"Tbms","version":"5.0","msr":[{"key":"ncloc","val":427062.0,"frmt_val":"427,062"}]},{"id":6156,"uuid":"AVqJnkVdkCpBdZtQIlHD","key":"com.testgroup.sara.services.xdm:xdmf","name":"sara Services :: XDMF","scope":"PRJ","qualifier":"TRK","date":"2017-03-01T16:59:57+0530","creationDate":"2017-03-01T16:55:35+0530","lname":"sara Services :: XDMF","version":"0.9","description":"sara :: SERVICES","msr":[{"key":"ncloc","val":5798.0,"frmt_val":"5,798"}]}]
at com.google.gson.JsonElement.getAsJsonObject(JsonElement.java:90)
at com.test.reldashboard.controller.SonarController.test(SonarController.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at com.test.reldashboard.filter.UriFilter.doFilter(UriFilter.java:64)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at com.test.reldashboard.filter.SessionFilter.doFilter(SessionFilter.java:43)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1082)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:623)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:662)

A: Not a JSON Object: [{"id":2772,"uuid":"AVeKDMBLuPlc0jzh2Dos".....
Here in your API response starting point was JSONArray not a JSONObject so you got java.lang.IllegalStateException: Not a JSON Object: please add if condition as answered by @rathna as below
if (jelement instanceof JsonObject) {
    JsonObject  jobject = new JsonObject(jelement .getAsJsonObject());
 } else if (jelement instanceof JsonArray) {
    JsonArray  jarray =  new JsonArray(jelement.getAsJsonArray());
 }

A: I think there could be a small mistake in rathna's code. Since jelement.getAsJsonObject() is already a JsonObject, the constructor is redundant. Here is the code that works for me:
if (jelement instanceof JsonObject) {
    JsonObject  jobject = jelement.getAsJsonObject();
 } else if (jelement instanceof JsonArray) {
    JsonArray  jarray = jelement.getAsJsonArray();
 }

A: read as JSONArray to read jsonarray
 if (jelement instanceof JsonObject) {
    JsonObject  jobject = new JsonObject(jelement .getAsJsonObject());
 } else if (jelement instanceof JsonArray) {
    JsonArray  jarray =  new JsonArray(jelement.getAsJsonArray());
 }


text:
Q: How to add an item into a JSON in Knockout.js EDIT: I want to be able to add any element into the object, not just specifically age.
Is there any way of adding items into a JSON in Knockout.js?
I want to add age into this existing JSON below and have it reflected on the web page. The click function in my code adds the age onto the JSON but fails to show it on the page.
I have also tried to use cleanNode() + applybindings to re-apply the bindings but the items in the foreach are duplicated
html:

<button id="button">Test</button>

code:
json = {
    name: 'Scott',
    children: [
        { id : 1, name : 'Alice' },
        { id : 2, name : 'Liv' }
    ]
}

var viewModel = ko.mapping.fromJS( json );
ko.applyBindings( viewModel, document.body );

document.getElementById( "button" ).addEventListener( "click", function() {
    json.age = "87";
    ko.mapping.fromJS( json, viewModel );
} );

fiddle example:
https://jsfiddle.net/f8qbu1j8/6/

A: Set the age property on the original JSON object, even if you leave it blank. This will cause it to map into your view model properly. Then, later on, you can set the age value on the view model without re-mapping. You should only ever have to use ko.mapping once on an object. See below:
HTML:

<button id="button">Test</button>

JavaScript:
var json = {
    name: 'Scott',
    children: [
        { id : 1, name : 'Alice' },
        { id : 2, name : 'Liv' }
    ],
    age: null
}

var viewModel = ko.mapping.fromJS({});
ko.mapping.fromJS(json, viewModel);
ko.applyBindings(viewModel, document.body);

document.getElementById("button").addEventListener("click", function() {
  viewModel.age(87);
});

Working fiddle: https://jsfiddle.net/dw1284/nvckyta4/

A: I approve Dennis's answer. After binding your "viewModel" to the element "document.body", you can change your json by setting the values of "viewModel" :

<button id="button">Test</button>

the javascript part :
var json = {
    name: 'Scott',
    children: [
        { id : 1, name : 'Alice' },
        { id : 2, name : 'Liv' }
    ],
    age: null
}

var viewModel = ko.mapping.fromJS({});
ko.mapping.fromJS(json, viewModel);
ko.applyBindings(viewModel, document.body);

document.getElementById("button").addEventListener("click", function() {
  viewModel.age(87); // edit the property "age"
  viewModel.children.push({id : 3, name : 'Adil' }); // add element to the property "children"
});

A: The first time when you are using the mapping plugin,it creates a view Model for you based on your object. Since your object does not have an age property so you won't have an observable variable for age in your model. Once you update your existing view model with a new Object, it just updates those variables which already have been created before and exist in your model.
Aside from that, since you are using knockout you should use the power of knockout and avoid using jquery in your model where I can see in your code you are using Jquery for clickevent. As you might read the knockout.js documentation, knockout does that for you by using click binding.
I assume you are going to have an array of Objects , here is my suggestion how to implement your model so in future it would be easier for you to maintain your model as you might want to add new functionalities to it.
Example : https://jsfiddle.net/9aLvd3uw/248/
HTML:

    <button data-bind="click:$parent.UpdateAge">Update age to 87</button>

JS:
var json = [{
    name: 'Scott',
    children: [
        { id : 1, name : 'Alice' },
        { id : 2, name : 'Liv' }
    ],
    age:null
},{
    name: 'Kevin',
    children: [
        { id : 3, name : 'Mike' },
        { id : 4, name : 'Alex' }
    ],
    age:55
}];
var MainViewModel = function (){
    var self = this;
  self.Items = ko.observableArray();
  self.Items($.map(json, function (item) {
    return new ItemViewModel(item);
  }));
    self.UpdateAge = function(item){
    //here you can have your logic to update the age.
    item.age(87);
  }
}
  var ItemViewModel = function (data){
    var self = this;
    self.name = ko.observable(data.name);
    self.children = ko.observableArray(data.children);
    self.age = ko.observable(data.age);
  }
 var vm = new MainViewModel();
ko.applyBindings(vm);


text:
Q: How to use ssh for gitlab scheduled jobs We recently changed our repo to use SSH and now our scheduled jobs wont run
This is the error we are seeing
Running with gitlab-runner 10.2.0 (0a75cdd1)
  on ff (4b9268cd)
Using Shell executor...
Running on pro1.staging.cardstream.net...
Cloning repository...
Cloning into '/home/gitlab-runner/builds/4b9268cd/0/Graham/QA_TEST'...
fatal: repository 'http://gitlab-ci-token:xxxxxxxxxxxxxxxxxxxx@dev.cardstream.com/Graham/QA_TEST.git/' not found
ERROR: Job failed: exit status 1

I would be grateful if someone could shed some light on this
Thanks

A: It seems that I have misunderstood after being misled by various internet postings.
It not possible to have gitlab use ssh when cloning a project within a job


text:
Q: How to do something at a specified date and time with Android AlarmManager? I want to start work to perform at 8:00 am on a specific date. Is there any way to perform this task using AlarmManager?

A: You should use AlarmManager instead of work manager. Work Manager is made for things which are deferrable and guaranteed, meaning it can be done later and not crucially now. To have some background service which does work that has to happen at an exact time and is guaranteed consider using AlarmManager.
There's also this StackOverflow answer:
Alarm Manager Example
There's no need to waste time by trying to implement work manager for your task.
Edit: My bad, the example was an old link. Messy it is!


text:
Q: Delete Not working in MVC 2 // GET: /Product/Delete/5
    public ActionResult Delete(int id)
    {
        var res = (from r in data.Products where r.ProductID == id select r).FirstOrDefault();
        //return View(data.Products.FirstOrDefault(p => p.ProductID == id));
        return View(res);
    }

    //
    // POST: /Product/Delete/5
   // [HttpPost]
   [AcceptVerbs(HttpVerbs.Post)]
    **public ActionResult Delete(Product producttodelete)**
    {

        try
        {
            // TODO: Add delete logic here
            var res = (from r in data.Products where r.ProductID == producttodelete.ProductID select r).FirstOrDefault();
           // var productto = data.Products.Single(p => p.ProductID == producttodelete.ProductID);
            data.Products.DeleteObject(res);
            data.SaveChanges();
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }
}

Here in the line "producttodelete" i am not getting any values it is cuming null.Rather than create,details,edit are working fine.... only delete not working.......I tried a lot

A: Assuming you are using strongly typed views, have you tried:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id, Product productToDelete)
{
    try
    {
        var res = (from r in data.Products where r.ProductID == id select r).FirstOrDefault();
        data.Products.DeleteObject(res);
        data.SaveChanges();
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

... or if you are not using strongly typed views:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id, FormCollection collection)
{
    try
    {
        var res = (from r in data.Products where r.ProductID == id select r).FirstOrDefault();
        data.Products.DeleteObject(res);
        data.SaveChanges();
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

In either case, you need to provide an id parameter which you can then use to get your object from your datastore. The default route mapping in MVC2 (in Global.asax.cs) will take the ID from the post URL and map it to this parameter for you.

A: why not just get the id like you were in the rest instead of trying to get the whole model?  it seems like you're just selecting using the id anyway.  try this:
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(int id)
        {

            try
            {
                // TODO: Add delete logic here
                var res = (from r in data.Products where r.ProductID == id select r).FirstOrDefault();
               // var productto = data.Products.Single(p => p.ProductID == producttodelete.ProductID);
                data.Products.DeleteObject(res);
                data.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }


text:
Q: Rails - using same form partial for AJAX and non-AJAX requests I have a form partial I am using in two places to add new ingredients (in a recipe app). When I first built the app, I wanted the user to be able to add a new ingredient while they were filling out a new recipe card. I used a modal popup and AJAX so the new ingredient form pops up, gets completed, and when the submit button is clicked some jQuery hides the modal box and updates some option tags on the page.
From the recipe form I call the ingredient partial using <%= link_to 'New ingredient', new_ingredient_path, :remote => true %>. My ingredient new.html.erb file only contains a call to the partial:
<%= render 'form' %>

And the _form.html.erb looks like: (other fields snipped for brevity)
<%= form_for @ingredient, :remote => true do |f| %>
    <%= render 'shared/ingredient_error_messages' %>

        <%= f.label :name %>
        <%= f.text_field :name %>

        <%= f.label :amount %>
        <%= f.text_field :amount%>

        <%= f.submit "Save ingredient" %>

<% end %>

My problem is that I now want the user to also be able to create a new ingredient from the ingredients section of the site. Since I don't need the modal box and jQuery functionality on that part of the site, I'd rather this be treated as a vanilla HTML request. However, I don't know how to "turn off" the AJAX functionality on demand, or if this is even good practice.
I thought of passing a parameter in the links to the new ingredient form and using that to control the :remote attribute in the form. What is the best practice here? Ideally a way to control the form's remote attribute from the link, allowing me to keep my AJAX in one spot and use HTML in the other. I could easily duplicate the form as a non-AJAX version and call that, but that's not very DRY...

A: How about simple:
<%= form_for @ingredient, :remote => request.xhr? do |f| %>


text:
Q: Getting PCA eigenvectors with the values of opposite sign I am performing a PCA analysis in Matlab on a $110\times 7$ dataset using some custom code. I am checking my code against Matlab's princomp and my eigenvectors are the same except that the 3rd and the 7th column are of the opposite sign.
What does that mean? And why does this happen?
My code is:
mu = mean(data);
data = bsxfun(@minus,data,mu);
sigma = transpose(data) * data / size(data, 1);
[eigenvectors, eigenvalues]=eig(sigma);
eigenvalues=diag(eigenvalues)
[ev index]=sort(eigenvalues,'descend');
eigenvectors=eigenvectors(:,index);
pc = data*eigenvectors';


text:
Q: Running into transient NoMethodError errors with T.cast in production we're running into transient NoMethodError errors in code paths using T.cast on our production services. Here are some notable facts

*

*Is happening in sorbet-runtime as of version 0.5.10012

*It only affects 1 host at a time and often happens in short spurts (ex. errors for < 10m and goes away).

*On some of our production services, we'll see errors daily. On others, it'll be weekly

*We were not seeing this error until we upgraded sorbet-runtime versions from 0.5.6001 to 0.5.9976 (2 years of changes). We were pinned on the old version until we could migrate off the now deprecated --dsl-plugins

*Ruby version 2.7.4

*We have disabled runtime validation in production - T::Configuration.default_checked_level = :never
What it looks like is that T::Utils.coerce(type) returns an unexpected value (not a subclass of T::Types::Base) for a short period of time, which leads to errors here when checking error_message_for_obj here: code
Recent stacktrace
NoMethodError: undefined method `valid?' for {:mode=>:compat}:Hash
  from sorbet-runtime (0.5.10012) lib/types/types/intersection.rb:33:in `block in valid?'
  from sorbet-runtime (0.5.10012) lib/types/types/intersection.rb:33:in `all?'
  from sorbet-runtime (0.5.10012) lib/types/types/intersection.rb:33:in `valid?'
  from sorbet-runtime (0.5.10012) lib/types/types/base.rb:133:in `error_message_for_obj'
  from sorbet-runtime (0.5.10012) lib/types/private/casts.rb:8:in `cast'
  from sorbet-runtime (0.5.10012) lib/types/_types.rb:133:in `cast'
  from < our code>

Where the line in our code looks like this
T.cast(self, T.all(T::Props::Serializable, Object)).as_json

I've not figured out a way to reproduce locally but I selectively enabled a debugging monkeypatch to T.cast to not raise some errors and log some more information.
# frozen_string_literal: true

module SorbetMonkeyPatches
  module TcastDebug
    module ClassMethods
      def cast(value, type, checked: true)
        super
      rescue NoMethodError => e
        Rails.logger.error(
          message: "[sorbet] - #{value.try(:class)} to #{type.try(:class)}",
          src_value: value.inspect,
          src_type: type.inspect,
          coerce_res: T::Utils.coerce(type).inspect,
        )
        value # ultimately don't want assertions from T.cast...this should return the same value unchanged
      end
    end
  end
end

if ENV["SORBET_DEBUG_UPGRADE"] == "true"
  ::T.singleton_class.prepend(SorbetMonkeyPatches::TcastDebug::ClassMethods)
end

When enabled, here are some sample log statements we see
[sorbet] - Class to Module {"src_value":"ProductsDomain::Api::LocaleCode","src_type":"T::Props::CustomType","coerce_res":"\"ssl_min_protocol_version\""}

...
[sorbet] - Class to Module {"src_value":"ProductsDomain::Api::LocaleCode","src_type":"T::Props::CustomType","coerce_res":"[\"workflow_state\", \"active\"]"}

If working correctly, I would've expected coerce_res to return a subclass of T::Types::Base, not random strings
My uninformed opinion is that we're somehow corrupting the cache for coerced types introduced by this PR - https://github.com/sorbet/sorbet/pull/4397 .

The questions I have

*

*Has this been seen before?

*Any advice for how to address or how to continue debugging?

*Ultimately we'd hope not to see errors from T.cast when runtime checks are disabled…should we override the optional checked param in the T.cast method definition?

Thanks for your help! Please let me know if you'd like any more debugging information

A: I don't know how recently you upgraded to Ruby 2.7. When we did the Ruby 2.7 upgrade in our codebase, one of the failure modes we saw frequently looked like this:
GC.compact was being called by certain low-level framework code (If memory serves, I think puma calls GC.compact if available, regardless of whether your application calls it directly anywhere. There may be others. You could grep the contents of your vendor/bundle directory and see if any gems have calls to it, if your codebase doesn't.)
The problems is then that certain Ruby gems with C extensions, especially on versions of those gems that were released before Ruby 2.7 was released, would not properly declare that certain objects needed to be pinned in memory.
This means that the Ruby VM would compact its heap, it would move values around under the hood such that what used to be a T::Types::Base suddenly became some object formerly owned by a C extension.
In the end, we played whack-a-mole trying to find the offending gem for a while before deciding to monkey patch GC.compact to be a no-op very early on in the process load time, which fixed our issues. It's possible the same thing will fix yours.
Unfortunately, I can't see any codepath through sorbet-runtime which would cause the code at lib/types/types/intersection.rb:33 to call .valid? on a Hash object, so I would be surprised if this were a Sorbet bug, but if you do manage to reproduce it, please file an issue against the Sorbet repo.


text:
Q: How to disable the marquee tag (text animations) on Mozilla Firefox? I don't want to allow any <marquee> tag on Mozilla Firefox.
I have created a new boolean preference in the about:config window with the name browser.display.enable_marquee and set it to false, but I'm still getting scrolling pieces of text on a web page.

A: This old help page has a solution that still works as of March 2015:

*

*Open Firefox and press ALT to show the top menu, then click on Help → Troubleshooting Information → Open Containing Folder

*If it doesn't exist yet, create a folder named Chrome

*If it doesn't exist yet, create a CSS file with the name UserContent.css

*Copy the following code to UserContent.css and restart Firefox:

/* Stop those <marquee> tags! */
marquee {
   -moz-binding                  : none !important;
   display                       : block;
   height                        : auto !important;
}


text:
Q: issue in Spring @pathvariable I have written a controller
package org.arpan.spring.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloController {

    @RequestMapping(value="/hello")
    public String getMessage(ModelMap model)
    {
        model.addAttribute("message", "Hello this is my first spring project!");
        return "Hello";
    }

    @RequestMapping(value="/hey/{username}")
    public String getMessage(ModelMap model,@PathVariable String username)
    {
        System.out.println(username);
        model.addAttribute("message", "Hey this is my first spring project!");
        return "Hello1";
    }

    @RequestMapping(value="/hi/{id}")
    public String getMessage1( ModelMap model,@PathVariable("username2") String id)
    {
        model.addAttribute("message", "Hi this is my first spring project!");
        return "Hello";
    }

}

when i run this /hello works fine but the second /hey/{username} and third /hi/{username} does not works giving error as below
URL : http://localhost:8080/FirstSpringMVCProject/hey/abc
HTTP Status 404 - /FirstSpringMVCProject/hey/WEB-INF/jsp/Hello1.jsp

A: Just one correction in view resolver will solve the problem
 <bean id="viewResolver" class ="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>

A: The error message tells that it is trying to look for Hello1.jsp.
Can you verify if your jsp file is named hello1.jsp or Hello1.jsp. The case should be same.


text:
Q: Ordering by Index of property in Anonymous Type Declaration I have a complex problem, without going into too many details.  I'm just wondering if this is possible.
I have an Ordered Linq query which gets a subset of data and pushes it into a DataTable.
var FormattedDataSet = DataSet.Select(t => new
{
    ItemNumber = t.ExtTitleID,
    Name = "" + t.TitleFullName + "",
    Master_Edited = t.MediaDetails.FirstOrDefault().Datecaptured
}).ToList();

Is it Possible Int to sort this based on the index of the declaration of the Anonymous Type?
0 => ItemNumber
1 => Name
2 => MasterEdited

I need to be able to do this with out explicitly declaring the column name to sort by, so this can work generically for any anonymous type.

A: Yes and no.  You cannot do this directly and properties/fields of anonymous types (or any object) are not indexed.  Therefore you cannot use an index to access those properties.
With that being said you can use reflection to access the data without their names.
var FormattedDataSet = /*linq query to create list of anon types*/

//we only need to analyze one of them since all items in the list should be of the same type
Type t = formattedDataSet[0].GetType();
PropertyInfo[] pi = t.GetProperties();

//get value of "property one" of the first anon object in your list
object data = pi[0].GetValue(FormattedDataSet[0]);

The above code creates an array of properties that you can use an index on, although you won't know what the properties actually are.  You can then loop through the array of PropertyInfo objects and call propInfo.GetValue(anonObject); to return the value stored in that property in the anonymous object.
If you want to get the name of a property out of the PropertyInfo object you can just call propInfo.Name.

A: I hope this is not too late but I have some working code for you.  I've used this in a project before and it hasn't caused any noticed problems.
public static IOrderedQueryable<T> OrderByPropertyDeclarionIndex<T>(this IQueryable<T> source, int propertyIndex, bool isDescending = false)
{
    string OrderByText = isDescending ? "OrderByDescending" : "OrderBy";
    return ApplyOrder(source, propertyIndex, OrderByText);
}

private static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, int property, string methodName)
{

    var type = typeof(T);
    var arg = Expression.Parameter(type, "x");
    Expression expr = arg;

    var propertyinfos = type.GetProperties();

    var pi = propertyinfos[property];

    expr = Expression.Property(expr, pi);
    type = pi.PropertyType;

    var delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
    var lambda = Expression.Lambda(delegateType, expr, arg);

    var result = typeof(Queryable).GetMethods().Single(
            method => method.Name == methodName
                    && method.IsGenericMethodDefinition
                    && method.GetGenericArguments().Length == 2
                    && method.GetParameters().Length == 2)
            .MakeGenericMethod(typeof(T), type)
            .Invoke(null, new object[] { source, lambda });
    return (IOrderedQueryable<T>)result;
}


text:
Q: How to upgrade gnuradio 3.7.5 to above? I want to upgrade gnuradio companion but I do not know any command any one who know please help me?

A: You can build it from sources, of cource, or install via PyBombs. I like the way with PyBombs. You got a most newer version, but i recommend to REMOVE currently installed via apt-get version of gnu-radio:
sudo apt-get remove gnuradio* libgnuradio-*

Do not forget to remove the libraries that depends on gnuradio. If something goes wrong, you can always install them back :)
First, install pip
sudo apt-get install python-pip python-dev build-essential
sudo pip install --upgrade pip
sudo pip install --upgrade virtualenv

Next: PyBombs
sudo pip install PyBOMBS
sudo pybombs prefix init /usr/local -a default_prx
sudo pybombs config default_prefix default_prx
sudo pybombs recipes add gr-recipes git+https://github.com/gnuradio/gr-recipes.git
sudo pybombs recipes add gr-etcetera git+https://github.com/gnuradio/gr-etcetera.git

Next, install gnuradio:
sudo pybombs install gnuradio

If you are like to use beautiful gr-fosphor, install it by:
sudo apt-get install libfreetype6-dev ocl-icd-opencl-dev libqt4-opengl-dev
sudo pybombs install gr-fosphor

Thats it, we are done!
PS: to avoid some possible errors, check if you gcc-compiler version are >= 5, but not => 6


text:
Q: Maximum value of $x$ such that $3x^2 - xy - 2x - 5y + 7 = 0$
Let $x, y \in \mathbb Z$ such that
  $$3x^2 - xy - 2x - 5y + 7 = 0$$
  What is the maximum value for $x$?

I tried to solve the problem by interpreting the equation as a conic section, but it took too much time and I gained no valuable information. As last resort I differentiated with respect to $x$ and tried to solve the resulting equation with respect to $y$, but I wasn't even sure about the correctness of what I was doing.
I wonder, how could one solve such a problem?

A: $$3x^2 - xy - 2x - 5y + 7 = 0$$
is equivalent to
$$(3x-y-17)(x+5)=-92.$$

A: $$3x^2 - xy - 2x - 5y + 7 = 0$$
$$3{x^2} - y(x + 5) - 2x + 7 = 0$$
$$y = \frac{{3{x^2} - 2x + 7}}{{x + 5}} = 3x - 17 + \frac{{92}}{{x + 5}}$$
Since $y$ is integer and $3x -17$ is integer, the fractional part must be an integer. We need to pick up the largest divisor of $92$, which is obviously itself. So we have
$$x + 5 = 92 \Leftrightarrow x = 87$$

A: Here is an approach if you don't have that much experience factorizing:
We are going to try to solve this in terms of $y$ and look at the $x$ as if it was a constant, and then determine for which values of $x$ a suitable $y$ exists.
Put the terms that have $y$ in one side:
$y(-x-5)+(3x^2-2x+7)=0\iff y(-x-5)=-(3x^2-2x+7)\iff y(x+5)=3x^2-2x+7$.
This has a solution if $x+5$ divides $3x^2-2x+7$.
So proceed to do polynomial division (this can be done with a standard algorithm, no geniality required):
You get $3x^2-2x+7=(x+5)(3x-17)+92$. From here we must have $(x+5)|92$. So the values of $x$ for which there is a solution in $y$ correspond to the divisors of $92$ minus $5$. The largest of which is $92-5=87$.


text:
Q: Cursor not displaying in UISearchBar for our app For the UISearchBars in our app, there's no cursor shown in the bar with focus when running under iOS 7.  How do we make that show?
We are using the SDK 7, with a minimum target of 6.  We do have the translucency off for the navigation bars, and set the color at runtime.  I can't think of anything else we are doing differently.

A: In  the searchbox property window
open View Section>Set Tint color - default.

Hope this will help.

A: This is how it can be done in Swift :
override func viewWillAppear(animated: Bool) {
    self.searchBar.tintColor = UIColor.whiteColor()

    let view: UIView = self.searchBar.subviews[0] as! UIView
    let subViewsArray = view.subviews

    for (subView: UIView) in subViewsArray as! [UIView] {
        println(subView)
        if subView.isKindOfClass(UITextField){
            subView.tintColor = UIColor.blueColor()
        }
    }

}

A: Set
searchBar.tintColor = [UIColor blueColor];

A: searchBar.tintColor = view.tintColor  // self.view usually has the proper tintColor

Better than .blue or whatever.

A: Our problem was that the tint color was set to white, so I didn't see it.

A: Just set the tintColor for UISearchBar, in your storyboard, xib or code. Xcode seems to ignore the default tintColor.

A: You could loop through the searchBars subviews and obtain the uitextfield subview and set its @"insertionPointColor" value to your desired color. Works but is private api
for (UIView *subView in self.searchBar.subviews) {
    if ([subView isKindOfClass:[UITextField class]]) {
        [[(UITextField *) subView valueForKey:@"textInputTraits"] setValue:[UIColor blackColor] forKey:@"insertionPointColor"];
    }
}


text:
Q: Find distinct field in multiple same collections mongodb I have 7 collections in one database that the collections are the same and I have to find a unique field in those collections and count it or show it in a new collection named result.
I tried lookup but it it did not work. Can anyone guide me how to do the job?
These are 7 collections: 20200309-20200310-20200311-20200312-20200313-20200314-20200315 and result is the collection for store the result of query.
col : 20200309
{
    "_id" : ObjectId("5e6f7c7c0371c86b8737628b"),
    "sid" : 13328,
    "trans-id" : "PROV_158374123364907198165",
    "status" : "1",
    "base-price-point" : "6000",
    "msisdn" : "989115506327",
    "keyword" : "",
    "validity" : 0,
    "next_renewal_date" : "",
    "shortcode" : "",
    "billed-price-point" : "",
    "trans-status" : 0,
    "chargeCode" : "AVMREWCAVMAW6000",
    "datetime" : "2020-03-09 11:37:13.649",
    "event-type" : "1.5",
    "channel" : "system"
}

{
    "_id" : ObjectId("5e6f7c7c0371c86b8737628c"),
    "sid" : 13328,
    "trans-id" : "PROV_158374123384007267165",
    "status" : "1",
    "base-price-point" : "6000",
    "msisdn" : "989107351827",
    "keyword" : "",
    "validity" : 0,
    "next_renewal_date" : "",
    "shortcode" : "",
    "billed-price-point" : "",
    "trans-status" : 0,
    "chargeCode" : "AVMREWCAVMAW6000",
    "datetime" : "2020-03-09 11:37:13.840",
    "event-type" : "1.5",
    "channel" : "system"
}
 col : 20200310
{
    "_id" : ObjectId("5e6f7d140371c86b873e6bce"),
    "sid" : 13328,
    "trans-id" : "PROV_158383144246275616515",
    "status" : "1",
    "base-price-point" : "6000",
    "msisdn" : "989909789746",
    "keyword" : "",
    "validity" : 0,
    "next_renewal_date" : "",
    "shortcode" : "",
    "billed-price-point" : "",
    "trans-status" : 0,
    "chargeCode" : "AVMREWCAVMAW6000",
    "datetime" : "2020-03-10 12:40:42.462",
    "event-type" : "1.5",
    "channel" : "system"
}
{
    "_id" : ObjectId("5e6f7d140371c86b873e6bcf"),
    "sid" : 13328,
    "trans-id" : "PROV_158382430015338271227",
    "status" : "1",
    "base-price-point" : "6000",
    "msisdn" : "989901812412",
    "keyword" : "",
    "validity" : 0,
    "next_renewal_date" : "",
    "shortcode" : "",
    "billed-price-point" : "",
    "trans-status" : 0,
    "chargeCode" : "AVMREWCAVMAW6000",
    "datetime" : "2020-03-10 10:41:40.153",
    "event-type" : "1.5",
    "channel" : "system"
}

and there is 5 collections like above

A: The following script can be used to get distinct msisdn values in an array and the count. Run the script from the mongo shell.
For this to run efficiently, there needs to be an index on the two fields msisdn and status as: { status: 1, msisdn: 1}. The index needs to be created on all the collections. Note the indexes are not required in case the collections have just few thousand documents.
collections = [ "20200309", "20200310", // ... ]
combined = [ ]

for (let coll of collections) {
  combined = combined.concat( db.getCollection(coll).distinct( "msisdn", { status: "1" } ) )
}

combined = [...new Set(combined) ]
print('Combined count:', combined.length)

The combined = [...new Set(combined) ] statement removes duplicates from the combined distinct values from the seven collections.


text:
Q: Question on convergence of improper integral For what values of $\alpha$ is the following integral convergent?
$$\int\limits_{-\infty}^{\infty}\frac{|x|^\alpha}{(1+x^2)^m}dx$$
Should the limit comparison theorem be used in this case? I am not familiar with the theorem and would appreciate any help on this.

A: Hint: Note that
$$
\int_{ - \infty }^\infty  {\frac{{|x|^\alpha  }}{{(1 + x^2 )^m }}dx}  = \int_{ - \infty }^\infty  {\frac{{|x|^\alpha  }}{{|x|^{2m} }}\frac{{|x|^{2m} }}{{(1 + x^2 )^m }}dx}  = \int_{ - \infty }^\infty  {|x|^{\alpha  - 2m} \bigg(\frac{{x^2 }}{{1 + x^2 }}\bigg)^m dx}.
$$
EDIT: For fixed $m$, $(\frac{{x^2 }}{{1 + x^2 }})^m  \to 1$ as $|x| \to \infty$. On the other hand,
$\frac{1}{{(1 + x^2 )^m }} \to 1$ as $x \to 0$.
From these observations one can easily conclude that the integral converges if and only if for any $\varepsilon > 0$
$$
\int_{ 0}^\varepsilon {x^\alpha  dx}  < \infty
$$
(this corresponds, by symmetry of $|x|^{\alpha}$, to the $x \to 0$ case) and for any $M > 0$
$$
\int_M^\infty  {x^{\alpha  - 2m} dx}  < \infty
$$
(this corresponds, by symmetry of $|x|^{\alpha-2m}$, to the case $|x| \to \infty$).

A: The function is symmetrical about the $y$-axis.  Break up the integral into two parts, $-\infty$ to $0$ and $0$ to $\infty$.  By symmetry, we need only deal with
$$\int_0^\infty \frac{x^\alpha}{(1+x^2)^m}dx$$
We are not told anything about $\alpha$, or indeed about $m$. In particular, $\alpha$ could be negative, which would make the integrand blow up near $x=0$.
And of course integrals over an infinite interval raise issues of convergence.
Let's break up the region of integration into two parts, say from $0$ to $1$ and from $1$ to $\infty$. (Instead of $1$ we could use any positive number.)
You probably know that $\int_0^1 x^\alpha dx$ converges if $\alpha>-1$ and diverges if $\alpha \le -1$.
Informally, near $0$, the function $x^\alpha/(1+x^2)^m$ "behaves like" $x^\alpha$, since if $x$ is near $0$, $(1+x^2)^m$ is almost $1$.
So informally, the convergence behaviour of the integral should be the same as the (known) convergence behaviour of the integral of $x^\alpha$.
Semi-formally,  we have the following result.  Suppose that $f(x)$ and $g(x)$ are positive functions, which are well-behaved everywhere on $(0,b]$ but may blow up as $x \to 0$.  If $\lim_{x\to 0}\frac{f(x)}{g(x)}=1$, then $\int_0^bf(x)dx$ converges if and only if $\int_0^b g(x)dx$ converges.
For our integral from $0$ to $1$, let $f(x)$ be our function, and let $g(x)$, the comparison function, be $x^\alpha$.  It is very easy to show that the limit of the ratio $f(x)/g(x)$ as $x \to 0$ is $1$.  So our integral from $0$ to $1$ converges if and only if $\int_0^1 x^\alpha dx$ converges, and we know everything about that.
Finally we look at the integral from $1$ to infinity.  It is useful to deal separately with positive and negative $m$.  In fact, from the notation, I expect that implicitly or explicitly $m$ is supposed to be positive.
For the integral to exist, the function must approach $0$ as $x\to \infty$. So we must have $2m>\alpha$.  But that's not enough: the function must go down kind of fast.
Informally, if $2m>\alpha$, then for large $x$ our function behaves like $g(x)$, where $g(x)= 1/x^{2m-\alpha}$. (Note that this is not the same $g(x)$ as the one we used for the integral from $0$ to $1$.)
We know that $\int_1^\infty 1/x^k dx$ converges if and only if $k>1$.
If our function is $f(x)$, it is easy to show that $\lim_{x\to\infty}f(x)/g(x)=1$.
So we can conclude that our integral from $1$ to $\infty$ converges if and only if $2m-\alpha>1$.
Finally, for our full integral to converge, both parts ($0$ to $1$, $1$ to $\infty$) must converge.
We conclude that our integral converges iff the two conditions $\alpha>-1$ and
$2m-\alpha>1$ both hold.
This can be written more nicely as
$$-1 < \alpha <2m-1$$

A: Undeleted and edited in response to Theo Buehler's comment.
Observe that the integrand
$$f(x)=\frac{\left\vert x\right\vert ^{\alpha }}{(1+x^{2})^{m}}$$
is even ($f(-x)=f(x)$). We thus have
$$I:=\int_{-\infty }^{\infty }f(x)dx=\int_{-\infty }^{\infty }\frac{\left\vert
x\right\vert ^{\alpha }}{(1+x^{2})^{m}}dx=2\int_{0}^{\infty }\frac{x^{\alpha
}}{(1+x^{2})^{m}}dx=2I_1+2I_2$$
where
$$I_1:=\int_{0}^{c}\frac{x^{\alpha}}{(1+x^{2})^{m}}dx,\qquad I_2:=\int_{c}^{\infty }\frac{x^{\alpha}}{(1+x^{2})^{m}}dx,\qquad c>0.$$
This last integral is an improper integral of the first kind with
nonnegative integrand. For $x>0$
$$f(x)=\frac{x^{\alpha }}{(1+x^{2})^{m}}=\frac{1}{\left( \frac{1+x^{2}}{%
x^{\alpha /m}}\right) ^{m}}=\frac{1}{\left( x^{-\alpha /m}+x^{2-\alpha
/m}\right) ^{m}}.$$
Let $g(x)=\dfrac{1}{x^{2m-\alpha }}=\dfrac{1}{\left( x^{2-\alpha /m}\right)^{m}}$. By the limit test
$$\lim_{x\rightarrow \infty }\frac{f(x)}{g(x)}=\lim_{x\rightarrow \infty
}\left( \frac{x^{2-\alpha /m}}{x^{-\alpha /m}+x^{2-\alpha /m}}\right)
^{m}=\lim_{x\rightarrow \infty }\left( \frac{1}{x^{-2}+1}\right) ^{m}=1$$
and since the standard integral
$$\int_{c}^{\infty }g(x)dx=\int_{c}^{\infty }\frac{1}{x^{2m-\alpha }}dx=\int_{c}^{\infty }\frac{1}{x^{p}}dx$$
is convergent if and only if $p=2m-\alpha >1$, i.e. $\alpha <2m-1$,
we conclude that $I_2$ is convergent if and only if $$\alpha < 2m-1.\qquad(1)$$ As for $I_1$ it is an improper integral of the second kind with nonnegative integrand. Let $h(x)=\dfrac{1}{x^{-\alpha}}$. Now the limit test is
$$\lim_{x\rightarrow 0^+}\frac{f(x)}{h(x)}=\lim_{x\rightarrow 0^+}\frac{x^{\alpha }}{(1+x^{2})^{m}}x^{-\alpha}=\lim_{x\rightarrow 0^+}\frac{1}{(1+x^{2})^{m}}=1$$
and since the standard integral
$$\int_{0}^{c }h(x)dx=\int_{0}^{c }\frac{1}{x^{-\alpha}}dx=\int_{0}^{c}\frac{1}{x^{p}}dx$$
is convergent if and only if $p=-\alpha <1$, $I_1$ is convergent if and only if  $$-1<\alpha \qquad (2)$$
From $(1)$ and $(2)$ follows that the given integral $I=2I_1+2I_2$ is convergent if and only if $$-1<\alpha<2m-1\qquad (3)$$


text:
Q: Is it possible to restore the cursor style in a terminal? It's possible, with ANSI codes, to modify the cursor shape (block, underscore or line) and whether it's blinking  or not.
My program is doing just that. But, is it possible to get the cursor style so it can be restored later (when my program exits)?
One can get the cursor position and even mouse position with ANSI codes, but it seams to me that we can only set the cursor style and not retrieve it or even reset it to an older state.


text:
Q: cancel is not toggling the ngHide in angularjs I have create unordered list where user can click and edit(update) item. I have some problem hiding/showing divs logic. I have showItem div and editItem div  when user click on edit it show editItem div and hide showItem but the cancel button is not working right when user click it will hide editItem div but will not open it
html

            <input class="" type="submit" value="Edit" data-ng-click="toggleVisibility(value)">
            <input class="" type="submit" value="Delete" data-ng-click="deleteValue(value)">
            {{value.formControllerValueName}}

            <input class="" type="submit" value="update" data-ng-click="updateValue(value)">
            <input class="" type="submit" value="Cancel" data-ng-click="toggleVisibility(value)">
            <input type="text" size="30" data-ng-model="value.formControllerValueName" placeholder="add new  here">

javascript
$scope.updateValue = function (value) {
    itemsManagementService.updateValue(value);
};

$scope.deleteValue = function (value) {

};

$scope.toggleVisibility = function (model) {
    $scope.selected = model;
};
$scope.isVisible = function (model) {
    return $scope.selected === model;
};
$scope.hide = function () {
    return $scope.isVisible = false;
};

A: You could add a scope variable editingMode to store if the current item is in editing mode and also you should store the value before entering the edit mode so you can restore the old value after cancel click.
Please have a look at the demo below or in this jsfiddle.

angular.module('demoApp', [])
    .controller('mainController', function ($scope) {
    $scope.editingMode = [];
    $scope.backup = [];

    $scope.model = {
        rrnConditionsValues: [{
            formControllerValueName: "a"
        }, {
            formControllerValueName: "b"
        }, {
            formControllerValueName: "c"
        }, {
            formControllerValueName: "d"
        }]
    };

    $scope.updateValue = function (value, index) {
        //itemsManagementService.updateValue(value); // just removed for the demo
        $scope.editingMode[index] = false;
    };

    $scope.cancel = function (index) {
        $scope.model.rrnConditionsValues[index].formControllerValueName
            = $scope.backup[index];
        $scope.editingMode[index] = false;
    };

    $scope.toggleEdit = function (index) {
        // save current model value so we can restore it on cancel
        $scope.backup[index] = $scope.model.rrnConditionsValues[index].formControllerValueName;
        console.log($scope.backup);
        $scope.editingMode[index] = !$scope.editingMode[index];
        //$scope.selected = model;
    };

    $scope.deleteValue = function(index) {
        $scope.model.rrnConditionsValues.splice(index,1);
    };
});

                <input class="" type="submit" value="Edit" data-ng-click="toggleEdit($index)">
                <input class="" type="submit" value="Delete" data-ng-click="deleteValue($index)">
                {{value.formControllerValueName}}

                <input class="" type="submit" value="update" data-ng-click="updateValue(value, $index)">
                <input class="" type="submit" value="Cancel" data-ng-click="cancel($index)">
                <input type="text" size="30" data-ng-model="value.formControllerValueName" placeholder="add new  here">

A: Since is a toggle, all you had to do is check if the model you are sending is the same as already are inside the selected. if it's , just set it to null.
$scope.toggleVisibility = function (model) {
    if($scope.selected === model){
        $scope.selected = null;}
    else{
        $scope.selected = model;
    }
};

Jsfiddle of example


text:
Q: Select displayed rows based on user criteria I have looked but not found a solution to the task I am attempting.  I am new to VBA so the learning curve is steep.  Here is what I am trying to do:
In Excel 2010/2013, I have a worksheet with fixed content in the top 9 rows, and starting with row 10, rows of data with consecutive dates in column B.  I need users to be able to evaluate data within a certain subset of all the dates in the sheet.
For example:  User enters the values "06/15/15" in cell K1, and "06/19/15" in cell N1.  Rows 10 through 20 each contain a record, with column B being the date field for each record.  In this example, cell B10 contains the date 06/12/15 through cell B20 which contains the date 06/22/15.  I need the code to look at the contents of cells K1 and N1, interpret them as boundaries of a date range, and display only the rows of data that both have a row value of 10 or greater and are within that defined range, hiding all the others, leaving the header rows 1 through 9 visible.  Only the rows greater than 9, with dates between and inclusive of the user selected criteria should be visible.

A: Try something like this:
dim iRow as integer
dim iColumn as integer

iRow = 10     'Row 10
iColumn = 2   'Column B

do until activesheet.cells(iRow, iColumn).value = ""
    if datediff("d", activesheet.range("K1").value, _
        activesheet.cells(iRow, iColumn).value) => -10 AND _
        datediff("d", activesheet.range("N1").value, _
        activesheet.cells(iRow, iColumn).value) =< 10 then _
        activesheet.rows(iRow).entirerow.hidden = true
    iRow = iRow + 1
loop

If you need to check multiple columns, you can add an extra loop inside of this loop with an iColumn = iColumn + 1. Is this what you were looking for?


text:
Q: Unable to reference HttpContext.SignInAsync using Microsoft.AspNetCore.Http.Abstractions I have a .net core 2.0.1 app that uses Microsoft.AspNetCore.Authentication.Abstraction assembly. In the app I'm referencing an extension method, SignInAsync from the AuthenticationHttpContextExtensions class. This is perfect!
However I've created a new application using .net core 2.0.3 and it seems that Microsoft have decided to remove the AuthenticationHttpContextExtensions class from the Microsoft.AspNetCore.Authentication.Abstraction assembly. I can't seem to find any links on the net that shows me what new package I need to reference. What's the work around from using await httpContext.SignInAsync()
I have a service that doesn't reference Microsoft.AspNetCore.All. It's an .NET CORE application with the following code:
public async Task SignInAsync(HttpContext httpContext, Guid userId, bool isPersistent = false)
{
    ClaimsIdentity identity = new ClaimsIdentity(GetUserClaims(userId), CookieAuthenticationDefaults.AuthenticationScheme);
    ClaimsPrincipal principal = new ClaimsPrincipal(identity);

    await httpContext.SignInAsync(
      CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties() { IsPersistent = isPersistent }
    );
}

.csproj:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Autofac" Version="4.8.1" />
  </ItemGroup>

  <ItemGroup>
    <Reference Include="Microsoft.AspNetCore.Authentication.Cookies">
      <HintPath>C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.authentication.cookies\2.0.4\lib\netstandard2.0\Microsoft.AspNetCore.Authentication.Cookies.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.AspNetCore.Authentication.JwtBearer">
      <HintPath>C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.authentication.jwtbearer\2.0.4\lib\netstandard2.0\Microsoft.AspNetCore.Authentication.JwtBearer.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.AspNetCore.Http.Abstractions">
      <HintPath>C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.http.abstractions\2.0.3\lib\netstandard2.0\Microsoft.AspNetCore.Http.Abstractions.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Extensions.Configuration.Abstractions">
      <HintPath>C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.extensions.configuration.abstractions\2.0.2\lib\netstandard2.0\Microsoft.Extensions.Configuration.Abstractions.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.IdentityModel.Tokens">
      <HintPath>C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.identitymodel.tokens\5.1.4\lib\netstandard1.4\Microsoft.IdentityModel.Tokens.dll</HintPath>
    </Reference>
    <Reference Include="System.IdentityModel.Tokens.Jwt">
      <HintPath>C:\Program Files\dotnet\sdk\NuGetFallbackFolder\system.identitymodel.tokens.jwt\5.1.4\lib\netstandard1.4\System.IdentityModel.Tokens.Jwt.dll</HintPath>
    </Reference>
  </ItemGroup>

</Project>

UPDATE:
The class AuthenticationHttpContextExtensions was not removed (sorry Microsoft). A hard-coded path to Microsoft.AspNetCore.Http.Abstractions.dll was being used instead of referencing the package Microsoft.AspNetCore.Authentication.Abstractions. This lead to the confusion as I had reference to the namespace Microsoft.AspNetCore.Authentication but no reference to the extension class that I was looking for.


text:
Q: JavaScript Making list from array I'm trying to make a list from arrays in JavaScript. I originally used dot notation to define the new values of each variable. However this produces what seems like an infinite list of the first value in the array.
{value: 10, rest: {value: 10, rest:{etc...}}}
The code given as a hint is the one commented out in the function below. When run, this gives the correct output (except assigning null to the last rest value which I haven't coded in yet).
function arrayToList(array) {
  var object = {};
  for (var i = array.length - 1; i >= 0; i--) {
    object.rest = object;
    object.value = array[i];
    //object = {value: array[i], rest: object};
  }
  return object;
}

console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}

What is the difference between using the two different methods?

A: You are making a circular reference with object, because you use the same object for assigning to object.rest.

function arrayToList(array) {
    var object = {};
    for (var i = array.length - 1; i >= 0; i--) {
        object.rest = object;
        object.value = array[i];
        //object = {value: array[i], rest: object};
    }
    return object;
}

console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}

The other example overwrites object with an assignment.

function arrayToList(array) {
    var object = {};
    for (var i = array.length - 1; i >= 0; i--) {
        //object.rest = object;
        //object.value = array[i];
        object = {value: array[i], rest: object};
    }
    return object;
}

console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}

You could use a short ES6 version with Array#reduce for returning the rest object.

function toList(arr) {
    var result = {};
    arr.reduce((o, a) => (o.value = a, o.rest = {}), result);
    return result;
}

console.log(toList([2, 3, 5, 7, 11]));

A: I think this could be another implementation for you linked list. You can simply change the link direction by replacing reduceRight with reduce.

function toList(arr) {
  return arr.reduceRight(function(rest, value) {
    return { value: value, rest: rest };
  }, null);
}

console.log(toList([1, 3]));


text:
Q: How to create a multilanguage label in Yii I am wondering if the Yii framework uses the defined Labels atttributes in a multilanguage process.
So if I have
 public function attributeLabels() {
        return array(
            'email' => 'Email address',
            'rememberMe' => 'Remember me next time',
            'password' => 'Password'
        );
    }

Will this be translated to some other language? Or do I have to do something manually to work?

A: Yii doesn't translate it automatically. You need to use the i18n built-in in Yii and manually add the translations and modify the labels as follow:
 public function attributeLabels() {
    return array(
        'email' => Yii::t('account','Email address'),
        'rememberMe' => Yii::t('account','Remember me next time'),
        'password' => Yii::t('account','Password')
    );
}

You can get more info about internationalize you app at Quick Start to Internationalize your application in Yii Framework

A: Well, you can use the built-in translation system to translate your attribute labels, for example:
 public function attributeLabels() {
    return array(
        'email' => Yii::t('myapp','Email address'),
    );
}

and then in messages folder create a directory for your language, for example:
messages\dk\myapp.php

myapp.php should return the translation, for example:
return array('Email address' => 'TRANSLATION...');

Next you need to set the language of your application in the config file for instance.
'language' => 'dk',

A: I had assumed that Yii AR would run getAttributeLabel through Yii::t. Not wanting to do all that copy and pasting on dozens of models, I added this function to my intermediate AR class:
public function getAttributeLabel($attribute)
{
    $baseLabel = parent::getAttributeLabel($attribute);
    return Yii::t(get_called_class(), $baseLabel);
}

Now to write a shell command that loops through the models and adds their labels to the message file.


text:
Q: Why aren't keystroke numbers working with lowercase alphabet? I'm still relatively new when it comes to keystroke. When I convert a character to a integer then try to keyPress it using robot, it doesn't print out lower case letters, it prints out uppercase letters to lowercase ones.
I tried running the code by changing the input into all-caps (using toUpperCase), which worked, but the code doesn't print out uppercase letters.
import java.awt.Robot;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class typeWriter {
    public static void main(String[] args) throws InterruptedException {
        Scanner scan=new Scanner(System.in);
        try {
            String text6 = scan.nextLine();
            String text = text6.toUpperCase();
            char[] text1 = text.toCharArray();
            Robot robot = new Robot();
            int[] Charkey= new int[text1.length];
            TimeUnit.SECONDS.sleep(scan.nextInt());
            for(int i = 0; i<text1.length; i++) {
                Charkey[i]=(int) text1[i];
            }
            for(int y = 0; y<text1.length; y++) {
                robot.keyPress(Charkey[y]);
                robot.keyRelease(Charkey[y]);
            }
        } catch (AWTException e) {

        }

    }
}

When I input "Hello", I expect it to type out "Hello", but it types out "h5/" instead (without the toUpperCase modifier). If I change the string to all-caps, it prints out the correct word, but all in lowercase. What should I do?

A: I somewhat found an answer. To those with the same problem, this might not be the best nor most efficient way to do this, but I made a 2nd array made of the original values, and in the for loop I added an if statement, stating if the original set of values in this certain index is between 65 and 90, It will stimulate a shift key press and the actual key press.


text:
Q: How to prevent doctrine:migration:migrate command from rolling back if an older version was specified? I have the following migrations structure within the Doctrine package:

*

*Version 1

*Version 2

*Version 3 (custom)

*Version 4

Version 3 is not a regular migration because it requires some code calculations and depends on the previous migrations. So it should be executed separately after version 2 and before version 4.
I tried to do the following in my CI/CD script:
bin/console doctrine:migrations:migrate Version2 # prepare
bin/console doctrine:migrations:migrate Version3 # run custom migration
bin/console doctrine:migrations:migrate # run the rest

This works well on the first run. But on the second run, the command doctrine:migrations:migrate Version2 rolls back everything to the version 2 which is definitely not what I need. What I need is to make commands doctrine:migrations:migrate Version2 and doctrine:migrations:migrate Version3 do nothing if newer migrations are already applied. How can I achieve that?


text:
Q: What minimum options should be given to configure for installing dbus across machines on shared directory? I am installing dbus from source on Redhat 6 server on NFS share to be used across all the servers (which are mostly similar).
Along with --prefix, which other options are required?
The reason for this is: some gtk related packages require dbus version above 1.8.0 and the current version is less than this. We don't want to effect the running processes in all servers and want to install separate dbus in a shared path.
After installing, do i need to just simply run the binary, that's all? I am hoping it won't conflict with existing dbus binary and the processes that depend on that dbus.
I am following the instructions in linuxfromscratch. But for shared installation, there is no specific instructions: http://www.linuxfromscratch.org/blfs/view/7.7/general/dbus.html
EDIT 1:
Some thoughts:

*

*--with-system-socket=/var/run/dbus/system_bus_socket_1.8.0 (to avoid conflict with existing dbus socket)

*--with-session-socket-dir= (I am guessing it will create random sockets in tmp, so I guess it's not required)

*--with-dbus-daemondir=/NFS_share/bin

*--with-system-pid-file=/var/run/messagebus_1.8.pid
Then after installing, I need to create this /var/run/dbus_1.8.0 in all servers and start the dbus agent from /NFS_share/bin. Am I right?
EDIT 2:
Along with the above options, I am adding the following options too: --disable-static --disable-systemd --without-systemdsystemunitdir.
And not sure if I need to add the following option to: --with-console-auth-dir and if, what it is exactly?


text:
Q: C (linux) - Emulate / Skip scanf input I have a program running 2 threads. The first is waiting for user input (using a scanf), the second is listening for some data over an udp socket. I would like to emulate user input to handle a specific notification with the first thread everytime I recive a specific udp packet. I know I can share variables between threads, so my question is: can I force the scanf to take input from a different thread? Can I skip the scanf in the first thread?

A: I believe scanf() by definition reads from stdin. Like you said, though, the different threads share memory so it's easy to pass information between them. Maybe have some shared variable and some sort of boolean value indicating whether or not the information has been updated from the thread reading from the network. It all depends on what you're specifically trying to do, but you may want to have some other mechanism for simulation that bypasses the scanf().

A: Since you've specifically mentioned Linux, I'm going to suggest a novelty here.
You can open (/proc/%d/fd/%d, getpid(), STDIN_FILENO) and write to it. This will actually open the input of the terminal. I wouldn't recommend this for a real program, but then again, scanf shouldn't be used in real programs either.


text:
Q: How to handle google analytics cookie for ex _ga in jmeter There r some cookies like _ga, jsessionid etc which are part of jmeter recording script but when i replay script these cookies are not handled by cookie manager. How can i send these values in jmeter request . Also i m unable to corelate these cookies . I guess client side js is responsible for sending these cookies.
I m completely blocked. Please help.

A: JMeter's HTTP Cookie Manager stores valid cookies which are coming in Set-Cookie response header, the invalid ones are being discarded.
You can inspect what's going on there by adding/uncommenting the next line in log4j2.xml file
<Logger name="org.apache.jmeter.protocol.http.control" level="debug" />

If you see the evidence that cookies are detected but not stored you can try the following:

*

*Set Cookie Policy to something less restrictive, i.e. netscape

*Add the next line to user.properties file:
CookieManager.check.cookies=true

More information: HTTP Cookie Manager Advanced Usage - A Guide


text:
Q: Reshape Pandas dataframe with DatetimeIndex to make grid I have a pandas dataframe with a DatetimeIndex, e.g.
In: ts = pd.date_range('2013-01-01 00:00', periods=17520, freq='30min')
In: values = list(range(1, 17520))
In: df = pd.DataFrame(values, index=ts)

I want to reshape the dataframe so it has dates as the index and hours [0,0.5,1.0,1.5,.....] as the columns.
I have this:
df.pivot(index=df.index.date, columns=df.index.time, values='values')

but it gives me a key error with a list of dates not in index

A: df.index = [df.index.date, df.index.hour + df.index.minute / 60]

df[0].unstack()

            0.0  0.5  1.0  1.5  2.0  2.5  3.0  3.5  4.0  4.5
2013-01-01    1    2    3    4    5    6    7    8    9   10
2013-01-02   49   50   51   52   53   54   55   56   57   58
2013-01-03   97   98   99  100  101  102  103  104  105  106
2013-01-04  145  146  147  148  149  150  151  152  153  154
2013-01-05  193  194  195  196  197  198  199  200  201  202
2013-01-06  241  242  243  244  245  246  247  248  249  250
2013-01-07  289  290  291  292  293  294  295  296  297  298
2013-01-08  337  338  339  340  341  342  343  344  345  346
2013-01-09  385  386  387  388  389  390  391  392  393  394
2013-01-10  433  434  435  436  437  438  439  440  441  442

A: You can use pd.crosstab for this:
pd.crosstab(df.index.date, df.index.time, df[0], aggfunc='sum')

#col_0      00:00:00    00:30:00    01:00:00    01:30:00  ... more columns
#row_0
#2013-01-01        1           2           3           4
#2013-01-02       49          50          51          52
#... more rows


text:
Q: How to setup customized logging with Fluentbit in EKS Fargate? We are using fargate type EKS pods and we would like to setup customized fluent bit logging, which will capture logs from different specified paths in different services containers and outputs them to cloudwatch.
For example,
service 1 keep logs at below paths:-
/var/log/nginx/*
/usr01/app/product/logs/*

service 2 keep logs at below paths:-
/jboss/product/logs/*
/birt/1.0.0/deploy/birt.war/logs"
/birt/1.0.0/logs/*

and so on ...
Therefore, we want to customize fluent bit configmap to capture logs generated in different paths for different services and they should be prefixed with the service name. Please help us to achieve that.

A: As explained in the documentation for Fargate logging,  you cannot define input blocks for fluent-bit configuration.
https://docs.aws.amazon.com/eks/latest/userguide/fargate-logging.html

In a typical Fluent Conf the main sections included are Service,
Input, Filter, and Output. The Fargate log router however, only
accepts:
The Filter and Output sections and manages the Service and Input
sections itself.
The Parser section.
if you provide any other section than Filter, Output, and Parser, the
sections are rejected.

You can try a sidecar container approach (which is a little more expensive) for your use case:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  namespace: example
  labels:
    app: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
          - containerPort: 80
        volumeMounts:
        - name: varlog
          mountPath: /var/log/nginx
      - name: fluent-bit
        image: amazon/aws-for-fluent-bit:2.14.0
        env:
          - name: HOST_NAME
            valueFrom:
              fieldRef:
                fieldPath: spec.nodeName
          - name: POD_NAME
            valueFrom:
              fieldRef:
                fieldPath: metadata.name
          - name: POD_NAMESPACE
            valueFrom:
              fieldRef:
                fieldPath: metadata.namespace
        resources:
          limits:
            memory: 200Mi
          requests:
            cpu: 200m
            memory: 100Mi
        volumeMounts:
        - name: fluent-bit-config
          mountPath: /fluent-bit/etc/
        - name: varlog
          mountPath: /var/log/nginx
          readOnly: true
      volumes:
        - name: fluent-bit-config
          configMap:
            name: fluent-bit-config
        - name: varlog
          emptyDir: {}
      terminationGracePeriodSeconds: 10

In this approach you use a fluentbit sidecar container and specify your custom settings for the input blocks. You can use this simple fluent-bit configmap as an example to test:
apiVersion: v1
kind: ConfigMap
metadata:
  name: fluent-bit-config
  namespace: example
  labels:
    k8s-app: fluent-bit
data:
  fluent-bit.conf: |
    [SERVICE]
        Flush                     5
        Log_Level                 info
        Daemon                    off
        Parsers_File              parsers.conf
        HTTP_Server               On
        HTTP_Listen               0.0.0.0
        HTTP_Port                 2020

    @INCLUDE application-log.conf

  application-log.conf: |
    [INPUT]
        Name                tail
        Path                /var/log/nginx/*.log

    [OUTPUT]
        Name                stdout
        Match               *

  parsers.conf: |
    [PARSER]
        Name                docker
        Format              json
        Time_Key            time
        Time_Format         %Y-%m-%dT%H:%M:%S.%LZ

You can test this approach by running the example above and sending an http request to the nginx pod. After that you should see in the fluent-bit sidecar logs something similar to this:
AWS for Fluent Bit Container Image Version 2.14.0
Fluent Bit v1.7.4
* Copyright (C) 2019-2021 The Fluent Bit Authors
* Copyright (C) 2015-2018 Treasure Data
* Fluent Bit is a CNCF sub-project under the umbrella of Fluentd
* https://fluentbit.io

[2021/09/27 19:06:06] [ info] [engine] started (pid=1)
[2021/09/27 19:06:06] [ info] [storage] version=1.1.1, initializing...
[2021/09/27 19:06:06] [ info] [storage] in-memory
[2021/09/27 19:06:06] [ info] [storage] normal synchronization mode, checksum disabled, max_chunks_up=128
[2021/09/27 19:06:06] [ info] [http_server] listen iface=0.0.0.0 tcp_port=2020
[2021/09/27 19:06:06] [ info] [sp] stream processor started
[2021/09/27 19:06:06] [ info] [input:tail:tail.0] inotify_fs_add(): inode=1592225 watch_fd=1 name=/var/log/nginx/access.log
[2021/09/27 19:06:06] [ info] [input:tail:tail.0] inotify_fs_add(): inode=1592223 watch_fd=2 name=/var/log/nginx/error.log
[0] tail.0: [1632769609.617430221, {"log"=>"10.42.0.139 - - [27/Sep/2021:19:06:49 +0000] "GET / HTTP/1.1" 200 612 "-" "Wget" "-""}]
[0] tail.0: [1632769612.241034110, {"log"=>"10.42.0.139 - - [27/Sep/2021:19:06:52 +0000] "GET / HTTP/1.1" 200 612 "-" "Wget" "-""}]


text:
Q: Responsive grid with masonry I want to build a responsive masonry grid like THIS
I have this HTML

and the SCSS
article{
width: 100%;
float: left;

    @include breakpoint(medium) {
        width: 50%;
    }

    @include breakpoint(large) {
        width: 33.33333%;
    }
}

When I remove the gutter daclared in the html the grid works as I want, but with it it displays 2 at the large breakpoint and 1 at medium. How can I get this to work with using margins to space out the article horizontally?

A: The problem is that masonry.js adds a margin to the element making the element 50% + 20px wide, with is to big to fit on one row.
The solution is to make the elements and gutter fit in your wrapper by making the gutter + elements in a row = wrapper. If you have a flexible layout this would be a problem as masonry.js only takes a fixed px as gutter size.
So if (like in you example) you make the elements a fixed width this would be no problem. But masonry.js has a solution; if you sett the gutter not to a fixed width but to a element, masonry.js will use the width of that element. So a flexible solution could be to do this:

and the Scss
article {
  width: 100%;
  float: left;
  @include breakpoint(medium) {
    width: 49.2%;
  }
  @include breakpoint(large) {
    width: 32.26%;
  }
}
.gutter-sizer {
  width: 0%;
  @include breakpoint(medium and large) {
    width: 1.6%; //About 20px on a regular monitor at full width.
  }
}


text:
Q: Master/detail flow layout and Android annotations I need to make an Android app that adjusts itself to handset and tablets. It's like the master/detail flow layout.
I will use Android Annotation do simplify the development.
How to create an application that adjusts itself for tablets (two panels) and handsets (single panel) using Android annotations?

A: try this: An Android Master/Detail Flow Tutorial
http://www.techotopia.com/index.php/An_Android_Master/Detail_Flow_Tutorial/


text:
Q: Configuring gulpfile.js: FIle path **/ means? I am working on configuring my file path in a gulpfile.
When I am looking at other's gulpfile for reference, there is file path that has been written like this:
gulp.src("src/lib/**/*.*)

What is **/ supposed to mean?
-
From http://gruntjs.com/configuring-tasks
All most people need to know is that foo/*.js will match all files ending with .js in the foo/ subdirectory, but foo/**/*.js will match all files ending with .js in the foo/ subdirectory and all of its subdirectories.

A: src/**/*.ext means match all elements with extension ext inside src and any sub-directory.

A: It means all directories or in other words all folders.


text:
Q: Data migration tool : How can i use time zone handler for order purchase time for magento 1 server on IST timezone I use the tool for migrate my data from my 1.9.2.4 to magento2.2.2
It works except a problem with date of purchase.
There is a difference of 5:30 hours, however the time zone on M1 Server is IST (Indian Standard Time)
I have configured map.xml
        <transform>
            <field>sales_order.created_at</field>
            <handler class="\Migration\Handler\Timezone">
                <param name="offset" value="+5:30"/>
            </handler>
        </transform>

It is not working

A: I am assuming you configured that in vendor/magento/data-migration-tool-etc/<FROM-TO>/map-sales.xml?  If so, also make sure to update your vendor/magento/data-migration-tool-etc/<FROM-TO>/<VERSION>/config.xml to point to the new file instead of the original distributed file.  So as an example, change...
<sales_order_map_file>etc/commerce-to-commerce/map-sales.xml.dist</sales_order_map_file>

to
<sales_order_map_file>etc/commerce-to-commerce/map-sales.xml</sales_order_map_file>


text:
Q: JavaFX Render stage below parent According to the JavaFX documentation, a child stage is defined by
 A stage will always be on top of its parent window.

The issue is I'd like to render them like normal windows according to each other (if you click on one, it will render above the other). Can I do this without a hacky workaround?

A: The only other functionality you get from making a stage a child of another stage is that the child stage is automatically closed when the parent stage is closed. You can emulate this with a listener:
Stage firstStage = ... ;

Stage secondStage = new Stage();

// secondStage.initOwner(firstStage);
firstStage.addEventHandler(WindowEvent.WINDOW_HIDDEN, evt -> secondStage.hide());

// ...

If you are relying on using getOwner() anywhere you would have to find a way around that.
(I'm not sure if this qualifies as a "hacky workaround", but it should work...).


text:
Q: Complicated sql query - select all landlords' properties and subtract costs in one query I have a table data structure similar to this:
Landlord table
Id    Name        Email
```````````````````````
1     J Johnson    ...
2     R Kelly      ...

Property table
Id    Address    Rent    LandlordId
```````````````````````````````````
1    ....        400    1
2    ....        600    1
3    ....        750    2

Maintenance table
Id    Details   Cost    MaintenanceDate    PropertyId
`````````````````````````````````````````````````````
1    ....        25     20/12/2012         1
2    ....        120    22/12/2012         2
3    ....        35     24/12/2012         3

Essentially, a Landlord has multiple properties.. Each month, I need to produce an invoice for the landlord which includes all his properties, all the maintenance done on his property. To calculate how much I need to pay to the landlord, I need to sum all his properties' Rent and subtract that with the sum of all his maintenance costs for that month.
So, amount payable to landlord L = Sum(Rent of properties of L) - Sum(maintenance costs on all properties of L during this month)
I am using telerik reporting, thought I could achieve it with some clever grouping but that was a waste of my time so I am now going to try and achieve this with SQL and sub reports instead.
The SQL query that I'm trying is this:
 SELECT l.Name, p.[Address], p.Rent, c.Details, c.Cost,
(select Rent From Property where Id = p.Id) -
    (select SUM(cost) from CarriedOutJobs where PropertyId = p.Id)
    as PayableToLandlord
FROM Landlord l JOIN PROPERTY p ON p.LandlordId = l.Id
LEFT OUTER JOIN Maintenance c ON c.PropertyId = p.Id
ORDER BY l.Fullname

This doesn't seem to work properly as it produces multiple fields
Because I am going to breakup the report into sub report, I thought I would just get landlord details first but I still need to calculate the amount payable to Landlord even in this case.. So I rewrote the query to this:
SELECT distinct l.Name,
(SELECT SUM(Rent) FROM PROPERTY WHERE LandlordId = l.Id) -
    (SELECT COALESCE(SUM(cost), 0)
    FROM CarriedOutJobs WHERE PropertyId = p.Id) AS     PayableToLandlord
FROM Landlord l
JOIN PROPERTY p ON p.LandlordId = l.Id
ORDER BY l.Fullname

I thought this worked okay, but even though I have used distinct, this seems to produce a duplicate row with different PayableToLandlord amount and I can't seem to figure out why.
Is there a way to select all landlords, their properties, and the amount payable to them in one query, please?
I have removed date where clause for the sake of simplicity here.
Thanks.

A: I suggest keep it simple and use sub-queries as these are easy to work out what's going on.  Hopefully you can then do your subtraction etc either in the report or quite simply as additional return columns.
Any date parameters you should pass in as variables in to the sub-queries (probably).
SELECT Landlord.Id as LandlordId, Landlord.Name,
       ISNULL(TotalRent,0) AS TotalRent,
       ISNULL(TotalCost,0) AS TotalCost
FROM Landlord
LEFT JOIN
    (SELECT SUM(Rent) as TotalRent, LandLordId
     FROM Property
     GROUP BY LandLordId) Rents
ON Landlord.Id = Rents.LandlordId
LEFT JOIN
    (SELECT LandLordId,SUM(Cost) AS TotalCost
     FROM Property
     INNER JOIN Maintenance
        ON Property.Id = Maintenance.PropertyId
     GROUP BY LandLordId
     ) MaintenanceCosts
ON Landlord.Id = MaintenanceCosts.LandlordId
ORDER BY Landlord.Name

Just noticed you also wrote:

Is there a way to select all landlords, their properties, and the amount payable to them in one query, please?

You can further join in the list of properties but you'll end up repeating the sum on each line.  This is fine as long as you don't try to SUM it within your reporting package.
If you do want the property details then my suggestion is to pull in each property rent and cost and then do the SUM / net figure in the reporting package.

A: Here is a shorter query: Please comment.
select l.name, x.propid,
sum(x.tot) as finalrent
from landlord l
left join
(select p.landlordid, (p.rent - m.cost) as tot,
p.id as propid
from property p left join
maintenance m
on p.id = m.propertyid) as x
on
l.id = x.landlordid
group by l.id, x.propid
;

NAME        PROPID  FINALRENT
J Johnson   1       375
J Johnson   2       480
R Kelly     3       715

25/12/2012

Edit to add SQLFIDDLE as well as results group by landlord only
Query shows Total rent after cost is deducted.

*

*SQLFIDDLE DEMO
Query:
-- group by landlord only

select l.id, l.name,
sum(x.tot) as finalrent,
sum(COALESCE(x.cost,0)) as TotalCost
from landlord l
left join
(select p.landlordid,
(p.rent - COALESCE(m.cost,0)) as tot,
p.id as propid, m.cost
from property p left join
maintenance m
on p.id = m.propertyid) as x
on l.id = x.landlordid
group by l.id
;

Results:
ID  NAME        FINALRENT   TOTALCOST
1   R Johnson   880         120
2   R Kelly     715         35

27/12/2012

A: Joel's answer is very good.  There is, however, a somewhat simpler way to express this.  You can do the summaries in the subqueries at the property level, and then summarize at the landlord level in the outer query:
SELECT l.Id as LandlordId, l.Name,
       sum(p.rent) as TotalRent,
       coalesce(sum(p.rent), 0) AS TotalRent,
       coalesce(sum(m.PropertyCost), 0) AS TotalCost
FROM Landlord l left outer join
     Property p
     on l.LandlordId = p.LandlordId left outer join
     (SELECT PropertyId, SUM(Cost) AS PropertyCost
      FROM Maintenance m
      group by PropertyId
     ) m
     on m.PropertyId = p.PropertyId
group by l.LandLordId, l.LandlordName
ORDER BY Landlord.Name

This saves a join in the second subquery.


text: Q: Criticism of physics in _The Beginning of Infinity_? Have any criticisms been written of the physics presented in David Deutsch's book The Beginning of Infinity? Does he make any mistakes? If so, please refer me to them.


text:
Q: How do I use BooleanJunction with Hibernate Search I trying to build this query with hibernate search, I could not succeed.
Select * from message where (sender.id = "1" AND message.status = "sent") OR (recipient.id = "1" AND message.status = "new") OR (recipient.id = "1" AND message.status = "seen")

how can I do it with lucene?
I stuck here
FullTextSession fullTextSession = Search.getFullTextSession(getSessionFactory().getCurrentSession());
    QueryBuilder qb = fullTextSession.getSearchFactory()
            .buildQueryBuilder().forEntity(getPersistentClass()).get();

    BooleanQuery bquery = new BooleanQuery();

    Query q1 = qb.keyword().onField("sender.id").matching(user.getId()).createQuery();
    Query q2 = qb.keyword().onField("status").matching(Message.Status.SENT).createQuery();
    BooleanJunction must1 = qb.bool();
    must1.must(q1);
    must1.must(q2);

    Query q3 = qb.keyword().onField("recipient.id").matching(user.getId()).createQuery();
    Query q4 = qb.keyword().onField("status").matching(Message.Status.NEW).createQuery();

    BooleanJunction must2 = qb.bool();
    must2.must(q3);
    must2.must(q4);

    Query q5 = qb.keyword().onField("recipient.id").matching(user.getId()).createQuery();
    Query q6 = qb.keyword().onField("status").matching(Message.Status.SEEN).createQuery();

    BooleanJunction must3 = qb.bool();
    must3.must(q5);
    must3.must(q6);

Any help?

A: Query query = qb.bool()
    .should(must1.createQuery())
    .should(must2.createQuery())
    .should(must3.createQuery())
    .createQuery();


text:
Q: Is it possible to restore centralManager state after application is updated? I am working on one application in which I need to support continuous background app execution. I am able to communicate continuously using Apple's available background modes. But facing one issue when application is in background (or not running) and install an updated version of app, after that, centralManager delegates have stopped functioning. So I am not sure whether can We restore CentralManager state after app update or not ??
If its not possible then is there any other option(or patch ;) ) available ??
One alternate way is to send silent push notification to start the application run in background (But for this, we have to send silent notification as soon as new app version is installed on all the devices)..

A: Centeral manager's information will be restored if it lost its handle when it goes to suspend state.
If application falls down to suspend mode then it's going to be lost its memory and at this time the system keeps application's BLE information to restore the information when the application comes up in foreground.
But not sure when application gets update...


text:
Q: How to fetch String from setValues() method of PreparedStatementSetter I want to fetch a string from setValues() method of ItemPreparedStatementSetter which is my SQL string. I want to use this String into setSql() method of ItemWriter. Can somebody help me to achieve this.
Below is my PreparedStatementSetter class:
public class PreparedStatementSetter implements
    ItemPreparedStatementSetter<Object>{

public static final int INT = 4;
public static final int STRING = 12;

public void setValues(Object item, PreparedStatement ps)
        throws SQLException{

    @SuppressWarnings({ "rawtypes", "unchecked" })
    Map<String, Object> map = (LinkedHashMap) item;
    int i = 0;
    String columnType;
    String sql="";
    String final_sql;

    try {
        sql=generateSql();

    } catch (ParserConfigurationException e) {

        e.printStackTrace();
    } catch (SAXException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }

    int len=map.size();

    for(int k=0 ; k<len ; k++)
    {
        sql=sql+","+"?";
    }
    sql=sql+")";

    // i want to use this final_sql string in setsql() method of itemwriter

    final_sql=sql.replaceFirst("," , " ");

    for (Map.Entry<String, Object> entry : map.entrySet()) {

        i++;
        columnType = entry.getKey().substring(0,
                (entry.getKey().indexOf("_")));

        switch (Integer.parseInt(columnType)) {
            case INT: {
                    ps.setInt(i, (Integer) (entry.getValue()));
                    break;
            }
            case STRING: {
                    ps.setString(i, (String) (entry.getValue()));
                    break;
            }
        }
    }
}

private String generateSql()
throws ParserConfigurationException, SAXException, IOException
{
    String sql="";
    Insert insert;
    String table="";
    try
    {
        File is = new File("C:/Users/AMDecalog.Trainees/workspace/SpringJobExecuter/config/input1.xml");
        JAXBContext context = JAXBContext.newInstance(Insert.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        insert = (Insert) unmarshaller.unmarshal(is);
        Insert in = insert;
        List<String> into = in.getInto().getTablename();

        for(String s : into)
        {
            table = table+s;
            System.out.println(table);
        }

        sql = "insert into" + " " + table + " " + "values(";
        System.out.println(sql);
    }
    catch (JAXBException e)
    {
        e.printStackTrace();
    }
    return sql;
}

A: OK, you don't implement your PreparedStatementSetter the right way.
All you have to do is to declare your SQL in the ItemWriter config or in the itemWriter Implementation.
I will assume you are using a JdbcBatchItemWriter:
public class MyItemWrtier extends  JdbcBatchItemWriter<MyDomainObj> implements InitializingBean{

@Override
public void afterPropertiesSet() throws Exception {
        // set the SQL

    String SQL= "UPDATE MYTABLE WHERE FIELD1 = ? AND FIELD2 = ?"

    super.setSql(SQL);

}
}

Now, your batch config should declare this writer like this.
    <bean id="myItemWriter" class="xxx.yyy.MyItemWriter">
    <property name="dataSource" ref="dataSourceIemt" />
    <property name="itemPreparedStatementSetter" ref="myPreparedStatementSetter" />
</bean>

And Finally,
@Component("myPreparedStatementSetter")
public class MyPreparedStatementSetter implements ItemPreparedStatementSetter<MyDomainObj> {

public void setValues(MyDomainObj obj, PreparedStatement ps) throws SQLException {
    ps.setString(1, obj.getsometing());
    ps.setString(2, obj.getsometingElse());

}
}

Hope it is clear.
Regards


text:
Q: How to apply css styles defined in html head to complete report in iReport? I want to include my own css styles while generating the report. Iam using iReport for report generation. I successfully set the html_header by setting the JRHtmlExporterParameter.HTML_HEADER. When i run the ireport the header value has the link tag with corresponding href.
<title></title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

 	<link rel="stylesheet" type="text/css" href="/apsrtc-oprs/_assets/skin/style.css" />

My question is how do i apply the defined css-style to the complete iReport ?
Any suggestions are welcome.


text:
Q: Why am I getting null results? So i have a very simple function that runs against a MySQL database of users with a few other credentials. I have written several other functions that run similar queries with that work as expected. However currently every time I run a query against my DB i get null result. I have taken the query itself and ran it directly against it(phpmyadmin) and was able to retrieve the desired results.
function getName( $user ){
    $con = mysqli_connect('localhost','*****','*****','*****');
    if(mysqli_connect_error()){
        echo 'Failed to Connect: '. mysqli_connect_error();
        die();
    }
    $stmt = $con->prepare('SELECT firstName,lastName FROM users WHERE user=? LIMIT 1');
    $stmt->bind_param('s',$user);
    $stmt->execute();
    $stmt -> bind_result($fname,$lname);

    $stmt->fetch();

    $lArr = str_split($lname);
    $canName = $fname . ' ' . $lArr[0].'.';
    return $canName;
}

I have tried with and without limit just in case. var_dump always shows null. Does anyone know why this would happen?

A: You forgot to ->fetch() any results from the result set, just binding them to variables is not enough
function getName( $user ){
    $con = mysqli_connect('localhost','*****','*****','*****');
    if(mysqli_connect_error()){
        echo 'Failed to Connect: '. mysqli_connect_error();
        die();
    }
    $stmt = $con->prepare('SELECT firstName,lastName FROM users WHERE user=? LIMIT 1');
    $stmt->bind_param('s',$user);
    $stmt->execute();
    $stmt -> bind_result($fname,$lname);

    // now fetch data into the bound variables
    $stmt->fetch();

    $lArr = str_split($lname);
    $canName = $fname . ' ' . $lArr[0].'.';
    return $canName;
}

A: You execute the query but you are not picking up the results (As RiggsFolly was saying). You shout use fetch() of fetchall()
http://php.net/manual/en/pdostatement.fetchall.php
http://php.net/manual/en/pdostatement.fetch.php