text:
Q: Two '==' equality operators in same 'if' condition are not working as intended I am trying to establish equality of three equal variables, but the following code is not printing the obvious correct answer which it should print. Can someone explain, how the compiler is parsing the given if(condition) internally?
#include<stdio.h>
int main()
{
        int i = 123, j = 123, k = 123;
        if ( i == j == k)
                printf("Equal\n");
        else
                printf("NOT Equal\n");
        return 0;
}

Output:
manav@workstation:~$ gcc -Wall -pedantic calc.c
calc.c: In function 'main':
calc.c:5: warning: suggest parentheses around comparison in operand of '=='
manav@workstation:~$ ./a.out
NOT Equal
manav@workstation:~$

EDIT:
Going by the answers given below, is the following statement okay to check above equality?
if ( (i==j) == (j==k))

A: You need to separate the operations:
  if ( i == j && i == k)

A: Expression
i == j == k

is parsed as
(i == j) == k

So you compare i to j and get true. Than you compare true to 123. true is converted to integer as 1. One is not equal 123, so the expression is false.
You need expression i == j && j == k

A: I'd heed the compiler's warning and write it as (i==j) && (j==k). It takes longer to write but it means the same thing and is not likely to make the compiler complain.

A:   if ( (i == j) == k )

  i == j -> true -> 1
  1 != 123

To avoid that:
 if ( i == j && j == k ) {

Don't do this:
 if ( (i==j) == (j==k))

You'll get for i = 1, j = 2, k = 1 :
 if ( (false) == (false) )

... hence the wrong answer ;)


text:
Q: Signed variant of the Flint Hills series I asked my Calculus 2 students to come up with a series the convergence of which they are unable to decide. One of the students, Denis Zelent, invented a very interesting one:
$$
 \sum_{n = 1}^\infty \frac{1}{n^2 \sin n} \, . \tag{1}
$$

Question (short version): Has convergence of this series been studied in literature?

My immediate answer was that this must have something to do with the irrationality measure $\mu$ of $\pi$. Obviously, $\mu \geqslant 2$, and the best currently known upper bound for $\mu$ is $\mu \leqslant 7.6063\!\ldots\,$, due to Salikhov; see [V. Kh. Salikhov, On the Irrationality Measure of $\pi$. Russ. Math. Surv 63(3):570–572, 2008]. It is widely believed that $\mu = 2$.
In fact, the inequality $\mu < 3$ is equivalent to convergence of $1 / (n^2 \sin n)$ to zero. Thus if we knew that $\mu \geqslant 3$, the series (1) would diverge. On the other hand, if we had $\mu < 2$ (which is of course absurd), then one could easily show that $1 / (n^2 \sin n) = O(n^{-1 - \varepsilon})$ for some $\varepsilon > 0$, which would imply absolute convergence of the series (1).
My student searched the web and realized that his question is related to the well-known open problem, asking whether the Flint Hills series
$$
 \sum_{n = 1}^\infty \frac{1}{n^3 \sin^2 n} \tag{2}
$$
converges. An extension of this problem asks for convergence of a more general series
$$
 \sum_{n = 1}^\infty \frac{1}{n^p |\sin n|^q} , \tag{3}
$$
which is equivalent to absolute convergence of the series (1) when $p = 2$ and $q = 1$. For more details, see [Max. A. Alexeyev, On convergence of the Flint Hills series, arXiv:1104.5100, 2011].
To summarise, this is what we have found so far:

*

*lack of convergence of $1 / (n^2 \sin n)$ to zero would imply that $\mu \geqslant 3$, which is very unlikely;

*convergence (in particular: absolute convergence) of the series (1) would imply $\mu \leqslant 3$, which means it is certainly an open problem;

*lack of absolute convergence of the series (1) would not have any consequences for the estimates of $\mu$.

Question (long version)

*

*Does absolute convergence of the series (1) imply any tighter bounds on the estimates of the irrationality measure $\mu$ of $\pi$?

*Vice versa: Assuming that $\mu$ is known, can one tell whether the series (1) converges absolutely?

*Same questions with absolute convergence changed into convergence. In other words: are cancellations of any help here?

*Does the series (1) has a fancy name, similar to Flint Hills series and Cookson Hills series? (And if not: can Denis choose an appropriate mountain range?)

Edited: I just noticed David Simmons's answer to an MO question on the Flint Hills series, which reduces the question of its convergence to a similar question for a series involving convergents of $\pi$. The same argument should work for the absolute convergence of the series (1), but I do not see right away if it leads to an answer to question 1.

A: You mentioned my argument from the other thread, which can be used to show that if $\mu(\pi) < 3$, then your series converges. But this also means you can't get any further information about $\mu(\pi)$ from knowing that your series converges -- it would converge if $\pi$ were any of the numbers with exponent of irrationality $<3$, so you cannot rule out $\pi$ being any of those numbers (I know I am speaking of $\pi$ as though it were a variable, but this is necessary in order for questions like "does A imply B?" to make sense when A and B are fixed) In other words, the answer to question 1 is "No".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Run command on logout, *before* encrypted home is unmounted I'm running 14.04 LTS with an encrypted home directory.  I've got a service (profile-sync-daemon) needs access to files in my home directory when it starts and stops, so needs to start after the encryped files are mounted and stop before they're unmounted.  Starting the service at the right time can be achieved running service psd start from Startup Applications.  Where can I put the service psd stop command?
I've tried using session-cleanup-script in /etc/lightdm.conf, but that seems to run too late.

A: The well-known Upstart event emitted when the desktop is shutting down is "desktop-end" (and there is also a corresponding "desktop-start"). Hence, something like the following should work:
mkdir -p ~/.config/upstart/
cat <<EOT|tee ~/.config/upstart/psd.conf
start on desktop-start
stop on desktop-end

exec psd

EOT

Note: you'll need to change that exec line to the command to start the psd daemon. Alternatively, you could create a job without an exec stanza and instead call commands to start and stop the daemon like this:
post-start exec command-to-start-psd
pre-stop exec command-to-stop-psd

I've never used psd, but your question seems to suggest it is running as root? If so, I think you should investigate if it is possible to run an instance of the daemon as your user (safer and will make it easier to create the Upstart job).
For more details on well-known upstart events:

*

*man upstart-events
(or http://upstart.ubuntu.com/cookbook/#ubuntu-well-known-events-ubuntu-specific)

See also:

*

*http://upstart.ubuntu.com/cookbook/#exec

*http://upstart.ubuntu.com/cookbook/#script

*http://upstart.ubuntu.com/cookbook/#expect

*http://upstart.ubuntu.com/cookbook/#run-a-job-as-a-different-user


text:
Q: Laravel Ajax JSON Object is empty I'm working on a laravel web app, I'm relatively new to laravel so I'm not very familiar with the ajax tokens and such, but I believe I have set it up correctly.
Below is my Ajax code for a test page that I want to try and send data from.
<meta name="csrf-token" content="{{ csrf_token() }}">

Here is my form:

    <form action="testSend" method="post" enctype="multipart/form-data">

        <button type="submit" id="btn"> submit</button>
    </form>

And here is a simple route that I have setup just to test this:
Route::post('testSend', function (Request $request) {
    return response()->json($request);
});

However when I go to check the network in chrome, the JSON Object is empty.
The empty JSON Object:

I'm pretty new to this, I have learned it but never really tried to create a web app until now. I have searched everywhere, but no one seemed to have the same problem, maybe they did but I just don't know.
The problem might just be a dumb mistake, but I really can't figure it out ):
Thanks.

A: Rather than passing Request instance try this:
return response()->json($request->all());


text:
Q: The ::after selector for external links is positioned with the text I was editing my profile when I noticed this:
On SO

On Code Review.SE

The ::after content should have a little margin from the text itself. Currently, it hinders the readability.


text:
Q: How to control the opacity of a container's background in CSS? How can i control the opacity of a picture or background color of a container or a button or a form in CSS?
Which property should use?

A: You can use the RGBA system. The A stands for Alpha which mean the opacity of the color. So let's say you want to have a transparency of 50% you have to use this code:
background-color: rgba(0,0,0,0.5);


text:
Q: How can I add padding to the container in the Skeleton Framework? I'm using the Skeleton Framework (http://getskeleton.com) and I want a page that has a background color and a white container page.
If I add .container {padding:0 10px;} the layout breaks when resizing the window for small devices.  Hopefully I'm missing something very obvious here.  How can I add padding to the container without breaking the responsive design?

A: My solution to this was found here, if I understand your post correctly.

Since this has a white background, I want some padding inside the box.
  Simple enough: I added a  inside the parent one and styled it
  appropriately with padding: 10px and a white background.

CSS
div.inner {
    padding: 4px 4px 8px 12px;
    overflow:auto;
}

HTML

You are not...

Result
http://home.grandecom.net/~scottmorse/

A: This is unfortunate with skeleton.
Note that your .container.column and .container.columns classes each have a 10px padding. By nesting your columns in containers correctly you get consistent padding.
One solution is to use the offset-by-one class, which gives you a 60px padding to the left.
Finally, you can hack the core classes in skeleton.css, adding the padding you need to each element and shrinking their widths.

A: You'll need to edit skeleton.css (or over-ride it with your own stylesheet) for the smaller media queries.
Comment out the rule that removes the padding and reduce the .container .one.column (and so-on) rule by 20px. This will leave you with the correct size and a nice 10px margin down both sides. :)
    /* Note: Design for a width of 320px */

@media only screen and (max-width: 767px) {
    .container { width: 300px; }

    /* removed to maintain margins
    .container .columns,
    .container .column { margin: 0; } */

    .container .one.column,
    .container .one.columns,
    .container .two.columns,
    .container .three.columns,
    .container .four.columns,
    .container .five.columns,
    .container .six.columns,
    .container .seven.columns,
    .container .eight.columns,
    .container .nine.columns,
    .container .ten.columns,
    .container .eleven.columns,
    .container .twelve.columns,
    .container .thirteen.columns,
    .container .fourteen.columns,
    .container .fifteen.columns,
    .container .sixteen.columns,
    .container .one-third.column,
    .container .two-thirds.column  { width: 280px; } /* this was reduced by 20px */
}

As an aside,  I need to write a solution for device width 601px for Nexus 7.

A: I could be misunderstanding your problem, but have you tried adding margins instead of padding
eg.

              Your text etc here

where the content class has margin-left:10px;

A: You can add padding if you use box-sizing to whatever DIV you want to add padding to. This will calculate the width of the div with the padding into consideration.
.someElementInSkeletonGrid {
    box-sizing: border-box;
}

I've been able to successfully add padding to Skeleton DIV's by using this. Browser support is pretty good too.
Read More:
http://css-tricks.com/box-sizing/
Browser Support:
http://caniuse.com/#feat=css3-boxsizing


text:
Q: Check pixel color and trigger a bash script How can we check the color of a determined pixel(x,y) and, if it is equal to a certain value, run a bash script.
In particular I'd like to write a script that:

*

*Wait for a determined key being pressed (in particular 'j' or 'f' or 'space' or 'y').

*Compare the color of 4 pixels to a color. If we found that one or
more (if there are more we can pick the first or a random one) we
can go to step 2.

*Run a bash script.

*Go to step 1.

I know only how to complete step 3, the first 2 steps are out of my coding skill.
Can you help me?

A: I don't know about the first step, but you could take a screenshot and use ImageMagick to print the colors of pixels.
tmp=/tmp/$(uuidgen).png
trap "rm $tmp" exit
screencapture $tmp
/usr/local/bin/convert $tmp[1x1+1000+500] $tmp[1x1+1100+500]\
$tmp[1x1+1000+510] $tmp[1x1+1100+510] txt: | grep '#FFFFFF' || exit

A: As for checking for keystrokes, I use this command line tool:
http://www.klieme.ch/pub/checkModifierKeys.zip
, which is discussed on macscripter.net (sorry, can't post this as link).
This command line command is utilized in a similar fashion to what I describe below ("do shell script").
Another command line tool is used to get the pixel position of the mouse:
www.bluem.net/en/mac/cliclick/
(again, sorry for inability to post this as link).
For getting pixel color ...
See my blog post about using python for this (my method is based on similar solutions):
http://thechrisgreen.blogspot.com/2013/04/python-script-for-getting-pixel-color.html
I have an AppleScript script that does "do shell script" with this python script, sets a variable "rgb" to the (string) result, then does
run script rgb

which gets you a list like
{255,255,255}

Seeing this rather late in the game ... this is for future surfers I guess ...


text:
Q: How to refresh SMS Listview automatically ? I am creating SMS app. I am sending and receiving SMS with my application and then can show them in ListView. But listview doesn't get updated as soon as I send or receive SMS. I have to press back button , after that if I again go to ListView Activity then new SMS are shown.
How can I make listview refresh automatically as soon as sms arrives or is send ?
Code is :
public class ChatActivity extends ListActivity {

private MyListAdapter adapter;
ArrayList<String> item_id = new ArrayList<String>();
ArrayList<String> item_phone_num = new ArrayList<String>();
ArrayList<String> item_msg_body = new ArrayList<String>();
ArrayList<String> item_time = new ArrayList<String>();
ArrayList<String> item_flag = new ArrayList<String>();
ArrayList<String> items = new ArrayList<String>();
private Button btn_send;
DbManager manager;
Cursor Cursor;
ViewHolder holder12;
String contact_for_chat;
String contact_no;
String message_body = "";
Calendar c;
SimpleDateFormat sdf;
String time;
EditText et_chat;
String flag;
String msg = "";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Bundle bundle = getIntent().getExtras();
    contact_for_chat = bundle.getString("contact_name");
    contact_for_chat = contact_for_chat.replace(" ", "");
    contact_no = Util.getContactNumber(contact_for_chat, ChatActivity.this);
    Toast.makeText(getApplicationContext(), contact_no, Toast.LENGTH_LONG).show();
    final ViewHolder holder = new ViewHolder();
    manager = new DbManager(this);
    Cursor = manager.Return_All(contact_no);
    showEvents(Cursor);

    c = Calendar.getInstance();
    sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
    time = sdf.format(c.getTime());
    setActionBar();
    findViewsById();
    adapter = new MyListAdapter(this);
    adapter.notifyDataSetChanged();
    setListAdapter(adapter);

    btn_send = (Button) findViewById(R.id.button1);
    btn_send.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

            SendSMS();
        }
    });
}

protected void SendSMS() {
    SmsManager sms_manager = SmsManager.getDefault();
    message_body = et_chat.getText().toString();
    ArrayList<String> parts = sms_manager.divideMessage(message_body);
    sms_manager.sendMultipartTextMessage(contact_no, null, parts, null, null);
    flag = "1";
    manager.Insert_sms_data(time, contact_no, message_body,flag);
    msg+= "SMS to :" + contact_for_chat + " \n";
    msg += "having number:" + contact_no + " \n";
    msg += "as" +message_body + " \n";
    msg += "at"+ time + " \n";
    Toast.makeText(getApplicationContext(), ""+msg , Toast.LENGTH_LONG).show();

}

private void setActionBar() {
    ActionBar mActionBar = getActionBar();
    mActionBar.setDisplayHomeAsUpEnabled(false);
    mActionBar.setDisplayShowTitleEnabled(false);
    LayoutInflater mInflater = LayoutInflater.from(this);
    View mCustomView = mInflater.inflate(R.layout.actionbar_chat, null);
    TextView tv_chat = (TextView)mCustomView.findViewById(R.id.title_text);
    tv_chat.setText(contact_for_chat);
    ColorDrawable colorDaawable = new ColorDrawable(Color.parseColor("#CFCFC4"));
    mActionBar.setBackgroundDrawable(colorDaawable);
    mActionBar.setLogo(R.drawable.ic_launcher);
    mActionBar.setDisplayHomeAsUpEnabled(true);
    mActionBar.setCustomView(mCustomView);
    mActionBar.setDisplayShowCustomEnabled(true);
}

private void findViewsById() {
    et_chat = (EditText)findViewById(R.id.et_chat);
    btn_send = (Button)findViewById(R.id.btn_send);
}

private void showEvents(Cursor cursor) {

    item_id = new ArrayList<String>(cursor.getCount());
    item_phone_num = new ArrayList<String>(cursor.getCount());
    item_msg_body = new ArrayList<String>(cursor.getCount());
    item_time = new ArrayList<String>(cursor.getCount());
    item_flag = new ArrayList<String>(cursor.getCount());
    int i=0;
    while (cursor.moveToNext()) {
        item_id.add(i+"");
        item_time.add(cursor.getString(1));
        item_msg_body.add(cursor.getString(3));
        item_phone_num.add(cursor.getString(2));
        item_flag.add(cursor.getString(4));
        i++;
    }

  }
public class MyListAdapter extends BaseAdapter {
    Context con;
    private LayoutInflater layoutinf;
    ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
    ArrayList<String> items_ = new ArrayList<String>();

    public MyListAdapter(ChatActivity context) {
        con = context;
    }

    public int getCount() {
        return item_id.size();
    }

    public Object getItem(int position) {
        return item_id.size();
    }

    public long getItemId(int position) {
        return item_id.get(position).hashCode();
    }

    public View getView(final int position, View arg1, ViewGroup arg2) {

        View v = arg1;
        ViewHolder holder = null;
        if (v == null) {
            layoutinf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = layoutinf.inflate(R.layout.row_chat, null);
            holder = new ViewHolder();

            holder.tv_contact = (TextView) v.findViewById(R.id.phone_num);
            holder.tv_sms_body = (TextView) v.findViewById(R.id.msg_body);
            holder.tv_time = (TextView) v.findViewById(R.id.time);

            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }

        if(item_flag.get(position).equals("1"))
        {
            holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_green);

        }
                    else
                    {
                        holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_yellow);

                    }

        holder.tv_contact.setText("" + item_phone_num.get(position));

        holder.tv_sms_body.setText(item_msg_body.get(position));

        holder.tv_time.setText(item_time.get(position));

        return v;
    }
}

public class ViewHolder {

    private TextView tv_contact;
    private TextView tv_sms_body;
    private TextView tv_time;

}
}

A: you should register a broadcast receiver to get notified upon receiving an SMS and in the onReceive of this receiver you can get new data from cursor and refresh the list view.
To know more about receiver try:
http://androidexample.com/Incomming_SMS_Broadcast_Receiver_-_Android_Example/index.php?view=article_discription&aid=62&aaid=87

A: You have to use notifydatasetchanged. check out following link.
https://stackoverflow.com/a/12229903/2930834


text:
Q: Sailsjs - Cloud SDK - Blueprint API auto generated routes? I wonder if it is possible to have the Blueprint API support in Cloud SDK.
But apparently, the generated cloud.setup.js file does not contain blueprint APIs. Just normal routes beginning with /api
It is written in the Cloud.js file :

   * ### Basic Usage
   *
   * var user = await Cloud.findOneUser(3);
   *
   * var user = await Cloud.findOneUser.with({ id: 3 });

It lets think that it's possible to have auto generated routes to the blueprint APIs like actionModel -> findOneUser, createServer, addToGame, and so on...
Do you know if that is possible ? I don't find a documentation about this.
Thanks

A: I took original code in rebuild-cloud-sdk.js and created a rcsdk.js with the code below before the actual for (let address in sails.config.routes):
_.each(_.keys(sails.models), model => {
    let action = sails.config.blueprints.prefix + sails.config.blueprints.restPrefix + '/' + model;
    _.each([['GET', 'find'], ['POST', 'create']], pair => {
        endpointsByMethodName[`${pair[1]}${model}`] = {
          verb: pair[0],
          url: action,
        }
    });
    _.each([['GET', 'findOne'], ['PUT', 'update'], ['DELETE', 'delete']], pair => {
        endpointsByMethodName[`${pair[1]}${model}`] = {
          verb: pair[0],
          url: action,
          args: ['id'],
        }
    });
});

A: I also asked this question the other day. It is not possible. We need to be explicit here. Blueprint routes is only for quick integration testing with postman. I don't recommend this though. You should not be using postman or auto routes. You should write tests in files so they are permanent.


text:
Q: Reshape nearby polygons so that they share a common border I am looking for an algorithm for reshaping polygons that are close to each other.
Given 2 polygons that have certain parts within proximity E reshape the polygons such that they share a common border within the area of proximity.
Example input:
        Q1   Q2
        +-----+
P1  P2  |     |
+----+  |     |
|    |  |     |
|    |  + Q5  |
|    |   \    |
+----+    +---+
P4  P3    Q4 Q3

Example output:
         Q1  Q2
         +----+
P1  P2Q /     |
+------+      |
|      |      |
|      + Q5P  |
|     / \     |
+----+   `+---+
P4  P3    Q4 Q3

As for what I tried: some Googling and thinking. I suppose I have a rough (untested) idea how I could do that but I don't want to reinvent the wheel.


text:
Q: Where can I find Drivers for Sharper Image Digital Camera Binoculars 10x25? I have some Digital Camera Binoculars from Sharper Image, but do not have the driver CD that came with them. I searched online and can not find the a place to download the device drivers for them. It doesn't say anything about the manufacturer on them so I can't even search the manufacturers website.
http://www.sharperimage.com/si/view/product/Digital+Camera+Binoculars+10+x+25/100311
Does anyone know where I can download device drivers for these?
Update: I previously thought that they might be similar to the Vivitar brand binoculars (which they still may be), but have since found that the manufacturers website is http://mscustomercare.com

A: I contacted The Sharper Image via the "live chat" on their website and they pointed me to the following website where the drivers can be downloaded from:
http://www.mscustomercare.com
You just click on the picture of the binoculars to view the download links. Also, just for simplicity sake, here's a direct link to the driver/software download for Windows:
https://web.archive.org/web/20160407031410/http://www.mscustomercare.com/forms/10x25%20Software.zip


text:
Q: WebAPI How I Can Fill Empty Results in JSON Format I have a result as that:

But as you just saw my some classes return empty results. Here my codes:
MyDBContext:
 public partial class MyContext : DbContext
{
    public MyContext()
        : base("name=MyContext")

    {
       this.Configuration.ProxyCreationEnabled = false;
      //this.Configuration.LazyLoadingEnabled = false;
    }

    public virtual DbSet<Announcement> Announcement { get; set; }
    public virtual DbSet<Class> Class { get; set; }
    public virtual DbSet<Discontinuity> Discontinuity { get; set; }
    public virtual DbSet<Grade> Grade { get; set; }
    public virtual DbSet<Group> Group { get; set; }
    public virtual DbSet<Lesson> Lesson { get; set; }
    public virtual DbSet<Management> Management { get; set; }
    public virtual DbSet<Payment> Payment { get; set; }
    public virtual DbSet<Questions> Questions { get; set; }
    public virtual DbSet<Student> Student { get; set; }
    public virtual DbSet<Teacher> Teacher { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Class>()
            .HasMany(e => e.Student)
            .WithOptional(e => e.Class)
            .HasForeignKey(e => e.Class_Id);

        modelBuilder.Entity<Group>()
            .HasMany(e => e.Student)
            .WithOptional(e => e.Group)
            .HasForeignKey(e => e.Group_Id);

        modelBuilder.Entity<Lesson>()
            .HasMany(e => e.Teacher)
            .WithRequired(e => e.Lesson)
            .HasForeignKey(e => e.Lesson_Id)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<Student>()
            .HasMany(e => e.Discontinuity)
            .WithOptional(e => e.Student)
            .HasForeignKey(e => e.Student_Id);

        modelBuilder.Entity<Student>()
            .HasMany(e => e.Grade)
            .WithOptional(e => e.Student)
            .HasForeignKey(e => e.Student_Id);

        modelBuilder.Entity<Student>()
            .HasMany(e => e.Payment)
            .WithOptional(e => e.Student)
            .HasForeignKey(e => e.Student_Id);
    }
}

My Controller Class:
public class StudentsController : ApiController
{
    private MyContext db = new MyContext();

    // GET: api/Students
    public IQueryable<Student> GetStudent()
    {
        return db.Student;
    }

    // GET: api/Students/5
    [ResponseType(typeof(Student))]
    public IHttpActionResult GetStudent(int id)
    {
        Student student = db.Student.Find(id);
        if (student == null)
        {
            return NotFound();
        }

        return Ok(student);
    }

    // PUT: api/Students/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutStudent(int id, Student student)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != student.Id)
        {
            return BadRequest();
        }

        db.Entry(student).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!StudentExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/Students
    [ResponseType(typeof(Student))]
    public IHttpActionResult PostStudent(Student student)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Student.Add(student);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = student.Id }, student);
    }

    // DELETE: api/Students/5
    [ResponseType(typeof(Student))]
    public IHttpActionResult DeleteStudent(int id)
    {
        Student student = db.Student.Find(id);
        if (student == null)
        {
            return NotFound();
        }

        db.Student.Remove(student);
        db.SaveChanges();

        return Ok(student);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool StudentExists(int id)
    {
        return db.Student.Count(e => e.Id == id) > 0;
    }
}

How i can fill my foreign classes? And im curious about is there any way to typing Class names at beginning of result. E.g. if i'm in Student it should begin as: "Student" : [{"Id" : 18 }] That classes are already filled in database. And i already have ModelBuilder. Bu i really dont know where i did a mistake?

A: You need to .Include those additional properties, which will instruct EF to go and retrieve the data for you.
To do this, you need to change syntax slightly to this:
var student = db.Student
    .Include(i => i.Discontinuity)
    .Include(i => i.Payment)
    .SingleOrDefault(s => s.Id == id);


text:
Q: $A$ says "I am a knight" and $B$ says "$A$ is a Knave?" therefore what is $A$ and $B$?
$A$ says "I am a knight" and $B$ says "$A$ is a Knave?" therefore what is $A$ and $B$ ?

The logic is Knights always tell the truth and Knaves always lie.

What I'm thinking is that $A$ is knight and $B$ is knave because if what $A$ says is true then $B$ says the opposite and that makes his statement false and $B$ becomes a knave and $A$ is a knight.
Although what if $A$ is lying then can't we similarly say that $B$ is telling the truth? Hence making $A$ to be a knave and $B$ to be a knight.
Can I have some help please?

A: You can only conclude that one is a Knight and the other a Knave, but not which one among A and B is the Knight
As mentioned in comments, both a Knight and a Knave can say "I am a Knight" so A's statement gives no information.
If B says "A is a Knave", then you can conclude that A and B are of different "type" (Knight or Knave). Indeed, if B is telling the truth, then B is a Knight and A is a Knave. But if he is lying, he has to be a Knave, and A is a Knight.

A: Note that $A$ saying that "$A$ is a knight" gives you no information at all: both a knight and a knave would claim themselves to be a knight.
So, all you effectively have to work with is $B$ saying that $A$ is a knave. Which has exactly the two solutions you mention: either $B$ is a knight and thus $A$ is indeed a knave, or $B$ is a knave and thus $A$ is a knight.
If you want to to this a bit more formal, note that we can nicely use biconditionals with these kinds of Knights and Knaves puzzles: one is a knight if and only if what they are saying is true.
Thus, if we use $A$ to represent the claim that "$A$ is knight", then $A$ saying that "$A$ is a knight" can be symbolized as $A \leftrightarrow A$ ... which is a tautology ... and thus, as pointed out above, effectively says nothing at all.
$B$ saying that $A$ is a knave becomes $B \leftrightarrow \neg A$ ... and if you have any experience with the logical operators at all, you know that that simply means that $A$ and $B$ have different truth-values, i.e. that the persons $A$ and $B$ are of opposite types.

A:
Enumeration by cases is the clearest way to see what is going on.

There are 4 cases to consider:

Case 1: A is a Knight, and B is a Knight

Case 2: A is a Knight, and B is a Knave

Case 3: A is a Knave, and B is a Knight

Case 4: A is a Knave and B is a Knave

For each case, check the statement against the characters of A and B.

It is quickly seen that cases 2 and 3 are consistent with what is said,
while cases 1 and 4 lead to inconsistency.


text:
Q: CEWP to set Infopath field value not working I have an infopath form web part on my web page along with a CEWP. I'm using javascript in my CEWP to set a field on my Infopath form to some value when a button is clicked. For some reason I can't get the Infopath field to update.
    <script type="text/javascript">
    function filter()
{       document.getElementById("#ctl00_m_g_01d631bf_e556_4975_acbb_226c880bfd44_FormControl0_V1_I1_E1").Value= "TestValue";
}
    </script>
    <button onclick="setTimeout(filter,3000);" type="submit">Click</button>

The #ctl00_m_g_01d631bf_e556_4975_acbb_226c880bfd44_FormControl0_V1_I1_E1 is the ID of my text field.

A: It seems to me you used a # in the getelementbyid where it should not be.
Try to remove the #.
Documentation here


text:
Q: Formula for speed of rigidly connected objects with one "turning off" of the line? In the diagram below I have two objects traveling up the diagram on the black track at some speed s, separated by distance D connected by a breakable rigid rod. Further along the straight-line track, there is a turnout consisting of an arc of the circle with radius R. The top object will take the turnout, the follower will continue straight, eventually breaking the connection when the distance between the two objects exceeds D.
While the two objects are connected, how can I calculate the speed over time of the follower as the leader enters and continues through the turnout?
I've used the equation for the circle and numerically calculated the required position of the follower at various times, but it's messy, surely there's a more direct way to do this given speed s, radius R and distance D?
Edit: After further machinations, I took the tack of starting at the instant the leader gets to the turnout and with the formula for the position of the follower, I took the derivative to get the speed of the follower on the straight line, where $\theta$ is the angle of the leader in the arc, getting

$\frac{\pi  \mathcal{R} \sin (\pi  \theta ) (\mathcal{R}-\mathcal{R}
 \cos (\pi  \theta ))}{\sqrt{\mathcal{D}^2-(\mathcal{R}-\mathcal{R}
 \cos (\pi  \theta ))^2}}+\pi  \mathcal{R} \cos (\pi  \theta )$

Minimizing that for $\mathcal{R}=30$ and $\mathcal{D}=10$ I got ~0.992, i.e., while connected the follower's speed is at minimum .992 of the leader's speed along the arc.
This seems too high intuitively (that is, imagining it, it seems one would need to slow down much more to keep the distance constant as the leader started the turn).
Cheers.

A: I should trust my mathematics and give myself the benefit of the doubt in my physics recollection - indeed, after graphing it, intuition failed me, and the slow-down required is very minor:


text:
Q: How to find Win 10 RDP/NLA Certificate I want to confirm that the RDP certificate on the remote Win 10 machine matches what the client is using in case of MITM attacks - how do I do this?
So far other answers I have seen do not point me to the location of the same certificate as the one presented to my RDP client. Could this be because my client is set to NLA as the security option? if so, then where is the NLA certificate, if such a thing exists? I have searched on Google and can't find it.
Background
I'm using Remmina RDP client to connect via RDP from my home linux computer to a work Windows 10 machine. Today I received a notification that the certificate used on my Windows 10 work machine had changed. Presumably the old one had expired, but how does one confirm this - it appears as if the old certificate is deleted by the system. When I compared the cert RDP client displayed with that stored in my Win 10 work machine I could not find a match.
Other notes

*

*Remmina > Advnaced > Security : set to "NLA" (other options include TLS, RDP, Negotiate)

*eventvwr.msc > System > The latest (and only) cert change event here does not match the one presented to my RDP client

*certlm.msc > Remote Desktop > Certificates : likewise I cannot find same cert in here

Certificate Error/Warning :
The certificate changed! Details:

Subject: CN = my.machine.name
Issuer: CN = my.machine.name
Old fingerprint: c2:de:....
New fingerprint: 67:2f:....

Accept changed certificate?

Screenshots
[Update 1] Remmina RDP Client - notification regarding certificate change. The new cert fingerprint does not match the one stored on the computer I am connecting to, as can be seen in certlm and event viewer pictures below.

[Update 2] Event Viewer - RDP Cert changed recently on Windows 10 host

[Update 3] certlm.msc - Certificate manager for local machine. As you can see the fingerprint does not match the one presented to the client

A: I believe you should've be able to find this by looking at the certs for the local system. Run mmc.exe and add the Cert Manager snap-in. Select local machine and not current user. Look under the personal store.


text:
Q: How to get and Bind() data from dynamic view in asp.net I wrote Create() method to create a Test and I input that data- 1)choose from dropdownlist ,for which Course I want to add this Test 2)name 3)description
I have issue when try to use method asp-for for dynamic model i do not know how use it correctly .For example, If i use
Create(Bind("name, description,...")Test test) and in View =>asp-for="name"....asp-for="description" -> i get msg that i can not use asp-for dynamic
This is my Create() methods in TestController.cs

public IActionResult Create()
       {

           dynamic mymodel = new ExpandoObject();
           mymodel.test = new Test();
           mymodel.coursesChoose = courseService.GetAllCourses().ToList();
           return View(mymodel);
       }

       [HttpPost]
       [ValidateAntiForgeryToken]
       public IActionResult Create([Bind("name,description,CourseId,Course")] Test test)
       {
           //testService.AddNewTest(test);
           Console.WriteLine("///////////" + test.name + test.description + test.CourseId + test.Course.name);//returns null
           return RedirectToAction(nameof(GetAllTests));

       }

This is mu cshtml View
@{
    ViewData["Title"] = "Create";
    Layout = "_Layout";
}

Create test

                        <form method="post" asp-controller="Test" asp-action="Create">
                            @Html.AntiForgeryToken()

                               Course Name

                                <select class="custom-select mr-sm-2" id="inlineFormCustomSelect">
                                    <option selected>Choose Course...</option>

                                    @foreach(Course course in Model.coursesChoose)
                                    {
                                        <option CourseId="@course.id" Course ="@course" >@course.name</option>

                                    }

                               </select>

                                Test Name
                                <input type="text" id="form3Example1cg" class="form-control form-control-lg" asp-for"name" value="@testMod.name"/>

                                Description
                                <textarea class="form-control" id="exampleFormControlTextarea1" rows="4" asp-for"description" value="@testMod.description"></textarea>

                                Cancel
                                <input type="submit" class="SaveCourseButton btn text-white" name="save" value="Save" />

                        </form>

Also there is my Classes. BaseEntity includes ONLY id

A: I solved my problem by not using dynamic model. I passed my available Courses using ViewData("myAviList") = courseRepository.GetAllCourses()
And get it in cshtml file.


text:
Q: BinaryFormatter seems to mess up with nested Dictionaries [Edit] I see that somewhy the post is downrated. I don't know why, but I'm sure that I did something wrong. So, please, if you have time, consider commenting and telling me what's wrong with the post please, before you downrateing it :) Thank you
So, I have this part of my Saving System in which I want to serialize a nested Dictionary given by a function called CaptureState. In my debugging, I check if CaptureState returns a Dictionary with a value under the key of SceneManager.GetActiveScene().buildIndex. It proves, that the method actually returns the desired Dictionary. However, if I serialize it and then deserialize it, the dictionary get's screwed up. It only contains 1 item(it supposed to contain 7), and that item is under the key 1 (SceneManager.GetActiveScene().buildIndex is 0 at the time of testing) (these things don't reveal in the attached code, but believe me :D) And of course (as we can see in the attached code snippet), trying to access the key SceneManager.GetActiveScene().buildIndex(which is 0) throws me a KeyNotFoundException.
I use Unity if it matters.
 void SaveFile(string saveFile)
    {
        string path = GetPathFromSaveFile(saveFile);
        using(FileStream stream = File.Open(path, FileMode.Open))
        {
            stream.Position = 0;
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, CaptureState(LoadFile(path, stream, formatted)));
            //From this point, testing purposes
            stream.Position = 0;
            Dictionary<int, Dictionary<string, object>> testDicta = (Dictionary<int, Dictionary<string, object>>)CaptureState(LoadFile(path, stream, formatter));
            print(testDicta[SceneManager.GetActiveScene().buildIndex].Count); // Shows the proper count
            stream.Position = 0;
            Dictionary<int, Dictionary<string, object>> testDict = (Dictionary<int, Dictionary<string, object>>)formatter.Deserialize(stream);
            print(testDict[SceneManager.GetActiveScene().buildIndex].Count); // Throws me a KeyNotFoundException
        }
    }

A: Okay, I found the solution.
The problem was that I started a Serialization, and passed in parameter containing a function which started a DeSerialization in the meantime. So they were Serializing and DeSerializeing at the same time, which caused the weird outcomes.


text:
Q: How to merge master branch into main I have created a new remote repo "infrastructure" on GitHub.
I have then created a local repo on my computer in the folder "infr" with git init
When I pushed my local repo with git push -u origin master the new branch "master" was created.
I want to merge "master" branch into "main" branch now.
After trying to open a pull request git does not detect differences between them and does not let me do the merging, although checking each branch, you can see all files from my project in the master and nothing in the main.
I have tried renaming my "master" branch into "main" but I got an error : "Could not rename branch "master" at this time: New branch already exists".
So how do I merge master into main branch ?

A: I encountered same problem 4 days ago and what I have done is I opened my online repo in git site and went into repo settings and clicked on branches option. I changed the default branch from main to master and i later deleted the main branch as it was empty. tell me if this works for you.

A: I had the same issue, I used git pull origin master --allow-unrelated-histories from main branch and then commit + push which solved the problem in my case.
Found the solution in this article


text:
Q: Syntax errors in sybase query I have never used sybase before until today.  I have a query in Access that is using First() and has multiple iif statements.  I hoped for the best and pasted my query in and I am getting errors on the First() section.  I removed the First's from the query, and I am getting errors on the iif statements.
Here is my query:
SELECT Client.ClientId, First(Trans.SysId) AS FirstOfSysId, Client.Name1,
Relation.Name1, Debtor.Name1, Account.AcctId, First(Trans.PostDate) AS FirstOfPostDate,
Sum(IIf([TransType]="uc",[Amount],IIf([TransType]="CA",[Amount],IIf([TransType]="RAC",
[Amount],IIf([TransType]="UCBR",[Amount],[amount]*-1))))) AS TransAmount,
Trans.CheckId,Relation.RelId
FROM (((Trans INNER JOIN Account ON Trans.SysAcctId = Account.SysId)
INNER JOIN Debtor ON Account.SysDtrId = Debtor.SysId)
INNER JOIN Relation ON Account.SysRelId = Relation.SysId) INNER JOIN Client ON
Relation.SysClientId = Client.SysId
WHERE (((Trans.TransType)="CA" Or (Trans.TransType)="NC" Or (Trans.TransType)="UC" Or
(Trans.TransType)="AC"
Or (Trans.TransType)="UCB" Or (Trans.TransType)="RAC" Or (Trans.TransType)="UCB" Or
(Trans.TransType)="UCBR"))
GROUP BY Client.ClientId, Client.Name1, Relation.Name1, Debtor.Name1, Account.AcctId,
Trans.CheckId, Relation.RelId
HAVING (((Client.ClientId)=[Forms]![frmCredit]![Combo112])
AND ((Sum(IIf([TransType]="uc",[Amount],IIf([TransType]="CA",[Amount],
IIf([TransType]="RAC", [Amount],IIf([TransType]="UCBR",[Amount],[amount]*-1))))))>0
Or (Sum(IIf([TransType]="uc",[Amount],IIf([TransType]="CA",[Amount],
IIf([TransType]="RAC", [Amount],IIf([TransType]="UCBR",[Amount],[amount]*-1))))))<0)
AND ((Relation.RelId) Not Like "281099"))
ORDER BY Relation.Name1, Account.AcctId, Trans.CheckId

[Edit] A more readable query has been added to http://sqlfiddle.com/#!2/4b98e0/1 [/Edit]
I can't find documentation on converting the first function, but with the IIF should I convert that to a Case when statement?  I saw an article here, but I am not sure if it is the most efficient, since it is from 1999...
The error I am getting is Syntax error near 'FIRST' on line 1. Which based on the article here I am using it in the right syntax.
Any help on using First in the right syntax and if I should use a Case When instead of the iif is greatly appreciated.

A: Based on what I think the query does I think you can rewrite it as below. I don't have access to any Sybase server to validate the query, so I tried it on MS SQL but I commented out some stuff with /* */ that might not be needed with Sybase.
It might be completely wrong, or it might be correct. If it's wrong, please let me know in a comment and I'll remove my answer.
SELECT
    Client.ClientId,
    FIRST_VALUE(Trans.SysId) /* OVER (ORDER BY Trans.Sysid) */ AS FirstOfSysId,
    Client.Name1,
    Relation.Name1,
    Debtor.Name1,
    Account.AcctId,
    FIRST_VALUE(Trans.PostDate) /* OVER (ORDER BY Trans.postdate) */ AS FirstOfPostDate,
    SUM(CASE
          WHEN [TransType] IN ('uc', 'CA', 'RAC', 'UCBR') THEN AMOUNT
          ELSE AMOUNT * -1
       END
       ) AS TransAmount,
    Trans.CheckId,
    Relation.RelId
FROM Trans
INNER JOIN Account ON Trans.SysAcctId = Account.SysId
INNER JOIN Debtor ON Account.SysDtrId = Debtor.SysId
INNER JOIN Relation ON Account.SysRelId = Relation.SysId
INNER JOIN Client ON Relation.SysClientId = Client.SysId

WHERE Trans.TransType IN ('CA','NC','UC','AC','UCB','RAC','UCB','UCBR')

GROUP BY
    Client.ClientId, Client.Name1,
    Relation.Name1, Debtor.Name1,
    Account.AcctId, Trans.CheckId,
    Relation.RelId /* , trans.sysid, trans.postdate */

HAVING
    1=1 --AND (((Client.ClientId)=[Forms]![frmCredit]![Combo112])
    AND SUM(
          CASE WHEN [TransType] IN ('uc', 'CA', 'RAC', 'UCBR') THEN AMOUNT
          ELSE AMOUNT * -1 END
          ) <> 0
    AND Relation.RelId <> '281099'

ORDER BY Relation.Name1, Account.AcctId, Trans.CheckId

My reasoning here is that
Sum(IIf([TransType]="uc",[Amount],IIf([TransType]="CA",[Amount],IIf([TransType]="RAC",
[Amount],IIf([TransType]="UCBR",[Amount],[amount]*-1))))) AS TransAmount,

just takes theamountifTransTypeis any of'uc', 'CA', 'RAC', 'UCBR'elseAmount*-1 and this should be equivalent with:
SUM(CASE WHEN [TransType] IN ('uc', 'CA', 'RAC', 'UCBR') THEN AMOUNT
        ELSE AMOUNT*-1 END) AS TransAmount,

and in thehavingclause this:
((Sum(IIf([TransType]="uc",[Amount],IIf([TransType]="CA",[Amount],
IIf([TransType]="RAC", [Amount],IIf([TransType]="UCBR",[Amount],[amount]*-1))))))>0
Or (Sum(IIf([TransType]="uc",[Amount],IIf([TransType]="CA",[Amount],
IIf([TransType]="RAC", [Amount],IIf([TransType]="UCBR",[Amount],[amount]*-1))))))<0)

just checks if the expression (sum(amount)) is either> 0or< 0and this should be equivalent with:
SUM(CASE WHEN [TransType] IN ('uc', 'CA', 'RAC', 'UCBR') THEN AMOUNT
        ELSE AMOUNT*-1 END) <> 0


text:
Q: Matlab: find mode in range I have a matrix like:
A=
    10 31 32 22
    32 35 52 77
    68 42 84 32

I need a function like mode but with range, for example mymode(A,10) that return 30, find most frequent number in range 0-10, 10-20, 20-30, .... and return most number in range.

A: You can use histc to bin your data into the ranges of your desire and then find the bin with the most members using max on the output of histc
ranges = 0:10:50;                 % your desired ranges
[n, bins] = histc(A(:), ranges);  % bin the data
[v,i] = max(n);                   % find the bin with most occurrences

[ranges(i) ranges(i+1)]           % edges of the most frequent bin

For your specific example this returns
ans =

    30    40

which matches with your required output, as the most values in A lay between 30 and 40.

A: [M,F] = mode(  A((A>=2) & (A<=5))  ) %//only interested in range 2 to 5

...where M will give you the mode and F will give you frequency of occurence

A: > A = [10 31 32 22; 32 35 52 77; 68 42 84 32]
A =

   10   31   32   22
   32   35   52   77
   68   42   84   32

> min = 10
min =  10
> max = 40
max =  40
> mode(A(A >= min & A <= max))
ans =  32
>

A: I guess by the number of different answers that we may be missing your goal. Here is my interpretation.
If you want to have many ranges and you want to output most frequent number for every range, create a cell containing all desired ranges (they could overlap) and use cellfun to run mode() for every range. You can also create a cell with desired ranges using arrayfun in a similar manner:
A = [10 31 32 22; 32 35 52 77; 68 42 84 32];

% create ranges
range_step = 10;
range_start=[0:range_step:40];
range=arrayfun(@(r)([r r+range_step]), range_start, 'UniformOutput', false)

% analyze ranges
o = cellfun(@(r)(mode(A(A>=r(1) & A<=r(2)))), range, 'UniformOutput', false)

o =
[10]    [10]    [22]    [32]    [42]


text:
Q: Replace backslash in string I have a String in which I am trying to replace the number enclosed by two backslashes.  For example: \10\  , I am trying to replace that with 10.  I am currently using this regex to do that:
String texter = texthb.replaceAll("\\.+\\", "\\"+String.valueOf(pertotal + initper)+"\\");

This line is giving the following error:
 Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Unexpected internal error near index 4

.+\
I know it is because the regex is wrong.  What is the proper way to accomplish this?  Thanks in advance.

A: Use four backslashes to match a single backslash character.
String texter = texthb.replaceAll("\\\\.+?\\\\", "\\\\"+String.valueOf(pertotal + initper)+"\\\\");


text:
Q: Unique Constraint performance When having a table with 450 million records and a unique constraint (no primary key, just constraint made out of 6 columns), how can I improve its performance while inserting 5 million rows daily.
at the moment I just disable the constraint and enable it after the loading has finished. But this takes some time.
By the way, there is no unique index supporting the constraint... it will just get super huge

A: In case your import procedure ensures uniquenes of new rows you can enable the constraint with NOVALIDATE, then existing data in the table are not checked.
See here:
http://docs.oracle.com/cd/B28359_01/server.111/b28286/clauses002.htm#SQLRF52204


text:
Q: Is it possible/feasable to write libraries that can be consumed by Jakarta AND Spring projects? At my workplace, we develop many different backend applications for many different customers. Some of them use Spring Boot, while others use JavaEE/Jakarta. For the JavaEE apps we have some shared libraries that are used by many projects, but these libraries can only be consumed by JavaEE projects, since the libraries use EJB and CDI beans, MicroProfile config and other EE specific concepts.
Is there a way to develop such libraries, so that they can be used as a Spring library as well as a JavaEE library? what would that entail?
I assume, one would need a core that is technology agnostic and two wrapper libraries that add the Spring and EE flavors respectively. Or is there a more light-weight solution? I cannot find very much information out there; my search results are cluttered with "Why X is better than Y" articles ^^'


text:
Q: Trying to redirect directory to https but getting double URL segment on return I'm trying to redirect one directory on my site to https. The directory is not really a directory at all because the site's dynamic. I'm using ExpressionEngine as the CMS.
I already have a few lines in my .htaccess file to remove the index.php ExpressionEngine adds to all of its urls.
Here's what I have:
<IfModule mod_rewrite.c>
        RewriteEngine On

RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} store
RewriteRule ^(.*)$ https://mysite.com/store/$1 [R,L]

        # Removes index.php
        RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ /index.php?/$1 [L]

</IfModule>

When I visit, http://mysite.com/store/, it returns https://mysite.com/store/store/.
I think it might have to do with the following:
    RewriteRule ^(.*)$ /index.php?/$1 [L]

The above line has a question mark after the index.php because I was getting a "No input file" error, and that was the recommended fix.
Any thoughts?

A: This line here:
RewriteCond %{REQUEST_URI} store

Should have a ! in front of "store":
RewriteCond %{REQUEST_URI} !store

because you don't want it to redirect if the URI is already /store.

A: Edited the line:
RewriteRule ^(.*)$ https://mysite.com/store/$1 [R,L]

to read:
RewriteRule ^(.*)$ https://mysite.com/$1 [R,L]

Now it works. Here's the full code:
<IfModule mod_rewrite.c>
        RewriteEngine On

        RewriteCond %{SERVER_PORT} 80
        RewriteCond %{REQUEST_URI} store
        RewriteRule ^(.*)$ https://mysite.com/$1 [R,L]

        # Removes index.php
        RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ /index.php?/$1 [L]

</IfModule>


text:
Q: O que é Level Trust de uma aplicação ASP.NET? Para que serve a configuração de Level Trust em uma aplicação ASP.NET?
Ela protege o servidor de alguma coisa?
Ela protege a aplicação de alguma coisa?
Em qual caso ou por qual motivo é recomendado ou necessário alterar essa configuração?

A:
Para que serve a configuração de Level Trust em uma aplicação ASP.NET?

Você determina o que a aplicação pode ou não fazer. Algumas funcionalidades podem ser um pouco perigosas, especialmente se ele puder ser invocada inadvertidamente de forma externa.
Quanto menos confiança você exigir da aplicação mais seguro ela estará (não quer dizer que só isso dá segunrança). Se ela exigir mais que o servidor permite ela não rodará. Se hospeda em um servidor compartilhado, só poderá usar o que eles permitirem.

Ela protege o servidor de alguma coisa?

Sim, você pode restringir o que as aplicações podem fazer no seu servidor.

Ela protege a aplicação de alguma coisa?

De certa forma sim, já que se você definir que a aplicação terá um nível limitado que impede ser funcionalidades, a aplicação não funcionará se uma delas for executada por acidente.

Em qual caso ou por qual motivo é recomendado ou necessário alterar essa configuração?

Em geral é muito útil quando o servidor é compartilhado e você não quer permitir que os outros usuários (desenvolvedores) dele possam fazer qualquer coisa no servidor.
Documentação dos níveis.
Mais informações.


text:
Q: This ITextSharp C# code generates empty pdf ? why? I am calling this method from a submit button which is not relevant. The Bindgv(); function binds database to gridview and then this code generates
empty PDF, I am not sure why. If anyone can fix this i will be thankfull.
 private void ExportToPdf()
 {
    gv.AllowPaging = true;
    Bindgv();

    //Create a table
    PdfPTable table = new PdfPTable(gv.Columns.Count);
    table.SpacingAfter = table.SpacingBefore = 5;

    //Set the column widths
    int[] widths = new int[gv.Columns.Count];
    for (int x = 0; x < gv.Columns.Count; x++)
    {
        widths[x] = (int)gv.Columns[x].ItemStyle.Width.Value;
        string cellText = Server.HtmlDecode(gv.HeaderRow.Cells[x].Text);
        PdfPCell cell = new PdfPCell(new Phrase(cellText));
        cell.BackgroundColor = new BaseColor(System
                           .Drawing.ColorTranslator.FromHtml("#008000"));
        table.AddCell(cell);
    }
    table.SetWidths(widths);

    //Transfer rows from GridView to table
    for (int i = 0; i < gv.Rows.Count; i++)
    {
        //does not enter here
        if (gv.Rows[i].RowType == DataControlRowType.DataRow)
        {
            for (int j = 0; j < gv.Columns.Count; j++)
            {
                string cellText = Server.HtmlDecode
                                  (gv.Rows[i].Cells[j].Text);
                iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(cellText));

                //Set Color of Alternating row
                if (i % 2 != 0)
                {
                    cell.BackgroundColor = new BaseColor(System.Drawing
                                        .ColorTranslator.FromHtml("#C2D69B"));
                }
                table.AddCell(cell);
            }
        }
    }

    //Create the PDF Document
    Document pdfDoc = new Document(PageSize.A4);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    pdfDoc.Add(table);
    pdfDoc.Close();
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;" +
                                   "filename=BillHistory.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Write(pdfDoc);
    Response.End();
}

Here is the Bindgv();
private void Bindgv()
{
    var idParam = new SqlParameter
    {
        ParameterName = "accNo",
        Value = txtAccountNo.Text
    };

    List<BillHistory> bh = new List<BillHistory>();
    bh = db.ExecuteStoreQuery<BillHistory>("exec BillHistory @accNo", idParam).ToList();
    gv.DataSource = bh;
    gv.DataBind();

    customer_registration cus = db.customer_registration.SingleOrDefault(p => p.account_number == txtAccountNo.Text);
    lblAccountNo.InnerHtml = cus.account_number;
    lblMeterNo.InnerHtml = cus.meter_number;
    lblPremises.InnerHtml = cus.apartment_number + "," + cus.house_name + "," + cus.street_name;
    lblBillingAddress.InnerHtml = cus.apartment_number + "," + cus.house_name + "," + cus.street_name;
    lblOwner.InnerHtml = cus.customer_name;
}

A: I think you'll need to handle the GridView's DataBound event and create the PDF as part of that event.


text:
Q: Difference between these two maven commands? What is the difference between these 2 maven commands? What does activating a profile really do??

*

*mvn deploy -s settings.xml -B -Dmaven.repo.local=/root/maven_repo -P production
&

*

*mvn deploy -s settings.xml -B -Dmaven.repo.local=/root/maven_repo

A: A profile is a part of the POM that can be activated. If you look into your POM (or parent POM), you will find a profile named production that contains some additional stuff.


text:
Q: Does free Heroku application has a SSL certificate? I would like to buy a .app domain and connect it to a heroku-hosted application. When I want to buy .app domain on Google domains (or anywhere else), I can read "For *.app, you need an SSL certificate before you can launch a website". If I buy that domain, will I be able to use it with Heroku application? If not, what do I need to do in order to be able to connect .app domain with heroku app?

A: yes, you can have a custom domain without incurring extra charges
https://devcenter.heroku.com/articles/custom-domains
all the configurations and setup details are detailed in the linked article


text:
Q: NServiceBus and MSDTC across domains? So I'm trying to use NServiceBus and everything goes fine until my application tries to write data to the database via EF6, where I consistently get this exception:

2016-11-18 13:35:28.340 INFO  NServiceBus.RecoverabilityExecutor
  Immediate Retry is going to retry message
  '28392aef-de00-4162-8cca-a6c200c0e68e' because of an exception:
  System.Data.Entity.Core.EntityException: The underlying provider
  failed on Open. --->
  System.Transactions.TransactionManagerCommunicationException:
  Communication with the underlying transaction manager has failed. --->
  System.Runtime.InteropServices.COMException: The MSDTC transaction
  manager was unable to pull the transaction from the source transaction
  manager due to communication problems. Possible causes are: a firewall
  is present and it doesn't have an exception for the MSDTC process, the
  two machines cannot find each other by their NetBIOS names, or the
  support for network transactions is not enabled for one of the two
  transaction managers. (Exception from HRESULT: 0x8004D02B)    at
  System.Transactions.Oletx.IDtcProxyShimFactory.ReceiveTransaction(UInt32
  propgationTokenSize, Byte[] propgationToken, IntPtr managedIdentifier,
  Guid& transactionIdentifier, OletxTransactionIsolationLevel&
  isolationLevel, ITransactionShim& transactionShim)    at
  System.Transactions.TransactionInterop.GetOletxTransactionFromTransmitterPropigationToken(Byte[]
  propagationToken)    --- End of inner exception stack trace ---    at
  System.Transactions.TransactionInterop.GetOletxTransactionFromTransmitterPropigationToken(Byte[]
  propagationToken)    at
  System.Transactions.TransactionStatePSPEOperation.PSPEPromote(InternalTransaction
  tx)    at
  System.Transactions.TransactionStateDelegatedBase.EnterState(InternalTransaction
  tx)    at
  System.Transactions.EnlistableStates.Promote(InternalTransaction tx)
  at System.Transactions.Transaction.Promote()    at
  System.Transactions.TransactionInterop.ConvertToOletxTransaction(Transaction
  transaction)    at
  System.Transactions.TransactionInterop.GetExportCookie(Transaction
  transaction, Byte[] whereabouts)    at
  System.Data.SqlClient.SqlInternalConnection.GetTransactionCookie(Transaction
  transaction, Byte[] whereAbouts)    at
  System.Data.SqlClient.SqlInternalConnection.EnlistNonNull(Transaction
  tx)    at
  System.Data.SqlClient.SqlInternalConnection.Enlist(Transaction tx)
  at
  System.Data.ProviderBase.DbConnectionInternal.ActivateConnection(Transaction
  transaction)    at
  System.Data.ProviderBase.DbConnectionPool.PrepareConnection(DbConnection
  owningObject, DbConnectionInternal obj, Transaction transaction)    at
  System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
  owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean
  allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions
  userOptions, DbConnectionInternal& connection)    at
  System.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass4.<b__3>d__6.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.d__91.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Data.Entity.Core.EntityClient.EntityConnection.<OpenAsync>d__8.MoveNext()
  --- End of inner exception stack trace ---    at System.Data.Entity.Core.EntityClient.EntityConnection.<OpenAsync>d__8.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Data.Entity.Core.Objects.ObjectContext.<EnsureConnectionAsync>d__9.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Data.Entity.Core.Objects.ObjectContext.<ExecuteInTransactionAsync>d__3d1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.d__91.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter1.GetResult()
  at
  System.Data.Entity.Core.Objects.ObjectQuery1.<GetResultsAsync>d__e.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter1.GetResult()
  at
  System.Data.Entity.Internal.LazyAsyncEnumerator1.<FirstMoveNextAsync>d__0.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.<ForEachAsync>d__51.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
  at
  DAS.Services.Notifications.Data.Repository.AccountConfigurationRepository.<GetConfigurationAsync>d__2.MoveNext()
  in
  C:\source\DigitalAirStrike\DAS_Platform\das.services.notifications\src\DAS.Services.Notifications.Data\Repository\AccountConfigurationRepository.cs:line
  38
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()
  at
  DAS.Services.Notifications.Service.Sms.SmsService.d__8.MoveNext()
  in
  C:\source\DigitalAirStrike\DAS_Platform\das.services.notifications\src\DAS.Services.Notifications.Service\Sms\SmsService.cs:line
  92
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()
  at
  DAS.Services.Notifications.Service.Sms.SmsService.<SendTextMessageAsync>d__7.MoveNext()
  in
  C:\source\DigitalAirStrike\DAS_Platform\das.services.notifications\src\DAS.Services.Notifications.Service\Sms\SmsService.cs:line
  76
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
  at
  DAS.Services.Notifications.Command.MessageDelivery.SmsDeliveryStrategy.<Deliver>d__3.MoveNext()
  in
  C:\source\DigitalAirStrike\DAS_Platform\das.services.notifications\src\DAS.Services.Notifications.Command\MessageDelivery\SmsDeliveryStrategy.cs:line
  19
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
  at
  DAS.Services.Notifications.Command.Handlers.SendSmsNotificationHandler.<Handle>d__3.MoveNext()
  in
  C:\source\DigitalAirStrike\DAS_Platform\das.services.notifications\src\DAS.Services.Notifications.Command\Handlers\SendSmsNotificationHandler.cs:line
  32
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
  at NServiceBus.LoadHandlersConnector.<Invoke>d__1.MoveNext() in
  C:\Build\src\NServiceBus.Core\Pipeline\Incoming\LoadHandlersConnector.cs:line
  40
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
  at NServiceBus.MutateIncomingMessageBehavior.<Invoke>d__0.MoveNext()
  in
  C:\Build\src\NServiceBus.Core\Pipeline\MutateInstanceMessage\MutateIncomingMessageBehavior.cs:line
  28
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
  at
  NServiceBus.DeserializeLogicalMessagesConnector.<Invoke>d__1.MoveNext()
  in
  C:\Build\src\NServiceBus.Core\Pipeline\Incoming\DeserializeLogicalMessagesConnector.cs:line
  31
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
  at NServiceBus.SubscriptionReceiverBehavior.<Invoke>d__1.MoveNext() in
  C:\Build\src\NServiceBus.Core\Routing\MessageDrivenSubscriptions\SubscriptionReceiverBehavior.cs:line
  29
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
  at
  NServiceBus.MutateIncomingTransportMessageBehavior.<Invoke>d__0.MoveNext()
  in
  C:\Build\src\NServiceBus.Core\Pipeline\MutateTransportMessage\MutateIncomingTransportMessageBehavior.cs:line
  27
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
  at NServiceBus.UnitOfWorkBehavior.<Invoke>d__0.MoveNext() in
  C:\Build\src\NServiceBus.Core\UnitOfWork\UnitOfWorkBehavior.cs:line 26
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at
  NServiceBus.UnitOfWorkBehavior.<Invoke>d__0.MoveNext() in
  C:\Build\src\NServiceBus.Core\UnitOfWork\UnitOfWorkBehavior.cs:line 49
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
  at NServiceBus.ProcessingStatisticsBehavior.<Invoke>d__0.MoveNext() in
  C:\Build\src\NServiceBus.Core\Performance\Statistics\ProcessingStatisticsBehavior.cs:line
  25
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
  at
  NServiceBus.ReceivePerformanceDiagnosticsBehavior.<Invoke>d__2.MoveNext()
  in
  C:\Build\src\NServiceBus.Core\Performance\Statistics\ReceivePerformanceDiagnosticsBehavior.cs:line
  40
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
  at
  NServiceBus.TransportReceiveToPhysicalMessageProcessingConnector.<Invoke>d__1.MoveNext()
  in
  C:\Build\src\NServiceBus.Core\Pipeline\Incoming\TransportReceiveToPhysicalMessageProcessingConnector.cs:line
  37
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
  at NServiceBus.MainPipelineExecutor.<Invoke>d__1.MoveNext() in
  C:\Build\src\NServiceBus.Core\Pipeline\MainPipelineExecutor.cs:line 32
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
  at
  NServiceBus.Transport.SQLServer.ReceiveStrategy.<TryProcessingMessage>d__12.MoveNext()
  in
  C:\Build\src\NServiceBus.SqlServer\Receiving\ReceiveStrategy.cs:line
  33
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()
  at
  NServiceBus.Transport.SQLServer.ReceiveWithTransactionScope.d__4.MoveNext()
  in
  C:\Build\src\NServiceBus.SqlServer\Receiving\ReceiveWithTransactionScope.cs:line
  99
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
  at
  NServiceBus.Transport.SQLServer.ReceiveWithTransactionScope.d__1.MoveNext()
  in
  C:\Build\src\NServiceBus.SqlServer\Receiving\ReceiveWithTransactionScope.cs:line
  39

The error suggests one of the follwing:

*

*The firewall is blocking DTC

*The computers can't resolve each other via NetBIOS

*Support for network transactions isn't enabled on one or both computers

I've added both inbound and outbound exceptions on the box where the application is running and the SQL Server box on port 135.
The SQL Server instance is running on a VM in Azure. I've added the exceptions to the network security group as well.
I've enabled network connections for DTC on both boxes.
The application box is running on DomainA while the VM is on DomainB
I'm having a bear of a time getting around this. What do I need to change to get this to work? Is there a workaround to prevent escalating to DTC?
UPDATE:
Both domains are run through some sort of Azure federation, so they were able to ping each other, they just could resolve each others' host names so I added the IP addresses to each box's host file and now they can find each other and everything seems to be working.
So I guess now, I'm wondering if there is a way to fix this through some sort of configuration so that I don't have to add host entries to every app box and every developer's box that wants to run locally to test.

A: I would try and avoid the use of MSDTC in your scenario, instead use the Outbox feature.
Does that help?


text:
Q: Why does my double lose its value? - (void)useX:(double)x {
    self.XVelocity = x;
    //This is called by the app delegate every 1/60 times a second
    printf("%f",x);
}

In a different method I use
- (void)update {
    printf("%f",self.XVelocity);
}

and self.XVelocity is equal to 0, how can I fix this

A: Try removing "self." and see what will happen.


text:
Q: Ring structure of the representation ring of a finite group I'm currently taking a course in representation theory, and I'm not entirely sure I understand the structure of the representation ring of a finite group. For a finite group $G$ with irreducible representations $(\rho_{i}, V_{i})_{i=1}^{n}$ over a field $F$, we denote
$$R_{F}[G] = \Big \{\sum_{i = 1}^{n}n_{i}V_{i} : n_{i} \in \mathbb{Z} \Big \}$$
to be the representation ring of the group $G$ with addition defined as direct addition of coefficients and multiplication defined by tensor product? I'm not entirely sure I understand the ring structure here. I understand that since we take coefficients in $\mathbb{Z}$, we clearly have an abelian group by directing taking sums of coefficients of $V_{i}$, but I'm not entirely sure I understand the multiplicative aspect of thing ring. From what I understand, it has to do with tensor products, but how is the tensor product actually taken? Do we distribute the tensor over all elements and then have to reduce the tensored representations back down to recover a ring element of this form? Would the multiplicative identity of this ring then just be the trivial representation with coefficient 1? This ring seems very odd to me, although it does seem to come up for instance in Brauer theorem.
This question is somewhat similar to this one, but reading through the question and answer here doesn't really answer the question to me.

A: It is better to think of $R_F[G]$ as being spanned by isomorphism classes of representations, and with the system $V_1, \ldots, V_n$ of irreducibles entering purely because they are an obvious basis.
For a finite-dimensional representation $U$ of $G$ over the field $F$, let $[U]$ denote its equivalence class up to isomorphism. Define the representation ring $R_F[G]$ to be the free abelian group with basis the set of equivalence classes, equipped with the product structure $[U][V] := [U \otimes V]$, and quotiented by the relation $[U \oplus V] = [U] + [V]$. You should check that this is well-defined (does not depend on choices of representatives from equivalence classes) and that it makes $R_F[G]$ into a commutative ring (associativity, etc).
Supposing that the representation theory of $G$ over $F$ is semisimple, and $V_1, \ldots, V_n$ is a full system of irreducibles, then it can be shown that $[V_1], \ldots, [V_n]$ is a basis for $R_F[G]$. Showing that the basis spans is easy: any representation $W$ is, by semisimplicity, isomorphic to a direct sum of the form
$$W \cong V_1^{\oplus k_1} \oplus \cdots \oplus V_n^{\oplus k_n}$$
for some $k_1, \ldots, k_n \in \mathbb{N}$, and hence by the additive relation we get
$$[W] = k_1 [V_1] + \cdots + k_n [V_n].$$
I think this should answer your question: if I have $[U] = [V_1] + 2[V_2]$ and $[W] = [V_3]$ then we have
$$ [U \otimes W] = [U][W] = ([V_1] + 2 [V_2])[V_3] = [V_1 \otimes V_3] + 2[V_2 \otimes V_3],$$
and we need to know how to decompose $[V_1 \otimes V_3]$ and $[V_2 \otimes V_3]$ to be able to write things back in the basis of simple representations. So indeed, the trivial representation is the multiplicative identity.
A few final comments:

*

*The irreducibles are just one choice of basis for $R_F[G]$, and depending on the group you study, there might be other good choices. For the symmetric group, the modules induced from trivial modules of a Young subgroup come to mind as another nice basis.

*What I've defined above is called the split Grothendieck group. If $G$ is not semisimple with respect to $F$ then you probably want the actual Grothendieck group, which has the extra relation $[U] - [V] + [W] = 0$ whenever $0 \to U \to V \to W \to 0$ is a short exact sequence. Authors will usually clarify which one they mean.


text:
Q: Missing values in a generated Heatmap using Databricks Pyspark
Hello.
I have this heatmap for the following dataset:
Dataset_DDoS_SDN
Why there are missing columns on the map?
This is the code I used to generate the map:
hdf = df_2.toHandy()
data = hdf.toPandas()
plt.figure(figsize=(15,10))
sns.heatmap(data.corr(), annot=True)
plt.show()


text:
Q: In Node.js, which queues are executed untill they are empty, and which are not? So, I know that when JavaScript runs in a browser there are a few event queues, like the micro and macro task queue. I know that in the case of the former its content is always entirely executed until it's empty, while in the case of the macro task queue, only the first task is executed per loop cycle.
Now, I'm totally new to Node.js and I was trying to grasp how the event loop works. I have not been able to find this kind of information (how many elements of a queue are executed to completion during every cycle) with regards to the queues and loop phases that Node.js uses.
I would appreciate if you could shed some light over this.


text:
Q: Function doesn't count emojis I'm getting a s=0 result when executing this code:
import emojis
import emoji
from collections import Counter

#count emoji
#function to check if sth is an emoji
def char_is_emoji(character):
    return character in emoji.UNICODE_EMOJI

#function to count emoji
def emoji_counter(text_string):
    count = 0
    for x in text_string:
        a = char_is_emoji(x)
        if a ==True:
            count+=1
    return count

#test
s = " Last clue! \nWho's the host of"
print(emoji_counter(s))

Any ideas why? Any help much appreciated!

A: In my version of emoji (v1.6.1), emoji.UNICODE_EMOJI_ENGLISH works:
import emoji

def emoji_counter(s):
    return sum(c in emoji.UNICODE_EMOJI_ENGLISH for c in s)

s = " Last clue! \nWho's the host of"
print(emoji_counter(s)) # 2

Or try emoji.UNICODE_EMOJI['en'] (https://github.com/carpedm20/emoji/issues/155):

From the v.1.0.0 added support for multilingual naming of emojis. Now UNICODE_EMOJI has language keys
UNICODE_EMOJI = {
'en': UNICODE_EMOJI_ENGLISH,
'es': UNICODE_EMOJI_SPANISH,
'pt': UNICODE_EMOJI_PORTUGUESE,
'it': UNICODE_EMOJI_ITALIAN,
}


text:
Q: Spring Security Custom login using Java Config Based I am using Spring Security Java based config. But unable to call process action when user submits login form.  Here are my config and java file.
please let me know where I am doing something wrong.
Thanks in advance.
1) Spring security Java Config class
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserService userService;
    @Bean
    public AuthenticationManager authenticationManager() throws Exception{
        AuthenticationManager authenticationManager = new ProviderManager(
                    Arrays.asList(authenticationProvider()));
            return authenticationManager;
        }
    @Bean
    public AuthenticationProvider authenticationProvider() throws     Exception {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userService);
        authenticationProvider.afterPropertiesSet();
        return authenticationProvider;
        }
        @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/**").permitAll()
        .antMatchers("/process/success").authenticated()
        .and()
        .formLogin()
        .usernameParameter("username")
        .passwordParameter("password")
        .loginPage("/")
        .failureUrl("/?auth=fail")
        .loginProcessingUrl("/process")
        .and().logout().logoutUrl("/logout")
         .invalidateHttpSession(true).deleteCookies("JSESSIONID")
        .permitAll();
        }
}

2) Jsp login Page.
<form name="f" action="./process" method="post">
    <fieldset>
    <legend>Please Login</legend>
    <c:if test="${'fail' eq param.auth}">

    Login Failed!!!
 Reason :
    ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}

    </c:if>
    <c:if test="${'succ' eq param.out}">

You have been successfully logged out.

    ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}

    </c:if>

${param.logout}

    Username <input type="text"id="username" name="username" /> Password
    <input type="password" id="password" name="password" />
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />

    <button type="submit" class="btn">Log in</button>

    </fieldset>
    </form>

3) Here is Home Controller
@Controller
public class HomeController {
    @Autowired
    AuthenticationManager authenticationManager;
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        System.out.println("index.....");
        return "index";
    }
    @RequestMapping(value = "/process", method = RequestMethod.POST)
    public String process(@PathVariable("username") String userName,
        @PathVariable("password") String password,
        HttpServletRequest request, RedirectAttributes redirectAttr) {
        try {
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, password);
            Authentication authenticate = authenticationManager.authenticate(token);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
        } catch (AuthenticationException e) {
            System.out.println(e.getMessage());
        }
        System.out.println("login....." + request.getSession(false));
        return "redirect:/process/success";
    }
    @RequestMapping(value = "/process/success", method = RequestMethod.GET)
    public String success() {
        System.out.println("success.....");
        return "success";
    }
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request) {
        System.out.println("logout....." + request.getSession(false)+ " is new " + request.getSession(false).isNew());
        request.getSession(false).invalidate();
        return "index";
    }
}

A: The problem is that Spring Security uses filters, and the request for normally intercepted and processed by the UsernamePasswordAuthenticationFilter. So it cannot reach your controller.
Spring Security uses a filter to process login for you and you should not even think to use a controller for that. You should read (again) the reference manual and start with a tutorial.


text:
Q: Python gc.get_referents() returning references that are unknown to inspect module I am trying to debug a memory leak and have tracked it down to a single object, call it "parent".
gc.get_referents(parent) indicates that it is effectively gaining more and more references to the object that is leaking. I'm trying to find out more information about how it is happening, however, inspect.getmembers(parent) knows nothing about these references that gc.get_referents does know about:
i.e.
import gc
import inspect

parent = someObject()
dependents = gc.get_referents(parent)
fromInspect = [b for (a,b) in inspect.getmembers(parent) if b in dependents]
notFromInspect = [b for (a,b) in inspect.getmembers(parent) if b not in dependents]
print len(fromInspect)
>>> 3
print len(notFromInspect)
>>> 69

So there are lots of objects (69 of them!) that the gc module knows about, but inspect does not.
How does gc.get_referents() construct the list of "referent" objects for a Python object?
Do I need to look at slots? Something else?

A: In my case, it turned out that "parent" was a custom python object implemented in C/C++.
The documentation here describes how you can write your own "container" objects in Python: https://docs.python.org/2/c-api/typeobj.html#Py_TPFLAGS_HAVE_GC
All that such objects have to do to then interface with the garbage collector is provide two function pointers, tp_traverse and tp_clear.
tp_traverse allows a custom type object to tell the Garbage collector anything it wants about which objects this object owns.
So in my case, this is how I am seeing references which are unknown to the inspect module.
Unfortunately for me, I still haven't found the actual cause of the leak - except now I know it's related to the C/C++ code.


text:
Q: Return short date string from property C# I am trying to return ShortDateString from my property,
  public DateTime PICKDT
{
    get { return PICKDT.ToShortDateString(); }

}

Input data will be in this format 2041-04-30T00:00:00.
Can any one point out the right way to do this?

A: private DateTime _pickdt;
public string PICKDT
{
    get {return _pickdt.ToShortDateString();}
}


text:
Q: RecyclerView lazy loading TextView content I am filling a RecyclerView with up to several thousand entries from a sqlite database, loaded through an AsyncTaskLoader. The list needs to be filterable, so I am required to load all entries at once. Some of the TextViews in the RecyclerView's ViewHolders contain results of further DB queries (based on the initial result) or other types of computations.
Expanding the initial query to include JOINs (which at least would make the secondary queries obsolete) really slows down loading. However doing the queries/computations inside the onBind method of the RecyclerView, makes flinging much less fluent, than without them.
Is there a way to do lazy load the content for these computed TextViews? I have searched for examples, but libraries like "Picasso" and "Glide" only allow loading images...
Any help appreciated!
Thanks,
Rob

A: I ended up using a Singleton class  using an ExecutorService to do my loading/calculations in seperate threads and then having the Handler update my ViewHolder. Don't know, if this is the best way to do it, but so far it's working without any issues.
private static class LazyLoadManager {
    private static LazyLoadManager INSTANCE;
    private final ExecutorService pool;
    private Map<ViewHolder, String> viewHolders = Collections.synchronizedMap(new WeakHashMap<ViewHolder, String>());
    private Context context;

    private LazyLoadManager(Context context) {
        this.context = context;
        pool = Executors.newFixedThreadPool(5);
    }

    public static LazyLoadManager getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new LazyLoadManager(context.getApplicationContext());
        }
        return INSTANCE;
    }

    private void loadData(final ViewHolder viewHolder, final Model myModel) {

        // Put ViewHolder and respective tag into Map
        viewHolders.put(viewHolder, myModel.getTag());

        final Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {

                // Get result object
                Model myResultModel = (Model) msg.obj;

                // Result was initialized
                if (myResultModel != null) {

                    // Get ViewHolder tag from map
                    String tag = viewHolders.get(viewHolder);

                    // Set ViewHolder content, if saved tag matches tag of this ViewHolder
                    if (tag != null && tag.equals(viewHolder.getTag())) {
                        viewHolder.viewA.setText(myResultModel.getThis());
                        viewHolder.viewB.setText(myResultModel.getThat());
                    }
                }
                return true;
            }
        });

        pool.submit(new Runnable() {
                        @Override
                        public void run() {
                            Model myResultModel = null;

                            if (myModel != null) {

                                // do required calculations and secondary queries based on myModel

                                myResultModel.setThis(result1);
                                myResultModel.setThat(result2);
                            }

                            Message message = Message.obtain();
                            message.obj = myResultModel;

                            handler.sendMessage(message);
                        }
                    }

        );
    }

In the onBindViewHolder method of my RecyclerView I then call my LazyLoadManager like this
LazyLoadManager.getInstance(context).loadData(viewHolder, myModel);


text:
Q: Get text rather than value of dropdown to populated another input field I have a form whee i am trying to populate the field #ef with the information from the field #emergency2
It works but what i want to happen is for it to pass the text YES or NO in to the second field #ef rather than the weighted value of 0 or 1. I want to keep the numeric value as i am using it for a sum later. However i want the text within the drop down to appear in the second input rather than the numerical value. Any ideas?

  Do you have  £1000 in your emergency fund?
              <select class="select-css" id="emergency2" name="emergency2" required>
             <option selected="selected">Please Select</option>
              <option value="0">Yes</option>
              <option value="1">No</option>
            </select>

Your emergency funds is large enough to cover at least 3 months of outgoings:

             <input id="ef">

A: Try this one
$('#ef').val($(this).text());


text:
Q: Linker Inserts Unnecessary Opcode Padding I've recently come across a minor issue when linking multiple object files for a Motorola 68000 based system (SEGA Mega Drive). The problem is, when an input section for one object file ends and the next one begins, the linker fills memory addresses with zeros so that the next object file begins aligned on a four byte boundary. The text below is a memory map output by the linker. As you can see, the .text output section contains three object files. The first two (main.o, swap.o), were written in C compiled and assembled using m68k-elf-gcc. The third one (swap_asm.o) was hand written in 68000 assembly and assembled using the vasm. The function at the beginning of swap.o would normally start at address 0x0000001E. But, the linker is *fill*ing the beginning of the swap.o file with two bytes, specifically 0x0000. So, swap.o starts at 0x00000020. But, swap_asm.o is not getting aligned and begins at a non-four-byte-aligned address, 0x00000036. Is there a way to make the linker not add any padding and just start the swap.o right away? I understand there are a few work arounds like filling the space with a NOP, but I was wondering if there is a way to just not do a *fill*?
.text           0x00000000       0x4c
 main.o(.text)
 .text          0x00000000       0x1e main.o
                0x00000000                main
 swap.o(.text)
 *fill*         0x0000001e        0x2
 .text          0x00000020       0x16 swap.o
                0x00000020                swap
 swap_asm.o(.text)
 .text          0x00000036       0x16 swap_asm.o
                0x00000036                swap_asm

A: The 68000 processor requires instructions to be aligned (and this requirement holds also for data).  Despite of the CPU requirements (which are unskipable) the linker also uses a script in which the segments are required to have some alignment (normally to provide for this cpu requirements)
While the linker script can be tweakable, It can be the case that changing the alignment makes the linker to produce incorrect code (because of what is said in the above paragraph)  but anycase, that's something you can try and test.
Motorola 68000 (and more the 16 bit version of the MegaDrive) triggers a bus error trap when a 16bit transfer is requested on an odd address.  The same happens if a 32bit (but this happens also up to the 68030, the 68040 I think already handles this making several bus accesses, like the Intel processors)

A: So I found my answer. When the assembler detects long (32-bits) data is being dealt with in an assembly file, it automatically aligns the input section along a 4 byte boundary. You can actually override this using SUBALIGN in a linker script. Here's my linker script aligning input sections along a 2 byte boundary.

MEMORY
{
    rom : ORIGIN = 0x00000000, LENGTH = 0x00400000
}

SECTIONS
{
  .text  : SUBALIGN(0x2) {
        *(.header)
        *(.boot)
        obj/main.o(.text)
        *(.text)
        *(.isr)
        *(.vdp)
  } > rom
  .data : { *(.data) } > rom
  .bss : { *(.bss) } > rom
}

New linker map:
.text           0x00000000       0x4a
 main.o(.text)
 .text          0x00000000       0x1e main.o
                0x00000000                main
 swap.o(.text)
 .text          0x0000001e       0x14 swap.o
                0x0000001e                swap
 swap_asm.o(.text)
 .text          0x00000034       0x16 swap_asm.o
                0x00000034                swap_asm