text:
Q: ServiceStack.Text: Forcing serialization of a property not decorated with DataMember attribute I have the following class (simplified).
[DataContract]
public class ServiceResponse
{
    public int Sequence { get; set; }

    [DataMember]
    public ServiceResponseStatus Status { get; set; }
}

I'm using ServiceStack to serialize objects for logging purposes, and letting DataContractSerializer do the rest. ServiceStack, as expected, will not serialize Sequence as it is not decorated with a DataMember attribute.
Is there a way to force ServiceStack to serialize this property?
Marc Gravell's answer to this similar question DataContract Serialization without DataMember Attribute seems to suggest a different approach, but I thought I'd ask.

A: Decorating your classes with DataContract/DataMember attributes is specifically used for opting in which properties you want serialized. If you want all properties serialized remove all the attributes.
See this answer for other ways to ignore properties in Servicestack serializers.


text:
Q: How to use enum item name which contains space? How to use enum item name which contains space?
enum Coolness
{
    Not So Cool = 1,
    VeryCool = 2,
    Supercool = 3
}

I am getting the Enum item name by below code
string enumText = ((Coolness)1).ToString()

I don't wont to change this code but above code should return Not So Cool.
Is there any use of oops concept to make this happen?
Here I don't want to change retrieving statement.

A: Use Display attributes:
enum Coolness : byte
{
    [Display(Name = "Not So Cool")]
    NotSoCool = 1,
    VeryCool = 2,
    Supercool = 3
}

You can use this helper to get the DisplayName
public static string GetDisplayValue(T value)
{
    var fieldInfo = value.GetType().GetField(value.ToString());

    var descriptionAttributes = fieldInfo.GetCustomAttributes(
        typeof(DisplayAttribute), false) as DisplayAttribute[];

    if (descriptionAttributes == null) return string.Empty;
    return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString();
}

(Credit to Hrvoje Stanisic for the Helper)

A: Avoid space on your enum
enum Coolness : int
{
    NotSoCool = 1,
    VeryCool = 2,
    Supercool = 3
}

To get the value in text, try this:
string enumText = ((Coolness)1).ToString()

If you want a friendly description for each item of enum, try using the Description attribute, for sample:
enum Coolness : int
{
    [Description("Not So Cool")]
    NotSoCool = 1,

    [Description("Very Cool")]
    VeryCool = 2,

    [Description("Super Cool")]
    Supercool = 3
}

And to read this attribute, you could use a method like this:
public class EnumHelper
{
    public static string GetDescription(Enum @enum)
    {
        if (@enum == null)
            return null;

        string description = @enum.ToString();

        try
        {
            FieldInfo fi = @enum.GetType().GetField(@enum.ToString());

            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributes.Length > 0)
                description = attributes[0].Description;
        }
        catch
        {
        }

        return description;
    }
}

And use it:
string text = EnumHelper.GetDescription(Coolness.SuperCool);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rspec: How to test recursion? I'd like to test that a method is called recursively with a specific argument.
My approach:
class Recursable
  def rec(arg)
    rec(7) unless arg == 7
  end
end

describe Recursable do
  it "should recurse" do
    r = Recursable.new('test')
    r.should_receive(:rec).with(0).ordered
    r.should_receive(:rec).with(7).ordered
    r.rec(0)
  end
end

Unexpectedly, RSpec fails with:
expected :rec with (7) once, but received it 0 times

Any idea what's wrong with my approach? How to test for effective recursion with a specific argument?

A: Often if you need to test recursion it is a code smell; you probably should split the method into different responsibilities or something.
But some times you just need to add some basic checks on your recursion.
You can do it with Rspec and_call_original:
it "should recurse" do
  r = Recursable.new('test')
  r.should_receive(:rec).with(0).ordered.and_call_original
  r.should_receive(:rec).with(7).ordered.and_call_original
  r.rec(0)
end

Normally should_receive will just stub the real method, that's why the recursion doesn't work. With and_call_original the stubbed method (that contains the test checks) will also call the original method implementation, that will perform the recursion as expected.

A: The problem with your test as it is now is that you are stubbing away the method you are trying to test. r.should_receive(:rec) is replacing r#rec with a stub, which of course doesn't ever call r.rec(7).
A better approach would be to simply test that the result of the initial method call is correct. It shouldn't strictly matter whether or not the method recurses, iterates, or phones a friend, as long as it gives the right answer in the end.


text:
Q: check and protect a thread in c++ Currently, I created a simple thread to clear memory:
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        CreateThread(0, 0, test, 0, 0, 0);
        break;
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }

    return TRUE;
}

Code:
DWORD WINAPI test(LPVOID lpvParam) {
memo:
    Sleep(10000);
    SetProcessWorkingSetSize(GetCurrentProcess(), 102400, 614400);
    goto memo;
}

Is there any way to protect this thread? And prevent it from being paused with some external program (such as Process Hacker 2)?
Example: if the thread is running, returns true, if it is externally paused or interrupted, returns false and closes the program with ExitProcess()?
I tried different methods like
std::thread
thread.join().
thread.joinable()
None of them worked.

A:
prevent thread from being paused with some external program (such as Process Hacker 2)?

Instead of creating a new thread to run your code periodically, create a waitable timer with CreateWaitableTimer and schedule it with SetWaitableTimer. The timer runs the callback in the thread that called SetWaitableTimer, so that there is no other thread to pause.
That also solves the problem that threads must not be created in DllMain.


text:
Q: current_user.is_authenticated not working on flask_login I'm using flask_login to make the authentication and something on my login does not work. In fact the current_user attribute is always false (or anonymousUserMixin...).
I tried to change something but it didn't work. I think there are some problems with the login_user(user) part.
@login_manager.user_loader
def load_user(user_id):
    try:
        return User.query.get(user_id)
    except:
        return None

This is my login routing:
@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect('profile', username=current_user.user_id)
    form = LoginForm()
    if form.validate_on_submit():
        email = form.email.data
        user = User.query.filter_by(email=email).first()
        pass_hashed = form.password.data
        if user:
            flash("user.password, pass_hashed" + user.password + "  " + pass_hashed, category="error")
            if pass_hashed == user.password:
                usr = UserData.query.filter_by(email=email).first()
                login_user(user, remember=form.remember.data)
                session['username'] = usr.username
                next = request.args.get('next')
                # if not is_safe_url(next):
                #   return abort(400)
                # return redirect(next or url_for('index'))
                username = usr.username
                return redirect(url_for('profile', username=username))
            flash("wrong password", category="error")
            return redirect(url_for('login'))
        flash("invalid email", category="error")
        return redirect(url_for('login'))
    return render_template('login.html', form=form)

And this one is my user model:
class User(db.Model, UserMixin):
    __tablename__ = 'user'
    user_id = db.Column(db.Integer(), autoincrement=True)
    email = db.Column(db.String(120), primary_key=True, unique=True, nullable=False)
    password = db.Column(db.String(200), nullable=False)

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return unicode(self.user_id)

    def get(self, id):
        return unicode(self.user_id)

    def __repr__(self):
        return '<Email %r>' % self.email

    def check_password(self, password):
        if self.password == password:
            return True
        else:
            return False

A: I have a few suggestions:
Try changing
@login_manager.user_loader
def load_user(user_id):
    try:
        return User.query.get(user_id)
    except:
        return None

to:
@login_manager.user_loader
def load_user(user_id):
    return User.query.filter(User.id == user_id).first()

Despite the docs uses .get(), I read in some places that SQLAlchemy might have some issues due to the Unicode thing. Making this change might be enought to get it to work.
The other suggestion is to not override the UserMixin methods if you're not actually changing them. (Talking about the is_* methods you implemented without actually needing to)
Another thing to note is:
If you check the UserMixin implementation for the get_id() method, it uses a text_type for converting the id. Maybe try using it as well instead of the builtin unicode.
If nothing works, the last solution is to change your User id field from user_id (which is kinda redundant, IMO) to id, cause FlaskLogin knows how to handle it as-is if that's the model identifier.


text:
Q: Add ONLY the total values on top of stacked bars I am working with the following bar plot:

And I would like to add only the total amount of each index on top of the bars, like this:

However, when I use the following code, I only get parts of the stacks of each bar.
import matplotlib.pyplot as plt

data = [['0.01 - 0.1','A'],['0.1 - 0.5','B'],['0.5 - 1.0','B'],['0.01 - 0.1','C'],['> 2.5','A'],['1.0 - 2.5','A'],['> 2.5','A']]

df = pd.DataFrame(data, columns = ['Size','Index'])

### plot

df_new = df.sort_values(['Index'])

list_of_colors_element = ['green','blue','yellow','red','purple']

# Draw
piv = df_new.assign(dummy=1) \
            .pivot_table('dummy', 'Index', 'Size', aggfunc='count', fill_value=0) \
            .rename_axis(columns=None)
ax = piv.plot.bar(stacked=True, color=list_of_colors_element, rot=0, width=1)

ax.bar_label(ax.containers[0],fontsize=9)

# Decorations
plt.title("Index coloured by size", fontsize=22)
plt.ylabel('Amount')
plt.xlabel('Index')
plt.grid(color='black', linestyle='--', linewidth=0.4)
plt.xticks(range(3),fontsize=15)
plt.yticks(fontsize=15)

plt.show()

I have tried with different varieties of ax.bar_label(ax.containers[0],fontsize=9) but none displays the total of the bars.

A: As Trenton points out, bar_label is usable only if the topmost segment is never zero (i.e., exists in every stack) but otherwise not. Here are examples of the two cases.

If the topmost segment is never zero, use bar_label
In this example, the topmost segment (purple '>2.5') exists for all A, B, and C, so we can just use ax.bar_label(ax.containers[-1]):
df = pd.DataFrame({'Index': [*'AAAABBCBC'], 'Size': ['0.01-0.1', '>2.5', '1.0-2.5', '>2.5', '0.1-0.5', '0.5-1.0', '0.01-0.1', '>2.5', '>2.5']})
piv = pd.crosstab(df['Index'], df['Size'])
ax = piv.plot.bar(stacked=True)

# auto label since none of the topmost segments are missing
ax.bar_label(ax.containers[-1])

Otherwise, sum and label manually
In OP's example, the topmost segment (purple '>2.5') does not always exist (missing for B and C), so the totals need to be summed manually.
How to compute the totals will depend on your specific dataframe. In OP's case, A, B, and C are rows, so the totals should be computed as sum(axis=1):
df = pd.DataFrame({'Index': [*'AAAABBC'], 'Size': ['0.01-0.1', '>2.5', '1.0-2.5', '>2.5', '0.1-0.5', '0.5-1.0', '0.01-0.1']})
piv = pd.crosstab(df['Index'], df['Size'])
ax = piv.plot.bar(stacked=True)

# manually sum and label since some topmost segments are missing
for x, y in enumerate(piv.sum(axis=1)):
    ax.annotate(y, (x, y+0.1), ha='center')


text:
Q: Date range filter not working properly in angular I'm using customized filter but its not working as per the requirement
  if(this.startdatefilter!=undefined && this.enddatefilter!=undefined){
      this.filterArray.push( { type:'startDate' ,value: "Start Date : "+this.startdatetime},{ type:'endDate' ,value: "End Date : "+this.enddatetime})
      filteredData = filteredData.filter(data => ((data.startDateTimeFilter)>=
        (this.startdatefilter) ) && (data.startDateTimeFilter)<=(this.enddatefilter) )
    }

the date the format is - Mon Nov 11 2019 05:30:00 GMT+0530 (India Standard Time)
startDateTimeFilter = Mon Nov 11 2019 05:30:00 GMT+0530 (India Standard Time) ,Thu Nov 07 2019 00:00:00 GMT+0530 (India Standard Time) .. goes on ..
startdatefilter = Thu Nov 07 2019 00:00:00 GMT+0530 (India Standard Time)
I think its breaking because of date format  ..
I tried stringifying the dates to a format 11 Nov , 2019  But didn't work ..
Any idea please help ..

A: I just changed the format to dd-M-yyyy .. it worked !!


text:
Q: MATLAB: Using second output of a function in a inline function
Possible Duplicate:
Skipping outputs with anonymous function in MATLAB

Say I have a MATLAB function that returns two arguments:
[A,B] = twoArgsBack(x)

I want to write an anonymous function that uses B (e.g. for passing to a minimization routine)
myfun = @(x) sum(twoArgsBack(x))

will return the sum of A, ignoring the output from B.  How can I write an anonymous function that returns the sum of B?


text:
Q: PHP Youtube: View Count/Time Duration stamp on the thumbnail mechanism I am having difficulties trying displaying a thumbnail with time DURATION. The code renders a thumbnail but without any times. Also, the views are coming out with a result of O views. Everything else is being fetch properly.
    <?php
error_reporting(E_ALL);
$feedURL = 'http://gdata.youtube.com/feeds/api/users/YOURUSERNAME/uploads?max-results=2';
$sxml = simplexml_load_file($feedURL);
$i=0;
foreach ($sxml->entry as $entry) {
      $media = $entry->children('media', true);
      $watch = (string)$media->group->player->attributes()->url;
      $thumbnail = (string)$media->group->thumbnail[0]->attributes()->url;

      // get <yt:duration> node for video length
      $yt = $entry->children('http://gdata.youtube.com/feeds/api/users/YOURUSERNAME/uploads?max-results=2');
      $attrs = $yt->duration->attributes();

      // get <yt:stats> node for viewer statistics
        $yt = $entry->children('http://gdata.youtube.com/feeds/api/users/YOURUSERNAME/uploads?max-results=2');
        $attrs = $yt->statistics->attributes();
        $viewCount = $attrs['viewCount'];
      ?>

<a href="<?php echo $watch; ?>" class="watchvideo"><?php echo $media->group->title; ?>

<?php
      echo sprintf("%0.2f", $length/60) . " min. |
        {$viewCount} views
\n"; ?>

<a href="<?php echo $watch; ?>" class="watchvideo"><img src="<?php echo $thumbnail;?>" alt="<?php echo $media->group->title; ?>" width="150px" height="85px" />

<?php $i++; if($i==3) { echo '

'; $i=0; } } ?>

A: You're passing wrong URI to the children method. Fixed code:
  // get <yt:duration> node for video length
  $yt = $media->children('http://gdata.youtube.com/schemas/2007');
  $attrs = $yt->duration->attributes();
  $length = $attrs['seconds'];

  // get <yt:stats> node for viewer statistics
  $yt = $entry->children('http://gdata.youtube.com/schemas/2007');
  $attrs = $yt->statistics->attributes();
  $viewCount = $attrs['viewCount'];


text:
Q: input float in C++? I code a program to calculate all possibilities, but with integers and now I have to do it for floats, how can I change the program to input floats instead of integers?
This is just a part but if I can do it for the fist switch I can do it for all:
#include <fstream>
using namespace std;
ifstream in("multimi.in");
ofstream out("produs.out");
void input(int *v)
{
    for(int i=1; i<=2; i++)
        in>>v[i];
}

int main()
{
    float a[3],b[3],c[3],d[3],e[3],s[3];
    int num_tot;
    in>>num_tot;
    switch(num_tot)
    {
        case 2:
        input(a);
        input(b);

        for(int i=1; i<=2; i++)
            for(int j=1; j<=2; j++)

                    out<<a[i]<<","<<b[j]<<endl;
        break;

This is the code with int which works:
#include <fstream>

using namespace std;
ifstream in("multimi.in");
ofstream out("produs.out");
void input(int *v)
{
    for(int i=1; i<=2; i++)
        in>>v[i];
}

int main()
{
    int a[3],b[3],c[3],d[3],e[3],s[3];
    int num_tot;
    in>>num_tot;
    switch(num_tot)
    {
        case 2:
        input(a);
        input(b);

        for(int i=1; i<=2; i++)
            for(int j=1; j<=2; j++)

                    out<<a[i]<<","<<b[j]<<endl;
        break;

A: If you want to parse a float value in your input function you'll have to have a compatible parameter, as you are passing an array of floats as an argument (which becomes a pointer to the first element of the array), you'll need a pointer to float instead of pointer to int.
void input(float *v){ ... }

I should also note that you are bypassing the first element in the array, the indexes start at [0].
Another thing I would do is to avoid using global variables, if you want to use your in stream in the function you can pass it by reference as an argument of the function, provided that you know its lifetime will outlive the reference:
All things considered you would have something like this:
void input(float *v, ifstream& in)
{
    for (int i = 0; i < 2; i++)
        in >> v[i];
}

int main()
{
    ifstream in("test.txt");
    ofstream out("produs.out");
    float a[2], b[2];
    int num_tot;

    if (in.is_open() && out.is_open()) //it's important to check for successful file opening
    {
        in >> num_tot;

        switch (num_tot)
        {
        case 2:
            input(a, in);
            input(b, in);
            for (int i = 0; i < 2; i++)
            {
                out << a[i] << ", " << b[i] << endl;
            }
            break;
        }
    }
}

If you want something that works for both int and float you can make a function that can take both types using templates, I'll admit that this may be too much for now but it's somenthing that you may consider when you are more comfortable with the language:
template<typename T> void input(T& v, ifstream& in)
{
    for (int i = 0; i < 2; i++)
        in >> v[i];
}

Here T can take both int or float, with the added advantage that it can also be passed by reference. Of course you can still use pointers if you wish to do so, but passing by reference is preferable as it's safer.

Footnote
Consider not using using namespace std; you can follow this link to know the reasons for it, when it's safe to use and alternatives.


text:
Q: Index out of date on appengine? I'm doing this query on my live appengine site:
orders = models.Order.gql("WHERE status IN ('accepted','packing') ORDER BY created_on DESC").fetch(100)

To my surprise, I get results where the status is not in 'accepted' or 'packing', but 'cancelled'.  I've never seen this problem before and I just noticed it today:
for order in orders:
...     order.status
...
u'accepted'
u'accepted'
u'cancelled'
u'cancelled'
u'accepted'

Any thoughts? It seems like something is fundamentally wrong.  I'm not caching any results, this was all on the remote shell and it happens on my live site.

A: If your entities have recently changed, this could be Datastore's eventual consistency in action.  When you update your entities, it takes a while for the indexes to reflect your changes, while the entities themselves are up-to-date.
If you data is structured appropriately, you could try an ancestor query and see what happens.


text:
Q: Reverse stack represented by pointer in C I tried to reverse stack with the following function. It seems to work fine at first but later after two inputs, it starts to modify the original stack.
I'm thinking something might be wrong with my while condition, but I test-ran it and it works fine. Below is my code:
void push(StackNodePtr *topPtr, BizarreNumber_t info) {
  StackNodePtr newPtr = malloc(sizeof(StackNode));

  if (newPtr != NULL) {
    newPtr->data = info;
    newPtr->nextPtr = *topPtr;
    *topPtr = newPtr;
  } else {  // no space available
    printf("%d is not inserted. Memory error!\n", info.num);
  }
}

BizarreNumber_t pop(StackNodePtr *topPtr) {
  StackNodePtr tmpPtr = *topPtr;
  BizarreNumber_t result = (*topPtr)->data;

  *topPtr = (*topPtr)->nextPtr;

  free(tmpPtr);

  return result;
}

StackNodePtr reverseStack(StackNodePtr currentPtr) {
  StackNodePtr newPtr = NULL;
  while (currentPtr != NULL) {
    push(&newPtr, pop(&currentPtr));
  }
  return newPtr;
}

I'm not sure if I need to include my definition for StackNode. thanks for any help and suggestions.


text:
Q: Creating SOAP request via Zeep with variable number of XML tags All, I am using Zeep to connect to CUCM to perform bulk AXL transactions. Some of the objects that I need to modify accept a variable number of XML tags. For example:
I want to add an entity(calling search space), which could have a variable number of partitions associated to it. Per the WSDL:

    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.cisco.com/AXL/API/11.5">
       <soapenv:Header/>
       <soapenv:Body>
          <ns:addCss sequence="?">
             <css>
                <!--Optional:-->
                <description>?</description>
                <!--Optional:-->
                <members>
                   <!--Zero or more repetitions:--> <------------------------------------------
                   <member>
                      <routePartitionName uuid="?">?</routePartitionName>
                      <index>?</index>
                   </member>
                </members>
                <!--Optional:-->
                <partitionUsage>General</partitionUsage>
                <name>?</name>
             </css>
          </ns:addCss>
       </soapenv:Body>
    </soapenv:Envelope>

I can easily script a fixed number of members:

    result = service.addCss({
        'name': 'SampleCSS',
        'description': 'Sample CSS Description',
        'members': {
            'member': [
                {'routePartitionName':{
                    '_value_1':None, 'uuid':'{07614566-ADC4-1ABB-3EB3-C08650E11CBE}'},
                    'index':1},
                {'routePartitionName': 'Auto Register','index': 2},
                {'routePartitionName': 'DNS External', 'index':3},
                {'routePartitionName':{
                    '_value_1':'On Cluster', 'uuid':'{F7FF933E-2B63-25DB-11AF-1DDDC8F9A52E}'},
                    'index':4},
            ]}
         })
    print (result)
    print(type(result))
    res = result['return']
    print("\n\n", res)

However, I am having a hard time scripting a variable number of members
I have my members stored on a dictionary:

    CSSes = {
        'Test1': ['Test1','Test1','07614566-ADC4-1ABB-3EB3-C08650E11CBE','Staging',1],
        'Test2': ['Test2','Test2','F7FF933E-2B63-25DB-11AF-1DDDC8F9A52E', 'On Cluster',1]
    }

If I am adding multiple CSS's and each has a different number of partitions(members) how do I accomplish this?
I've only been able to come up with something where every CSS has the same number of partitions assigned to it:
for css in CSSes:
    result = service.addCss({
        'name': CSSes[css][0],
        'description': CSSes[css][1],
        'members': {
            'member': [
                {'routePartitionName':{
                        '_value_1':CSSes[css][3], 'uuid':CSSes[css][1]},
                        'index':CSSes[css][4]}
        ]}
    })

A: I'm not 100% sure I understand your scenario (mostly based on the snippets provided), but given this data set, where one CSS to be created has 2 partitions and the other has 3:
CSSs = [
    {
        'name': 'CSS1',
        'description': 'CSS1 description',
        'members': [
            {
                'name': 'Partition1',
                'index': 1
            },
            {
                'name': 'Partition2',
                'index': 2
            }
        ]
    },
    {
        'name': 'CSS2',
        'description': 'CSS2 description',
        'members': [
            {
                'name': 'Partition1',
                'index': 1
            },
            {
                'name': 'Partition2',
                'index': 2
            },
            {
                'name': 'Partition3',
                'index': 3
            }
        ]
    }
]

I was able to get this working by dynamically appending members, like so:
for css in CSSs:
    css_data = {
        'name': css['name'],
        'description': css['description'],
        'members': {
            'member': []
        }
    }
    for memb in css['members']:
        css_data['members']['member'].append(
            {
                'routePartitionName': memb['name'],
                'index': memb['index']
            }
        )
    css_resp = service.addCss(css_data)


text:
Q: SWIG c# with a virtual pure interface I'am trying to wrap a C++ virtual pure interface into c# using SWIG.
Here is my dll C++ interface:
class EXPORT FeatureItf
{
protected:
    virtual ~FeatureItf() { }
public:
    virtual void PrintMe() = 0;
    virtual void Delete() = 0;
};

bool EXPORT FeatureItfCreator(FeatureItf*& feat);

For a C++ user linking the dll, API is simple :
FeatureItf* feat = nullptr;
FeatureItfCreator(feat); // will allocate feat
feat->PrintMe();
feat->Delete();

How to wrap the FeatureItf class into a c# class using SWIG ?
In particular to manage the *& in creator function and the construction on the c# object.

A: This works fine :
%include swigtype_inout.i
%apply SWIGTYPE *& OUTPUT { SWIGTYPE *& }


text:
Q: Gmail API changes the content disposition from "inline" to "attachment" I'm running into an odd problem with sending inline attachments via Gmail's API.  I am using the .NET client (version 1.10.0).  The email is a reply to a message I've received with an inline attachment, so the attachment is part of the quoted block in the reply.
Here's the raw MIME message that I'm sending out:
From: ...
To: ...
Date: Fri, 01 Jul 2016 11:48:29 -0700
Subject: Re: attachment test #2
Message-Id: ...
In-Reply-To:...
References: ...
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="=-JOa+9Bw0690XCFj1YCPc1Q=="

--=-JOa+9Bw0690XCFj1YCPc1Q==
Content-Type: text/html; charset=utf-8
Content-Id: <W4PKNTOPLYT4.32IVHE45EWK21@BILLRAVDIN9F02>

back atcha.

On Fri, Jul 01, 2016 at 11:38 AM, ... wrote:
[Omitted for clarity]

--=-JOa+9Bw0690XCFj1YCPc1Q==
Content-Type: image/jpeg; name="ha ha.jpeg"
Content-Disposition: inline; filename="ha ha.jpeg"
Content-Transfer-Encoding: base64
Content-Id: <8AF6D64A-9AAD-4E54-8998-5F08C42F537F>

[Base64 encoded attachment]

--=-JOa+9Bw0690XCFj1YCPc1Q==--

Note above the content disposition on the mime part for the inline attachment:
Content-Disposition: inline; filename="ha ha.jpeg"
Here's what the MIME headers on the inline attachment part look like when it comes in:
Content-Type: image/jpeg; name="ha ha.jpeg"
Content-Disposition: attachment; filename="ha ha.jpeg"
Content-Transfer-Encoding: base64
Content-ID: <8AF6D64A-9AAD-4E54-8998-5F08C42F537F>
X-Attachment-Id: 594301951148d672_0.1

My question is: why is the Content-Disposition now rewritten as attachment rather than inline?
I've found that when viewing the email in my browser, it appears as expected.  But when viewing with my Mac's Mail client, the inline attachment appears in the email twice.  I suspect that the change in the content disposition might be the reason- any light you can shed on this would be much appreciated!


text:
Q: Odd Java String[] issue, contains value but acts like null when inserting into List I am having an issue with a String array and trying to add it to a list (List).
Below is the code that is used and creating the issue.
The program fails on the first run through of the loop and I have verified the input which comes from a CSV using OpenCSV.
List<String[]> output = null;
String[] temp;

for(int i = 0; i < 13; i++)
{
    temp = reader.readNext();                           //read next line into temp
    System.out.println(temp[0]+temp[1]+temp[2]);        //temp output
    temp[2] = String.valueOf((values[i])/100);          //assign new value
    System.out.println(temp[0]+temp[1]+temp[2]);        //temp output
    output.add(temp);
}

When this code runs the output is.
VANCBULLET0.311
VANCBULLET0.308
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Main.updateCSV(Main.java:951)
    at Main.start(Main.java:863)
    at Main.access$23(Main.java:853)
    at Main$23.actionPerformed(Main.java:520)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)

The first two lines are correct and are split up like:
temp[0] temp[1] temp[2]
VANC BULLET 0.311
VANC BULLET 0.308
The issue is (like the error reads) at:
output.add(temp);

The documentation reads:
NullPointerException - if the specified element is null and this list does not permit null elements

but as you can see from my output (the second line) the array "temp" is not null, it contains "VANC BULLET 0.308" in each element respectively.
I'm stumped. Does anyone have an idea or see something I have failed to see?
Thanks

A: From what i can see you never initialized List<String[]> output = null; in your code. Thus when it call's List.add as List is still null it throws NPE
initialize it first:
List<String[]> output = new ArrayList<String[]>();

A: The list ouput is defined as null
List<String[]> output = null;

And in the loop you are trying to add values to output.
Initialize the output object.
List<String[]> output = new ArrayList<String[]>();


text:
Q: Is offsetting portions of grids possible when using a grid system? I'm wondering if it is possible to offset by portions or percentages of grids instead of the whole grid width.
Let's say for example, I had:
   <div class="span1 offset6" >

...and I wanted it to the left a little more, should I just add an < id > and put a css "left" or is it possible to offset by something like 6.5 (for example)?
Maybe I'm over thinking it a bit (or maybe not enough :p

A: You could always just add a custom class to the top of your page with the amount you want to increase the offset. If you put the following style in your head:
<style type="text/css">
 .offset6-5 {
  margin-left: 540px;
 }
</style>

You now have a class that offsets in between Twitter bootstraps .offset6 class which has a 500px offset and the .offset7 class which has a 580px offset. You would of course have to be careful of throwing off the the rest of the grid system by creating custom widths that eventually change the overall grid size. (for example your 960px grid is now at 1000px.)
Hope that helps.


text:
Q: Custom streambuffer in std::ofstream I know that in std::ostream, I can use a custom streambuf through either stating so in the constructor:
std::ofstream temp;
temp.open("file.txt", std::ios_base::in);
std::ostream example(temp.rdbuf());

as well as by setting it afterwards (same first two lines as before, but change the last line to:
std::ostream example;
example.rdbuf(temp.rdbuf());

My question is: How can I do that in std::ofstream? I want to be able to overwrite the methods xsgetn and xsputn implemented in std::streambuf in my own custom class and use this in my ofstream, but, short of writing my own custom ofstream am unsure of how to do so.

A: The concrete file stream classes have their own rdbuf() method that takes  0 arguments and it hides the other rdbuf() method inherited from the virtual base std::basic_ios. Qualifying the name to lookup the base class method should work:
std::ofstream ofs;
ofs.basic_ios<char>::rdbuf(example.rdbuf());


text:
Q: Feynman screwjack problem What is a thread? How does he know you need to turn the handle "around" 10 times? From where does the 126 inches come from?
I thought Feynman  explanations were easy...

Let us now illustrate the energy principle with a more complicated
  problem, the screw jack shown in Fig. 4-5. A handle 20 inches long is
  used to turn the screw, which has 10 threads to the inch. We would
  like to know how much force would be needed at the handle to lift one
  ton (2000 pounds). If we want to lift the ton one inch, say, then we
  must turn the handle around ten times. When it goes around once it
  goes approximately 126 inches. The handle must thus travel 1260 inches.

No need to say I don't speak English very well but the Spanish version of the book is horrible and confusing.

A: Threads refer to the helical ridge that wraps around a screw—tornillo in Spanish. Each complete rotation of a screw with 10 threads per inch advances it one tenth of an inch.
As mentioned in the comments, 126 inches is the circumference of the circle swept out by the handle—the distance you move your hand to put the screw through one full rotation.


text:
Q: How can I launch the tutorial for the GNU info pages? I would like to learn how to use the info pages - i.e. the documentation for GNU programs.
If I run info from a terminal, the info program launches
File: dir,      Node: Top,      This is the top of the INFO tree.

This is the Info main menu (aka directory node).
A few useful Info commands:

  'q' quits;
  '?' lists all Info commands;
  'h' starts the Info tutorial;
  'mTexinfo RET' visits the Texinfo manual, etc.

however if I type h I get a man page for info, not the info tutorial. How can I launch the tutorial?

A: You can try starting from the command line with info info. Also, my info accepts H to enter the tutorial.

A: I had the identical problem which I posted here:
Cannot start the info tutorial in Debian 9 (stretch)
The solution (maybe overkill) was to install emacs, then the emacs24-common-non-dfsg package. I could then invoke the tutorial with info info, h. It also works with just info, h.


text:
Q: PostGIS 2 st_intersection FROM-clause error I'm trying to run this query in a PostGIS 2 database:
create TABLE data.agri_grc as select
id, code_00,
ST_Intersection(data.agri.geom,data.grc_bor.geom) as geom from
data.agri;

But I'm getting this error:
ERROR:  missing FROM-clause entry for table "grc_bor"
LINE 3: ST_Intersection(data.agri.geom,data.grc_bor.geom) as geom fr...

What am I missing?

A: @Mapperz Link pointed me to the right direction.
The correct SQL query seems to be :
create table data.agri_grc as select
 a.id,
 a.code_00,
 ST_Intersection(a.geom,b.geom_3035) as geom from
  data.agri as a,
  data.grc_bor as b;

you need to put the arguments as table aliases

A: Try to put the entire SELECT clause in (...)


text:
Q: JQuery не добавляется класс при нажатии Есть несколько svg сердечек
<svg id="svg_2" width="640" height="480" viewbox="0 0 640 480" xmlns="http://www.w3.org/2000/svg">
   <path d="m219.28949,21.827393c-66.240005,0 -119.999954,53.76001 -119.999954,120c0,134.755524 135.933151,170.08728 228.562454,303.308044c87.574219,-132.403381 228.5625,-172.854584 228.5625,-303.308044c0,-66.23999 -53.759888,-120 -120,-120c-48.047913,0 -89.401611,28.370422 -108.5625,69.1875c-19.160797,-40.817078 -60.514496,-69.1875 -108.5625,-69.1875z"/>
</svg>

Необходимо, чтобы при нажатии сердечко меняло цвет.
Реализовал таким образом:
$('#svg_2').on('click', function(){
    $(this).toggleClass('filled');
});

CSS-код
svg{
  display: block;
  width: 50px;
  height: auto;
}

#svg_2{
  fill:transparent;
  stroke:#f00;
  stroke-width:6px;
  cursor:pointer;
  transition:fill .3s;
}
#svg_2.filled{
  fill:#f00;
}

Работает, но только на первый объект, игнорируя последующие.
Как это можно исправить?
https://jsfiddle.net/pq65rbdj/2/

A: Это связанно с тем, что вы используете id и отталкиваетесь от него. id может быть только ОДИН уникальный на всю страницу. Поэтому скрипт обращается к первому, и после этого перестает выполняться. В Вашем случаи на странице несколько раз есть элемент с id="svg_2".
Стоит сделать вот так вот:
$('.js-heart').on('click', function(){
    $(this).toggleClass('filled');
});

Обращайтесь к классу svg элемента. При этом, естественно, добавьте ему класс.
<svg id="svg_2" class="svg-heart js-heart" width="640" height="480" viewbox="0 0 640 480" xmlns="http://www.w3.org/2000/svg">
   <path d="m219.28949,21.827393c-66.240005,0 -119.999954,53.76001 -119.999954,120c0,134.755524 135.933151,170.08728 228.562454,303.308044c87.574219,-132.403381 228.5625,-172.854584 228.5625,-303.308044c0,-66.23999 -53.759888,-120 -120,-120c-48.047913,0 -89.401611,28.370422 -108.5625,69.1875c-19.160797,-40.817078 -60.514496,-69.1875 -108.5625,-69.1875z"/>
</svg>

Стили:
.svg-heart {
  display: block;
  width: 50px;
  height: auto;
  fill:transparent;
  stroke:#f00;
  stroke-width:6px;
  cursor:pointer;
  transition:fill .3s;
}

.svg-heart.filled{
  fill:#f00;
}

A: Используйте классы, а не идентификаторы:

$('.heart').on('click', function(){
    $(this).toggleClass('filled');
});
svg{
  display: block;
  width: 50px;
  height: auto;
}

.heart{
  fill:transparent;
  stroke:#f00;
  stroke-width:6px;
  cursor:pointer;
  transition:fill .3s;
}
.heart.filled{
  fill:#f00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<svg width="640" height="480" viewbox="0 0 640 480" xmlns="http://www.w3.org/2000/svg">
   <path id="svg_2" class="heart" d="m219.28949,21.827393c-66.240005,0 -119.999954,53.76001 -119.999954,120c0,134.755524 135.933151,170.08728 228.562454,303.308044c87.574219,-132.403381 228.5625,-172.854584 228.5625,-303.308044c0,-66.23999 -53.759888,-120 -120,-120c-48.047913,0 -89.401611,28.370422 -108.5625,69.1875c-19.160797,-40.817078 -60.514496,-69.1875 -108.5625,-69.1875z"/>
</svg>

<svg width="640" height="480" viewbox="0 0 640 480" xmlns="http://www.w3.org/2000/svg">
   <path id="svg_2"  class="heart" d="m219.28949,21.827393c-66.240005,0 -119.999954,53.76001 -119.999954,120c0,134.755524 135.933151,170.08728 228.562454,303.308044c87.574219,-132.403381 228.5625,-172.854584 228.5625,-303.308044c0,-66.23999 -53.759888,-120 -120,-120c-48.047913,0 -89.401611,28.370422 -108.5625,69.1875c-19.160797,-40.817078 -60.514496,-69.1875 -108.5625,-69.1875z"/>
</svg>

<svg width="640" height="480" viewbox="0 0 640 480" xmlns="http://www.w3.org/2000/svg">
   <path id="svg_2"  class="heart" d="m219.28949,21.827393c-66.240005,0 -119.999954,53.76001 -119.999954,120c0,134.755524 135.933151,170.08728 228.562454,303.308044c87.574219,-132.403381 228.5625,-172.854584 228.5625,-303.308044c0,-66.23999 -53.759888,-120 -120,-120c-48.047913,0 -89.401611,28.370422 -108.5625,69.1875c-19.160797,-40.817078 -60.514496,-69.1875 -108.5625,-69.1875z"/>
</svg>


text:
Q: Script keep showing "SettingCopyWithWarning' Hello my problem is that my script keep showing below message

SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  downcast=downcast

I Searched the google for a while regarding this, and it seems like my code is somehow
assigning sliced dataframe to new variable, which is problematic.
The problem is ** I can't find where my code get problematic **
I tried copy function, or seperated the nested functions, but it is not working
I attached my code below.
def case_sorting(file_get, col_get, methods_get, operator_get, value_get):

ops = {">": gt, "<": lt}
col_get = str(col_get)
value_get = int(value_get)

if methods_get is "|x|":
    new_file = file_get[ops[operator_get](file_get[col_get], value_get)]
else:
    new_file = file_get[ops[operator_get](file_get[col_get], np.percentile(file_get[col_get], value_get))]
return new_file

Basically what i was about to do was to make flask api that gets excel file as an input, and returns the csv file with some filtering. So I defined some functions first.
def get_brandlist(df_input, brand_input):
if brand_input == "default":
    final_list = (pd.unique(df_input["브랜드"])).tolist()
else:
    final_list = brand_input.split("/")
if '브랜드' in final_list:
    final_list.remove('브랜드')
final_list = [x for x in final_list if str(x) != 'nan']
return final_list

Then I defined the main function
def select_bestitem(df_data, brand_name, col_name, methods, operator, value):

# // 2-1 // to remove unnecessary rows and columns with na values
df_data = df_data.dropna(axis=0 & 1, how='all')
df_data.fillna(method='pad', inplace=True)

# // 2-2 // iterate over all rows to find which row contains brand value
default_number = 0
for row in df_data.itertuples():
    if '브랜드' in row:
        df_data.columns = df_data.iloc[default_number, :]
        break
    else:
        default_number = default_number + 1

# // 2-3 // create the list contains all the target brand names
brand_list = get_brandlist(df_input=df_data, brand_input=brand_name)

# // 2-4 // subset the target brand into another dataframe
df_data_refined = df_data[df_data.iloc[:, 1].isin(brand_list)]

# // 2-5 // split the dataframe based on the "brand name", and apply the input condition
df_per_brand = {}
df_per_brand_modified = {}
for brand_each in brand_list:
    df_per_brand[brand_each] = df_data_refined[df_data_refined['브랜드'] == brand_each]
    file = df_per_brand[brand_each].copy()
    df_per_brand_modified[brand_each] = case_sorting(file_get=file, col_get=col_name, methods_get=methods,
                                                     operator_get=operator, value_get=value)

# // 2-6 // merge all the remaining dataframe
df_merged = pd.DataFrame()
for brand_each in brand_list:
    df_merged = df_merged.append(df_per_brand_modified[brand_each], ignore_index=True)
final_df = df_merged.to_csv(index=False, sep=',', encoding='utf-8')
return final_df

And I am gonna import this function in my app.py later
I am quite new to all the coding, therefore really really sorry if my code is quite hard to understand, but I just really wanted to get rid of this annoying warning message. Thanks for help in advance :)


text:
Q: How to let cmake find CUDA I am trying to build this project, which has CUDA as a dependency. But the cmake script cannot find the CUDA installation on the system:
cls ~/workspace/gpucluster/cluster/build $ cmake ..
-- The C compiler identification is GNU 4.7.1
-- The CXX compiler identification is GNU 4.7.1
-- Check for working C compiler: /usr/bin/gcc
-- Check for working C compiler: /usr/bin/gcc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
CMake Error at /usr/share/cmake/Modules/FindCUDA.cmake:488 (message):
  Specify CUDA_TOOLKIT_ROOT_DIR
Call Stack (most recent call first):
  CMakeLists.txt:20 (find_package)

-- Configuring incomplete, errors occurred!
I've tried adding it as an environment variable to .bashrc, to no effect:
export CUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-5.5

How do I Specify CUDA_TOOLKIT_ROOT_DIR correctly?

A: cmake mentioned CUDA_TOOLKIT_ROOT_DIR as cmake variable, not environment one. That's why it does not work when you put it into .bashrc. If you look into FindCUDA.cmake it clearly says that:

The script will prompt the user to specify CUDA_TOOLKIT_ROOT_DIR if the prefix
  cannot be determined by the location of nvcc in the system path and REQUIRED
  is specified to find_package(). To use a different installed version of the
  toolkit set the environment variable CUDA_BIN_PATH before running cmake
  (e.g. CUDA_BIN_PATH=/usr/local/cuda1.0 instead of the default /usr/local/cuda)
  or set CUDA_TOOLKIT_ROOT_DIR after configuring.  If you change the value of
  CUDA_TOOLKIT_ROOT_DIR, various components that depend on the path will be
  relocated.

So put CUDA_BIN_PATH into .bashrc or specify CUDA_TOOLKIT_ROOT_DIR to cmake:
cmake -D CUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-5.5 ..

A: Since CMake 3.8, FindCUDA is deprecated and the proper way of using CUDA in CMake projects is enabling it via project() or enable_language()
https://cmake.org/cmake/help/v3.8/release/3.8.html#cuda

A: FindCMake.cmake looks for /usr/local/cuda. In your case, that directory might not be there. Just create a symbolic link of that name to your actual CUDA installation directory:
$ sudo ln -s /usr/local/cuda-5.5 /usr/local/cuda

Your CMake should be able to generate the Makefile for your project now.

A: In terminal, type nano ~/.bashrc. Then add the following lines to the file:
export PATH=$PATH:/usr/local/cuda/bin
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib:/usr/local/lib
export CPLUS_INCLUDE_PATH=/usr/local/cuda/include

Save the file, then type source ~/.bashrc in terminal.
You may validate if CUDA path has been setup by typing nvcc --version in terminal.

A: Maybe CUDA was installed from sources (and nvcc is not in the path). Then the script can not set CUDA_TOOLKIT_ROOT_DIR because of nvcc missing. For me it worked fine after running:
sudo apt install nvidia-cuda-toolkit

(This package might require several GiB of space)

A: In my case I had to make /usr/lib/cuda point to an actual CUDA installation. So I did:
ln -s /usr/lib/cuda /home/nvidia_libraries/cuda_10.2

I had cuda_10.2 installed locally in my home folder instead of system wide.


text:
Q: Fullscreen functioning inconsistently My goal is to create a window that can resize itself and go to a fullscreen mode. The resizing works fine, but when I got to fullscreen, it will look like this:

The blue square is supposed to be centered and so is the white. I've found the cause for this but I'm not sure why it happens or how to fix it. What causes this would be if the screen's height is smaller than the window's height. So, how would I make it so that when I go to fullscreen, the background and the blue square would be centered on my screen?
import pygame
import sys
from pygame.locals import *
from math import floor

# Initialize ------------------------------------------------------------------------------------- #
pygame.init()
FPS = 60
clock = pygame.time.Clock()
SCREEN_SIZE = [800, 450]
SCREEN_RATIO = SCREEN_SIZE[0]/SCREEN_SIZE[1]
window_size = [800, 450]
screen = pygame.Surface(SCREEN_SIZE)
window = pygame.display.set_mode(window_size, RESIZABLE)
pygame.display.set_caption('Project')

monitor_size = pygame.display.list_modes()[0]
print(monitor_size)

def display_edges(surface, color=(255, 0, 0)):
    pygame.draw.aaline(surface, color, (window_size[0] - 1, 0), (window_size[0] - 1, window_size[1] - 1))
    pygame.draw.aaline(surface, color, (0, window_size[1] - 1), (window_size[0] - 1, window_size[1] - 1))
    pygame.draw.aaline(surface, color, (0, 0), (window_size[0] - 1, 0))
    pygame.draw.aaline(surface, color, (0, 0), (0, window_size[1] - 1))

full_screen = False

# Game loop -------------------------------------------------------------------------------------- #
running = True
while running:

    # Event loop --------------------------------------------------------------------------------- #
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False

        elif event.type == VIDEORESIZE:
            window_size = (event.w, event.h)
            window = pygame.display.set_mode(window_size, RESIZABLE)

        if event.type == KEYDOWN:
            if event.key == K_F5:
                full_screen = not full_screen

                if full_screen:
                    window_size_before = window_size
                    window_size = monitor_size
                    window = pygame.display.set_mode(window_size, FULLSCREEN)
                    screen = pygame.transform.scale(screen, window_size)
                else:
                    window_size = window_size_before
                    window = pygame.display.set_mode(window_size, RESIZABLE)
                    screen = pygame.Surface(SCREEN_SIZE)

    # Render ------------------------------------------------------------------------------------- #
    screen.fill((240, 240, 240))
    pygame.draw.rect(screen, (0, 100, 200), (SCREEN_SIZE[0]/2-25, SCREEN_SIZE[1]/2-25, 50, 50))

    if window_size[0]/window_size[1] > SCREEN_SIZE[0]/SCREEN_SIZE[1]:
        SCREEN_SIZE[1] = window_size[1]
        SCREEN_SIZE[0] = floor(window_size[1]*SCREEN_RATIO)
        screen = pygame.transform.scale(screen, SCREEN_SIZE)

    elif window_size[0]/window_size[1] < SCREEN_SIZE[0]/SCREEN_SIZE[1]:
        SCREEN_SIZE[0] = window_size[0]
        SCREEN_SIZE[1] = floor(window_size[0]/SCREEN_RATIO)
        screen = pygame.transform.scale(screen, SCREEN_SIZE)

    window.blit(screen, (window_size[0]/2 - SCREEN_SIZE[0]/2, window_size[1]/2 - SCREEN_SIZE[1]/2))
    display_edges(window)

    # Update ------------------------------------------------------------------------------------- #
    pygame.display.update()
    clock.tick(FPS)

pygame.quit()
sys.exit()


text:
Q: Get all .class from jar when running a class in the jar So, the problem sounds like this:
I need to get all classes that have a certain annotation in my project. I have managed to do this without any external libraries ( I literally get all .class files in src folder and check is the class has an annotation). It works fine when I run it locally ( run as java application). When I export my project as .jar and try to run the same class, of course it is not working, as my parser cant find any class. Basically, now I'm trying to get all .class files inside the jar file when running the same jar. Is there any method I can do this without adding another library like reflections ?
Thank you

A: If you really feel the need to reinvent the wheel then 3rd party libraries can still help you since most of them are open source.  In particular this is Spring's implementation of a classpath scanner and it utilizes this class to actually find the resources.
If you really want to do it without any differences in the implementation then you one way, as martijno suggested, extract the jar first.  However, if the jar isn't on your classpath then you will need something like a URLClassLoader to load the class from the jar.
Another way, is to change your current implementation to scan the classpath.  This involves using the ClassLoader.getResources method to find all classes and subpackages in a given package.  Then, whether you are using files or a jar all you have to do is get a class loader (e.g. a URLClassLoader) that contains the classes you want (or use the system class loader if they're on the classpath).


text:
Q: Compute the Volume of the Region - Confused about boundaries Compute the volume of the region bounded by the surfaces $z=0, \ y^2=x^3 \ and \ \sqrt{x} +z=2$.
I have previously computed similar questions, however there has been an integral already given, so I am confused as to how I would find the boundaries. I think a sketch would help, but difficult with it being 3d.
Edit:

$\text{Limits of z: } 0 \leq z \leq 2-\sqrt{x} \\ z = 0 \ gives \ \sqrt{x} = 2, x = 4 \text{ on xy plane} \\ \text{hence }, 0 \leq y^2 \leq x^3 \leq 64 \\ 0 \leq y \leq 8 \\ \text{Then this gives the integral:} \\ V = \int_{y=0}^8\int_{x=y^{2/3}}^4\int_{z=0}^{2-\sqrt{x}}dzdxdy \\ \text{which solves to: }64/15$
Would this be correct? I feel like I am at least moving in the right direction with this answer?

A: Yes your edited work is correct except note that the volume is double of what you wrote.
$y^2 = x^3 = 64 \implies y = \pm 8$, so $-8 \leq y \leq 8$. Using symmetry above and below xz-plane, we can write it as
$ \displaystyle V = 2 \int_{ 0}^8\int_{y^{2/3}}^4\int_{0}^{2-\sqrt{x}}dz ~ dx ~ dy = \frac{128}{15}$
Alternatively, we can change the order of integration of $dy$ and $dx$.
$ \displaystyle V = 2 \int_{ 0}^4\int_0^{x^{3/2}}\int_{0}^{2-\sqrt{x}}dz ~ dy ~ dx =  \frac{128}{15}$


text:
Q: AngularJS filter not working when filter's model is in different view which has same controller I have two views with same controller "TabsController as TabsVM". I need to use filter in second view, "item in items | filter:modelName" and modelName is in first view in an input field. Its not working, It works when I put input field in the same view where I am using filter, How can I do it without having to merge these views?
UPDATE:
well I tried a lot but not able to connect models in filter.
first_view.html

        .......
        .......
    <input type="search" class="form-control" ng-model="NavBarVM.searchInputFieldText" ng-change="NavBarVM.updateSearchInputValue()"/>
        .......
        .......

first_view.js
app.controller('NavigationBarController', ['$scope', 'NewProjectService', function ($scope, NewProjectService) {

    var vm = this;

    NewProjectService.searchInputFieldText = vm.searchInputFieldText;

    vm.updateSearchInputValue = function()
    {
        NewProjectService.updateSearchInputFieldText(vm.searchInputFieldText);
        NewProjectService.searchInputFieldText = vm.searchInputFieldText;
    };
}]);

second_view.html

        .......
        .......

        .......
        .......

second_view.js
app.controller('TabsController', ['$scope', 'NewProjectService', function ($scope, NewProjectService)
{
    var vm = this;
    vm.searchInputFieldText = NewProjectService.searchInputFieldText;
    ............
    ...........
}]);

service.js
app.service('NewProjectService', function(){
...........
...........
    var searchInputFieldText = '';
    var updateSearchInputFieldText = function(text)
    {
        searchInputFieldText = text;
    };
    return{
        updateSearchInputFieldText: updateSearchInputFieldText,
        searchInputFieldText: searchInputFieldText,
    };

});

A: Controller is a factory function that is returning an object and in your scenario you're calling your controller twice which means that you'll have two different objects in your views.
Ref. https://docs.angularjs.org/guide/controller
Update:
Try changing

to


text:
Q: Only list Item of the Array Appear in the Spinner I am Currently Developing that required to list all the counters with their cities, I am using battuta Api for this purpose, I managed to fetch to the spinner but unfortunately, only the last item appears there (Spinner)
for (int i=0; i<response.length(); i++){
                        try {
                            worldlist = new ArrayList<String>();
                            ID = response.getJSONObject(i).getString("code");
                            name = response.getJSONObject(i).getString("name");
                            // Retrieve the name on the Spinne
                            worldlist.add(name);
                            System.out.println("Name\n"+name);
                          //  System.out.println("WorldList"+worldlist.toString());

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                       ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, worldlist);
                       spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
                       spinner.setAdapter(spinnerArrayAdapter);
                       spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                           @Override
                           public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

                           }

                           @Override
                           public void onNothingSelected(AdapterView<?> adapterView) {

                           }
                       });

                   }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            System.out.println("Error"+error.getMessage());

        }
    });

    mQueue.add(request);

A: I guess your logic code is not correct, try to put wordlist declaration and init spinner adapter outside for loop.
worldlist = new ArrayList<String>();

for (int i = 0; i < response.length(); i++) {
    try {
        ID = response.getJSONObject(i).getString("code");
        name = response.getJSONObject(i).getString("name");

        // Retrieve the name on the Spinne
        worldlist.add(name);

        System.out.println("Name\n"+name);
        // System.out.println("WorldList"+worldlist.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, worldlist);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
});


text:
Q: How does this pointer arithmetic work? #include <stdio.h>

int main(void){
  unsigned a[3][4] = {
    {2,23,6,7},
    {8,5,1,4},
    {12,15,3,9}
 };
 printf("%u",*((int*)(((char*)a)+4)));
 return 0;
}

The output in my machine is the value at a[0][1] i.e 23.Could somebody explain how is this working ?
Edit: Rolling Back to old yucky code,exactly what was presented to me :P

A: The array:
unsigned a[3][4] = {
    {2,23,6,7},
    {8,5,1,4},
    {12,15,3,9}
};

is laid out in memory as (assuming a itself is at memory location 0x8000, a particular endian-ness and for a four-byte int):
0x8000  0  0  0  2
0x8004  0  0  0 23
0x8008  0  0  0  6
0x800C  0  0  0  7
0x8010  0  0  0  8
0x8014  0  0  0  5
0x8018  0  0  0 14
0x801C  0  0  0 12
0x8020  0  0  0 15
0x8024  0  0  0  3
0x8028  0  0  0  9

Breaking down the expression:
*((int*)(((char*)a)+4))

*

*((char*)a) gives you a char pointer.

*+4 advances that pointer by 4 bytes (4 * sizeof(char))

*(int*) turns the result of that back into an int pointer.

** dereferences that pointer to extract the int.

This is a very silly way of doing it since it's inherently non-portable (to environments where an int is two or eight bytes, for example).

A: It first implicitly converts the array a into a pointer to its beginning. Then it casts the pointer to char* and increments the value by 4. The value 4 happens to be the same as sizeof(unsigned) on your system, so actually it has moved one element forward from the beginningn. Then it casts the address to int* and reads the value pointed by it (operator*). This resulting value is printed as unsigned integer, which works because int and unsigned are same size.
The layout of the static 2D array in memory is so that all the elements are actually stored in sequence as a one-dimensional array.

A: So you have your array in memory as so:
2, 23, 6, 7, 8...

What this does is cast the array to a char*, which lets you access individual bytes, and it points here:
2, 23, 6, 7, 8...
^

It then adds four bytes, moving it over to the next value (more on this later).
2, 23, 6, 7, 8...
   ^

Then it turns it into an int* and dereferences it, getting the value 23.

There are technically three things wrong with this code.
The first is that it assumes that an unsigned is 4 bytes in size. (Hence the + 4). But this isn't necessarily true! Better would have been + sizeof(unsigned), ensuring correctness no matter what size unsigned happens to be.
The second problem is the cast to int: the original array was unsigned, but the value is being cast to an int. There exists values in the unsigned range that int cannot represent (because in an int half of the range is in the negatives.) So if one of the values in the array was not representable as an int (meaning the value was greater than INT_MAX), you'd get the wrong value. Better would be to convert to unsigned*, to maintain the correct type.
The last thing is the format specifier. The specifier for integers is %d, but the code uses %u, which is for unsigned integers. In effect, even though casting back to int* was wrong, printf is going to cast that value back into an unsigned*, restoring it's integrity. By fixing problem two, problem three fixes itself.
There is a hidden fourth problem: The code sucks. This may be for learning purposes, but yuck.

A: unsigned int is of size 4. i.e. sizeof(unsigned) == 4
it can hold 4 chars, each of which is a byte [in C not in Java/C# etc.].
Array is allocated consecutively in memory. When you treat unsigned array as char* you need to move the pointer 4 steps to reach next unsigned value in array.

A: First, you create a 2-dim array with size 3x4.
After ((char*)a) you can work with this as a char array. Let's designate it as b.
((char*)a)+4 is the same as b[4], it points to the 5-th element of char array (you remember, that aarays in C are 0-based). Or just 5-th byte.
When you convert the array back to int, i-th element of int array begins from i*4 byte if sizeof(int) = 4. So, on the 5-th byte the second element of int array begins that's where your pointer points. The compiler gets 4 bytes beginning from 4-th position and says it's int. That's exactly a[0][1].


text:
Q: Bitmask in big endian This isn't a question as much as it's a sanity check!
If you needed to read 4 bytes into Java as a bitmask in Big endian and those bytes were:
0x00, 0x01, 0xB6, 0x02.
Making that into an int would be: 112130
The binary would be: 00000000000000011010011000000010
The endian of a series of bytes wouldn't affect the bit position, would it?
Thanks
Tony

A: In general, if the thing you're reading from is giving you whole bytes, then you don't need to worry about the order of bits making up those bytes: it is just the order of the bytes that matters, as you correctly suppose.
The time you might have to worry about the "endianness" of individual bits is where you're actually reading/writing a stream of bits rather than whole bytes (e.g. if you were writing a compression algorithm that operated at the bit level, you'd have to make a decision about what order to write the bits in).

A: Endian-ness reflects the ordering of bytes, but not the ordering of the bits within those bytes.
Let's say I want to represent the (two-byte) word 0x9001.
If I just type this out in binary, that would be 1001000000000001.
If I dump the bytes (from lower address to higher) on a big-endian machine, I would see 10010000 00000001.
If I dump the bytes (from lower address to higher) on a little-endian machine, I would see 00000001 10010000.

A: The only thing you have to pay attention is how exactly you "read 4 bytes into Java" - that's where endianness matters and you can mess it up (DataInputStream assumes big endian). Once the value you've read has become the int 112130, you're set.


text:
Q: implement success handler with more parameters Continuing from this post of mine
passing id to ajax call
There is still something I would like to understand more.
My problem is like this
I have 2 pages (default.cshtml+click.cshtml)
In default.cshtml, I have a js code to initialize a div region with its id some image. When I click the link as mentioned in my previous post I need to change the image in this region because the new image is loaded from the database. Each image is associated with an assigned id; now that I don't know how or where I should put this initialize script because it is used by both default and click pages
function init(id)
{
   //...initialize options
   var id=document.GetElementByID("displayimg");
   //...display image
}

How can I implement the success handler in java script that has 2 or more parameters ?
$(document).ready(function ()
{
    $('.viewp').click(function ()
    {
        var responseUrl="~/click?id="+id;
        $.ajax(
        {
            type: "GET",
            data:id,
            url:responseUrl,
            success:function(data1, data2)
            {

            }
        });
    });
});

because the click.cshtml will query the database table for 2 more data values to redisplay the image, it is its new width and height :-D

A: The success function must be in the form: function (data, textStatus, jqXHR). Which means, whatever the server outputs is in data. You will have to parse data.responseText to get your data1 and data2.

A: I'd respond from your server with JSON, so something like:
{
    height: 20,
    width: 20
}

Then in your ajax call, you can just do
$.ajax({
    url: url,
    dataType: "json",
    success: function( dimensions ) {
        // Do something with dimensions.width and dimensions.height
    }
});

A: put height and width into an array and send it to ajax.
in c# code
int[] val = { 10, 20 };

and in js ajax success function
success: function(value) {
//  process value[0] which is height or width.... value[1] etc.


text:
Q: MS SQL: Performance for querying ID descending This question relates to a table in Microsoft SQL Server which is usually queried with ORDER BY Id DESC.
Would there be a performance benefit from setting the primary key to PRIMARY KEY CLUSTERED (Id DESC)? Or would there be a need for an index? Or is it as fast as it gets without any of it?
Table:
CREATE TABLE [dbo].[Items] (
    [Id] INT IDENTITY (1, 1) NOT NULL,
    [Category] INT NOT NULL,
    [Name] NVARCHAR(255) NULL,
    CONSTRAINT [PK_Items] PRIMARY KEY CLUSTERED ([Id] ASC)
)

Query:
SELECT TOP 1 * FROM [dbo].[Items]
WHERE Catgory = 123
ORDER BY [Id] DESC

A:
Would there be a performance benefit from setting the primary key to PRIMARY KEY
CLUSTERED (Id DESC)?

Given as you show is: IT DEPENDS.
The filter is on Category = 123. To find all entries of Category 123, because there is NO INDEX defined, the server has to do a table scan. Unless you havea VERY large result set, and / or some awfully comically bad configured tempdb and very low memory (because disc is only used when running out of memory for tempdb) the sorting of hte result will be irrelevant compared to the table scan.
You are literally following the wrong tail. You are WAY more likely to speed up the query by adding a non-unique index to Cateogory so that the query can prefilter the data fast based on your query condition.
If you would analzy the query plan for this query (which you should - technically we should not even ANSWER this quesstion without you showing SOME effort, and a look at the query plan is like the FIRST thing you do) you would very likely see that the time is spent on on the query, NOT the result sort.

A: Creating an index in asc or desc order does not make a big difference in "ORDER BY" when there is only one column, but when there is a need to sort data in two different directions one column in ascending order and the other column in descending order the way the index is created does make a big difference.
Look this article that do many example:
https://www.mssqltips.com/sqlservertip/1337/building-sql-server-indexes-in-ascending-vs-descending-order/
In your scenario I advise you to create an index on Category Column without include "Id" because the clustered index is  always included in non-clustered index.

A: There is no difference according to the following

A: I'd suggest defining an index on (category, id desc).
It will give you best performance for your query.

A: As others have indicated, an index on Category (assuming you don't have one) is the biggest performance boost possible here.
But as for your actual question.  For a single order by query like you have, it does not matter if the query/index is ordered by desc or asc as far as performance goes.  SQL Server can swap those easily (starting a the beginning or the end of the data structure)
Where performance becomes an issue for performance is when you:

*

*Have more than order by column

*Your index has more than one column

*Your order by is opposing the order on the index.

So, say your Primary Key had ID asc and Category asc, and then you query by ID asc and Category desc.  Then SQL Server can't use the order on the index to do the search.
There are a few caveats and gotchas.  After searching a bit, this answer seems to have them listed:
SQL Server indexes - ascending or descending, what difference does it make?


text:
Q: Getting wrong integer when trying to read through an array via linked list I've been trying to create a program that will read through a fixed array via linked list. Whenever I run my code, the program gives me a clearly inaccurate number and will not iterate through the array. Any advice on what i'm doing wrong?
#include <stdio.h>
#include <stdlib.h>

struct number
{
int array[10];
struct number *next;
};

int main()
{

    struct number array[10] = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90};

    struct number *head = 0;
    struct number *tail = 90;

    array[0].next = &array[1];
    array[1].next = &array[2];
    array[2].next = &array[3];
    array[3].next = &array[4];
    array[4].next = &array[5];
    array[5].next = &array[6];
    array[6].next = &array[7];
    array[7].next = &array[8];
    array[8].next = &array[9];
    array[9].next = NULL;

    printf("%i", array[10].array[2]);

    struct number *current = head;
    while(current != NULL)
    {
        printf("Node %i contains the element and is stored in address %p\n", current->array[0], current);
        current = current->next;
    }
}

A: The reason this isn't working is because of the initializers for struct number. More information on using C initializers can be found on the GCC website.
Struct Initializer: struct number array[10] = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90};
This is an ambiguous way of initializing a struct that evaluates to
struct number array[10];
array[0].array = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90};

Head pointer:
struct number *head = 0;
...
struct number *current = head;
while(current != NULL)

The first line, struct number *head = 0;, is equivalent to struct number *head = NULL; As is, your while loop will never be executed. You could use either head = array; or head = &array[0]; here.
Tail pointer: struct number *tail = 90;
This gives the following warning in VS2015 -
Warning C4047 'initializing': 'number *' differs in levels of indirection from 'int'

You could use tail = &array[9]; here.
Print Error: printf("%i", array[10].array[2]);
This is accessing an element outside the bounds of array. C generally uses 0-based indices, so for your definition struct number array[10], the maximum element is array[9].


text:
Q: Execve() of more than one program Say I have two programs X and Y asking for input from stdin.  X and Y are run using fork() followed by execve() from a third from say A.
What is happening is X is scheduled first.  When X reaches the scanf statement, Y gets scheduled and X never gets an input. How do I take care of it?

A: Have A mediate the input for X and Y. A can create a pipe to and from each child process. It can read a prompt from a pipe, write the prompt to standard output, read the response from standard input, and write the response to the pipe for the child process.


text:
Q: Program type already present: android.support.annotation.AnimRes This problem happened to me after i updated to the latest version of Xamarin.Forms (4.6.0)
I get this error whenever i try to build my Android Projects in Visual Studio For Mac (8.5.4)
What i tried so far:

*

*Using different versions of the Android Support libraries

*Cleaning my NuGet Cache

*Reinstalling the SDK

*Cleaning, Rebuilding, Restarting VS (several times)

Oddly i managed to get it working for a few builds after changing my support library versions from 28.0.0.3 to 28.0.0.1 manually in the csproj file. However i tried this several times and it doesn't solve the problem.
The problem occurs if i create a fresh Xamarin.Forms project aswell.
Any advice appreciated, as this is starting to be frustrating.

A: I don't know if this will help, but you should migrate to AndroidX as soon as possible, nevertheless. Xamarin has migrated to them, starting from Forms 4.5
Here is some more information about the libraries - Introducing AndroidX for Xamarin
There is a special NuGet package for the migration - Xamarin.AndroidX.Migration. Also available is a built-in functionality in Visual Studio - here
What I can suggest is you try to migrate to AndroidX libraries, since the old support libraries won't be supported from now on, and you will surely encounter some issues if not like this one, then something else will pop-up in the future.


text:
Q: Javascript navigate with payload An HTTP request can hold a payload not necessarily coming from an HTML form. I mean not being in the classical key/value format.
I would like to achieve that in JavaScript : when the user clicks on a button, a function is invoked that will issue an HTTP PUT request with text payload.
XMLHttpRequest does not seem to allow the complete page reload of the page when receiving the server answer.
On the other hand, JavaScript Navigate method does not allow payload addition.
Can you help me please ?
Thanks.

A: You need to create a hidden <form> tag with <input>s containing your payload, then submit() it.

A: If you need to use the PUT verb, then XMLHttpRequest is your only option. You cannot do a PUT with a hidden (or non-hidden) form, and you cannot set the content-transfer-encoding using a form either.
However, when the XMLHttpRequest succeeds, you can use the Document Object Model to change the contents of the page based on what the server returns.
So for example, you could remove all the existing elements, and replace them with the HTML returned by the server. Or you could redirect the user to a different page.


text:
Q: Invalid gemspec when trying to exec rake After executing command:
 sudo bundle exec rake snorby:setup

I get the error:
 Invalid .gemspec format in '/var/lib/gems/1.8/specifications/dm-active_model-1.2.1.gemspec
WARNING:  #<ArgumentError: Illformed requirement ["#<YAML::Syck::DefaultKey:0x7f8cb7e8a1c0> 1.2.3"]>

I am pretty new to ruby, just trying to install a program. Anyone have any ideas on this?
greenlantern@greenlantern:~/snorby/snorby$ ruby -v
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]

A: From what has been said I'd assume that you use rvm, rbenv or similar, which are not loaded when you use sudo. So in sudo, you get ruby 1.8.
Why do you use sudo anyway? Try to run just bundle exec rake snorby:setup, without sudo.

A: What version of ruby are you using? Snorby only supports ruby >= 1.9.2. Hope this helps.


text:
Q: Unable to resolve dependency for ':app@releaseUnitTest/compileClasspath' Unable to resolve dependency for ':app@releaseUnitTest/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0. Open File Show Details
Could not resolve com.android.support:appcompat-v7:26.1.0.
Required by:

Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Could not GET 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  dl.google.com

A: Do you have this on your gradle repositories ?
If you're using a version of Gradle lower than 4.1
maven {
    url 'https://maven.google.com'
}

else :
google()


text:
Q: Get All the associations that belongs to the federation where president_id = user_id In Laravel 5.2 I have 3 tables :
Federation - Association - User
An Association belongsTo a federation.
A Federation hasMany Association
Federation has a president : president_id that refers to User Model
Association has a president : president_id that refers to User Model
What I want to get:
All the associations that belongs to the federation that have the president_id == Auth::user()->id
I tried:
$associations = Association::with(['federation' =>function($query){
        $query->where('federation.president_id', Auth::user()->id);
    }])->get();

And also:
    $associations = Association::with('federation')
        ->where('federation.president_id', Auth::user()->id)
        ->get();

But in the first case, I get all the association with the federation relationship to null, and in the second case, it doesn't know federation.president_id as it queries table 'association'
Any idea what's wrong?

A: with() only modifies the eager loaded relationships. In order to modify a query based on its relationships, you're looking for whereHas():
$associations = Association::whereHas('federation', function($query) {
        $query->where('president_id', Auth::user()->id);
    }])
    ->get();


text:
Q: Native Ads overlapped RecyclerView items I try to implement Native Ads inside RecyclerView. The ad should be placed every 3 items in recycler view. I use a native ads template. Ads are loaded but they have overlapped items in RecyclerView. I try couple of solution but they didn't work. Please help me, thank you in advance.
Below is the code for Adapter class:
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

Context c;
ArrayList<Model> models;

private static final int CONTENT_TYPE = 1;
private static final int AD_TYPE = 0;

public MyAdapter(Context c, ArrayList<Model> models) {
    this.c = c;
    this.models = models;
}

@Override
public int getItemViewType(int position) {
    if (position % 3 == 0) {
        return AD_TYPE;
    } else {
        return CONTENT_TYPE;
    }

}

class adViewHolder extends RecyclerView.ViewHolder {
    TemplateView adTemplate;

    public adViewHolder(@NonNull View itemView) {
        super(itemView);
        adTemplate = itemView.findViewById(R.id.native_ad);
    }
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    if (viewType == AD_TYPE) {
        adViewHolder myadViewHolder = new adViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_ads, null, false));
        return myadViewHolder;
    } else {
        MyHolder myHolder = new MyHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.single_list_item, null, false));
        return myHolder;
    }
}

@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
    if (getItemViewType(position) == CONTENT_TYPE) {

        ((MyHolder) holder).mTitle.setText(models.get(position).getTitle());
        ((MyHolder) holder).mDescription.setText(models.get(position).getDesc());
        ((MyHolder) holder).mImageView.setImageResource(models.get(position).getImage());
    } else if (getItemViewType(position) == AD_TYPE) {
        final AdLoader adLoader = new AdLoader.Builder(c, "ca-app-pub-3940256099942544/2247696110")
                .forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
                    @Override
                    public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
                        NativeTemplateStyle styles = new NativeTemplateStyle.Builder().build();
                        TemplateView template = ((adViewHolder) holder).adTemplate;
                        template.setStyles(styles);
                        template.setNativeAd(unifiedNativeAd);
                    }
                })
                .withAdListener(new AdListener() {
                    @Override
                    public void onAdFailedToLoad(int errorCode) {

                    }
                })
                .withNativeAdOptions(new NativeAdOptions.Builder()
                        .build())
                .build();
        adLoader.loadAd(new AdRequest.Builder().build());
    }
}

@Override
public int getItemCount() {
    return models.size();
}


text:
Q: Spring Security OAuth2 Setting Custom Error Page I am currently implementing Spring Security OAuth2 and would like to provide my own custom error page when an OAuth2Exception is thrown.  Currently there is a Framework endpoint in WhitelabelErrorEndpoint.java that is mapped to /oauth/error, which provides the default error handling.  The reference docs claim:

All you need to do is provide a Spring MVC controller with @RequestMappings for those endpoints, and the framework defaults will take a lower priority in the dispatcher.

However, in practice I am not seeing my Spring controller taking priority over the Whitelabel default.  What am I doing wrong?
Example Controller:
@Controller
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class OAuthExceptionController {

    private static final Logger logger = LoggerFactory.getLogger(OAuthExceptionController.class);

    @RequestMapping("/oauth/error")
    public ModelAndView defaultOAuthErrorHandler(HttpServletRequest request) throws Exception {
        logger.error("Oauth2 exception occurred");
        Map<String, Object> model = Maps.newLinkedHashMap();
        model.put("path", request.getServletPath());
        return new ModelAndView("error/accessDenied", model);
    }
}


text:
Q: Using arsenal function tableby to create multiple columns and adding specific numeric stat to one row I'd like to point out, that this is my second week into coding so it's all new to me.
I've tried to search for answers to my questions, but have failed so far, so I thought I'd try and ask on here. I have two questions:
First, I've successfully created a table using arsenal's tableby function - so far so good. Using "countpct" as my numeric stats, so I have my overall numbers and percentages, my string:
Table1 <- tableby( ~ sex + agehilo + HiloDOW + URV.Y.N + URV.days + triagefactorsum + chronicdisease + death , data = all_data1, control = mycontrols)

I would now like to include two more columns in my Table1, so I have three total. One with "overall" and one with URV.Y.N = 1 and one with URV.Y.N = 0. (URV.Y.N is either 1 or 0)
I have tried:
Table1 <- tableby(URV.Y.N ~ sex + agehilo + HiloDOW + URV.Y.N + URV.days + triagefactorsum + chronicdisease + death , data = all_data1, control = mycontrols)

Which gets me my two extra columns, in the correct manner, so now I'm now to "fuse" the two - so I get one table, with three columns:
Table1 <- tableby(overall + URV.Y.N ~ sex + agehilo + HiloDOW + URV.Y.N + URV.days + triagefactorsum + chronicdisease + death , data = all_data1, control = mycontrols)

This is not working - I've tried a myriad of other things as well, so I'm hoping someone has a way to get all three colums into one table.
My second question is simpler, but equally frustrating: How do I get URV.days to show up only as the median?
I've tried:
Table1 <- tableby( ~ sex + agehilo + HiloDOW + URV.Y.N + URV.days(numeric.stats=c("median")) + triagefactorsum + chronicdisease + death , data = all_data1, control = mycontrols)

and
Table1 <- tableby( ~ sex + agehilo + HiloDOW + URV.Y.N + URV.days("median") + triagefactorsum + chronicdisease + death , data = all_data1, control = mycontrols)

In both cases, I get: "Error in URV.days: Could not fund function "URV.days".
The line of codes words fine if I don't put anything after "URV.days" - I just don't get the output I'm looking for.


text:
Q: C#: How to initialize an object and all it's attributes Is there any way in C# to initialize an object without the need of initializing his attributes to use them?
I find myself mapping json objects in to classes and I wonder if it's inefficiento to do stuff like this:
Class1 object1 = new Class1 ();
object1 .Name = new Class2 ();
object1 .Name.Content = "name";

I don't want to use initializers for code clarity to avoid stuff like:
Class1 obj1 = new Class1 ()
{
    Name = new Class2()
    {
        Content = "name"
    }
 };

This looks fine, but the models I have to work with are usually big and with many layers and ends up beeing a bit of an unreadeable cluster if I use initializers.
I can not change the models I recieve so simplifying the models is not an option either.
Is there any way were I can do something like:
Class1 object1 = new Class1 ();
object1.Name.Content = "name";

That automatically implement Name = new Class2() implicitly?
Allowing me to avoid the Name is not initialized exception. I know I can do my own constructors and initialize it's attributes in them, but there's already a LOT of code done and it's not feasble anymore to do this.
And if is not possible, I am interested in any alternative ways that could help me to reduce some code initializing attributes.

A: You can't implicitly instantiate a property, no. It must be instantiated somewhere.
What you could do, to enable the syntax you're wanting, is instantiate it within the Class1 constructor or in the property declaration. For example:
public class Class1
{
  public Class2 Name { get; set; } = new Class2();
}

Demo: https://dotnetfiddle.net/ZySMLX
or
public class Class1
{
  public Class2 Name { get; set; }

  public Class1()
  {
    this.Name = new Class2();
  }
}

Demo: https://dotnetfiddle.net/Sbd2wP
But obviously this has its own side-effects - I don't know if you want to force that to be always instantiated in this way, or if there are scenarios in your application where that wouldn't be desirable.

P.S. You said this situation arose because you were

mapping json objects in to classes

...but surely this is something that should be done by an automated serialisation library, rather than writing all these instantiations out in literals. It's not clear precisely what the scenario was. I've answered your question directly, but  I would potentially question whether this is actually the best approach to your overall problem.


text:
Q: Extract Instagram Follower/Following Data I wanted to extract Instagram Follower/Following Data(other user, not my own) and also the names/userid of the Follower/Following. I have searched through the forum but so far what I found is that need authentication before could access any basic data from the Instagram user.
May I know is it possible not to go through the authentication but still able to pull the relationship data (following/follower) data?
What I am trying to achieve here is to track for example do a data analysis of how many followers does a particular public profile of a instagram user has (i.e. maybe some newly opened toy shop that has started a instagram profile). Authenticating each and every single shops that have started a public instagram profile is not feasible. Hence, would there be a way to extract that data using going through the authentication process as described by the API?
Thanks.

A: My answer is that you need need authentication with some IG account first. After that, the information is all available as long as the account you are looking at is 'public'

A: API doesn't provide the list of follower anymore even if you are authentificate
You need to do some other technique like the web scraping one (parse the code of the HTML )

A: This is seriously not my area and the question I was answering to has been closed.
I have spent so long trying to figure this out and although it is a very different solution it's probably going to work for longer.
Open your browser in Mobile mode (no idea how to do).
I have used a python script which did this for me but I will update it with help from the comments
Open a New Tab, acess the profile you want to explore and press followers/following respectively.
Looking at the list of followers/folowing
Inspect any element and go to 'Console' at the top
On the console, paste this and hit Enter.
const arrHtml = document.getElementsByClassName('_ab8w  _ab94 _ab99 _ab9f _ab9m _ab9p  _abb- _abcm');

while (!!arrHtml.length) {
  arrHtml[0].parentNode.removeChild(arrHtml[0])
}

And this
const arrHtml = document.getElementsByClassName('_ab8w  _ab94 _ab99 _ab9f _ab9m _ab9p  _abbj _abcm');

while (!!arrHtml.length) {
  arrHtml[0].parentNode.removeChild(arrHtml[0])
}

And this
const arrHtml = document.getElementsByClassName('_ab8y  _ab94 _ab99 _ab9f _ab9m _ab9p  _aba_ _abcm');

while (!!arrHtml.length) {
  arrHtml[0].parentNode.removeChild(arrHtml[0])
}

And this
const arrHtml = document.getElementsByClassName('_ab8w  _ab94 _ab97 _ab9h _ab9k _ab9p  _abb0 _abcm');

while (!!arrHtml.length) {
  arrHtml[0].parentNode.removeChild(arrHtml[0])
}

Now that everything has been stripped away, except for the usernames.
Click anywhere and use Ctrl + A
Copy (Ctrl + C)
And paste (Ctrl + V) wherever you like. enjoy'


text:
Q: Can a PHP script be scheduled to run at a specific time or after a specific amount of time has expired? I am writing a social cloud game for Android and using PHP on the server.  Almost all aspects of the game will be user or user-device driven, so most of the time the device will send a request to the server and the server will, in turn, send a response to the device.  Sometimes the server will also send out push messages to the devices, but generally in response to one user's device contacting the server.
There is one special case, however, where a user can set a "timer" and, after the given time has elapsed, the server needs to send the push messages to all of the devices.  One way to do this would be to keep the timer local to the user's device and, once it goes off, send the signal to the server to send the push messages.  However, there were several reasons why I did not want to do it this way.  For instance, if the user decides not to play anymore or loses the game, the timer should technically remain in play.
I looked around for a method in PHP that would allow me to do something like this, but all I came up with were alarms, which are not what I need.  I also thought of cron jobs and, indeed, they have been recommended for similar situations on this and other forums, but since this is not a recurring event but, rather, a one time event to take place at an arbitrary point in time, I did not know that a cron job is what I want either.
My current best solution involves a cron job that runs once a second and checks to see if one of these events is to occur in the next second and, if so, sends out the push messages.  Is this the proper way to handle this situation, or is there a better tool out there that I just haven't found yet?

A: cron is great for scripts run on a regular basis, but if you want a one-off (or two-off) script to run at a particular time you would use the unix 'at' command, and you can do it directly from php using code like this:
/****
 * Schedule a command using the AT command
 *
 * To do this you need to ensure that the www-data user is allowed to
 * use the 'at' command - check this in /etc/at.deny
 *
 *
 * EXAMPLE USAGE ::
 *
 * scriptat( '/usr/bin/command-to-execute', 'time-to-run');
 * The time-to-run shoud be in this format: strftime("%Y%m%d%H%M", $unixtime)
 *
 **/

function scriptat( $cmd = null, $time = null ) {
    // Both parameters are required
    if (!$cmd) {
        error_log("******* ScriptAt: cmd not specified");
        return false;
    }
    if (!$time) {
        error_log("******* ScriptAt: time not specified");
        return false;
    }

    // We need to locate php (executable)
    if (!file_exists("/usr/bin/php")) {
        error_log("~ ScriptAt: Could not locate /usr/bin/php");
        return false;
    }

    $fullcmd = "/usr/bin/php -f $cmd";

    $r = popen("/usr/bin/at $time", "w");
    if (!$r) {
        error_log("~ ScriptAt: unable to open pipe for AT command");
        return false;
    }
    fwrite($r, $fullcmd);
    pclose($r);

    error_log("~ ScriptAt: cmd=${cmd} time=${time}");

    return true;
}

A: soloution 1 :
your php file can include a ultimate loop
$con = true;
 while($con)
   {
   //do sample operation
   if($end)
      $con = false;
   else
   sleep(5); // 5 seconds for example
   }

soloution 2 :
use cron jobs -- Depend on yout CP you can follow the instruction and call your php program at the specific times
limit : in  cron job the minimum time between two calling is 1 minute

soloution 3 :
use a shell script and call your php program when ever you want

A: You can make PHP sleep for a certain amount of time - it will then resume the code afterwards but this is seriously not recommended because when a script sleeps it still uses up processor resources, and if you had multiple scripts sleeping for long periods of time it would put impossible load on your server.
The only other option that I know of is Cron. As @Pete says, you can manage Cron jobs from within PHP, e.g.:
http://net.tutsplus.com/tutorials/php/managing-cron-jobs-with-php-2/
This is going to involve a fair bit of coding, but I think it is your best options.
Another option is to have your user's browser call a PHP function using an Ajax request and JavaScript's setTimeout as suggested by the accepted answer in this question:
how to call a function in PHP after 10 seconds of the page load (Not using HTML)


text:
Q: JSX parsing in React but not parsing in dependency (webpack, babel) I have a React app using JSX which works fine until I import a dependency which also uses JSX, at which point I receive the following error message:
ERROR in ./node_modules/simple-test-react-app/src/Component.js 9:9
Module parse failed: Unexpected token (9:9)
You may need an appropriate loader to handle this file type.
|
|   render() {
>       return
I'm a super simple thing!

|   }
| }
 @ ./src/App.js 4:0-46
 @ multi (webpack)-dev-server/client?http://localhost:3101 ./src/App.js

The interesting thing is that the JSX parses just fine everywhere EXCEPT for the dependency. I suspect this probably has something to do with how webpack and/or babel are configured, but after a lengthy search, I'm as lost as ever. It's also possible I need to fix something in the dependency (which is also mine).
Here's a link to a barebones app github repo that exhibits the problem. And here's a link to the dependency. For simplicity, I've also included some code snippets below (from the parent, NOT the dependency):
App.js (if I remove the 3rd import statement, is parses just fine)
import React from "react";
import ReactDOM from "react-dom";

//Problem is here. The problem goes away when this is commented out.
import Component from "simple-test-react-app";

ReactDOM.render(
Hello world
, document.getElementById("app"));

Webpack.config.js
const path = require("path");
const port = 3101;
const APP_DIR = path.resolve(__dirname, "src");

const config = {
    entry: [
        APP_DIR + "/App.js",
    ],
    output: {
        filename: "app.[contenthash].js",
    },
    mode: "development",
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader",
                },
            },
        ],
    },
    resolve: {
        extensions: [
            "*",
            ".js",
        ],
    },
    devServer: {
        compress: true,
        port: port,
    },
};

module.exports = config;

Any help would be greatly appreciated.

A: Babel doesn't process your dependency because of exclude: /node_modules/. Remove that and it should work.