text:
Q: data not passed from View to controller I am new to MVC. i have problem to pass data from view to controller.
This application is for ordering  Shirts. I have different types like T-shirts, Casual shirts and Formal Shirts. In a single  order, I would like to place order for 2 T-shirts, 3 Casual shirts and 5 Formal Shirts. I am able to edit single value, i.e. either of them, in one order. The problem I am facing is with ordering multiple types of shirts in one order.
public class Shirt
{
   //[Key]
   public int ShirtId{ get; set; }
   public string ShirtName{ get; set; } // This is an read-only field
}

public class Order
{
    public int ShirtId { get; set; }
    public virtual Shirt Shirt { get; set; } // a reference to Shirt
    public int Quantity { get; set; }
    public int OrderId { get; set; }
}

I have a view that is strongly typed with my viewmodel "Order". Initially I passed data from my Controller to View using
     [HttpGet]
    public ActionResult Index()
    {
       OrdersList();
       return View(db.Order.ToList());
    }

Here OrdersList is a function that interacts with database and gets a list of Orders
   void OrdersList()
   {
     ViewBag.OrdersLsit= from f in db.Shirt
                            orderby f.ShirtName
                            select f;
   }

I am getting data back to Controller using,
    [HttpPost]
    public ActionResult Index(List<Order> order)
    {
        Order newOrder = new Order();
        for (int i = 0; i < order.Count; i++)
        {
            newOrder.Quantity = order.ElementAt(i).Quantity;
            if (ModelState.IsValid)
            {
                db.Entry(newOrder).State = EntityState.Modified;

                db.SaveChanges();
            }
        }
    }

My problem is List order is passed as Null. If I do
public ActionResult Index(Order order) in HttpPost, I am getting only the first item(in this case a T shirt is getting updated in database).
In Index.cshtml, I am doing something like this
  <legend>Order Shirts</legend>

                @{List<Order> orderList = new List<Order>(); }
                @foreach (Order ord in ViewBag.OrderList)
                {

                    @Html.DisplayFor(model => ord.Shirt.Shirtname)

                    orderList.Add(ord);
                }

                @for (int i = 0; i < orderList.Count; i++)
                {

                            @Html.HiddenFor(model => orderList.ElementAt(i).Shirt.ShirtId)
                            @Html.HiddenFor(model => orderList.ElementAt(i).OrderId)
                            @Html.ValidationSummary(true)
 @Html.HiddenFor(model => orderList.ElementAt(i).ShirtId)
                            @Html.EditorFor(model => orderList.ElementAt(i).Quantity)
                            @Html.ValidationMessageFor(model => orderList.ElementAt(i).Quantity)

                }

    </fieldset>

       <input id = "btnSubmit" type="submit" value="Save Order" />

        @Html.ActionLink("Back to List", "Index")

I am new to MVC and this is my first application. Any constructive comments and suggestions are appreciated.
Thanks

A: I don't understand why you are creating orderList instead the view, actually you have to pass that from the controller and strongly type the view to List<Order>.
Instead of using this,
@Html.EditorFor(model => orderList.ElementAt(i).Quantity)

You could try (if you strongly type the view to List<Order>),
@Html.EditorFor(m => m[i].Quantity)

If the view is not strongly typed to List<Order> you could try this,
@Html.EditorFor(m => orderList[i].Quantity)

But in this case you have to change the action as below,
[HttpPost]
public ActionResult Index([Bind(Prefix="orderList")]List<Order> order)
{
}

The reason is I'm not sure whether the ElementAt(i) generate the names properly for fields, so try index approach!


text:
Q: GridView in fragment is not working getItem not going to called here is my code its is not working if i am use activity then its work properly but in fragment getItem method not gonna call please help
this is my Fragment:
public class HomeFragment extends BaseFragment{

    private static final String TAG = "HomeFragment";
    private GridView gvMainItems;
    private HomeFragmentGridAdapter homeFragmentGridAdapter;
    private ArrayList<HashMap<String, String>> arrayList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view=inflater.inflate(R.layout.fragment_home,container,false);
        gvMainItems = (GridView) view.findViewById(R.id.gvMainItems);

        arrayList = new ArrayList<>();
        for(int i = 1; i < 100; i++){
            HashMap<String, String> map = new HashMap<>();
            map.put("item", String.valueOf(i));
            arrayList.add(map);
        }

        homeFragmentGridAdapter = new HomeFragmentGridAdapter(getActivity(), arrayList);
        gvMainItems.setAdapter(homeFragmentGridAdapter);

        return view;
    }
    @Override
    public void onClick(View view) {

    }
}

This is my adapter:
 public class HomeFragmentGridAdapter extends BaseAdapter {
    private final Context context;
    private final ArrayList<HashMap<String, String>> arrayList;
    private ViewHolder holder;

    public HomeFragmentGridAdapter(Context context, ArrayList<HashMap<String,String>> arrayList){
        this.context = context;
        this.arrayList = arrayList;
    }

    @Override
    public int getCount() {
        return arrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return arrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View cinvertview, ViewGroup viewGroup) {

        if(cinvertview == null) {
            holder = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            cinvertview = inflater.inflate(R.layout.fragment_home_grid_raw, null, true);
            holder.textView = (TextView) cinvertview.findViewById(R.id.textView);
            cinvertview.setTag(holder);
        }else{
            holder = (ViewHolder) cinvertview.getTag();
        }
        Log.d(TAG, "getItem: "+arrayList.get(position).get("item"));

        holder.textView.setText(arrayList.get(position).get("item"));
        return cinvertview;
    }
    public class ViewHolder{

        public ImageView ivGridItem;
        public TextView textView;
    }
}

this is xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/content_main"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.neodocto.activity.MainActivity"
tools:showIn="@layout/app_bar_main">

<GridView android:id="@+id/gvMainItems"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp"
/>
</LinearLayout>

A: Change this code in your HomeFragment :
homeFragmentGridAdapter = new HomeFragmentGridAdapter(getActivity().getApplicationContext(), arrayList);

Because Your construct uses a Context instead of an FragmentActivity (returned by the getActivity().

A: Please try on this way i have work fine
Change on your adapter like
private final Context context;
private final ArrayList<HashMap<String, String>> arrayList;
private ViewHolder holder;
LayoutInflater inflater;

public HomeFragmentGridAdapter(Context context, ArrayList<HashMap<String, String>> arrayList) {
    this.context = context;
    this.arrayList = arrayList;
    inflater = LayoutInflater.from(this.context);
}

@Override
public int getCount() {
    return arrayList.size();
}

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View cinvertview, ViewGroup viewGroup) {

    if (cinvertview == null) {
        holder = new ViewHolder();
        cinvertview = inflater.inflate(R.layout.list_purchase_items, null);

        holder.textView = (TextView) cinvertview.findViewById(R.id.textView);
        cinvertview.setTag(holder);
    } else {
        holder = (ViewHolder) cinvertview.getTag();
    }
    Log.d(TAG, "getItem: " + arrayList.get(position).get("item"));

    holder.textView.setText(arrayList.get(position).get("item"));
    return cinvertview;
}

public class ViewHolder {

    public ImageView ivGridItem;
    public TextView textView;
}

A: I change my gridview to this and it working
<GridView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/gvMainItems"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:numColumns="4" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: Auto populating a text box based on listbox selected value and drop down value javascript sharepoint I have a list named "Assigning to Individual" which has a drop down 'Initial Training'
The values in the drop down are Immediate, Hire Date, Specific. There is another textbox Date
There is a listbox which contains employee name.
There is another list "Employees" which contains Employee name and Hire Date.
The scenario is when the user selects hire date in the drop down in "Assigning to Individual", and selects employee name from the listbox, then the text box should populate based on the Employees list.
I have got the code using drop down but I do not know how to get the listbox selected value. If somebody could show the changes required in my code
    $(document).ready(function () {
    var currentPage = decodeURIComponent(window.location.href.replace(/\+/g, " "));
    var result = null;
    if (currentPage.contains("Assigning to Individual")) {

        var dropdown = $("select[title = 'Initial Training']");
        var dropdownid = dropdown[0].id;
        if (dropdown.length != 0) {
            populateCourseAssignment(dropdown, dropdownid)

            $('#' + dropdownid).change(function () {
                onChangeValueDropDown(dropdownid);
            });
        }

    }

});

function populateCourseAssignment(dropdown, dropdownid) {
    //var dropdown = $("select[title = 'Course Name']");
    if (dropdown.length != 0) {
        var selectedtext = $('#' + dropdownid + ' option:selected').text();
        if (selectedtext == "Hire Date")
        result = getCourseAssignment("Initial Training", selectedtext);
        fillValuesInCourseAssignment();

    }
}

function fillValuesInCourseAssignment() {
    $("input[title = 'Date']").val(result[0].Hire_x0020_Date);
    //    $("input[title = 'Instructor Name']").val(result[0].Instructor);

}

function onChangeValueDropDown(dropdownid) {
    var currentvalue = $('#' + dropdownid + ' :selected').text();
    {
        if (currentvalue == "Hire Date")
        result = getCourse("Course_x0020_Title", currentvalue);
        fillValuesInTrainingStatus();

    }
}
function getCourseAssignment(whereColumnName, whereColumnValue) {

    var CAMLQuery = '<Query><Where><Eq><FieldRef Name="' + whereColumnName + '" /><Value Type="Text">' + whereColumnValue + '</Value></Eq></Where></Query>';

    // var CAMLQuery = '<Query><Where><Eq><FieldRef Name="' + whereColumnName + '" /><Value Type="Text">' + whereColumnValue + '</Value></Eq></Where></Query>';
    var course;
    $().SPServices({
        operation: "GetListItems",
        async: false,
        listName: "Course Details",
        CAMLQuery: CAMLQuery,
        CAMLViewFields: "",
        completefunc: function (xData, Status) {
            //            $(xData.responseXML).SPFilterNode("z:row").each(function () {
            //                wizardId = getData($(this).attr("ows_" + returnColumnName));
            //            });
            course = $(xData.responseXML).SPFilterNode("z:row").SPXmlToJson({
                includeAllAttrs: true,
                removeOws: true
            });
        }
    });

    return course;
}

A: var selectedtext = $('#' + dropdownid).val();

...
var currentvalue = $('#' + dropdownid).val();

A: In your onChangeValueDropDown function change this line
 var currentvalue = $('#' + dropdownid + ' :selected').text();

To what you have in populateCourseAssignment:
var currentvalue = $('#' + dropdownid + ' option:selected').text();

Also, remove the uneccessary curly braces in the onChangeValueDropDown function. So the final will be:
function onChangeValueDropDown(dropdownid) {
    var currentvalue = $('#' + dropdownid + ' option:selected').text();
    if (currentvalue == "Hire Date")
    result = getCourse("Course_x0020_Title", currentvalue);
    fillValuesInTrainingStatus();
}

Lastly, I notice you are using SPServices. Why not use their Cascading dropdowns function?


text:
Q: What is the difference between [value] and value in Angular and what is the method of checking value for null? <mat-form-field>
    <input matInput placeholder="Organization name" [value]="organizationDetail.name"
        formControlName="organizationName" required>
</mat-form-field>

What is the way to check if organizationDetail.name is null or not? I am getting error
ERROR TypeError: Cannot read property 'name' of null
in my .ts file I am initializing it like below:
organizationDetail: any = {};

constructor() {
    this.organizationDetail = {
        address: '',
        attachmentId: null,
        createdBy: '',
        createdDateTime: '',
        industryFramework: [],
        invitation: [],
        location: '',
        name: '',
        orgAssessment: [],
        organizationId: 0,
        organizationPolicy: [],
        ownerId: 0,
        partnerType: null,
        partnerTypeId: 0,
        phone: '',
        updateBy: '',
        updateDateTime: '',
        user: [],
    };
}

Thanks for your help in advance. I wasn't able to find any good article which can help me to identify the difference and solve the error.

A: Interpolation and Property binding are virtually the same, and bind-src is just an alternate way that is wordy and not often used.
the difference:
interpolation "injects" the value into the html, so when you say value="{{ hello }}" Angular is inserting your variable between the brackets.
property binding allows Angular to directly access the elements property in the html. this is a deeper access. When you say [value]="hello" Angular is grabbing the value property of the element, and setting your variable as that property's value.
event binding allows you to use events such as a click to trigger functions. these bindings use parenthesis for example (click)="myFunction($event)". this will call the myFunction() method on defined in your .ts file. the parenthesis around '(click)' bind the function to the dom event.$event is a keyword passing the event object to the function. you could also pass a string with single quotes, or even a variable with interpolation.
Two way (data) binding allows you to have an event combined with a property binding. For example
<input [(ngModel)]="username">

Hello {{username}}!

will allow you to have an input and display the value at the same time. learn more here
Lastly when to use interpolation and when to use data-binding. This is usually a formality, typically when using a smart component and dumb (presentation) component, you would bind to the html with property binding because of readability, and because it is shall I say, "more secure" to bind to a property in that case. If you have simple values, then maybe interpolation is your friend. It all comes down to readability, best practice, and preference.


text:
Q: Prove a Field is a commutative ring with identity I was just introduced to rings and fields recently and am in need with help for the following proof.
Prove: A field $F$ is a commutative ring with identity and with at least two elements, such that for all $a \ne 0$ and $b \in F$, the equation $ax=b$ has a unique solution in $F$.
I have a few hints from earlier problems: proving that if $ab=ac$ then $b=c$ (set $a(b-c) = 0$, multiply by $a^{-1}$ to get $b=c$) and proving $ax=b$ has a unique solution by setting $x = a^{−1} b$.
I'm just having trouble putting two and two together here.

A: First, suppose that $F$ is a field. Let's show that, for any $a,b\in F$, $a\neq 0$, the equation $ax=b$ has a unique solution.
Since $a\neq 0$, then $a$ is invertible, that is, exists $a^{-1}\in F$ such that $aa^{-1}=1$. Then $a(a^{-1}b)=(aa^{-1})b=1b=b$, so $(a^{-1}b)$ is a solution. Now, if $x\in F$ is another solution of $ax=b$ and $ay=b$, then, $x=1x=(a^{-1}a)x=a^{-1}(ax)=a^{-1}b$. This proves the uniqueness of the solution of $ax=b$. Also $F$ has at least two elements ($0$ and $1$).
Now, suppose $F$ is a commutative ring with at least two elements and such that $ax=b$ has an unique solution for all $a,b\in F$, $a\neq 0$. If $1=0$, then $F=\left\{0\right\}$ (prove this!), a contradiction. So $1\neq 0$. Also, in particular, given $a\neq 0$, there exists a unique $x\in F$ such that $ax=1$. This proves that $F$ is a field.


text:
Q: Error sending an email with an .eml attachment using Mailjet Send API v3.1 I'm trying to send an email with an attachment that will be an email in format .eml using Mailjet Send API with java (Java 8).
I have the email I want to attach in raw format (obtained using the Gmail API) and I try to add it to the main email as the Mailjet documentation says, but when I try to open the email attached, I get the following error:

I tried to open the email with the Thunderbird client too, and it shows me strange content, as if the .eml file were corrupted.

I think that I'm adding the attachment correctly to the email that will be sent, following the format indicated in the documentation. The variable raw is the string that has the email I want to send as an .EML file.

I don't know if the problem is related to the way Mailjet creates the eml attachment, or because how Gmail API give me the raw email.


text:
Q: python grid control / spreadsheet I am designing a thick-client (i.e. non-browser) Python application that will communicate with a hosted database.  One of the screens of this application needs to have a grid / spreadsheet area that allows presentation of many rows of data, filtering, sorting, and updating of multiple rows of information.  Does anyone have a recommendation for an open-source UI control in Python that has this capability?
** Note - It must be platform-indepedent: will likely be deployed on Mac and Windows clients. **
Thank you!
Ron

A: I've had good results with wxPython's CSheet, though I ended up modifying it somewhat so that it acted a little more "Excel-like" (arrow keys and context menu) as per a coworker's request.  wxPython works on OS X but it's 32-bit only right now I believe (based on Carbon API).


text:
Q: checking for errors in a program that implements a System V signal API using the standard POSIX API How can I modify the error checking program? I check or pass the returned value of sigprocmask (), but I don't check the return value of most other sig * () functions. However, it all returns an error code that I should check. How can I do that?
I wrote a program that implements a POSIX signal API. It implements the functions sigset(), sighold(), sigrelse(), sigignore() and sigpause().
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>

#define SIG_HOLD ((__sighandler_t)2)
typedef void (*sighandler_t)(int);

sighandler_t
sigset(int sig, sighandler_t disp);
int sighold(int sig);
int sigrelse(int sig);
int sigignore(int sig);
int sigpause(int sig);

sighandler_t
sigset(int sig, sighandler_t disp)
{
    struct sigaction old_set;
    if (disp == SIG_HOLD)
    {
        sighold(sig);

        sigaction(sig, NULL, &old_set);
        return old_set.sa_handler;
    }

    struct sigaction act;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    act.sa_handler = disp;
    sigaction(sig, &act, &old_set);
    return old_set.sa_handler;
}

int sighold(int sig)
{
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, sig);
    return sigprocmask(SIG_BLOCK, &set, NULL);
}

int sigrelse(int sig)
{
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, sig);
    return sigprocmask(SIG_UNBLOCK, &set, NULL);
}

int sigignore(int sig)
{
    if (signal(sig, SIG_IGN) == SIG_ERR)
        return -1;
    return 0;
}

int sigpause(int sig)
{
    sigset_t old_set;
    if (sigprocmask(SIG_BLOCK, NULL, &old_set) == -1)
        return -1;
    sigdelset(&old_set, sig);
    return sigsuspend(&old_set);
}

void handler(int sig)
{
    printf("handler\n"); // it's unsafe
}

int main()
{
    sigset(SIGTERM, handler);
    sighold(SIGABRT);
    sigrelse(SIGABRT);
    sigignore(SIGABRT);
    sighold(SIGTERM);
    raise(SIGTERM);
    sigpause(SIGTERM);

    return 0;
}

A:
However, it all returns an error code that I should check. How can I
do that?

Similar to how you check the return value of sigprocmask(), simply check the return values of the rest. Most, if not all, of these functions return -1 on failure.
A sample example:
if (sigset(SIGTERM, handler) == -1) {
    perror ("sigset()");
    /* Handle error here. */
}


text:
Q: Qt Creator. Qt Quick Application screen doesn't show up on my Android device I'm new to Qt Creator and I'm attempting to create a simple application. So far it's only very basic with just the main screen.
I have written the QML code, and tried to run it on my OnePlus One Android phone.
I have all the necessary components in order to run the program on my phone, as the Qt examples have all worked fine.
The application builds and installs on my device, however It resolves in a blank black screen, with nothing on it. I have tried for about 2 hours different possible solutions, but nothing has worked. Can anyone point me in the right direction, please?
My QML code (the pictures are correctly added to the directory), everything else is unaltered:
import QtQuick 2.3
import QtQuick.Window 2.2
import QtQuick.Controls 1.3

Window {
    id: applicationWindow1
    visible: true
    width: 360
    height: 360
    color: "#343434"

    Image {
        id: cammbutticon
        x: 208
        y: 169
        width: 150
        height: 150
        opacity: 1
        fillMode: Image.PreserveAspectFit
        anchors.verticalCenter: parent.verticalCenter
        anchors.horizontalCenter: parent.horizontalCenter
        source: "camera-icon.png"

        Rectangle {
            id: centRect
            width: 150
            height: 150
            opacity: 1
            color: "#00000000"
            radius: 35
            border.color: "#ef0707"
            border.width: 3

            MouseArea {
                id: mouseAreaCam
                anchors.fill: parent
                onClicked: 'GO TO CAMERA'
            }

        }
    }

    Image {
        id: exitman
        x: 473
        y: 338
        width: 150
        height: 120
        opacity: 1
        sourceSize.height: 250
        sourceSize.width: 250
        anchors.right: parent.right
        anchors.rightMargin: -15
        anchors.bottom: parent.bottom
        anchors.bottomMargin: -10
        source: "exitman.png"

        Rectangle {
            id: exitRect
            x: 37
            y: 12
            width: 100
            height: 100
            opacity: 1
            color: "#00000000"
            radius: 35
            border.width: 3
            border.color: "#ef0707"
            anchors.right: parent.right
            anchors.rightMargin: 20
            anchors.bottom: parent.bottom
            anchors.bottomMargin: 15

            MouseArea {
                id: mouseAreaExit
                anchors.fill: parent
                onClicked: Qt.quit()
            }

        }
    }
    Label {
        id: welcometext
        width: 227
        height: 130
        opacity: 1
        color: "#ef0707"
        text: qsTr("WELCOME TO THE APPLICATION")
        anchors.top: parent.top
        anchors.topMargin: -8
        styleColor: "#f9f9f9"
        style: Text.Normal
        font.bold: false
        font.pointSize: 20
        font.family: "Arial"
        verticalAlignment: Text.AlignVCenter
        horizontalAlignment: Text.AlignHCenter
        wrapMode: Text.WordWrap
        anchors.verticalCenterOffset: -123
        anchors.horizontalCenterOffset: 1
        anchors.centerIn: parent
    }
}


text:
Q: SQL Query with Typo not working in MySQL (Order by on calculated field) I have this query in which one of the column is a calculated one. Every thing is working except it is not ordering the results when I use that calculated column in query. The query is a very large one so I have simplified it below for understanding. Here the calculated column is "remaining"
SELECT t1.id, t1.name, t2.duration - datediff(now(), t1.posting_time) as "remaining"
  FROM table1 t1, table2 t2
 WHERE td.id = t1.timefield
 ORDER BY id, name, remaining DESC

Even if I remove this "remaining" from order by clause or use it with asc or desc, nothing happens and order stays the same.

A: The only time when 'remaining' alters the sort order is when the id and the name in two rows are the same.  Otherwise, it has no effect on the ordering.
You need to fix the typo of 'td.id' to 't2.id'.
You should learn the JOIN notation too:
SELECT t1.id, t1.name, t2.duration - datediff(now(), t1.posting_time) as "remaining"
  FROM table1 t1
  JOIN table2 t2 ON t2.id = t1.timefield
 ORDER BY id, name, remaining DESC

A: use a trick:
SELECT *
FROM (
  SELECT
    t1.id,
    t1.name,
    t2.duration - datediff(now() , t1.posting_time) as "remaining"
  FROM table1 t1, table2 t2
  WHERE t2.id = t1.timefield
  ) AS i
ORDER BY id, name, remaining DESC


text:
Q: In general, do 3rd-party laptop AC adapters / chargers work reliably? The AC adapters for my 2 dell laptops wore out very quickly.
One supplies power but won't charge the battery (it's about 3 years old, the other is a bit newer).
Both have worn through to the shielding around the notebook connector and look like they'll be unusable soon.
Checking user reviews of the replacement adapter on Dell's own website, it appears they usually fail this fast. Apparently Dell does this deliberately to make money (their adapters sell for about 10-15 times what they cost to make). Same with replacement batteries.
I can see there are plenty of much cheaper ($50, not $150) compatible AC adapters on eBay. Does anyone have experience with these? Naturally I'm nervous a crappy knock-off could fry my notebook, but has this ever actually happened to anyone recently? Has anyone had a good experience? Can anyone recommend a good online seller (who doesn't charge nonsensical shipping costs to Australia, preferably?)
.
Update:
For anyone who's interested, I eventually went ahead and bought one on eBay from China that was claimed to be a genuine original Dell. It's likely a factory second or very good counterfeit, but it looks genuine and worked fine - charged the battery etc - but only for a year. I've since bought 2 more on ebay because, while one of the three failed in the first year, it's still cheaper to buy 10 of these than to buy one from Dell (and the dell one, I now know, won't last either). Further details here: Dell 1720 laptop replacement battery and power adapter if anyone is interested.

A: I don't know what series of Dell notebooks you have but I have had bad experiences.  I've purchased a few 3rd party power supplies for Dell Latitude D series notebooks and they will not charge the battery.  A warning message appears that the power supply is not Dell approved and subsequently the battery will not be charged.

A: Sounds like you are pretty rough with your equipment.  For the most part, yes third party adapters will work fine with your equipment.  Even though they adapter manufacture says its for your model, you should closely check the voltage and amperage output of the adapter.  Voltage should match exactly and amperage needs to meet or exceed the OEM adapter.  Of course this does void any warranties, which probably isn't an issue with the age of the machine.
The usual difference between OEM and aftermarket adapters is that the after market adapters may not meet the required specs or provide clean power.  Dirty power leads to strange behavior of failed devices.
I guess it really comes down to, how long do you want to keep your notebook.  If it will be for a few years or more, go with an OEM.  If only for a year, try out the aftermarket.


text:
Q: Getting java.net.UnknownHostException: in retrofit When I try to access a URL with getting method getting,
D/OkHttp: <-- HTTP FAILED: java.net.UnknownHostException: Unable to resolve host "xyz.aaa.net": No address associated with hostname

But I am getting success response in POST MAN. Its been two days but not getting any clue.Changed the Actual URL to xyz.aaa.net due to autorization issue.Sorry for that :
Call<Response> call2 = apiInterface.getEmployeeListNew("1190",1008,"true"
                );
        call2.enqueue(new Callback<Response>() {
            @Override
            public void onResponse(Call<TaxProResponse> call, Response<Response> response) { }

            @Override
            public void onFailure(Call<TaxProResponse> call, Throwable t) {
                call.cancel();
            }
        });

API Client :
class APIClient {

    private static Retrofit retrofit = null;

    static Retrofit getClient() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        retrofit = new Retrofit.Builder()
                .baseUrl("http://xyz.aaa.net/api/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        return retrofit;
    }

}

APIInterface :
@GET("Profile")
Call<Response> getEmployeeListNew(
        @Header("app_id") String app_id,
        @Query("office_id") int office_id,
        @Query("need_only_active") String need_only_active
);

whole URL need to be like this with app_id as Header :
http://xyz.aaa.net/api/Profile?office_id=1008&need_only_active=true

If Any of you has faced this issue before please give some suggetion.
Tried with some other request,It working fine.Provide the permission,
 <uses-permission android:name="android.permission.INTERNET"/>

Its not issue of permission like other questions in Stackoverflow.Tried with there solutions and its not working.
As Asked here is Full Log
06-25 12:11:38.143 8450-8450/? I/zygote64: Late-enabling -Xcheck:jni
06-25 12:11:38.436 8450-8450/com.journaldev.retrofitintro D/NetworkSecurityConfig: No Network Security Config specified, using platform default
06-25 12:11:38.495 8450-8469/com.journaldev.retrofitintro D/OkHttp: --> GET http://xyz.aaa.net/api/AMTPProfile?office_id=1008&need_only_active=true http/1.1
    app_id: 1190
06-25 12:11:38.497 8450-8469/com.journaldev.retrofitintro D/OkHttp: --> END GET
06-25 12:11:38.516 8450-8471/com.journaldev.retrofitintro D/OpenGLRenderer: HWUI GL Pipeline
06-25 12:11:38.561 8450-8471/com.journaldev.retrofitintro I/Adreno: QUALCOMM build                   : 8e59954, I0be83d0d26
    Build Date                       : 09/22/17
    OpenGL ES Shader Compiler Version: EV031.21.02.00
    Local Branch                     : O17A
    Remote Branch                    :
    Remote Branch                    :
    Reconstruct Branch               :
06-25 12:11:38.564 8450-8471/com.journaldev.retrofitintro D/vndksupport: Loading /vendor/lib64/hw/gralloc.msm8994.so from current namespace instead of sphal namespace.
06-25 12:11:38.581 8450-8471/com.journaldev.retrofitintro I/Adreno: PFP: 0x00000000, ME: 0x00000000
06-25 12:11:38.598 8450-8471/com.journaldev.retrofitintro I/zygote64: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
06-25 12:11:38.602 8450-8471/com.journaldev.retrofitintro I/OpenGLRenderer: Initialized EGL, version 1.4
06-25 12:11:38.603 8450-8471/com.journaldev.retrofitintro D/OpenGLRenderer: Swap behavior 2
06-25 12:11:38.622 8450-8471/com.journaldev.retrofitintro D/vndksupport: Loading /vendor/lib64/hw/android.hardware.graphics.mapper@2.0-impl.so from current namespace instead of sphal namespace.
    Loading /vendor/lib64/hw/gralloc.msm8994.so from current namespace instead of sphal namespace.
06-25 12:11:41.808 8450-8469/com.journaldev.retrofitintro D/OkHttp: <-- HTTP FAILED: java.net.UnknownHostException: Unable to resolve host "xyz.aaa.net": No address associated with hostname

Thanks in Advance.

A: @Override
public void onRequestFailure(RetrofitError errorCode, String errorFrom) {
super.onRequestFailure(errorCode, errorFrom);
    try {
        throw (errorCode.getCause());

    } catch (UnknownHostException e)
    {

        DialogManager.showSingleBtnPopup(thisAcivity, new DialogMangerCallback() {
            @Override
            public void onOkClick() {
                // doLogout(" ");

                Intent i = new Intent(thisAcivity, MainActivity.class);
                startActivity(i);
            }

            @Override
            public void onCancelClick(View view) {

            }
        }, "Alert!", "Network error,  ", "Ok");

        // unknown host
    } catch (SSLHandshakeException e) {

        Intent intent1 = new Intent(this, MainActivity.class);
        startActivity(intent1);

        // ssl handshake exception
    } catch (Exception e) {

        Intent intent1 = new Intent(this, MainActivity.class);
        startActivity(intent1);

        // unknown error
    } catch (Throwable throwable) {
        throwable.printStackTrace();
        Intent intent1 = new Intent(this, MainActivity.class);
        startActivity(intent1);
    }

}


text:
Q: Importing data from csv to Mysql using Yii Framework I need to import data from CSV file into MySql database using YII Framework,
CSV files contains datas which should to imported to two tables in Mysql DB, Please provide any information to proceed.

A: try this
Importing CSV file to mysql table using "LOAD DATA" command

A: You can take a look at this extension:
www.yiiframework.com/extension/importcsv/


text:
Q: Determine pdf of a random process given a fixed parameter Given a random process $X(t) = Y \cos(\omega t)$, where $Y$ is a uniform RV on $[0,1]$, $t \geq 0$ and $\omega$ is a constant. Determine the pdf at $t = \frac{\pi}{2}$.
For any other given $t$ I could solve as usual for functions of a random variable:
$$f_X(x) = f_y(h(x)) \left | \frac{d h(x)}{dx} \right| $$
where $h(x)= g^{-1}(x) = \frac{x_t}{\cos(\omega t)}$, but I can't divide by $\cos(\frac{\pi}{2})$ for obvious reasons.
How do I proceed ?


text:
Q: Prove $\forall n \in\Bbb N$, $0 < a < 1$ $\implies$ $a^n \leq 1$ I'm trying to prove this by induction but I'm running into some trouble.
The base case is $0$, so,
$a^0 = 1$, the inequality holds true
Being new to induction, I don't exactly know what to do for the A and proving it in the inequality.
at this point, do I just prove $a^n \le 1$ implies $a^{n + 1}\le 1$?
I don't understand how the $0 < a < 1$ changes things.
Please help!

A: Lemma: If $0<a<1$ I claim for any $b>0$ that $0<ab<b$
Proof: $b(1-a)$ is a product of positive numbers hence is positive.
Corollary: $a^n<1\implies a^{n+1}<1$ when $0<a<1$
Proof: By induction, the base case being given, then let $b=a^n$ in the lemma.

Alternatively, a direct proof:
Write
$$a^n-1=(a-1)(a^{n-1}+a^{n-2}+\ldots +a+1)$$
Then as the latter element of the product is positive--since $a>0$ (note this means $a^n-1>0$ which is equivalent to $a^n>1$)--the whole thing is positive if $a>1$ and negative if $0<a<1$.

A: Yes, you want to show that given $a^n\le 1$, then $a^{n+1}\le 1$. Well since $a>0$, we know that
$a^{n+1}\le a$. But $a<1$. So we have $a^{n+1}\le a\le1$ as desired.
This proof would clearly not work if $a$ were not less than $1$.

A: $0 < a < 1 \ \Rightarrow \ 1 = a + x$ with $x > 0$. Thus,
$$
1 = 1^n = (a + x)^n = a^n + \sum_{k=0}^{n-1}{n \choose k}a^kx^{n-k} \geq a^n \quad \Rightarrow \quad a^n \leq 1
$$

A: Proof: by mathematical induction
Choose any positive real number a which is smaller than 1, then
0

Because of (1), we conclude that
   0

Good luck


text:
Q: Visio opens as READ Only from a List I have SharePoint 2013 Enterprise.  If I open a Visio Document from a Doc Library it is immediately available to edit.  If I open it from a List attachment ,it opens as Read Only.  The only way to edit the document is to Check In and Check Out the document.
Please let me know how a document can be immediately available for edit when I open it from a list.

A: I believe the difference between the 2 options is because 2 different functions are called.
When you click a title in a document library, it calls for its onclick:
return DispEx(this,event,'TRUE','FALSE','FALSE','SharePoint.OpenDocuments.3','1','SharePoint.OpenDocuments','','','','1','0','0','0x7fffffffffffffff')

and you get the windows 'Open Document' prompt that allows you to choose Read Only or Edit.
When you click an attachment for a list item, it calls
DispDocItemExWithServerRedirect(this, event, 'FALSE', 'FALSE', 'FALSE', 'SharePoint.OpenDocuments.3', '0', ''); return false;

which opens the .vsd file as read only.
I wonder if you could add a customization to your form to replace the attachment onclick event with the one used by the view?

A: The setting you want is in Visio, not in SharePoint. Visio will, by default, open documents in Protected View from potentially unsafe locations (that includes SharePoint, but doesn't include local or network drives).
In Visio 2013, the option is in File > Options > Trust Center > Trust Center Settings > Protected View. You'll want to uncheck the box that says Enable Protected View for files located in potentially unsafe locations. Depending on your network setup, the setting might be Enable Protected View for files originating from the Internet.

A: I was able to get the file to open properly (not READ Only) by going to File > Options > Trust Center > Trust Center Settings > Trusted Locations.  Then I selected the box for "Allow Trusted Locations on my network (not recommended)".  I did try to add the specific Sharepoint path and it was not allowed.


text:
Q: Chain function calls which return error codes or 0 on success in C I used to call functions which returns int error code or 0 on success like this:
int tmp = function_a() ?:
          function_b() ?:
          function_c();

if (tmp)
        handle_error();

Now I'm working on a project which -std=c90 -Wpedantic and I get:
warning: ISO C forbids omitting the middle term of a ?: expression [-Wpedantic]

Is there any good ISO C approach for this? I want to avoid this:
int tmp;

tmp = function_a();

if (tmp)
        handle_error();

tmp = function_b();

if (tmp)
        handle_error();

And this:
int tmp;

if ((tmp = function_a()))
       handle_error();

And mangling code with #define macros.

A: While you could use a temporary variable to save the result, you'd end up with something like:
int tmp;
tmp = (tmp = function_a()) ? tmp : ((tmp = function_b()) ? tmp : function_c());

Needless to say, don't do this.  It is the equivalent of your old code, but is far less elegant.  Even if it is more verbose, you should simply go with the more readable solution:
int tmp;
if(tmp = function_a()) {
    handle_error(tmp);
} else if (tmp = function_b()) {
    handle_error(tmp);
} else if (tmp = function_c()) {
    handle_error(tmp);
}

You could also write it like this, which perhaps would be a little more straightforward:
int tmp;
if((tmp = function_a()) || (tmp = function_b()) || (tmp = function_c())) {
    handle_error(tmp);
}


text:
Q: How get the address(location) of the VMT table of a EXE generated by delphi i need to enumerate the classes used in a external application written in delphi
, so i need access to the VMT table to get that information, but i can't find any documentation about how find the location (address) of the VMT (virtual-method table) in a exe (generated by delphi) file.

A: Please note that there is a difference in runtime type info and only a VMT. If you need type information (like names of methods and types) that is RTTI and not a VMT; a VMT if you can reach it (you can via a type via the RTTI of a class type see below)will contain a list of pointers to methods and no method mnames, parameter information etc etc. Delphi does not create information like IDispatch  for each and every class/interface..
Up to Delphi 2007 you do not have a list of all types, later versions are probably the same but I am not sure. If you have a map file you can get some data from that or you can use some heuristics to search through the file: types in Delphi are always prepended with a pointer to self (eg e PPTypeInfo pointing to the PTypeInfo). Since a PTypeinfo also has a specific format you can detect these quite easily with a scan through the executable.
Once a PTypeInfo is found you can parse the data that follows yielding the typename and following that you have the TypeData. For class types here you can find a poiter to the class which contains the VMT at possitive offsets. Types containing published methods / properties will have those after the type data. You can find all details of the structures in the unit TypInfo.
You will never find all addresses of all methods except in a map file; only methods with RTTI (eg are published) have an address with a name. Only a selected set of types have RTTI (later Delphi's have new RTTI information but I do not know their construct in a module).
Good luck.

A: There is not one single VMT in an .exe file. Each class has its own VMT. There is, AFAICT, no reliable way to enumerate the classes in an executable. I assume the executable is only a file. The only way to do that is to analyze how such data is stored in an .exe file.
But even if the .exe is running, and you have access to one of the objects, you can merely find the VMT of the class of that object (at offset 0 of the object). This will also give you access to the base classes of the class, but that is about it.

A: Yes it's possible to some extent!
To depict it, what you need is a kind of Class browser for EXE file similar to the way the IDE does with pascal unit.

*

*Interactive Delphi Reconstructor is one the best advanced application of the concept.

*DeDe 3.50.02 Build 1619 too (with Source code included?).
The source code of Revendepro illustrate the way to tackle it.
Excerpts from http://www.ggoossen.net/revendepro/findingClasses.html (seems to be a dead link now):

  I := Code - vmtSelfPtr;
  while I < Code + CodeSize do
  begin
    // vmtSelfPtr must point to itself.
    if PPChar(I + vmtSelfPtr)^ = I then
    begin
        if PPChar(I + vmtParent)^ = nil then
        try
          // If no classParent then class can be object
          if (not UsePackages) and (TClass(I).ClassName = 'TObject') then
            // if class if object add it to classes.
            Add(TClass(I))
        except
          on EAccessViolation do
        end
        else
          // className must be in the code section.
          // classParent must be in the code section or the import section (when it is imported).
          if (PPChar(I + vmtClassName)^ <= Code + CodeSize) and
             (PPChar(I + vmtClassName)^ >= Code) and
             (((PPChar(I + vmtParent)^ <= Code + CodeSize) and
               (PPChar(I + vmtParent)^ >= Code)) or
              ((PPChar(I + vmtParent)^ <= ImportStart + ImportSize) and
               (PPChar(I + vmtParent)^ >= ImportStart))) then
          // Add possible class to possible class list.
          PossClasses.Add(I);
    end;
    Inc(I, 4);
  end;
   // Can't be more then 1 TObject.
  if (not TPEFileClass(PEFileClass).UsePackages) and (Count > 1) then
    raise EDecompilerError.Create('There can only be one TObject.');

  // If no classParent then class can be object
  if TClass(I).ClassName = 'TObject' then
    Add(TClass(I)) // if class if object add it to classes.

    // Add Classes to the list which parent is in the list.
  repeat
    Added := False;
    for J := PossClasses.Count -1 downto 0 do
    begin
      // Try to find parent class in classList
      if FindClass(TClass(PossClasses[J]).ClassParent) <> nil then
      begin
        // Class in class list
        Add(PossClasses[J]);
        PossClasses.Delete(J);
        Added := True;
      end;
      // Try to find parent class in a other package.
      for K := 0 to High(PEFiles) do
        if PEFiles[K].Classes.FindClass(TClass(PossClasses[J]).ClassParent) <> nil then
        begin
          // Class in class list
          Add(PossClasses[J]);
          PossClasses.Delete(J);
          Added := True;
          Break;
        end;
    end;
  until not Added;

Disclaimer: I never tested these codes.


text:
Q: How to link D3 zoom and pan controls I would like to link the zoom and pan controls of multiple charts together so they all pan and zoom together when one of the charts pan and zoom controls are engaged.
I tried creating a single zoom object and passing it to the charts, but only the last chart actually pan and zoomed.   The others remained static even though I was zooming in their areas.
Here's a snapshot of the charts.  Each chart has an overview chart with a viewport that can be moved as well.  I would like to link all the controls together so the viewports are also the same on each chart.
So, how can I link the pan and zoom controls on multiple charts?
Here is a jsfiddle for this code: https://jsfiddle.net/babazaroni/a52oukzn/

Here is my code:
The overall chart creator.  This code makes 3 charts.

define([
    'd3',
    'components/sl',
    'MockData',
    'components/candlestickSeries',
    'Chart'
], function (d3, sl, MockData,candlestickSeries,Chart) {
    'use strict';

    function generateData()
    {

      var data = new MockData(0.1, 0.1, 100, 50, function (moment) {
        return !(moment.day() === 0 || moment.day() === 6);
      })
      .generateOHLC(new Date(2014, 1, 1), new Date(2014, 8, 1));

      return data;
    }

    var data = generateData();

   d3.select('#chart1')
       .datum(data)
     .call(Chart());

     data = generateData();

    d3.select('#chart1')
        .datum(data)
      .call(Chart());

         data = generateData();

          d3.select('#chart1')
        .datum(data)
      .call(Chart());

});

Here is the chart code:

define([
    'd3',
    'components/sl',
    'MockData',
    'components/candlestickSeries'
], function (d3, sl, MockData) {
    'use strict';

    function timeSeriesChart() {

        function chart(selection)
        {
            selection.each(function(data) {

                var minDate = new Date(d3.min(data, function (d) { return d.date; }).getTime() - 8.64e7);
                var maxDate = new Date(d3.max(data, function (d) { return d.date; }).getTime() + 8.64e7);
                var yMin = d3.min(data, function (d) { return d.low; });
                var yMax = d3.max(data, function (d) { return d.high; });

                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // The primary chart

                // Set up the drawing area

                var margin = {top: 20, right: 20, bottom: 30, left: 35},
                    width = 600 - margin.left - margin.right,
                    height = 200 - margin.top - margin.bottom;

                var plotChart = d3.select(this).classed('chart', true).append('svg')
                    .attr('width', width + margin.left + margin.right)
                    .attr('height', height + margin.top + margin.bottom)
                    .append('g')
                    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

                var plotArea = plotChart.append('g')
                    .attr('clip-path', 'url(#plotAreaClip)');

                plotArea.append('clipPath')
                    .attr('id', 'plotAreaClip')
                    .append('rect')
                    .attr({ width: width, height: height });

                // Scales

                var xScale = d3.time.scale(),
                    yScale = d3.scale.linear();

                // Set scale domains
                xScale.domain([minDate, maxDate]);
                yScale.domain([yMin, yMax]).nice();

                // Set scale ranges
                xScale.range([0, width]);
                yScale.range([height, 0]);

                // Axes

                var xAxis = d3.svg.axis()
                    .scale(xScale)
                    .orient('bottom')
                    .ticks(10);

                var yAxis = d3.svg.axis()
                    .scale(yScale)
                    .orient('left');

                plotChart.append('g')
                    .attr('class', 'x axis')
                    .attr('transform', 'translate(0,' + height + ')')
                    .call(xAxis);

                plotChart.append('g')
                    .attr('class', 'y axis')
                    .call(yAxis);

                plotChart.append("text")
                    .attr("x", (width / 2))
                    .attr("y", 1 - (margin.top / 2))
                    .attr("text-anchor", "middle")
                    .style("font-size", "16px")
                    .style("text-decoration", "underline")
                    .text("Your title goes here");

                // Data series

                var series = sl.series.candlestick()
                    .xScale(xScale)
                    .yScale(yScale);

                var dataSeries = plotArea.append('g')
                    .attr('class', 'series')
                    .datum(data)
                    .call(series);

                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // Navigation chart

                var navWidth = width,
                    navHeight = 100 - margin.top - margin.bottom;

                // Set up the drawing area

                var navChart = d3.select(this).classed('chart', true).append('svg')
                    .classed('navigator', true)
                    .attr('width', navWidth + margin.left + margin.right)
                    .attr('height', navHeight + margin.top + margin.bottom)
                    .append('g')
                    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

                // Scales

                var navXScale = d3.time.scale()
                        .domain([
                            new Date(minDate.getTime() - 8.64e7),
                            new Date(maxDate.getTime() + 8.64e7)
                        ])
                        .range([0, navWidth]),
                    navYScale = d3.scale.linear()
                        .domain([yMin, yMax])
                        .range([navHeight, 0]);

                // Axes

                var navXAxis = d3.svg.axis()
                    .scale(navXScale)
                    .orient('bottom');

                navChart.append('g')
                    .attr('class', 'x axis')
                    .attr('transform', 'translate(0,' + navHeight + ')')
                    .call(navXAxis);

                // Data series

                var navData = d3.svg.area()
                    .x(function (d) { return navXScale(d.date); })
                    .y0(navHeight)
                    .y1(function (d) { return navYScale(d.close); });

                var navLine = d3.svg.line()
                    .x(function (d) { return navXScale(d.date); })
                    .y(function (d) { return navYScale(d.close); });

                navChart.append('path')
                    .attr('class', 'data')
                    .attr('d', navData(data));

                navChart.append('path')
                    .attr('class', 'line')
                    .attr('d', navLine(data));

                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // Viewport

                function redrawChart() {

                    dataSeries.call(series);
                    plotChart.select('.x.axis').call(xAxis);
                }

                function updateZoomFromChart() {

                    var fullDomain = maxDate - minDate,
                        currentDomain = xScale.domain()[1] - xScale.domain()[0];

                    var minScale = currentDomain / fullDomain,
                        maxScale = minScale * 20;

                    zoom.x(xScale)
                        .scaleExtent([minScale, maxScale]);
                }

                var viewport = d3.svg.brush()
                    .x(navXScale)
                    .on("brush", function () {
                        xScale.domain(viewport.empty() ? navXScale.domain() : viewport.extent());
                        redrawChart();
                    })
                    .on("brushend", function () {
                        updateZoomFromChart();
                    });

                navChart.append("g")
                    .attr("class", "viewport")
                    .call(viewport)
                    .selectAll("rect")
                    .attr("height", navHeight);

                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // Zooming and panning

                function updateViewpointFromChart() {

                    if ((xScale.domain()[0] <= minDate) && (xScale.domain()[1] >= maxDate)) {

                        viewport.clear();
                    }
                    else {

                        viewport.extent(xScale.domain());
                    }

                    navChart.select('.viewport').call(viewport);
                }

                var zoom = d3.behavior.zoom()
                    .x(xScale)
                    .on('zoom', function() {
                        if (xScale.domain()[0] < minDate) {
                            zoom.translate([zoom.translate()[0] - xScale(minDate) + xScale.range()[0], 0]);
                        } else if (xScale.domain()[1] > maxDate) {
                            zoom.translate([zoom.translate()[0] - xScale(maxDate) + xScale.range()[1], 0]);
                        }
                        redrawChart();
                        updateViewpointFromChart();
                    });

                var overlay = d3.svg.area()
                    .x(function (d) { return xScale(d.date); })
                    .y0(0)
                    .y1(height);

                plotArea.append('path')
                    .attr('class', 'overlay')
                    .attr('d', overlay(data))
                .call(zoom);

                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // Setup

                var daysShown = 30;

                xScale.domain([
                    data[data.length - daysShown - 1].date,
                    data[data.length - 1].date
                ]);

                redrawChart();

                updateViewpointFromChart();

                updateZoomFromChart();

                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // Helper methods

            });

        }
 //      alert("here we are again and again");
        return chart;
    }
    return timeSeriesChart;
});

A: From this example : http://bl.ocks.org/mbostock/6123708
Create the zoom:
var zoom = d3.behavior.zoom()
    .scaleExtent([1, 10])
    .on("zoom", zoomed);

function zoomed() {
  container.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}

Call zoom on your container :
var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.right + ")")
    .call(zoom); //<<<<<HERE

That is what it will look like on a single canvas, but in your case it will look something like this :
Create the zoom:
var zoom = d3.behavior.zoom()
    .scaleExtent([1, 10])
    .on("zoom", zoomed);

transform each of your canvas's/containers
    function zoomed() {
      container1.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
container2.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
container3.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
    }

Call zoom on all of your containers :
    var svg1 = d3.select("body").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.right + ")")
        .call(zoom); //<<<<<HERE

var svg2 = d3.select("body").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.right + ")")
        .call(zoom); //<<<<<HERE

var svg3 = d3.select("body").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.right + ")")
        .call(zoom); //<<<<<HERE

Something along those lines should work but can't test it without any example.


text:
Q: OpenVPN --auth-user-pass FILE option on Windows If you try to pass the username/password to OpenVPN from a file via the --auth-user-pass switch, you get the following error:
"Sorry, 'Auth' password cannot be read from a file."

At least they're polite.
So our workaround was to programmatically write to "standard in" when we get the Auth Username: and Auth Password: prompts (this is in C#).
Something with the timing isn't 100% reliable, so I was looking for a way to pass the credentials to OpenVPN in a different way and came across this post: OpenVPN Post
It says you can recompile the source with a --enable-password-save option.  Has anyone been able to do this?
My final question is: How can I pass an auth username/password to openvpn.exe on the client side?  And does OpenVPNGUI somehow do this (maybe we can copy what they do)?

A: NOTE! param auth-user-pass not work if start by GUI "C:\Program Files\OpenVPN\config\name.ovpn"
Made start file start_openvpv.cmd (+ link to with "run as admin") with content:
cd C:\Users\Name\Documents\VPN
"C:\Program Files\OpenVPN\bin\openvpn.exe" --config C:\Users\Name\Documents\VPN\myvpnconfig.ovpn --auth-user-pass "C:\Users\Name\Documents\VPN\pass.txt"

pass.txt:
yourusername
yourpassword

OR put line to name.ovpn, as in upper messege:
auth-user-pass pass.txt

+start_openvpv.cmd:
cd C:\Users\Name\Documents\VPN
"C:\Program Files\OpenVPN\bin\openvpn.exe" --config C:\Users\Name\Documents\VPN\myvpnconfig.ovpn

A: It's possible to open a VPN connection via a script by using the following DOS command (however this is not recommended since the password is not encrypted)
$openvpn.exe config.ovpn < username < password

A: It turns out the problem wasn't with standard in.
I was using some locking where if the process exited in the middle of writing to standard in, there could be a deadlock.
There is no issue sending the password in this manner.

A: For automatic authentication to Openvpn you have to modify the config.ovpn file.
-Go to OpenVPN\config directory and edit the .ovpn file
-Add this line to the config file -> auth-user-pass password.txt
-Then create the password.txt file and write in it:
yourusername
yourpassword

-After these steps your openvpn will connect automatically.


text:
Q: When I run gem install *some gem name* where does it install? As the question states - where does the gem install?
Is it installing within the app directory that I'm working in (i.e. user/sites/sample_app)? Or is it being installed on my computer? If the latter where exactly?
Thanks!

A: gem install process
first download gem and save desktop
1.next step open command prompt and set location that means c:/desktop> gem install  --local "gemname"
2.next step com to rails consoler and type $bundle install --local.
3. type the gem name on gem list

A: I have two questions:
Where do you install your ruby?
Did you use RVM or rbenv?
Now I will explain your question using my situation as an example.
I use RVM to manage rubies on my mac os.
now the ruby install in path
/Users/pin/.rvm/rubies/ruby-2.1.1

and these will be a gems directory under .rvm path. In this directory,
/Users/pin/.rvm/gems

there are many gems group, I have a group named
ruby-2.1.1@global

which is used by the default ruby version.
This is a directory and there will be a gems directory under it.
/Users/pin/.rvm/gems/ruby-2.1.0/gems

In this directory, you will find all of the gems you installed using cmd
bundle install

If you don't use ruby version management tools like rvm or rbenv, you may find the gems
around your ruby path. If you still can't find them, you can post the details of how you
install the rubies and other system configs, so that we can discuss here.

A: If you are using rvm then its get installed in
/home/user/.rvm/gems/ruby-version@global/ or /home/user/.rvm/gems/ruby-version/

If you are using specific gemset for gems then
/home/user/.rvm/gems/ruby-version@gemset_name/

A: Gems
If you use gem install x, you're adding the gem to the local ruby version on your system. This is a system-wide installation, and will be stored in your rubylib/ruby/gems dir:

The install command downloads and installs the gem and any necessary
  dependencies then builds documentation for the installed gems.

Bundler
Using the bundle install command (when you have a Gemfile & use bundler), you basically tell bundler to install the gems relative to your specific applicaiton:

Bundler makes sure that Ruby can find all of the gems in the Gemfile
  (and all of their dependencies). If your app is a Rails 3 app, your
  default application already has the code necessary to invoke bundler.
  If it is a Rails 2.3 app, please see Setting up Bundler in Rails 2.3.

For example, if you have a Rails 3.2 app, and a Rails 4.1 app on your system, using bundler allows you to instal the dependencies (gems) for each app independently
If you use gem install x, it will install the gem for all  applications, and should only be used for things like rmagick and the database connection gems

A: If you want to know where gem is installed use gem which *gem_name* e.g.:
gem which rails

If you installed your gems with bundle install use bundle show *gem name* e.g.:
bundle show rails


text:
Q: Unable to connect to denodo via jdbc driver to mavenized mule application I'm trying to establish a connection with denodo using JDBC driver to mulesoft which is a maven based application.
Mule runtime: 3.8.6
Denodo version: Denodo 7.0 update-20181011
JDBC Jar used: denodo-vdp-jdbcdriver-7.0-update-20181011.jar
Maven dependency:
<dependency>
<groupId>com.denodo</groupId>
<artifactId>denodo-vdp-jdbcdriver</artifactId>
<version>7.0</version>
</dependency>

I'm using a generic database configuration to establish connection. I'm able to maven install the jar file and add maven dependency to pom file but when I try to lead driver classes available for denodo, I'm unable to find the right driver class. The classes I see are
com.denodo.util.security
com.denodo.util.logging
But I'm looking for this class. com.denodo.vdp.jdbc.Driver
Please help.

A: It got resolved with anypoint studio restart and reimport of jar file. For others who might stumble on this question I'm listing the steps I followed to connect denodo to mulesoft via JDBC driver.
1) Downloaded Jar file from denodo site. denodo-vdp-jdbcdriver-7.0-update-20181011.jar
2) My mule project is mavenized, So, I had to install drivers using maven install command as follows. Install while you are on the project path on terminal. Make sure the path to denodo jar file is correct.
mvn install:install-file -Dfile=/Documents/denodo-vdp-jdbcdriver-7.0-update-20181011.jar -DgroupId=com.denodo -DartifactId=denodo-vdp-jdbcdriver -Dversion=7.0 -Dpackaging=jar
3) Right-click on the project in any point studio and manually add maven dependency to the project. This should add denodo dependency to pom.xml. At this point, you should be able to see 'com.denodo.vdp.jdbc.Driver listed under referenced libraries in the project.
4) Now, I chose to have a config file in global.xml. Add generic database configuration and fill in 'com.denodo.vdp.jdbc.Driver' where driver class is required.
5) DB URL should be in the format jdbc:vdb://denodo-host:port/database?user=test&password=test
6) with proper permissions to the server and right user name and password, you would be able to connect.

A: The other answer really helped me. Here are the steps I took to connect to a Denodo 8.0 instance:

*

*Download latest driver jar file ('denodo-vdp-jdbcdriver-8.0-update-20210209') from https://community.denodo.com/drivers/jdbc/34
(the driver version and Denodo instance version need to match).

*Add the Driver to your Mule Project.
In your Mule flow, add a database operation (e.g. Select). Under Basic Settings, click to add a Connector configuration. From the Connection dropdown, choose 'Generic Connection'.
In the General / Required Libraries section, choose Configure -> Use Local File. In the 'Choose local file' dialog, browse to your downloaded driver jar.
Add the Group Id, Artifact ID as below:
<dependency>
    <groupId>com.denodo</groupId>
    <artifactId>denodo-vdp-jdbcdriver-8.0-update-20210209</artifactId>
    <version>8.0</version>
</dependency>

*Configure connection properties

*

*url: jdbc:vdb://denodo-host:port/database (you can use jdbc:denodo with this driver version)

*driver: com.denodo.vdp.jdbc.Driver

Troubleshooting:

*

*You should see the denodo dependency in pom.xml. You should also be able to see the jar file listed under 'Project Libraries' in the project.

*If you get SSL handshake errors, try adding ?ssl=true&sslTrustServerCertificate=true to the url.


text:
Q: Script, input with addClass and link.attr so I'm trying to wrap my head around this script.
I'm not the best with JavaScript and jQuery yet, but I'm trying to learn.
<script>
  var link = $("#to-toggle");
  $("#toggle").on("change", function() {
    if (this.checked) {
      .addClass("active");
      link.attr("href", link.data("href"));
    } else {
      .removeClass("active");
      link.removeAttr("href");
    }
  });
</script>

Before I added the .addClass and .removeClass it worked fine, but I can't seem to be able to get a class to toggle as well, when my check box is checked/unchecked.
Any help is greatly appreciated.

A: You forgot where to add and remove the class to/from ---> link:
if(this.checked) {
    link.addClass("active");
    link.attr("href", link.data("href"));
} else {
    link.removeClass("active");
    link.removeAttr("href");
}
});

A: Assuming  #toggle to be your checbox Id and you are trying to add and remove class to this checbox, replace your line
   .addClass("active");
By
   $(this).addClass("active");
Similarly replace
      .removeClass("active");
By
$(this).removeClass("active");
I am on mobile, excuse me for format issues.

A: if(this.checked) {
    $(this).addClass("active");
    link.attr("href", link.data("href"));
} else {
    $(this).removeClass("active");
    link.removeAttr("href");
}
});


text:
Q: Spacemacs: "No such file or directory, Racket.exe" I'm running Windows 10, and I'm trying to get Racket working on spacemacs. I've added it to my .spacemacs file, so racket-mode starts just fine, but whenever I try to evaluate an expression using SPC m s e I get Searching for program: No such file or directory, Racket.exe.
I've added Racket.exe to my PATH variable, but it doesn't seem to do anything. I've seen something about geiser, but according to this I don't need that to make Racket work.

A: I met the same problem at Emacs, and then I changed the configuration code into
(require 'racket-mode)
(setq racket-racket-program "C:/Program Files/Racket/racket.exe")
(setq racket-raco-program "C:/Program Files/Racket/raco.exe")

Change the program path to an absolute path.
Then the error disappears.
I hope useful to you.


text:
Q: Assigning variable value as table column name if request.POST['table'] == 'a':
   get_table = A_table()
   get_column = 'a'
elif request.POST['table'] == 'b':
   get_table = B_table()
   get_column = 'b'

get_table. + get_column + _column = 'some text'

The sample code above is just an idea which of course won't work.
How do I assign a variable value as table column name in django?
this will be used in a separate function for dynamic filtering..
a simpler example would be:
tablename.+'col'+name = 'test data'

tried using exec() and it worked according to my needs but some suggested that it is a bad way of initiating a code, any replacement for it?


text:
Q: Display Zero Count in MySQL query i have a table in my database named subscriber which contains two rows one for the subscriber id and another one for points earned by each subscriber .
My Select query :
SELECT 1000 * ( LOYALTY_POINTS DIV 1000 ) AS  'from', 1000 * ( LOYALTY_POINTS DIV 1000 ) +1000 AS  'to', COUNT( * ) AS NUMBER FROM SUBSCRIBER GROUP BY LOYALTY_POINTS DIV 1000

should return for each range of points the number of subscribers but unfortunately it only returns the number of subscribers different than zero.
My result is:
from   to            NUMBER
0          1000     8
1000  2000     2
3000  4000     1

I want the query to return records with zero coun also.
The result should be:
from   to            NUMBER
0          1000     8
1000  2000     2
2000  3000     0
3000  4000     1

How to do it? Thank you in advance.

A: You need to generate some numbers to indicate your range
 SELECT 0 as RangeStart UNION Select 1000 UNION Select 2000 UNION Select 3000

and LEFT JOIN this to your results.
SELECT
    RangeStart, RangeStart + 999 as RangeEnd, RangeCount
FROM
    (SELECT 0 as RangeStart UNION Select 1000 UNION Select 2000 UNION Select 3000) range
         LEFT JOIN
    (Select LoyaltyPoints DIV 1000 as loyaltypoints, count(*) as RangeCount group by LoyaltyPoints DIV 1000 ) counts
    ON range.rangestart = counts.loyaltypoints


text:
Q: Alpha animation not working Pretty simple: I add a dynamic button on screen and I try to fade it out after adding, but the animation never plays. I tried adding it later when it is already rendered on the screen, but still nothing. Below is the code:
btn = new ImageButton(context);
btn.setBackgroundColor(0xFFFF0000);

params = new WindowManager.LayoutParams(
    width,height,
    WindowManager.LayoutParams.TYPE_SYSTEM_ALERT |
    WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
    WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
    PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;

windowManager.addView(btn, params);

btn.startAnimation(new AlphaAnimation(1,0));

Any ideas?

A: Try this:
btn.setAlpha(0f);
btn.animate().alpha(1).setDuration(1000);

A: This answer may explain why you're getting such strange behavior if you've set the alpha to 0 in xml.


text:
Q: Prove that a polynomial ring over R in infinitely many variables is non-Noetherian. I am struggling with understanding this proof. I am confused as to why they took $a_{n+1}$ and how they got $a_{n+1}= b_1a_1+...+ b_na_n$, $a_1 = ... = a_0 = 0,$ and $a_{n+1} = 1$ gives $1 = 0$ in $\mathbb{R}$. Please help with explaining the steps of this proof in more detail. I am also not sure how to tie in that the ideals are infinitely generated and a proper susbset of each other.
Let $S = \mathbb{R}[a_0,a_1,a_2...]$ be a polynomial ring over R in infinitely many variables. Prove $S$ is non-Noetherian.
Proof: We want to show that S in non-Noetherian.Take the infinite chain of ideals: $<a_0>\subset<a_0, a_1>\subset...\subset<a_0,...,a_n>\subset ...$. Suppose that for any $n, a_{n+1}$ were an element of $<a_1,...,a_n>$. In other words, there exist polynomials $b_1,...,b_n$ such that $a_{n+1} = b_1a_1+...+ b_na_n$. Setting $a_1 = ... = a_0 = 0,$ but $a_{n+1} = 1$ gives $1 = 0$ in $\mathbb{R}$, a contradiction. So, S is non-noetherian.

A: If $S=\mathbb{R}[a_0,a_1,\dots]$ were Noetherian then any chain of ideals $$I_0\subset I_1\subset\dots$$ would stabilize, that is, for some $n$ we would have $$I_n=I_{n+1}=I_{n+2}=\dots$$ To prove that $S$ is not Noetherian, we first assume that it is, and then see if we get a contradiction.
First we need a chain of ideals, so let's look at the chain: $$(a_0)\subset(a_0,a_1)\subset (a_0,a_1,a_2)\subset\dots$$
If we assume that $S$ is Noetherian, then this chain eventually stabilizes, so we would have, for some $n$, that $$(a_0,a_1,\dots,a_n)=(a_0,a_1,\dots,a_n,a_{n+1})$$
This would mean, in particular, that $a_{n+1}\in (a_0,a_1,\dots,a_n)$ so it should be possible to write $$a_{n+1}=\sum_{i=0}^{n}b_ia_i$$ Now, every polynomial ring has an evaluation homomorphism (this is what first confused me, but was clearified by @Leon Hendrian) that maps each $a_i$ to some element in the ring. (For instance, the evaluation homomorphism for $R[x]$, $R$ is any ring, is $\phi_a:R[x]\rightarrow R$, such that $f(x)\mapsto f(a)$, for some $a\in R$).
Using this homomorphism we can evaluate $a_{n+1}=\sum_{i=0}^nb_ia_i$ at $a_0=a_1=a_2=\dots =a_n=0$ and $a_{n+1}=1$. This gives $1=0$ which is a contradiction. Therefore $(a_0,a_1,\dots,a_n)\neq (a_0,a_1,\dots,a_n,a_{n+1})$ and so $S$ is not Noetherian.

A: When you write $a_n+1$, I assume that you mean $a_{n+1}$. Actually, this might already solve your confusion.
The logic of the proof you wrote is as follows: Assume $<a_0, \ldots, a_n> = <a_0, \ldots, a_{n+1}>$. This means that $a_{n+1} \in <a_0, \ldots, a_n>$, which means that $a_{n+1}=\sum_{i=0}^n b_ia_i$. But then, evaluate both sides on $a_0=\ldots=a_n=0, a_{n+1}=1$ to get the contradiction.


text:
Q: Evaluate $∫ydx+zdy+xdz$ where C is intersection of $x+z=a$ and $x^2+y^2+z^2=a^2$
Evaluate $∫ydx+zdy+xdz$ where C is intersection of $x+z=a$ and $x^2+y^2+z^2=a^2$

I am using Stoke's Theorem to find the integral. I could solve the first half

$\operatorname{curl}\text{ }F = -\hat{\textbf{i}} -\hat{\textbf{j}} -\hat{\textbf{k}}$

Normal Vector N = $\frac{\hat{\textbf{i}}+\hat{\textbf{k}}}{\sqrt2}$

Ultimately I end up with having to find surface integral of $ds$. How do I proceed?

A: It's been a while since I've done stokes theorem, so apologies if I make any error or whatnot.
The boundary curve is given by
we can choose any surface that has this boundary. I'll go for the plane since it is most simple where $z=a-x$ with restrictions on the ellipse boundary.
You calculated the curl to be $\langle -1, -1, -1\rangle$ and the normal vector denotes positive orientation so we are good.
Thus we have $$\int_C\overrightarrow{\textbf{F}}\cdot\text{ d}\overrightarrow{\textbf{r}}=\iint_S\operatorname{curl }\overrightarrow{\textbf{F}}\cdot\text{ d}\overrightarrow{\textbf{S}}=\iint_D\langle -1, -1, -1\rangle\cdot\nabla f\text{ d}A$$
where $D$ is the 2D shadow of the ellipse boundary on the $x-y$ plane and $$\nabla f=\nabla\left(z-a+x\right)=\langle 1, 0, 1 \rangle$$

Now we have $$\iint_D\langle -1, -1, -1\rangle\cdot\langle 1, 0, 1 \rangle\text{ d}A=-2\iint_D\text{ d}A$$
We just need to calculate the area of the ellipse given by the equation $$\frac{x^{2}}{\left(\frac{a}{2}\right)^{2}}+\frac{y^{2}}{\left(\frac{a}{\sqrt{2}}\right)^{2}}\le1$$ so this is just $$\pi\cdot \frac{a}{2}\cdot \frac{a}{\sqrt{2}}$$
So if I havent made a mistake the answer should just be $$-2\cdot\frac{a^2\pi}{2\sqrt2}=-\frac{a^2\pi}{\sqrt2}$$


text:
Q: Worker service with parallel task queue, performance I'm trying to create an worker service that polls database every few seconds for emails. Emails are passed to a priorityQueue and from there sent via Rest API to external provider. I would like to also implement some kind of limit on number of threads used by queue.
So here is my ExecuteAsync from BackGroundService:
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {/*Poll email database*/
            var emails = await _emailRepository.GetEmailsToSend();

            foreach (var email in emails) /*Queue downloaded emails*/
                _queue.QueueEmail(email);

            await Task.Delay(_emailOptions.PollTime, stoppingToken);
        }
    }

And here is my BackgroundEmailQueue to which emails are given:
public class BackgroundEmailQueue : IBackgroundEmailQueue
{
    private readonly ILogger<BackgroundEmailQueue> logger;
    private readonly ConcurrentPriorityQueue<EmailToSend> queue;
    private readonly SemaphoreSlim signal;

    private event Action EmailQued;

    public BackgroundEmailQueue(ILogger<BackgroundEmailQueue> logger)
    {
        this.queue = new ConcurrentPriorityQueue<EmailToSend>();
        this.signal = new SemaphoreSlim(5, 5);
        this.EmailQued += OnEmailQued;

        this.logger = logger;
    }

    public void QueueEmail(EmailToSend email)
    {
        if (email == null)
            return;

        queue.Add(email);

        EmailQued.Invoke();
    }

    private async void OnEmailQued()
    {
        await signal.WaitAsync();

        var email = queue.Take();

        await Task.Run(async () => { .... /*sending email*/ } );

        signal.Release();
    }

}

This solution works as intended
My problem is:
Was using the event to fire new thread good solution?
Is there a better way to do this?


text:
Q: Ruby - Access Response Headers for Rate Limiting (Help Scout) I'm using the helpscout ruby gem and trying to check when request limit is under a certain number (i.e 2 requests remaining) and sleep the loop for the remaining interval to allow for rate limit to be reset.
Is there a way to access the response headers from an API when making a request?
https://developer.helpscout.com/help-desk-api/#basic-rate-limiting
X-RateLimit-Interval-*  Length of the rate limiting interval in seconds

X-RateLimit-Limit-* Maximum number of requests per interval

X-RateLimit-Remaining-* Number of requests remaining in the current rate limit interval

Intercom (https://developers.intercom.com/reference#rate-limiting) allows your to check the rate_limit_details and returns the headers, but I can't find anything for Help Scout or understand how to access them.
intercom.rate_limit_details
#=> {:limit=>180, :remaining=>179, :reset_at=>2014-10-07 14:58:00 +0100}

A: The issue is the helpscout gem doesn't capture that info. If you look at the source code
https://github.com/hramos/helpscout/blob/db8da936853c8df694186ab11100d4482f74d302/lib/helpscout/models.rb#L44
  # Error Envelope
  class ErrorEnvelope
    attr_reader :status, :message

    # Creates a new ErrorEnvelope object from a Hash of attributes
    def initialize(object)
      @status = object["status"]
      @message = object["message"]
    end
  end

When an error occurs they only capture status and message. You can enhance the class below if you want to capture additional header values
  # Error Envelope
  class ErrorEnvelope
    attr_reader :status, :message, :limit

    # Creates a new ErrorEnvelope object from a Hash of attributes
    def initialize(object)
      @status = object["status"]
      @message = object["message"]
      @limit = object["header"]["X-RateLimit-...."]
    end
  end

But this would only tell you limits when you get an error. You can enhance the library further to capture these limits on every call. You will need to modify the client.rb
https://github.com/hramos/helpscout/blob/2449bc2604667edfca5ed934c8e61cd129b17af5/lib/helpscout/client.rb
module HelpScout
  class Client
    include HTTParty
    @@last_headers

    def self.get(*more)
        response = HTTParty.get(*more)
        @@last_headers = response.headers
        return response
    end

    def self.last_headers
        @@last_headers
    end

    ....
    ....
 end

So doing HelpScout.last_headers will give you the headers from last response and then you can capture whichever field you need from the same


text:
Q: CSS: position: fixed; right margin I might be doing something wrong, but I want to cut off my picture on the right side.
#background
{
    width: 100%;
    height: 100%;
    position: fixed;
    right: 20em;
    left: 20em;
    top: 0em;
    z-index: -1;
    margin-right: 20em;
}

Background is a picture I want to cut off at the right side, 20em in so I tried right margin without luck.
But with the fixed position I can only use left or right and top. Anyone got a smart fix for this?
Image of website as it is
EDIT: So right now the side is cut off on the left side. I want it to be cutted off on the right side too.
I have styled margins to be 20em from left and 20 em from the right. This white transparent picture should only cover that area.
I also need me reputation to post a picture, sadly.

A: make a div with the good width, and then place the image in it, and apply css to the div:
div {
overflow: hidden;
}

A: try to comment width and right params. It may help, but I am not sure that this you want
#background {
  /* widht: 100% */
  height: 100%;
  position: fixed;
  /* right: 20em; */
  left: 20em;
  top: 0em;
  z-index: -1;
  margin-right: 20em;
}

http://cssdeck.com/labs/j7zbc2zs

A: Fiddle
http://jsfiddle.net/eqE9J/135/

CSS
div{
    max-width:750px;
}
img{
    width:80%;
    padding:1%;
    border:1px solid red;
    position: fixed;
    right: 20em;
    top: 0;
}


text:
Q: Rewrite Specific URL PHP htaccess I have a custom php file at the following url
http://example.com/index.php?route=product/overview&pid=85

and i want only this URL to rewrite like as below
http://example.com/overview/85

No other URLs shall be affected in the website. Is that possible using htaccess to rewrite only one specific URL.
I tried like below
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/$ /product/overview&pid=?$1 [L]

But it is not working

A: You can use this :
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?route=product/$1&pid=$2 [L]


text:
Q: Error while validating the service descriptor
I am trying to add a handler to my services in Startup.cs. Doing this will give me the following error:
Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Authorization.IAuthorizationService Lifetime: Transient ImplementationType: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService': Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'ApiPortal.Classes.PolicyAuthorizationHandler')
Here is my Startup.cs ConfigureServices:
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));

            services.Configure<OpenIdConnectOptions>("azure", options =>
            {
                var existingOnTokenValidatedHandler = options.Events.OnTokenValidated;
                options.Events.OnTokenValidated = async context =>
                {
                    await existingOnTokenValidatedHandler(context);

                    await context.HttpContext.SignInAsync(
                        CookieAuthenticationDefaults.AuthenticationScheme, context.Principal);
                };
                var existingOnUserInformationReceived = options.Events.OnUserInformationReceived;
                options.Events.OnUserInformationReceived = async context =>
                {
                    await existingOnUserInformationReceived(context);
                };
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("AzureAccount", policy_builder => policy_builder.AddRequirements(new PolicyRequirement()));
            });

            services.AddScoped<IAuthorizationHandler, PolicyAuthorizationHandler>();

            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });

            services.AddRazorPages()
                .AddMicrosoftIdentityUI();
        }

Here is my PolicyAuthorizationHandler.cs:
    public class PolicyAuthorizationHandler : AuthorizationHandler<PolicyRequirement>
    {
        readonly IHttpContextAccessor _contextAccessor;

        public PolicyAuthorizationHandler(IHttpContextAccessor ca)
        {
            _contextAccessor = ca;
        }

        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PolicyRequirement requirement)
        {
            if (context.Resource is AuthorizationFilterContext filterContext)
            {
                var area = "";
                var controller = (filterContext.RouteData.Values["controller"] as string)?.ToLower();
                var action = (filterContext.RouteData.Values["action"] as string)?.ToLower();
                var id = "";
                if (await requirement.Pass(context, _contextAccessor, area, controller, action, id))
                {
                    context.Succeed(requirement);
                }
            }
            if (context.Resource is DefaultHttpContext httpContext)
            {
                var area = "";
                var controller = httpContext.Request.RouteValues["controller"].ToString();
                var action = httpContext.Request.RouteValues["action"].ToString();
                var id = "";
                if (await requirement.Pass(context, _contextAccessor, area, controller, action, id))
                {
                    context.Succeed(requirement);
                }
            }
        }
    }

Here is my PolicyRequirement.cs class:
    public class PolicyRequirement : IAuthorizationRequirement
    {
        IHttpContextAccessor _contextAccessor;
        AuthorizationHandlerContext _context;

        public async Task<bool> Pass(AuthorizationHandlerContext context, IHttpContextAccessor contextAccessor, string area, string controller, string action, string id)
        {
            _context = context;
            _contextAccessor = contextAccessor;
            bool authorized = false;

            //authorization logic goes here
            string email = contextAccessor.HttpContext.User.Identity.Name;
            if (email == "myemail@email.com") authorized = true;

            return await Task.FromResult(authorized);
        }
    }

I have already tried changing services.AddScoped<IAuthorizationHandler, PolicyAuthorizationHandler>() to services.AddTransient<IAuthorizationHandler, PolicyAuthorizationHandler>() and services.AddSingleton<IAuthorizationHandler, PolicyAuthorizationHandler>(). These don't seem to work.
I have also taken a look at this and this thread, but I can't seem to find a solution for my problem here as well.
What am I doing wrong and what can I do to fix this error? Thanks in advance.

A: This error means that PolicyAuthorizationHandler class depends on a service of type IHttpContextAccessor, but that service is not registered in the service container.
you need to register IHttpContextAccessor in ConfigureServices  by adding line services.AddHttpContextAccessor();
and after this, you can pass IHttpContextAccessor  to the constructor of PolicyAuthorizationHandler
`


text:
Q: ksh: How to get all "log" directories ordered by most recent activity? I would like to order a set of 50 directories based on most its recently written file in its respective log subdir. So, each directory has scripts and a log subdir. The idea is, to find out which code is most active so we migrate that first.
I started by something like
for dir in $(find . -name log -type d); do printf $dir; ls -lcrt $dir | tail -n 1; done
but this gives a messy result, that needs further parsing in order to sort on date. Maybe there is a simpler way?
thank you

*

*update: since there are many files per directory, the first step would be to get the newest per directory, and iterate over that.
So I built a double for loop, that did that.

A: This method may not be able to 100% solve your problem, but it is easy to use.
Assuming that there are at most 99 file in past 2 days, then
find . -type f -mtime -2 | xargs -n 99 ls -ltr | grep '/log/'

This command will find all files with modification time in past 2 days and then do a ls -ltr sorting and then filter the /log/ directory
Hope this can help a little.

A: update: since there are many files per directory, the first step would be to only get the newest one per directory (ls -lh |tail -1; something like that), and iterate over that. So I built a double for loop, which won't win any beauty contest, but got me the results.


text:
Q: Upper bound of product If $x \in [a,b]$, then I want to find the optimal upper bound of the product
$$
|x - a| |x - b| \leq M
$$
It seems obvious that
$$
|x - a| |x - b| \leq |b-a|^2
$$
however it seems that the optimal upper bound is in fact
$$
|x-a||x-b| \leq \frac{|b-a|^2}{4}
$$
Does anyone know how to prove this?

A: First using the arithmetic mean - geometric mean inequality, we get that
$$ |x-a||x-b| \le \left(\frac{|x-a|+|x-b|}{2}\right)^2.$$
Now since $x \in [a,b]$ we have that $|x-a|+|x-b| = |b-a|$. Thus, we have that
$$ |x-a||a-b| \le \frac{|b-a|^2}{4}.$$

This bound is tight, as can be seen by picking $x = (b+a)/2$. Then
$$|x-a||x-b| = \frac{|b-a|}{2}\frac{|a-b|}{2} = \frac{|b-a|^2}{4}.$$

A: In order to prove a statement $A$ it can be worthwhile to search for a stronger statement $B$ that is simpler to establish and implies statement $A$.
The task at hand requires knowledge about the range of the function $$f : [a,b] \rightarrow \mathbb{R}$$ given by
$$ f(x) = (x-a)(x-b).$$
We have $$f(a) = f(b) = 0.$$ It is clear that $f$ is differentiable and $$f'(x) = 2x - (a+b).$$
We have $$f'(x) = 0$$ if and only if $$x= \frac{a+b}{2} =: \mu$$
Since $f$ is continuous and $$f(\mu) = -\frac{(b-a)^2}{4} =: -M$$ the range of $f$ is the interval $[-M,0]$ and the desired result is immediate.
 Obviously, simplicity is a matter of perspective and depends on the intended audience, which is why it is so valuable to have different proofs for the same result.

A: Since $a \leq x \leq b$, we have,
$|x-a||x-b|=(x-a)(b-x)$
$=\left(\frac{x-a+b-x}{2}\right)^2-\left(\frac{x-a-b+x}{2}\right)^2$, by the identity $pq=\left(\frac{p+q}{2}\right)^2-\left(\frac{p-q}{2}\right)^2$
$=\left(\frac{b-a}{2}\right)^2-\left(\frac{2x-a-b}{2}\right)^2 \leq \frac{(b-a)^2}{4}$,
the equality holds when $2x=a+b$ i.e., $x=\frac{a+b}{2}$.


text:
Q: узнать какой модуль определяет типы Вопрос теоретический, не могу проверить.
Есть прога Delphi (10.3), в ней подключены модули
uses m1 {там type tm000=string}, m2 {там type tm000=integer};

type tm000=byte; {local}

var v:tm000;

begin
// тут узнать тип переменной v
end;
end.

A: Всегда будет использоваться тип определенный в текущем модуле. Затем используются типы из подключаемых подмодулей справа налево. Т.е. сначала из m2, затем m1.
Если требуется использовать все типы в одном модуле, то необходимо указать имя модуля.
var
  v:tm000;
  v1:m2.tm000;
  v2:m1.tm000;


text:
Q: Parameterized query which sends NULL value, with C# and SQL Server I tried to pass some variables into a parameterized query but when the value is NULL it throws an exception that says the value is not provided.
How can I fix that without an if or something like that?
My code is this
var cmdPersona_Log = new SqlCommand();
cmdPersona_Log.Parameters.Clear();
cmdPersona_Log.Connection = mySqlConnection;
cmdPersona_Log.CommandType = CommandType.Text;
cmdPersona_Log.CommandText = @"INSERT INTO [Tomin].[TominRH].[Persona_Log] "
+ "([Id_Action],[Id_User],[Id_Date],[Id_Entidad],[Nombre],[Paterno],[Materno],[Sexo],[Id_Nacionalidad])"
+ " Values (1, 'Admin', @fecha, @id_entidad, @nombre, @paterno, @materno, 1, 52)";

cmdPersona_Log.Parameters.Add("@fecha", DateTime.Now);
cmdPersona_Log.Parameters.Add("@id_entidad", dbRow["CUENTA"]);
cmdPersona_Log.Parameters.Add("@nombre", nombre);
cmdPersona_Log.Parameters.Add("@paterno", paterno);
cmdPersona_Log.Parameters.Add("@materno", materno);

cmdPersona_Log.ExecuteNonQuery();

A: I will assume that your problem is that the underlying field doesn't support nulls. If this is the case, you could do something like this
cmdPersona_Log.Parameters.Add("@nombre", nombre ?? string.Empty);
cmdPersona_Log.Parameters.Add("@paterno", paterno ?? string.Empty);
cmdPersona_Log.Parameters.Add("@materno", materno ?? string.Empty);

You'll be inserting an empty string in case you have a null using the null-coalescing operator.


text:
Q: X3D, Shape Creation, Curve, Manipulation I have created a box in X3D but i want to curve the top right and left corners of the box.
Any ideas on how? At the moment i have the code for the box only.
I cannot find much on the net about simple shape manipulation.
Thanks

A: You can't do it manually, directly in X3D.
You have to use a software like Blender or 3DS Max to create non-primitive shapes (more complex shapes than cubes, spheres, cylinders and so on.) There you have all kinds of functions that would change your object and then you can export it in several formats, including X3D.


text:
Q: Is it possible to change Magento backend language for one user only? We got multi-lingual team, and couple of members do not speak each others languages. Is it possible to set Magento backend in separate languages for corresponding users?

A: each user can choose a language with the localization drop down at the left bottom of every admin pages

A: You should find that this module from AOE allows you to save the user's preferred language for the admin interface: https://github.com/AOEmedia/Aoe_BackendDefaultLanguage
Once the user has logged in, navigate to System>My Account and the last field (select drop-down) is language).

A: I don't know how it is in the pay version of magento, but it seems that the community edition has only the ability to change the backend language to one language regardless of who is logged in. Maybe you code this feature by yourself or you keep the english language.