text:
Q: decimal number to utf-8 rational number in Java i want to change 2.5 to 2½. Not sure how to change it.
Let say I have "AMZN 2½ 22" in a long text that I have to highlight in java swing textpane but I have values in three variable as below
A = AMZN
B = 2.5
C = 22

Based on this value I will not be able to match so changing B to Rational number (String) and then matching and it's working fine but I don't want to do this… it's just a temp fix.
Can someone help me ?
B = B.toString().replace(".25", "¼")
                        .replace(".5", "½")
                        .replace(".75", "¾")
                        .replace(".375", "⅜")
                        .replace(".625", "⅜")
                        .replace(".125", "⅛")
                        .replace(".875", "⅞")
                        .replace(".0", "")
                        .replace(".000", "")
                        .replace(".00", "");

Thanks

A: Here's how to print the symbol 'half':
String half = "\u20BD";

System.out.println("2" + half);

determining if a number is an integer plus half is left as an exercise to the reader.

A: You can swap .0 replaces with a regex (replaceAll("\\.[^1-9]+","" comes to mind), you can move the replaces to a map or utility class, have them happen only when Float.parseFloat(var) doesn't throw NumberFormatException...
But there is no truly better way to do such arbitrary replaces. Those unicode strings have no intrinsic connection with the numbers they represent that you could use.

A: There are two alternatives for real numbers: double (an approximation of a real number) or BigDecimal (maintaining a precission).
String a = "AMZN";
BigDecimal b = new BigDecimal("2.5");
double b2 = 2.5;
int c = 22;

// %s = string, %f = floating point, %d = digits, %n = newline.
System.out.printf("%s %f %d%n", a, b2, c);

For double you have not really any control but you might format the output (printf) using "%.3f" for a precission of 3 decimals.
In your case you want to represent the numbers using fractions from the Unicode.
Let's do that with the less suited double:
System.out.printf("%s %s %d%n", a, asFraction(b2), c);

static String[] fractionTexts =  { "", "¼", "½", ... }; // Maybe char
static double[] fractionValues = { 0.0, 0.25, .5, ... };

static String asFraction(double x) {
    if (x < 0) {
        return "\u2212" + asFraction(-x); // U+2212 is Unicode minus.
    }
    long integralPart = (long)x;
    double decimalsPart = x - integralPart;

    for (int i = 0; i < fractionValues.length; ++i) {
        if (almostEqual(decimalsPart, fractionValues[i]) {
            decimalPoint = "";
            return MessageFormat("{0}", integralPart) + fractionTexts[i];
        }
    }
    return MessageFormat("{0}", x);
}

private boolean almostEqual(double x, double y) {
    final double EPS = 0.0001;
    return x >= y - EPS && x <= y + EPS;
}

The code uses MessageFormat for thousand separators / decimal separator. For 0.0, 0.00, 0.00ß0 (the same number) it leaves away the numbers explicitly. The java source code must be in the same encoding as the java compiler and be able to hold ¼ and others (like UTF-8).
For the error bearing double I have introduced almostEqual.


text:
Q: Database Design Strategy Help Thanks for reading this.   I've completely overthought this so I'm hoping to get some feedback.
I have a customer table (custID, statusID), a notes table (custID, noteID), an action table (custID, actionID, noteID)  and a status table (custID, actionID, noteID).
The notes table contains self-referential hierarchical data (like a conversation or a forum with a parent note).
Here are the scenarios:
Every customer has a status (like Approved) but they only have one current status.
A customer might have an action that requires a status update (i.e. credit review leading to an increase in credit)
Any user can record notes about a customer
An action will require one parent note.
Any status change will require one parent note.
Here's where I'm stuck:  I'm thinking I'm getting myself into a data spiral where everything references something else in a random way.  I need to look up a customer and have all the notes available so that was the thinking with my initial design but something seems not right.
I appreciate any thoughts and feedback on this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't extend SpannableStringBuilder? I need to create a custom class by extending SpannableStringBuilder.
I havent even added anything to the class yet. So my class goes like this.
public class xyz extends SpannableStringBuilder{

}

But when I try to use this class instead of SpannableStringBuilder app crashes.
It is working fine when I use SpannableStringBuilder.
I have tried adding the constructors too.

A: When you call xyz(), are you passing in any parameters? If so, make sure you call the appropriate super() constructor from your xyz constructor.


text:
Q: Looking for one linear algebra library for embedded systems (without malloc and free) I use to work with microcontrollers. The RTOSs that I employ in my applications do not have free and malloc (and other calls like assert), sometimes they could be available, but I prefer  to have everything Static in my system.
I have started to employ linear Algebra, but most of them need dynamic memory. My matrices are dense and 'small' (not more than 10x10).
I really like Eigen (everything can be static decided in compile time), but apparently there is a bug calling for asserts which are not provided by my RTOS (even with -DNDEBUG). The library
should provide matrix decomposition routines (like QR, Cholesky, LU...)
I would prefer C instead C++. Any suggestions?
Many thanks in advance!

A: Anything wrong with CLAPACK? Or even straight Fortran LAPACK (you can compile it with gfortran, which is part of gcc).
[C]LAPACK's routines take all memory buffers in their arguments as already allocated, and do not do themselves any heap allocation whatsoever. For the routines that take "work" buffers in addition to the other arguments (for example, dgesdd for computing an SVD), you can usually call them with special "size only" argument, and get back in response the required size for the work buffers, which you can then allocate however you wish.

A: Redefining the assert macro seems a good solution.
But you can even provide your own malloc and free implementation or statically linking with the appropriate memory management library:
http://blog.reverberate.org/2009/02/one-malloc-to-rule-them-all.html

A: If Q16.16 fixed point math is fine for your application, libfixmatrix can be an option:
https://github.com/PetteriAimonen/libfixmatrix


text:
Q: Systemd как запустить и остановить демона [Service]
Type=simple
User=root
OOMScoreAdjust=-1000
WorkingDirectory=/usr/local/bin/checkmate_wbot
ExecStart=/usr/bin/python3 /usr/local/bin/checkmate_wbot/main.py
ExecStop=/usr/bin/python3 /usr/local/bin/checkmate_wbot/main.py
TimeoutSec=595
RestartSec=600
Restart=always

В файле wbot.service прописаны TimeoutSec и RestartSec, как правильно прописать здесь значения, чтобы бот выключился через 595 секунд и сразу запустился? Не смог понять чем отличаются TimeoutStopSec и TimeoutSec, а также не уверен что правильно использую для моих целей RestartSec


text:
Q: Do i lose quality switching from (JPEGTIFF to LZW) to (JPEGTIFF to JPEG)? I build an application that handles a lot of scanned images. These images are imported using JPEGTIFF files. I split the TIFF files to single page LZWTIFF files because the application cant handle JPEGTIFF files. The LZW files are a lot larger that the original JPEGTIFF files and are loading really slow. I'm wondering if i should switch to using single page JPEG files instead of the LZW files. I'm a little scared to do this because JPEG is a lossy compression and LZW is not. But I'm not sure if i gain any quality by going from JPEGTIFF to LZWTIFF. So my question is do i lose quality switching to JPEG instead of LZWTIFF?

A: By definition if you are switching from a lossless compression algorithm to a lossy one you are potentially going to lose quality - though the fact that you're starting from something called "JPEGTIFF" implies there might already be some compression in there. However, there are other factors to take into account which will minimise the issues.

*

*Increasing the quality of the JPEG compression. You can control how much detail is lost by changing the Quality value of the compression. The higher the value, the less data is lost - but obviously this doesn't gain you as much in other areas (disk space, load times etc.)

*Photographs can cope better with lossy compression. Compression artefacts are most noticeable when you have hard edges - such as text, lines and blocky areas that are in manufactured images. A photo of a real scene has less of this and so compression artefacts are less noticeable.
However, you really need to do some tests to see if the quality of images produced is acceptable to your customer.


text:
Q: web scraping for counting news about stocks for an assignment I have I need to count the number of news on different stocks and compare it by graph, this is the link to the site and I attached an example for one of the stock where you can see 49 times for this specific stock,
what will be the best way to attack it -using what type of  package-bs4 or another one  ? what is the best approach here ?
url='https://www.calcalist.co.il/stocks/home/0,7340,L-3959-1102532--4,00.html'


text:
Q: Is there any way to make couchbase server index a document on insert? I can use StaleState=false to force a reindex of the documents when querying but this will index all new documents in the bucket.
What I have is a scenario where largely, there is no need to immediately index most documents being inserted (50-100/sec), but a select few (and i do mean few, like once or twice every minute or so) need to be immediately indexed.
StaleState will force the reindex of all documents and i'd rather just reindex the one document and leave the rest to the background indexer.
Is this possible?

A: At the moment, there is not.  There is a feature being worked on that will allow an application to be more granular about what updates need to be considered in the query.  It should reduce the cost and thus the latency for queries along these lines.  It may not align perfectly since index recalculation will be in order, but it would be closer.


text:
Q: I want to convert fractions of a binary into a decimal fraction, but my program keeps on giving wrong output The formula for solving binary point into decimal point is... if 10.110 then: 1x10\*\*-1, 1x10\*\*-2, ...
but my code is so messed idk... The output of this should be .75
        string a = "10.110";
        if (a.Contains('.'))
        {
            int i = a.IndexOf('.');
            string s = a.Substring(i + 1);
            char[] c = s.ToCharArray();
            int m = 0;

            while (m < c.Length)
            {
                int x = -1;
                int b = c[i] * (10 * x);
                int p = 0;
                p = b + b;
                Console.WriteLine(p);

                x = x + -1;
                m++;
            }

        }

The formula for solving binary point into decimal point is... if 10.110 then: 1x10**-1, 1x10**-2, ... but my code is so messed idk... The output of this should be .75

A: First of all, please, note that if 10.110 is binary (i.e. radix = 2) then its value is
10.110 (binary) == 2**1 + 2**-1 + 2**-2 == 2 + 0.5 + 0.25 == 2.75

if we ignore integer part, i.e. we have .110 binary then
.110 (binary) == 2**-1 + 2**-2 = 0.5 + 0.25 == 0.75

In order to manipulate with these numbers easily, I suggest to enumerate all powers of 1s in the given value:
private static IEnumerable<int> Factors(string value, char decimalSeparator = '.') {
  int pointAt = value.IndexOf(decimalSeparator);

  if (pointAt < 0)
    pointAt = value.Length; // we have an integer value

   for (int i = 0; i < value.Length; ++i)
     if (value[i] == '1')
       yield return i < pointAt
         ? pointAt - i - 1
         : pointAt - i;
}

Then you can do whatever you like with that enumeration (with a little help of Linq):
using System.Linq;

...

string text = "10.110";

// Remark:  in the correct formula it should be 2, not 10
// I've kept "10" to demonstrate the Linq query
string fractionPartPowers = string.Join(", ", Factors(text)
  .Where(power => power < 0)  // fraction part only, no integer part
  .Select(power => $"1x10**{power}"));

Console.WriteLine(fractionPartPowers);

double fractionPart = Factors(text)
  .Where(power => power < 0) // fraction part only, no integer part
  .Sum(power => Math.Pow(2, power)); // note radix == 2

Console.WriteLine(fractionPart);

Output:
1x10**-1, 1x10**-2
0.75

Edit: your code corrected
//TODO: come up with a better name: what does "a" stand for?
string a = "10.110";

double total = 0.0;

int startAt = a.IndexOf('.');

// If we have a fractional part which starts from startAt
if (startAt >= 0)
  // for is more readable than while here;
  // let's track index i within a and corresponding power
  for (int i = startAt + 1, power = -1; i < a.Length; ++i, --power) {
    // we ignore all but 1's
    if (a[i] != '1')
      continue;

    total += Math.Pow(2.0, power);

    // let's print powers
    Console.WrietLine(power);
  }

// 0.75
Console.Write(total);

Output:
-1
-2
0.75


text:
Q: Why does reading take so much time? I have this simple C++ code for loading images into buffer.
FILE *f = fopen("myimage.jpg", "rb");
fseek(f,0,SEEK_END);
unsigned long fsize = ftell(f);
rewind(f);
unsigned char *buf = new unsinged char[size];
fread(buf, 1, fsize, f);
fclose(f);

I use ~1MB large files from my HDD for testing, and the execution time is usually between 100 - 200 ms. That seems too much for me. I've done a benchmark of my HDD and the reading speed was about 80 MB/s. That would mean that reading of 1MB file should take 1000/80 = 12.5 ms, right? Is it actually possible to read the file in such time? Is there anything wrong with my code?

A: For a hard drive here are some of the required actions:

*

*Get the drive up to proper speed (a.k.a. 5400 rev/second).

*Read the directory (the drive may have already cached this).

*Search the directory for the starting track and sector.

*Position the head to the correct track.

*Wait for the sector to come around.

*Read the bits from the sector.

*{optional} Reposition the head to the next block of data (sector & track)

*Read more data.

*The bits have to travel from the hard drive to the memory on the platform.
There may be wait times, because the address bus and the data bus are shared with many devices.

For an SSD drive, you can skip the part about waiting for the platters to speed up and waiting for sectors to come around.  The location of sectors is calculated by math.  Don't need to reposition a read head.
All of the above takes time.
One of the roadblocks is having to reposition the head of the hard drive to read another sector.  Contiguous sectors have less overhead than fragmented sectors.
Edit 1: Increasing performance
You can increase the read performance by purchasing a hard drive that has a faster spin rate and a larger cache.
You can use an application that will Defragment your hard drive.  This reduces the need to reposition the head to different locations for the next block.
Probably, the best performance optimization is to keep the data flowing.  There is an overhead with each transaction (a.k.a read).  For example, reading 1 byte has the same overhead as reading 1024 bytes, thus 1 read of 1024 bytes is more efficient than 1024 reads of one byte.
In keeping up with the data flowing principle, use multiple threads.  Use one thread that reads into one or more buffers.  If one buffer fills up before the other threads finish processing the buffer, read into another one.  Keep the data flowing.
Don't search the file for data, use memory.  Rather than reading until a newline, read in a huge block of data into memory.  Search the memory for the newline.  Searching memory is always faster than searching a hard drive.
Lastly, if your platform has hardware support, use it.  Some platforms have a DMA (Direct Memory Access) chip.  This chip can read data from a port and store into memory without using the CPU.  This allows your CPU to execute instructions while the data is dumped into memory by the DMA chip.  Again, block transfers will be more optimal that single byte transfers.  You will have to check the data sheet on your platform to see if your I/O hardware has DMA and that the processor can access it.


text:
Q: Quickly locate the product configuration in Eclipse When starting working on an unfamiliar Java project, how do I quickly locate the product configuration? The normal way I know is first you have to know which project the product configuration is located, then expand that project in the package explorer and double click the ".product" file. What if I don't have this information? Do I have to search the ".product" in the file system to find out its path?

A: Assuming your project has a .product file (maybe you meant a .project file), you could use ctrl-shift-r and then enter ".product" (or ".project") in the Open Resource pop-up.


text:
Q: galera cluster how to run an ALTER without using RSU/TOI I need to run an alter statement but would like to prevent locking/stall the cluster. The Galera docs advised using:
SET wsrep_OSU_method='RSU';

Then Run the ALTER statement, once finich:
SET wsrep_OSU_method='TOI';

Problem is that this needs to be run in every node, and I have only access to one node behind a load balancer, any alternatives or workarounds?

A: RSU:  You must bypass the load balancer and go straight to each node in turn.
TOI:  Simply run the ALTER on any node.  The downside is that if the ALTER takes a long time, it will, as you say, lock/stall the cluster.
gh-ost:  This depends on the binlog, which (I think) is not used in Galera.
pt-online-schema-change:  This requires adding TRIGGERs to the table -- perhaps a problem?  And it requires a script to continually talk to the server in question -- will your load balancer allow such?  And it probably wants to treat the system as Master-Slave(s), not Multi-Master -- apparently you have set up Galera set up Multi-Master?


text:
Q: Capturing the output of STDERR while piping STDOUT to a file I have a rather odd situation. I'm trying to automate the backup of a collection of SVN repositories with Perl. I'm shelling out to the svnadmin dump command, which sends the dump to STDOUT, and any errors it encounters to STDERR.
The command I need to run will be of the form:
svnadmin dump $repo -q >$backupFile

STDOUT will go to the backup file, but, STDERR is what I need to capture in my Perl script.
What's the right way to approach this kind of situation?
EDIT:
To clarify:
STDOUT will contain the SVN Dump data
STDERR will contain any errors that may happen
STDOUT needs to end up in a file, and STDERR needs to end up in Perl. At no point can ANYTHING but the original content of STDOUT end up in that stream or the dump will be corrupted and I'll have something worse than no backup at all, a bad one!

A: Well, there are generic ways to do it within perl too, but the bash solution (which the above makes me think you're looking for) is to redirect stderr first to stdout and then redirect stdout to a file.  intuitively this doesn't make a whole lot of sense until you see what's happening internally to bash.  But this works:
svnadmin dump $repo -q 2>&1 >$backupFile

However, do not do it the other way (ie, put the 2>&1 at the end), or else all the output of both stdout and stderr will go to your file.
Edit to avoid some people's confusion that this doesn't work:
What you want is this:
# perl -e 'print STDERR "foo\n"; print "bar\n";' 2>&1 > /tmp/f
foo
# cat /tmp/f
bar

and specifically you don't want this:
# perl -e 'print STDERR "foo\n"; print "bar\n";' > /tmp/f 2>&1
# cat /tmp/f
foo
bar

A: Here's one way:
{
    local $/;   # allow reading stderr as a single chunk

    open(CMD, "svnadmin dump $repo -q 2>\&1 1>$backupFile |") or die "...";
    $errinfo = <CMD>;    # read the stderr from the above command
    close(CMD);
}

In other words, use the shell 2>&1 mechanism to get stderr to a place where Perl can easily read it, and use 1> to get the dump sent to the file.  The stuff I wrote about $/ and reading the stderr as a single chunk is just for convenience -- you could read the stderr you get back any way you like of course.

A: While tchrist is certainly correct that you can use handle direction and backticks to make this work, I can also recommend David Golden's Capture::Tiny module. It gives generic interfaces to capturing or tee-ing STDOUT and STDERR, from there you can do with them what you will.

A: This stuff is really easy. It's what backticks were invented for, for goodness' sake.  Just do:
$his_error_output = `somecmd 2>&1 1>somefile`;

and voilà you're done!
I don't understand what the trouble is. Didn't have your gazzintas drilled into you as a young child the way Jethro did? :)

A: From perldoc perlop for qx:

To read both a command's STDOUT and its STDERR separately, it's
  easiest to redirect them separately to files, and then read from those
  files when the program is done:

*

*system("program args 1>program.stdout 2>program.stderr");


text:
Q: How do I pass a newly created ID from the Order Controller to the Order Item Controller in MVC? What I want to do is pass a newly created OrderID from my Order Controller Create Form to the OrderItem Controller Create Form, and add Order_Items related to that specific OrderID I just passed. I managed to redirect the Create Order button to take me straight to the OrderItem Index Form, but it's still pulling all the previously created OrderIDs including the new OrderID when I want to add new OrderItems. I want the form to only pull the OrderID I just created, not all the other OrderIDs previously created.
Also, the reason I redirected it to the Order Item Index Form was so that I could see all the Order Item's related to that specific OrderID, yet it still displays all the OrderItems created for every single OrderID.
I have no idea how to do this since I'm fairly new to MVC, so all help is greatly appreciated.
This is the code for the Order Controller:
   using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    using HealthHabitat.DAL;
    using HealthHabitat.Models;

    namespace HealthHabitat.Controllers
    {
          {
            private HealthContext db = new HealthContext();

        // GET: Order
        public ActionResult Index()
        {
            var orders = db.Orders.Include(o => o.Delivery).Include(o => o.Hospital).Include(o => o.Staff);
            return View(orders.ToList());
        }

        // GET: Order/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Order order = db.Orders.Find(id);
            if (order == null)
            {
                return HttpNotFound();
            }
            return View(order);
        }

        // GET: Order/Create
        public ActionResult Create()
        {
            ViewBag.HospitalID = new SelectList(db.Hospitals, "HospitalID", "Name");
            ViewBag.StaffID = new SelectList(db.Staffs, "StaffID", "First_Name");
            return View();
        }

        // POST: Order/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "OrderID,HospitalID,StaffID,Date,Time")] Order order)
        {
            if (ModelState.IsValid)
            {
                db.Orders.Add(order);
                db.SaveChanges();

                return RedirectToAction("Index","OrderItem", new { id = "OrderID" });
            }

            ViewBag.HospitalID = new SelectList(db.Hospitals, "HospitalID", "Name", order.HospitalID);
            ViewBag.StaffID = new SelectList(db.Staffs, "StaffID", "First_Name", order.StaffID);
            return View(order);
        }

        // GET: Order/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Order order = db.Orders.Find(id);
            if (order == null)
            {
                return HttpNotFound();
            }
            ViewBag.DeliveryID = new SelectList(db.Deliverys, "DeliveryID", "DeliveryID", order.DeliveryID);
            ViewBag.HospitalID = new SelectList(db.Hospitals, "HospitalID", "Name", order.HospitalID);
            ViewBag.StaffID = new SelectList(db.Staffs, "StaffID", "First_Name", order.StaffID);
            return View(order);
        }

        // POST: Order/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "OrderID,HospitalID,StaffID,DeliveryID,Date,Time")] Order order)
        {
            if (ModelState.IsValid)
            {
                db.Entry(order).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.DeliveryID = new SelectList(db.Deliverys, "DeliveryID", "DeliveryID", order.DeliveryID);
            ViewBag.HospitalID = new SelectList(db.Hospitals, "HospitalID", "Name", order.HospitalID);
            ViewBag.StaffID = new SelectList(db.Staffs, "StaffID", "First_Name", order.StaffID);
            return View(order);
        }

        // GET: Order/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Order order = db.Orders.Find(id);
            if (order == null)
            {
                return HttpNotFound();
            }
            return View(order);
        }

        // POST: Order/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Order order = db.Orders.Find(id);
            db.Orders.Remove(order);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

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

This is the code for the Order_Item Controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using HealthHabitat.DAL;
using HealthHabitat.Models;

namespace HealthHabitat.Controllers
{
    public class OrderItemController : Controller
    {
        private HealthContext db = new HealthContext();

        // GET: OrderItem
        public ActionResult Index()
        {

            var order_Items = db.Order_Items.Include(o => o.Item).Include(o => o.Order);

            return View(order_Items.ToList());

        }

        // GET: OrderItem/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Order_Item order_Item = db.Order_Items.Find(id);
            if (order_Item == null)
            {
                return HttpNotFound();
            }
            return View(order_Item);
        }

        // GET: OrderItem/Create
        public ActionResult Create()
        {

            ViewBag.ItemID = new SelectList(db.Items, "ItemID", "Name");
            ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderID");
            return View();
        }

        // POST: OrderItem/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Order_ItemID,OrderID,ItemID,Type,Quantity")] Order_Item order_Item)
        {
            if (ModelState.IsValid)
            {

                db.Order_Items.Add(order_Item);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.ItemID = new SelectList(db.Items, "ItemID", "Name", order_Item.ItemID);
            ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderID", order_Item.OrderID);
            return View(order_Item);
        }

        // GET: OrderItem/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Order_Item order_Item = db.Order_Items.Find(id);
            if (order_Item == null)
            {
                return HttpNotFound();
            }
            ViewBag.ItemID = new SelectList(db.Items, "ItemID", "Name", order_Item.ItemID);
            ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderID", order_Item.OrderID);
            return View(order_Item);
        }

        // POST: OrderItem/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Order_ItemID,OrderID,ItemID,Type,Quantity")] Order_Item order_Item)
        {
            if (ModelState.IsValid)
            {
                db.Entry(order_Item).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.ItemID = new SelectList(db.Items, "ItemID", "Name", order_Item.ItemID);
            ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderID", order_Item.OrderID);
            return View(order_Item);
        }

        // GET: OrderItem/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Order_Item order_Item = db.Order_Items.Find(id);
            if (order_Item == null)
            {
                return HttpNotFound();
            }
            return View(order_Item);
        }

        // POST: OrderItem/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Order_Item order_Item = db.Order_Items.Find(id);
            db.Order_Items.Remove(order_Item);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

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

Order Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace HealthHabitat.Models
{
    public class Order
    {
        public int OrderID { get; set; }

        [Display(Name = "Hospital")]
        public int HospitalID { get; set; }

        [Display(Name = "Staff")]
        public int StaffID { get; set; }
        public int? DeliveryID { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime Date { get; set; }

        [DataType(DataType.Time)]
        [DisplayFormat(DataFormatString = "{0:H:mm}", ApplyFormatInEditMode = true)]
        public DateTime Time { get; set; }

        public virtual Hospital Hospital { get; set; }
        public virtual Staff Staff { get; set; }
        public virtual Delivery Delivery { get; set; }
        public virtual ICollection<OrderItem> OrderItems { get; set; }
    }
}

OrderItem Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace HealthHabitat.Models
{
    public class OrderItem
    {

        public int OrderItemID { get; set; }
        public int OrderID { get; set; }
        public int ItemID { get; set; }

        [Required]
        public string Type { get; set; }

        public int Quantity { get; set; }

        public virtual Order Order { get; set; }
        public virtual Item Item { get; set; }

    }
}

Item Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace HealthHabitat.Models
{
    public class Item
    {
        public int ItemID { get; set; }

        [Required, Display(Name = "Item Type")]
        public string Type { get; set; }

        [Required, Display(Name = "Item Name")]

        public string Name { get; set; }

        [Display(Name = "Item Quantity")]
        public int Quantity { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-mm-dd}", ApplyFormatInEditMode = true)]
        [Display(Name = "Expiry Date")]
        public DateTime Expiry_Date { get; set; }
        public int Consumption { get; set; }

        public virtual ICollection<OrderItem> OrderItems { get; set; }
    }
}

A: Its a little unclear of what the purpose of your Index() method in OrderItemController would be. Your just displaying all order items for all orders. Typically your Details() method for OrderController would display details of the order and a list of items associated with that order (perhaps as a table showing all details of each OrderItem in cluding links to edit/delete, or as links to the Details() method of OrderItemController if there is too much information to display on the one page)
I would suggest the following structure
OrderController
public ActionResult Index()
{
  // Display a collection on all orders
}
public ActionResult Details(int ID)
{
  // Display the details of an order, including a collection of its order items
}
public ActionResult Create()
{
  // Create a new Order
}
[HttpPost]
public ActionResult Create(Order model)
{
  // Save the order
  return RedirectToAction("Details", new { ID = model.ID });
}

The Details.cshtml view would then include a link (menu item) to create a new OrderItem associated with the Order
@Html.ActionLink("Create Item", "Create", "OrderItem", new { ID = Model.OrderID }, null)

OrderItemController
public ActionResult Create(int ID) // ID is the ID of the Order
{
  OrderItem model = new OrderItem() { OrderID = ID };
  return View(model);
}
[HttpPost]
public ActionResult Create(OrderItem model)
{
  // Save the OrderItem and redirect to the order details page
  return RedirectToAction("Details", "Order", new { ID = model.OrderID });
}

In the Create.cshtml view for OrderDetails, include the OrderID as a route value in the form, or include a hidden input inside the form
@model OrderDetail
@using (Html.BeginForm(new { OrderID = Model.OrderID }))
{
  ....
}

Side note: Recommend you follow normal naming conventions - OrderItem, not Order_Item - and use view models, especially for creating/editing and remove those awful [Bind(Include = "...")] attributes.

A: Add an id parameter to your Index action in your OrderItemController and use that id to filter the order items.
public ActionResult Index(int id)
{

    var order_Items = db.Order_Items.Include(o => o.Item).Include(o => o.Order).Where(o => o.OrderId == id);

    return View(order_Items.ToList());
}


text:
Q: NSKeyedArchiver NOT writing Data to File...? @interface
@interface Patient : NSObject <NSCoding>

@implementation
- (id)initWithCoder:(NSCoder *)decoder{

    self.patientPhoto = [decoder decodeObjectForKey:kPatientPhoto];
    self.firstName = [decoder decodeObjectForKey:kFirstName];
    self.lastName = [decoder decodeObjectForKey:kLastName];
    self.age = [decoder decodeIntForKey:kAge];
    self.photoPaths = [decoder decodeObjectForKey:kPhotoPaths];
    self.photoDates = [decoder decodeObjectForKey:kPhotoDates];

    return self;

   }

- (void)encodeWithCoder:(NSCoder *)encoder{

        [encoder encodeObject:self.patientPhoto forKey:kPatientPhoto];
        [encoder encodeObject:self.firstName forKey:kFirstName];
        [encoder encodeObject:self.lastName forKey:kLastName];
        [encoder encodeInt:self.age forKey:kAge];
        [encoder encodeObject:self.photoPaths forKey:kPhotoPaths];
        [encoder encodeObject:self.photoDates forKey:kPhotoDates];

    }

In a different implementation I attempt to archive the Patient Object.
     IMDataController* dataCtr = [IMDataController sharedDataController];

     Patient *currentPatient = [[Patient alloc]init];

     currentPatient.patientPhoto = self.photo.image;
     currentPatient.firstName = self.firstName.text;
     currentPatient.lastName = self.lastName.text;
     currentPatient.age = [self.lastName.text intValue];
     currentPatient.photoDates = nil;
     currentPatient.photoPaths = nil;

     NSString *patientNameForWriting = [self.firstName.text stringByAppendingString:self.lastName.text];

     NSString *stringToPatientObjectFile = [dataCtr createPatient:patientNameForWriting];

     NSFileManager* filemanager = [NSFileManager defaultManager];

    NSData *patientObjectArchived = [NSKeyedArchiver archivedDataWithRootObject:currentPatient];

     if([patientObjectArchived writeToFile:stringToPatientObjectFile atomically:YES]){

     }else{

         NSLog(@"Patient Object Didn't Archive");

     }

The above method within the if statement is not returning YES. I have checked the data against nil, I have checked my encoder method and I cannot find the problem. I am writing the data to a NSString file Path:.../Documents/PatientName/PatientObject.archive. I am conforming to the protocol in the patient class also.

A: Make sure the parent directory exists. As far as I can remember, writeToFile:atomically: does not create the directory hierarchy automatically.

A: Replace your NSCoding implementation with the following:
- (id)initWithCoder:(NSCoder *)decoder{
    if (self = [super initWithCoder:(NSCoder *) decoder])
    {
        self.patientPhoto = [decoder decodeObjectForKey:kPatientPhoto];
        self.firstName = [decoder decodeObjectForKey:kFirstName];
        self.lastName = [decoder decodeObjectForKey:kLastName];
        self.age = [decoder decodeIntForKey:kAge];
        self.photoPaths = [decoder decodeObjectForKey:kPhotoPaths];
        self.photoDates = [decoder decodeObjectForKey:kPhotoDates];
    }
    return self;

   }

- (void)encodeWithCoder:(NSCoder *)encoder{
        [super encodeWithCoder:encoder];
        [encoder encodeObject:self.patientPhoto forKey:kPatientPhoto];
        [encoder encodeObject:self.firstName forKey:kFirstName];
        [encoder encodeObject:self.lastName forKey:kLastName];
        [encoder encodeInt:self.age forKey:kAge];
        [encoder encodeObject:self.photoPaths forKey:kPhotoPaths];
        [encoder encodeObject:self.photoDates forKey:kPhotoDates];

 }

And then, change the line:
NSData *patientObjectArchived = [NSKeyedArchiver archivedDataWithRootObject:currentPatient];

with:
NSMutableData *patientObjectArchived = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData: patientObjectArchived];
[archiver encodeObject:currentPatient forKey:@"someKey"];
[archiver finishEncoding];


text:
Q: ${n\choose 2} - {k\choose 2} = {n-k\choose 2} +k(n-k)$ Marked box or unmarked box ${n\choose 2}$ counts the 2-combination $(a,b)$ where

*

*$a\,\in\,\{\text{Set with n-k elements}\}\,b\,\in\,\{\text{Set with n-k elements}\}$

*$a\,\in\,\{\text{Set with n-k elements}\}\,b\,\in\,\{\text{Set with k elements}\}$ Order trivial here?

*$a\,\in\,\{\text{Set with k elements}\}\,b\,\in\,\{\text{Set with k elements}\}$
${k\choose 2}$ counts the 2-combination $(a,b)$ where

*

*$a\,\in\,\{\text{Set with k elements}\}\,b\,\in\,\{\text{Set with k elements}\}$
${n-k\choose 2}$ counts the 2-combination $(a,b)$ where

*

*$a\,\in\,\{\text{Set with n-k elements}\}\,b\,\in\,\{\text{Set with n-k elements}\}$
$k(n-k)$ counts the 2-combination $(a,b)$ where

*

*$a\,\in\,\{\text{Set with n-k elements}\}\,b\,\in\,\{\text{Set with k elements}\}$

*First question, is that because the order is trivial, either $k(n-k)$ or $(n-k)k$ would suffice?

*Second question, under what circumstances will both $k(n-k)$ and $(n-k)k$ have to be counted?

A: Maybe it is clearer as
$$\binom{n}{2}=\binom{k}{2}+\binom{n-k}{2}+k(n-k),$$
which you can prove combinatorially as follows. The LHS counts the number of 2-subsets $\{a,b\}$ (with $a<b$) of
$\{1,\dots,n\}$.  The RHS counts the same objects according to three mutually exclusive cases:

*

*$\{a,b\} \subset \{1,\dots,k\}$

*$\{a,b\} \subset \{k+1,\dots,n\}$

*$a\in \{1,\dots,k\}$ and $b \in\{k+1,\dots,n\}$
Because $a < b$, these are the only possibilities.


text:
Q: How to stop Pipe in getopt? I'm trying to run something like this in getopt.

./bmptool -s 2 example.bmp | ./bmptool -r 90 -o out.bmp

My code works but I would like to know if there is a way for me to not run this command

./bmptool -r 90 -o out.bmp

if something goes wrong when I'm running

./bmptool -s 2 example.bmp

The following method is used to catch if a user enters a case that is not present and exits the program if needed. It works when I'm only running one command, but when I chain commands together it stills run the following command giving me some an output that I do not want. Any help will be much appreciated. Thanks!
if (err || optind + 1 < argc) {
    fprintf(stderr, usage, argv[0]);
    exit(-1);
}


text:
Q: cmake fails to find OpenSSL libs (cpp-netlib) I'm trying to build the cpp-netlib on windows (8.1) with VS2013 (express).
When I run cmake:
C:\...\build\cmake ..\source -DCMAKE_BUILD_TYPE=Release
it writes:

Could NOT find OpenSSL, try to set the path to OpenSSL root folder in
  the system variable OPENSSL_ROOT_DIR (missing:  OPENSSL_LIBRARIES)
  (found version "0.9.8h")

I installed OpenSSL using the GnuWin32 installer (http://gnuwin32.sourceforge.net/packages/openssl.htm) using the full package (except sources).
I've also set the OPENSSL_ROOT_DIR and OPENSSL_LIBRARIES env. variables but to no avail.
I've searched, and there's quite a bit of information about it, but nothing I found helped me solve it..
Any ideas?
Thanks.

A: You just need to install the libssl-dev package (ubuntu)


text:
Q: What is the clearcut difference between re-entrant and thread-safe function in linux?
Possible Duplicate:
Threadsafe vs re-entrant

Could someone show me the URL where i can look at the difference between re-entrant and thread-safe concept ?


text:
Q: Pagination for JSON data I have a large data set of quotes in JSON format e.g.
[
  {
    "Quote": "Don't cry because it's over, smile because it happened.",
    "Author": "Eleanor Roosevelt,  This is My Story",
    "Category": "wisdom"
  },
  {
    "Quote": "No one can make you feel inferior without your consent.",
    "Author": "Dr. Seuss",
    "Category": "life"
  },
  {
    "Quote": ""Be yourself; everyone else is already taken.",
    "Author": "Oscar Wilde",
    "Category": "inspiration"
  },

As it is a rather large data set, I would like to paginate it so that only 10 will be shown at a time. I came across the paginate.js plugin and tried to implement it into my code. I want to present these quotes along with the author and category to users of my website in a stylish manner (cards that expand on hover).
I am able to get and create the correct amount of entries/cards for the first page but the issue is that there doesn't seem to be any other page(s) or a navigator to get to the other quotes.
What my page looks like currently: https://i.stack.imgur.com/8GgQA.png
As you can see from the image, the cards are created correctly, however, there isn't the pagination links to the other quotes, which I believe should be before the next div(little grey bit at the bottom of the image).
HTML:

Quote Collection

Inspiration

                    "I'm selfish, impatient and a little insecure. I make mistakes, I am
                    out of control and at times hard to handle. But if you can't handle
                    me at my worst, then you sure as hell don't deserve me at my best."

Author

                Marilyn Monroe

JS Code:
$("#card-list").pagination({
    dataSource: quotes,
    pageSize: 10,
    callback: function (data, pagination) {
      $("#card-list").empty();
      $.each(data, function (key, val) {
        const card = createQuoteCard(val.Quote, val.Author, val.Category); // function that creates the card markup
        $("#card-list").append(card);
      });
    },
  });

I expect there to be 3 pages as I am testing the pagination with 30 objects/cards. There isn't any errors and I can't find anything wrong with my code. Can anyone give me advice or point me in the right direction, it would be greatly appreciated.

A: You can use the event afterRender in order to move the pagination bar before the section card-list....so you can see it.
Your updated fiddle
The function changed:
function paginateQuotes(quotes) {
   let quoteCards = [];
   $("#card-list").pagination({
     dataSource: quotes,
     pageSize: 10,
      afterRender: function() {  // added this event
            if ($("#card-list div.paginationjs").length == 1) {
            $("#card-list div.paginationjs").insertBefore("#card-list")
        }
     },
     callback: function(data, pagination) {
       $("#card-list").empty();
       $.each(data, function(key, val) {
         const card = createQuoteCard(val.Quote, val.Author, val.Category); // funtion that creates the card markup
         $("#card-list").append(card);
       });
     },
   });
 }


text:
Q: Send to client pdf file with AJAX request i'm developing a web application using javascript and nodejs.
I have to respond to an ajax post request of the client with pdf file.
Client code is:
 $.ajax({
        type: "POST",
        url: "/getSlides",
        data:{name,professor},

    }).done(function(data){

        console.log(data);

    });

So i want that client side the object datacontains the pdf or to get pdf reference from data object.
Server side i'm trying to send this as follow:
   app.post("/getSlides",function(req,res) {

    name = req.body.name;
    professor = req.body.professor;

    daoQuery.getSlides(name,professor,infoStudent[0].email,function(result){

        var form = new FormData();

          fs.readFile(result[0].slides_path,'application/pdf',function(err,file){

            if(err) throw err;

            form.append("0",file);

            console.log(file);

                res.send(form);

           });

        });

    });

Where daoQuery.getSlides function returns an array of objects with the fields .slides_path that is the path where the pdf is stored on the server.
I choose to use the form-data because it worked on the opposite route (when i upload slides from client to server) but i don't know if it is the right way to work.
I just need a way to receive pdf from the server.

A: Well i took a quick look at your code and i think you have missed to mention name and professor as a variables, the data undefined.
i guess, it should be:
var name = req.body.name; //variable defined
var professor = req.body.professor; //variable defined

app.post("/getSlides",function(req,res) {

    var name = req.body.name; //variable defined
    var professor = req.body.professor; //variable defined

    daoQuery.getSlides(name,professor,infoStudent[0].email,function(result){

        var form = new FormData();

          fs.readFile(result[0].slides_path,'application/pdf',function(err,file){

            if(err) throw err;

            form.append("0",file);

            console.log(file);

                res.send(form);

           });

        });

    });

go thru step by step, hopefully this will help u


text:
Q: Building a recurrence relation for this code? I need to build a recurrence relation for the following algorithm (T(n) stands for number of elemental actions) and find it's time complexity:
Alg (n)
{
    if (n < 3) return;
    for i=1 to n
    {
       for j=i to 2i
       {
           for k=j-i to j-i+100
              write (i, j, k);
       }
    }

    for i=1 to 7
       Alg(n-2);
 }

I came to this Recurrence relation (don't know if it's right):

T(n) = 1 if n < 3
T(n) = 7T(n-2)+100n2 otherwise.

I don't know how to get the time complexity, though.
Is my recurrence correct? What's the time complexity of this code?

A: Let's take a look at the code to see what the recurrence should be.
First, let's look at the loop:
    for i=1 to n
    {
       for j=i to 2i
       {
           for k=j-i to j-i+100
               write (i, j, k);
       }
    }

How much work does this do? Well, let's begin by simplifying it. Rather than having j count up from i to 2i, let's define a new variable j' that counts up from 0 to i. This means that j' = j - i, and so we get this:
    for i=1 to n
    {
       for j' = 0 to i
       {
           for k=j' to j'+100
               write (i, j' + i, k);
       }
    }

Ah, that's much better! Now, let's also rewrite k as k', where k' ranges from 1 to 100:
    for i=1 to n
    {
       for j' = 0 to i
       {
           for k'= 1 to 100
               write (i, j' + i, k' + j);
       }
    }

From this, it's easier to see that this loop has time complexity Θ(n2), since the innermost loop does O(1) work, and the middle loop will run 1 + 2 + 3 + 4 + ... + n = Θ(n2) times. Notice that it's not exactly 100n2 because the summation isn't exactly n2, but it is close.
Now, let's look at the recursive part:
for i=1 to 7
    Alg(n-2);

For starters, this is just plain silly! There's no reason you'd ever want to do something like this. But, that said, we can say that this is 7 calls to the algorithm on an input of size n - 2.
Accordingly, we get this recurrence relation:

T(n) = 7T(n - 2) + Θ(n2)  [if n ≥ 3]
T(n) = Θ(1) [otherwise]

Now that we have the recurrence, we can start to work out the time complexity. That ends up being a little bit tricky. If you think about how much work we'll end up doing, we'll get that

*

*There's 1 call of size n.

*There's 7 calls of size n - 2.

*There's 49 calls of size n - 4.

*There's 343 calls of size n - 6.

*...

*There's 7k calls of size n - 2k

From this, we immediately get a lower bound of Ω(7n/2), since that's the number of calls that will get made. Each call does O(n2) work, so we can get an upper boudn of O(n27n/2). The true value lies somewhere in there, though I honestly don't know how to figure out what it is. Sorry about that!
Hope this helps!

A: A formal method is to do the following:

The prevailing order of growth can be intuitively inferred from the source code, when it comes to the number of recursive calls.
An algorithm with 2 recursive calls has a complexity of 2^n; with 3 recursive calls the complexity 3^n and so on.


text:
Q: Extract cross-table duplicates not incl. table duplicates Imagine the following tables:
Table A:
x, y

Table B:
a, b

To find matches we will be performing the following query:
SELECT A.x, B.a FROM A, B WHERE A.y = B.b
However, Table B will contain duplicates itself and therefore the same value will match multiple times with the value (unique) in Table A how to avoid this?
Edited: An other acceptable answer if the above is impossible to do in a single query is to find all duplicates in Table B ignoring Table A and remove all of them except for one.
Edit 2 as per request:
Table A
col, 'hi'
col, 'bye'
col, 'lol'
col, 'teehee'
col, 'example'

Table B
col, 'hi'
col, 'hi'
col, 'bye'
col, 'hi'
col, 'bye'
col, 'example'
col, 'teehee'
col, 'lol'
col, 'hi'

Because there is multiple values hi and bye in Table B it will extract the value (col) in Table A multiple times which should be avoided since we're talking about 1000s of rows.

A: If you want all rows from A and one arbitrary value from B, you have several options.  Most involve group by or distinct, which is rather expense.  The most performant method is probably to use a correlated subquery:
select a.*,
       (select b.a
        from b
        where A.y = B.b
        limit 1
       ) as b_a
from a;

For performance, you want an index on b(b).


text:
Q: How to install AMD Drivers correctly?
Possible Duplicate:
What is the correct way to install ATI Catalyst Video Drivers (fglrx)?

I recently installed ATI Drivers from the Ubuntu repository but after the installation when I try to open ATI Catalyst Control Center. I get a message that ATI Drivers are not properly installed or there is a problem with the hardware.
Similar problem was faced by a friend of mine. On his laptop Mint worked smoothly but the drivers for ATI were not installed correctly
.

A: There is a really good community wiki on this which should help you on this site here
Ask Ubuntu ATI Community Wiki
Ubuntu also have an easy to follow guide here
Ubuntu Community Wiki
To start with you will have to purge the installation you have of all the ATI information by doing the following command:
sudo apt-get remove --purge fglrx-updates fglrx-amdcccle-updates

This will clean out any crudd that is left over/obsolete and then you can follow either of the guides above.


text:
Q: Set new text in JEditorPane I am facing a problem when setting new text in JEditorPane in a subclass Index that extends JFrame.
package gui;
...
public class Index extends JFrame {
    JEditorPane editorPaneMR = new JEditorPane();

public static void main(String[] args) {
    ...
}

public Index() {
        JButton SearchButton = new JButton("OK");
        SearchButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                parser GooBlog = new parser(url);
                try {
                    GooBlog.hello(); // Go to subclass parser
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

And this the code of subclass called parser
package gui;
public class parser extends Index{
    String url;

    public parser (String urlInput){
        this.url = urlInput;
    }

    public void hello () throws IOException{
        editorPaneMR.setText("Hello World");
    }
}

The problem is when I pressed OK button it doesn't show me the text "Hello world" in JEditorPane! and it doesn't show me any error, just nothing happened.

A: The code line
parser GooBlog = new parser(url);

instantiates not only a parser but also a new Index/JFrame. The JEditorPane of this newly created JFrame is used inside method hello and since the frame is not visible, nothing will happen.
A solution might be to provide a reference to your JFrame or JEditorPane into method hello, e.g.
public class Parser {  // does no longer extend Index
    String url;

    public Parser(String urlInput) {
        this.url = urlInput;
    }

    public void hello(JEditorPane editorPane) {  // has argument now
        editorPane.setText("Hello World");
    }
}

which will then be called via
Parser gooBlog = new Parser(url);
gooBlog.hello(Index.this.editorPaneMR);

Note: Please stick to common Java coding standards and use upper case names for classes, i.e. Parser instead of parser, and lower case variable/field/method names, e.g. gooBlog.


text:
Q: automorphism of the projective space $\mathbb{P}_A^n$ In exercise 16.4.B of Vakil's notes, he establishes that the group of automorphisms of $\mathbb{P}_k^n$ is $PGL_{n+1}(k)$. This I can manage to show, but in the remarks following the exercise he asks why this does not work over an arbitrary base ring $A$, and I have a hard time to see why. I have three questions and would be grateful if someone can comment on them:
1) First, is it true that $\pi^*O_{\mathbb{P}_A}(1)\simeq O_{\mathbb{P}_A}(1)$ if $\pi:\mathbb{P}_A^{n}\to\mathbb{P}_A^{n}$ is an automorphism? Over a field $k$, this holds because an automorphism induces an isomorphism on Picard groups. So a generator must be sent to a generator, but I do not understand the Picard group of $\mathbb{P}_A^{n+1}$, so I can't see if this generalizes. In any case, if it is true, please give an argument. If it's not, please give a counter-example.
2) Does it make sense to define $PGL_{n+1}(-)$ as the functor that sends $A$ to the set of $(n+1)\times (n+1)$  invertible matrices over $A$ modulo multiples of identity? If so, is it representable (possibly in some sub-category of schemes over $A$)?
3) If $PGL_{n+1}(A)$ does not parametrize automorphisms of $\mathbb{P}_A^{n+1}$, what does it parametrize?
4) Is there a good description of automorphisms of $\mathbb{P}_A^n$?

A: Ch. 0, §5 of Mumford's Geometric Invariant Theory (3rd ed.) answers 1) and 4) well, I think. Let $PGL(n+1) = \{\operatorname{det} (a_{ij}) \ne 0\} \subset \operatorname{Proj}\mathbb{Z}[a_{00},\ldots,a_{nn}]$ denotes the projective general linear group which acts on $\mathbb{P}^n_\mathbb{Z}$ in the usual way. Let $\mathscr{PGL}(n+1)$ denote the functor $S \mapsto \operatorname{Hom}(S,PGL(n+1))$ in the category of noetherian schemes. Let $\operatorname{Aut}(\mathbb{P}^n)$ denote the functor sending $S$ to the group of automorphisms $\operatorname{Aut}_S(\mathbb{P}^n_S)$ of $\mathbb{P}^n_S$ over $S$.
Theorem. The functors $\mathscr{PGL}(n+1)$ and $\operatorname{Aut}(\mathbb{P}^n)$ are isomorphic.
I don't know of a better description in general (i.e. for non-noetherian schemes), but this seems to answer 4).
Moreover, his proof answers 1): the invertible sheaves on $\mathbb{P}^n_S = \mathbb{P}^n_\mathbb{Z} \times S$ are all of the form $p_1^*(\mathcal{O}_{\mathbb{P}^n_\mathbb{Z}}(k)) \otimes p_2^*(L)$ where $L$ is an invertible sheaf on $S$, and $p_1,p_2$ are the projection morphisms. So, if $\alpha \in \operatorname{Aut}_S(\mathbb{P}^n_S)$, then $\alpha^*(\mathcal{O}_{\mathbb{P}^n_S}(1)) \cong p_1^*(\mathcal{O}_{\mathbb{P}^n_\mathbb{Z}}(k)) \otimes p_2^*(L)$ for some $k$ and $L$. Then, since $\alpha$ is an automorphism over $S$, we must have
$$\bigoplus_{i=0}^n X_i \cdot \mathcal{O}_S \cong p_{2*}p_1^*\mathcal{O}_{\mathbb{P}^n_\mathbb{Z}}(1) \cong p_{2*}(p_1^*(\mathcal{O}_{\mathbb{P}^n_\mathbb{Z}}(k)) \otimes p_2^*(L)) \cong
\bigoplus_{r_0+\cdots+r_n=k}^n (X_0^{r_0}\cdots X_n^{r_n}) \cdot L$$
so $k=1$ and in fact by [EGAII, 4.2] every isomorphism $\alpha$  can be obtained by choosing an invertible sheaf $L$ and an isomorphism $\bigoplus_{i=0}^n X_i \cdot \mathcal{O}_S \overset{\sim}{\to} \bigoplus_{i=0}^n X_i \cdot L$. What's nice is that before, $PGL(n+1)$ consisted of $(n+1) \times (n+1)$ matrices of sections of $\mathcal{O}_{\mathbb{P}^n_\mathbb{Z}}(1)$ with non-vanishing determinant; now the isomorphisms $\bigoplus_{i=0}^n X_i \cdot \mathcal{O}_S \overset{\sim}{\to} \bigoplus_{i=0}^n X_i \cdot L$ are given by $(n+1) \times (n+1)$ matrices of sections of $L$ with non-vanishing determinant.
In particular, to answer your comment on Qiaochu's answer, it looks like $S$ having trivial Picard group is sufficient went to answer 3) affirmatively, but I'm not convinced it's necessary: by the proof it looks like what we need is that for all invertible sheaves $L$ on S such that $\bigoplus_{i=0}^n X_i \cdot \mathcal{O}_S$ and $\bigoplus_{i=0}^n X_i \cdot L$ are isomorphic, we also have that $\mathcal{O}_S$ and $L$ are isomorphic.

A: 2) No. Here is a topological analogy, which I learned from MO: instead of commutative rings, let's think about C*-algebras of continuous functions on compact Hausdorff spaces $X$. Then $\text{GL}_n(C(X))$ is equivalently the space of continuous functions $X \to \text{GL}_n(\mathbb{C})$, for example. The "correct" definition of $\text{PGL}_n(C(X))$, e.g. the one that makes it representable by a space, is therefore the space of continuous functions $X \to \text{PGL}_n(\mathbb{C})$.
This is not the same as $\text{GL}_n(C(X))$ mod its center; the discrepancy is described up to homotopy by an exact sequence
$$H^{0}(X, \mathbb{C}^{\times}) \to H^{0}(X, \text{GL}_n(\mathbb{C})) \to H^{0}(X, \text{PGL}_n(\mathbb{C})) \to H^{1}(X, \mathbb{C}^{\times}) \to \cdots$$
associated to the short exact sequence
$$1 \to \mathbb{C}^{\times} \to \text{GL}_n(\mathbb{C}) \to \text{PGL}_n(\mathbb{C}) \to 1$$
of topological groups, where by $H^0(X, G)$ I mean homotopy classes of continuous maps $X \to G$ and by $H^1(X, G)$ I mean homotopy classes of continuous maps $X \to BG$, where $BG$ is the delooping of $G$. Here $H^1(X, \mathbb{C}^{\times}) \cong \text{Pic}(X) \cong H^2(X, \mathbb{Z})$ is the Picard group of continuous line bundles on $X$, so the exact sequence tells us that the obstruction to lifting an element in $\text{PGL}_n(C(X))$ to an element of $\text{GL}_n(C(X))$, up to homotopy, is given by a line bundle on $X$; roughly speaking this is because there is a $\mathbb{C}^{\times}$s worth of lifts locally but no guarantee that it is possible to patch them up globally into a consistent global lift.


text:
Q: Using log4net in F# as a singleton separate class I've seen a few posts about implementing log4net using C# and F# - but I am wanting to implement it as a singleton in a separate class ( so I can call from anywhere )
I am loosely following this post.  I just think my translation from C# to F# is a bit behind.
I set up the log4net.config and run the following code at the start of my console app
namespace MyNamespace

open System.IO
open log4net.Config

module LoggerConfigure =
    let configureLogging() =
        FileInfo("log4net.config")
        |> XmlConfigurator.Configure
        |> ignore

The following ( from the link above ) is C# and I want it to be an F# class that can be called as a singleton.
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

My primary quwation is - I'm a bit stuck converting that to an F# class.  How do I do that?.  Any ideas you have around the whole concept is appreciated as well.

A: There may be cases where a more sophisticated handling of singletons is needed, but I believe that standard global let declaration in an F# module would work well enough.
You just need to make sure that the configuration code is run before the log value is accessed, which you can do by making that call as part of the let binding that defines log:
module LoggerConfigure =
    let configureLogging() =
        FileInfo("log4net.config")
            |> XmlConfigurator.Configure
            |> ignore
        log4net.LogManager.GetLogger
            (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
    let log = configureLogging()

Or if you prefer to put everything in a single expression:
module LoggerConfigure =
    let log =
        FileInfo("log4net.config") |> XmlConfigurator.Configure |> ignore
        log4net.LogManager.GetLogger
            (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)


text:
Q: Parsing json with JSON.net on windows phone c# I'm a novice developer for WP. I have some problems with parsing json data.
I take it from the server and parse with JSON.Net.
Example of JSON  data
{"response":
     {"ad6a95dd8f90fad7e281994cb5a8cacd":
           {"status":"offline", "name": "Test Name",
            "id":"ad6a95dd8f90fad7e281994cb5a8cacd"}
     }
 "success":true
}

The first chield of "response" varies with each request to the server.
How I can extract value of "name" field ?! Thank you in advance for your reply.
I try that in Page.xaml.cs
var o = JObject.Parse(result);
        var id = o["response"].First;
        ServerList.ItemsSource = id;

and in Page.xaml
<ScrollViewer Foreground="White">
                        <ListBox Margin="0,0,-12,0" Name="ServerList" Height="508" Width="415">
                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel Margin="0,0,0,20" Width="300">
                                        <TextBlock Text="{Binding Path=name}" />
                                    </StackPanel>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>
                    </ScrollViewer>

I did it by example.

A: To get the name value from that Json I did this:
var o = JObject.Parse(result);
var id = o["response"].First.First["name"];
string name = id.Value<string>();

If you are actually trying to do this operation over an array of responses such as this:
{"responses":
    [
        {"response":
            {"ad6a95dd8f90fad7e281994cb5a8cacd":
                {"status":"offline", "name": "Test Name","id":"ad6a95dd8f90fad7e281994cb5a8cacd"} },"success":true },
        {"response":
            {"ad6a95dd8f90fad7e281994cb5a8cacd":
                {"status":"offline", "name": "Test Name2","id":"ad6a95dd8f90fad7e281994cb5a8cacd"} }, "success":true }
    ]
}

Then your code would need to look something like:
var o = JObject.Parse(result);
var ids = from c in o["responses"].Children() select c["response"].First.First;
var names = ids.Select(t => t.SelectToken("name").Value<string>());


text:
Q: While com PHP e Datapicker Tenho uma página que é alimentado com informações do Banco de Dados Mysql. Esta página também contém um Input Text com calendário dataPicker. O problema é que apenas a primeira linha do looping funciona com DataPicker, as demais não.
Formulario:
    while($fetch = mysql_fetch_assoc($xxx)){

     <input  name="protocolo" id="protocolo" type="text"
     placeholder="00/00/0000"
     style="width:100px;font-size: 13px" class="form-control input-md">

DataPicker
<script type="text/javascript">
$(document).ready(function(e) {
    $("#protocolo").datepicker({
        dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
        dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
        dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'],
        monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
        monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
        dateFormat: 'yy-mm-dd',
        nextText: 'Próximo',
        prevText: 'Anterior'
    });
});
</script>
     } ?>

Ambos estão dentro do While, testei colocando o DataPicker fora do white, porem o problema permanece, apenas a primeira linha do While abre o calendário, as demais não.

A: O atributo ID deve ser único. Quando você tem mais de dois elementos com o mesmo atributo ID. O JavaScript irá considerar apenas o primeiro.
Ao invés de utilizar ID, utilize outros atributos como class, data-* etc.
Ex:
while($fetch = mysql_fetch_assoc($xxx)){
    <input name="protocolo[]" type="text"
            placeholder="00/00/0000"
            style="width:100px;font-size: 13px" class="form-control protocolo input-md"/>
}

JavaScript:
<script type="text/javascript">
$(document).ready(function(e) {
    $(".protocolo").datepicker({
        dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
        dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
        dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'],
        monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
        monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
        dateFormat: 'yy-mm-dd',
        nextText: 'Próximo',
        prevText: 'Anterior'
    });
});
</script>

O mesmo vale para o atributo name. Quando você enviar o formulário, apenas um dos valores serão enviados os repetidos serão descartados, por isso você deve usar name="protocolo[]"


text:
Q: Pixel relocation, showing side-by-side I want to read individual pixels from one image and "relocate" them to another image. I basically want to simulate how it would be if I grabbed pixel by pixel from one image and "move" them to a blank canvas. Turning the pixels I grab from the original image white.
This is what I have right now, I'm able to read the pixels from the image and create a copy (which comes out saturated for some reason) of it.
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageTest
{
public static void main(String args[])throws IOException
{
   //create buffered image object img
   File oldImgFile = new File("/path/to/image/shrek4life.jpg");
   BufferedImage oldImg = null;
   BufferedImage newImg = null;
   try{
      oldImg = ImageIO.read(oldImgFile);
   }catch(IOException e){}
   newImg = new BufferedImage(oldImg.getWidth(), oldImg.getHeight(), BufferedImage.TYPE_INT_ARGB);
   File f = null;
   try
   {
      for(int i = 0; i < oldImg.getWidth(); i++){
          for(int j = 0; j < oldImg.getHeight(); j++){
              //get the rgb color of the old image and store it the new
              Color c = new Color(oldImg.getRGB(i, j));
              int r = c.getRed();
              int g = c.getGreen();
              int b = c.getBlue();

              int col = (r<<16) | (g<<8) | b;
              newImg.setRGB(i, j, col);
          }
      }
      //write image
      f = new File("newImg.jpg");
      ImageIO.write(newImg, "jpg", f);
   }catch(IOException e){
     System.out.println("Error: " + e);
   }
}//main() ends here
}//class ends here

And I would like to basically slow the process down and display it happening. But I'm not sure how to do that. Would I need to use to accomplish this ? I'm somewhat new to threading but I think I would need multiple threads to handle the painting of both pictures.

A: First of all, I would like to mention you are working in a very inefficient way. You are creating a Color, decomposing a pixel in its channels, and moving to the new image by a bit-shift. It is easier if you work directly with the integer the whole time (and more efficient).
I will assume the image "/path/to/image/shrek4life.jpg" has ARGB color space. I recommend ensure this, because if the old image does not have this color space you  should make a conversion.
When you create the new image, you create it as ARGB color space, so each channel is expressed in a byte of the int, first byte for Alpha, second byte for red, third byte for green and the last one for blue.
I think you forgot the alpha channel when you manipulated the old image pixel to move it into the new image.
With this explanation in mind, I think you can change your code to increase the efficiency, like this:
for(int i = 0; i < oldImg.getWidth(); i++){
  for(int j = 0; j < oldImg.getHeight(); j++){
    int pixel = oldImg.getRGB(i,j);
    newImg.setRGB(i, j, pixel );
    //If you like to get more control over the pixels and print
    //you can decompose the pixel using Color as you already do
    //But when you understand fully the process I recommend erase it
    Color c = new Color(pixel);
    //Print the color or do whatever you like
  }
}

About how to display the process of pixel relocation:
In process:

*

*You can print the changed pixel as a number with its position in image (discouraged). System.out.println("pixel"+pixel+" X:"+i+" Y:"+j);

*Use this tutorial in baeldung to print an image. I suggest draw a rectangle with the color of the image and wait for a key press (enter, for example) using Scanner. After the key was press, you can load the next pixel, an so on.

*If a single rectangle with just one pixel has little information, I suggest add an array of rectangles to draw several pixels in a time. Even you can print an image, and see the process pixel by pixel, using Scanner to mark each step.

*As @haraldK suggest, you can use Swing to display de relocation image. Through  swing timer and invokes update()
Post process:

*Save the image in a file. To improve the speed of process, I suggest save a few pixels (10 - 100).


text:
Q: Multiple forms, instances and using them in a class. VB.net I have an MDI Parentform and it has multiple forms which are declared as :
Partial Public Class Giriş

Private clients As thirdperson
Private suppliers As thirdperson
Private activecontrol As thirdperson
Private proposals As transactions
Private addproposal As addtransaction
private sales as transactions
private addsales as addtransation
Private products As products
...
...

I also have a dataworks sub which works as a class but i code it in form and also for each form as below :
'for example for pressing add new button
If ActiveControl Is **clients** Or ActiveControl Is **suppliers** Then
  activeform.dataworks (counter, "add new")
ElseIf ActiveControl Is products Then
  products.dataworks (counter, "add new")
ElseIf ActiveControl Is addproposal Then
  addproposal.dataworks (counter, "add new")
End If

i need a way to figure out how to use a vairble name for instance name. (I don't want to define each instance name everytime i just want to know if there is a way to use like below :
    'for example
    dim formvariable as form
formvariable.dataworks(counter,"add new") --> just want to use this and assign the value for products, proposals vs to this variable.

is this possible?
Thanks for your help in advance.
Sertac.

A: The proper way would be to develop an Interface that all of your Child Forms Implement.  That interface would have a dataworks() method.  Then you can cast the current mdichild to the interface type and run the method.  This would result in strongly typed coded that makes sense.
If you just want to hack your way through it, though, then attempt grab the dataworks() sub from the current mdichild using reflection and execute it like below:
    Dim frm As Form = Me.ActiveMdiChild
    If Not IsNothing(frm) Then
        Dim MI As Reflection.MethodInfo = frm.GetType.GetMethod("dataworks", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.IgnoreCase)
        If Not IsNothing(MI) Then
            MI.Invoke(frm, New Object() {counter, "add new"})
        End If
    End If

Here's a quick example of the Interface approach:
Public Interface Data

    Sub DataWorks(ByVal counter As Integer, ByVal msg As String)

End Interface

This is what thirdperson looks like implementing the interface:
Public Class thirdperson
    Implements Data

    Public Sub DataWorks(counter As Integer, msg As String) Implements Data.DataWorks
        Debug.Print(counter & ", " & msg)
    End Sub

End Class

All of your mdichild forms would have to be modified in a similar approach.
Then the code in the MdiParent would change to:
    Dim frm As Form = Me.ActiveMdiChild
    If TypeOf frm Is Data Then
        Dim D As Data = DirectCast(frm, Data)
        D.DataWorks(counter, "add new")
    End If


text:
Q: Android 2.2 ndk cmake windows 32 bit Как настроить cmake для android studio 2.2. В оф. тутуриале написано закачать с sdk tools -> LLDB, CMake, and NDK. Но у меня нет cmake. Система 32 bit. Скачал сайта положил cmake в папку ndk.
При создании проекта возникает такая ошибка:
External Native Build Issues Build command failed. Error while executing 'D:\SDK\Sdk\cmake\bin\cmake.exe' with arguments {-HD:\ADR\MyApplication4\app -BD:\ADR\MyApplication4\app.externalNativeBuild\cmake\release\armeabi -GAndroid Gradle - Ninja -DANDROID_ABI=armeabi -DANDROID_NDK=D:\SDK\Sdk\ndk-bundle -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=D:\ADR\MyApplication4\app\build\intermediates\cmake\release\obj\armeabi -DCMAKE_BUILD_TYPE=Release -DCMAKE_MAKE_PROGRAM=D:\SDK\Sdk\cmake\bin\ninja.exe -DCMAKE_TOOLCHAIN_FILE=D:\SDK\Sdk\ndk-bundle\build\cmake\android.toolchain.cmake -DANDROID_NATIVE_API_LEVEL=17 -DCMAKE_CXX_FLAGS=-frtti -fexceptions} CMake Error: Could not create named generator Android Gradle - Ninja Generators Visual Studio 15 2017 [arch] = Generates Visual Studio 2017 project files. Optional [arch] can be "Win64" or "ARM". Visual Studio 14 2015 [arch] = Generates Visual Studio 2015 project files. Optional [arch] can be "Win64" or "ARM". Visual Studio 12 2013 [arch] = Generates Visual Studio 2013 project files. Optional [arch] can be "Win64" or "ARM". Visual Studio 11 2012 [arch] = Generates Visual Studio 2012 project files. Optional [arch] can be "Win64" or "ARM". Visual Studio 10 2010 [arch] = Generates Visual Studio 2010 project files. Optional [arch] can be "Win64" or "IA64". Visual Studio 9 2008 [arch] = Generates Visual Studio 2008 project files. Optional [arch] can be "Win64" or "IA64". Visual Studio 8 2005 [arch] = Generates Visual Studio 2005 project files. Optional [arch] can be "Win64". Visual Studio 7 .NET 2003 = Deprecated. Generates Visual Studio .NET 2003 project files. Borland Makefiles = Generates Borland makefiles. NMake Makefiles = Generates NMake makefiles. NMake Makefiles JOM = Generates JOM makefiles. Green Hills MULTI = Generates Green Hills MULTI files (experimental, work-in-progress). MSYS Makefiles = Generates MSYS makefiles. MinGW Makefiles = Generates a make file for use with mingw32-make. Unix Makefiles = Generates standard UNIX makefiles. Ninja = Generates build.ninja files. Watcom WMake = Generates Watcom WMake makefiles. CodeBlocks - MinGW Makefiles = Generates CodeBlocks project files. CodeBlocks - NMake Makefiles = Generates CodeBlocks project files. CodeBlocks - Ninja = Generates CodeBlocks project files. CodeBlocks - Unix Makefiles = Generates CodeBlocks project files. CodeLite - MinGW Makefiles = Generates CodeLite project files. CodeLite - NMake Makefiles = Generates CodeLite project files. CodeLite - Ninja = Generates CodeLite project files. CodeLite - Unix Makefiles = Generates CodeLite project files. Sublime Text 2 - MinGW Makefiles = Generates Sublime Text 2 project files. Sublime Text 2 - NMake Makefiles = Generates Sublime Text 2 project files. Sublime Text 2 - Ninja = Generates Sublime Text 2 project files. Sublime Text 2 - Unix Makefiles = Generates Sublime Text 2 project files. Kate - MinGW Makefiles = Generates Kate project files. Kate - NMake Makefiles = Generates Kate project files. Kate - Ninja = Generates Kate project files. Kate - Unix Makefiles = Generates Kate project files. Eclipse CDT4 - NMake Makefiles = Generates Eclipse CDT 4.0 project files. Eclipse CDT4 - MinGW Makefiles = Generates Eclipse CDT 4.0 project files. Eclipse CDT4 - Ninja = Generates Eclipse CDT 4.0 project files. Eclipse CDT4 - Unix Makefiles= Generates Eclipse CDT 4.0 project files. Error:executing external native build for cmake D:\ADR\MyApplication4\app\CMakeLists.txt Build command failed. Error while executing 'D:\SDK\Sdk\cmake\bin\cmake.exe' with arguments {-HD:\ADR\MyApplication4\app -BD:\ADR\MyApplication4\app.externalNativeBuild\cmake\debug\armeabi -GAndroid Gradle - Ninja -DANDROID_ABI=armeabi -DANDROID_NDK=D:\SDK\Sdk\ndk-bundle -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=D:\ADR\MyApplication4\app\build\intermediates\cmake\debug\obj\armeabi -DCMAKE_BUILD_TYPE=Debug -DCMAKE_MAKE_PROGRAM=D:\SDK\Sdk\cmake\bin\ninja.exe -DCMAKE_TOOLCHAIN_FILE=D:\SDK\Sdk\ndk-bundle\build\cmake\android.toolchain.cmake -DANDROID_NATIVE_API_LEVEL=17 -DCMAKE_CXX_FLAGS=-frtti -fexceptions} CMake Error: Could not create named generator Android Gradle - Ninja Generators Visual Studio 15 2017 [arch] = Generates Visual Studio 2017 project files. Optional [arch] can be "Win64" or "ARM". Visual Studio 14 2015 [arch] = Generates Visual Studio 2015 project files. Optional [arch] can be "Win64" or "ARM". Visual Studio 12 2013 [arch] = Generates Visual Studio 2013 project files. Optional [arch] can be "Win64" or "ARM". Visual Studio 11 2012 [arch] = Generates Visual Studio 2012 project files. Optional [arch] can be "Win64" or "ARM". Visual Studio 10 2010 [arch] = Generates Visual Studio 2010 project files. Optional [arch] can be "Win64" or "IA64". Visual Studio 9 2008 [arch] = Generates Visual Studio 2008 project files. Optional [arch] can be "Win64" or "IA64". Visual Studio 8 2005 [arch] = Generates Visual Studio 2005 project files. Optional [arch] can be "Win64". Visual Studio 7 .NET 2003 = Deprecated. Generates Visual Studio .NET 2003 project files. Borland Makefiles = Generates Borland makefiles. NMake Makefiles = Generates NMake makefiles. NMake Makefiles JOM = Generates JOM makefiles. Green Hills MULTI = Generates Green Hills MULTI files (experimental, work-in-progress). MSYS Makefiles = Generates MSYS makefiles. MinGW Makefiles = Generates a make file for use with mingw32-make. Unix Makefiles = Generates standard UNIX makefiles. Ninja = Generates build.ninja files. Watcom WMake = Generates Watcom WMake makefiles. CodeBlocks - MinGW Makefiles = Generates CodeBlocks project files. CodeBlocks - NMake Makefiles = Generates CodeBlocks project files. CodeBlocks - Ninja = Generates CodeBlocks project files. CodeBlocks - Unix Makefiles = Generates CodeBlocks project files. CodeLite - MinGW Makefiles = Generates CodeLite project files. CodeLite - NMake Makefiles = Generates CodeLite project files. CodeLite - Ninja = Generates CodeLite project files. CodeLite - Unix Makefiles = Generates CodeLite project files. Sublime Text 2 - MinGW Makefiles = Generates Sublime Text 2 project files. Sublime Text 2 - NMake Makefiles = Generates Sublime Text 2 project files. Sublime Text 2 - Ninja = Generates Sublime Text 2 project files. Sublime Text 2 - Unix Makefiles = Generates Sublime Text 2 project files. Kate - MinGW Makefiles = Generates Kate project files. Kate - NMake Makefiles = Generates Kate project files. Kate - Ninja = Generates Kate project files. Kate - Unix Makefiles = Generates Kate project files. Eclipse CDT4 - NMake Makefiles = Generates Eclipse CDT 4.0 project files. Eclipse CDT4 - MinGW Makefiles = Generates Eclipse CDT 4.0 project files. Eclipse CDT4 - Ninja = Generates Eclipse CDT 4.0 project files. Eclipse CDT4 - Unix Makefiles= Generates Eclipse CDT 4.0 project files. Error:executing external native build for cmake D:\ADR\MyApplication4\app\CMakeLists.txt


text:
Q: Semaphores not working properly in terminal I am trying to use semaphores but they are not working in the terminal for some reason.
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>

sem_t mySem;

void *p1a(void *arg)
{
    sem_wait(&mySem);
    printf("B");
    return NULL;
}
void *p2a(void *arg){

    printf("A");
    sem_post(&mySem);
    return NULL;
}

int main(void)
{
    sem_init(&mySem, 0, 0);
    pthread_t p1;
    pthread_t p2;

    if (pthread_create(&p1, NULL, p1a, NULL))
    {
        printf("Error creating thread.\n");
        exit(1);
    }
    sleep(2);
    if (pthread_create(&p2, NULL, p2a, NULL))
    {
        printf("Error creating thread.\n");
        exit(1);
    }

    pthread_join(p1,NULL);
    pthread_join(p2,NULL);

    sem_destroy(&mySem);
    exit(0);
}

The result I get is BA but when I ran the same code in replit, it printed AB. Im not sure why this is happening and any help would be appreciated.


text: Q: iOS Development, Objective-c Development, Сложная проблема, Swift ошибка У меня есть большая проблема, которую не могу решить, пожалуйста, помогите. Вот и сама проблема - https://prnt.sc/26tm3rp. Сложность в том, что я пробовал pod deintegrate -> pod init -> pod install, cmd+shift+k, clear derived data, также нашел видео на ютубе - https://www.youtube.com/watch?v=L1OY9WKfQbQ&ab_channel =FreeLearning с той же проблемой и кстати с тем же .sh файлом но мне это не помогло. Я был в https://developer.apple.com/forums/thread/123790 и здесь https://stackoverflow.com/questions/53289524/xcode-10-2-1-command-phasescriptexecution-failed-with-a- nonzero-exit-code и все эти варианты не подходят, к вашему сведению сам проект основан на Objective-c, хотя не думаю, что это как-то влияет на него, но оставлю это для информации. Убедительно прошу помощи, уже 4 дня не могу запустить проект и перерыл все страницы в интернете. Всем хорошего дня и спасибо за уделенное время.


text:
Q: Redis 3.0 for .NET application Can I use Redis 3.0 for my ASP.NET website?
Redis 3.0 as Distributed Cache on Linux and my website in ASP.NET 4.5, does this make any sense?

A: You absolutely can do this, in fact, in Windows Azure, Microsoft recommends using Redis as the distributing caching layer, and their turn-key Redis instances are running Redis 3.0 now.
You'll want to take a look at either StackExchange.Redis or ServiceStack.Redis. Both are excellent .NET Redis libraries and available via NuGet. As pointed out in the comments below (thanks thepirat000), ServiceStack is a paid library above 6,000 Redis requests per hour, while the StackExchange library is released under the MIT license.


text:
Q: How to fix npm vulnerabilities and moderate and high manually? When I run npm install, it says

When I run npm audit it gives me list of tables, similar to this:

I'm still new in node.js and those messages confuses me a lot. Is there any way to fix it manually or get rid of those messages, I can't do anything with?


text:
Q: ANDROID | Native crash | signal 7 (SIGBUS), code 1 (BUS_ADRALN) I was unable to understand what could have caused this issue. Though it refers to RegexMatcher.
Does it mean, regular expression used in app may have caused this?
I am unable to reproduce this in devices. And it doesn't look like every-time issue.
Need support to understand what backtrace suggests?
Devices where Issue is seen
Huawei honor 10 Lite (HWHRY-H), Android 9
Huawei Mate 10 Pro (HWBLA), Android 9
Huawei Mate 20 Pro (HWLYA), Android 9
Huawei P20 Pro (HWCLT), Android 9
Huawei P10 Plus (HWVKY), Android 9
Huawei FIG-LX1 (HWFIG-H), Android 9
Huawei P20 Pro (HWCLT), Android 9
**Error received from Google Play console:**
backtrace:
  #00  pc 0000000000133d69  /system/lib64/libicuuc.so
  #01  pc 000000000019cf58  /system/lib64/libicui18n.so (icu_60::RegexMatcher::~RegexMatcher()+48)
  #02  pc 000000000019cfec  /system/lib64/libicui18n.so (icu_60::RegexMatcher::~RegexMatcher()+16)
  #03  pc 000000000002336c  /system/lib64/libjavacore.so (Matcher_free(void*)+68)
  #04  pc 0000000000094120  /system/framework/arm64/boot-core-libart.oat (java.math.NativeBN.BN_copy [DEDUPED]+160)
  #05  pc 000000000018340c  /system/framework/arm64/boot-core-libart.oat (libcore.util.NativeAllocationRegistry$CleanerThunk.run+76)
  #06  pc 000000000040c754  /system/framework/arm64/boot.oat (sun.misc.Cleaner.clean+164)
  #07  pc 00000000001daa0c  /system/framework/arm64/boot.oat (java.lang.ref.ReferenceQueue.enqueueLocked+236)
  #08  pc 00000000001dab2c  /system/framework/arm64/boot.oat (java.lang.ref.ReferenceQueue.enqueuePending+172)
  #09  pc 00000000001d7b04  /system/framework/arm64/boot-core-libart.oat (java.lang.Daemons$ReferenceQueueDaemon.runInternal+244)
  #10  pc 000000000015978c  /system/framework/arm64/boot-core-libart.oat (java.lang.Daemons$Daemon.run+76)
  #11  pc 00000000002c1038  /system/framework/arm64/boot.oat (java.lang.Thread.run+72)
  #12  pc 000000000056ef88  /system/lib64/libart.so (art_quick_invoke_stub+584)
  #13  pc 00000000000d4204  /system/lib64/libart.so (art::ArtMethod::Invoke(art::Thread*, unsigned int*, unsigned int, art::JValue*, char const*)+200)
  #14  pc 0000000000472fd4  /system/lib64/libart.so (art::(anonymous namespace)::InvokeWithArgArray(art::ScopedObjectAccessAlreadyRunnable const&, art::ArtMethod*, art::(anonymous namespace)::ArgArray*, art::JValue*, char const*)+104)
  #15  pc 0000000000474090  /system/lib64/libart.so (art::InvokeVirtualOrInterfaceWithJValues(art::ScopedObjectAccessAlreadyRunnable const&, _jobject*, _jmethodID*, jvalue*)+424)
  #16  pc 000000000049f684  /system/lib64/libart.so (art::Thread::CreateCallback(void*)+1120)
  #17  pc 0000000000083588  /system/lib64/libc.so (__pthread_start(void*)+36)
  #18  pc 00000000000241dc  /system/lib64/libc.so (__start_thread+68)


text:
Q: Running a function in Wordpress when publishing a custom post type I am trying to run the following function anytime a wordpress "Jobs" custom post is published. The code works (lines 2-7) when it is placed in my theme template, but it only runs when the post is viewed. I want the code to run when the post is published, and so I have tried adding the code in a function inside my functions.php, but nothing is happening when each custom post is published. Any suggestions?
function indeedgeo(){
    $indeedgeo = get_post_meta($post>ID, indeedgeo, true);
    $indeedgeos=explode(' ',$indeedgeo);
    $_jr_geo_latitude = $indeedgeos[0];
    $_jr_geo_longitude = $indeedgeos[1];
    update_post_meta($post->ID, _jr_geo_latitude, $_jr_geo_latitude);
    update_post_meta($post->ID, _jr_geo_longitude, $_jr_geo_longitude);
    }
add_action('publish_Jobs', 'indeedgeo');

A: You should hook into one of the three actions;
do_action('edit_post', $post_id, $post);
do_action('save_post', $post_id, $post);
do_action('wp_insert_post', $post_id, $post);

that are run when a post is either saved, or has its status updated. Something like the following should do the trick.
function se_10441543_save_post($post_id, $post){
    //determine post type
    if(get_post_type( $post_id ) == 'your_post_type'){
        //run your code
        $indeedgeo = get_post_meta($post_id, indeedgeo, true);
        $indeedgeos=explode(' ',$indeedgeo);
        $_jr_geo_latitude = $indeedgeos[0];
        $_jr_geo_longitude = $indeedgeos[1];
        update_post_meta($post_id, _jr_geo_latitude, $_jr_geo_latitude);
        update_post_meta($post_id, _jr_geo_longitude, $_jr_geo_longitude);
    }
}

add_action('save_post', 'se_10441543_save_post', 10, 2);

http://codex.wordpress.org/Plugin_API/Action_Reference

A: Not exactly sure how your "publish_jobs" hook is working but right off the bat, if you are placing this function in your functions.php, you will need to give it context. Replace $post>ID with the post number (an integer). If this applies to many post you will probably want to use another method of querying post data: http://codex.wordpress.org/Class_Reference/WP_Query. Let me know if this helps.


text:
Q: Information being uploaded to database even when conditions are false I have a form which gets data from the user via edit boxes and combo boxes, this information then has to be uploaded into a database table so I have to do validation. I did just that and it keeps on saying ''is not a valid integer' yet it is not even supposed to upload anything to the database table as all conditions where not met because of the null check that I did. Did I do my validation wrong?

unit Unit6;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Spin, ExtCtrls,unit7,unit5,unit4, DB, ADODB, Grids, DBGrids,
  pngimage;

type
  Tfrmupload = class(TForm)
    Panel1: TPanel;
    edtname: TEdit;
    edtsurn: TEdit;
    edtidn: TEdit;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label5: TLabel;
    Label6: TLabel;
    Panel2: TPanel;
    btnupload: TButton;
    edtmail: TEdit;
    cbprov: TComboBox;
    Image1: TImage;
    cbdiv: TComboBox;
    Label4: TLabel;
    procedure btnuploadClick(Sender: TObject);
    procedure Label7Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  frmupload: Tfrmupload;

implementation

{$R *.dfm}

procedure Tfrmupload.btnuploadClick(Sender: TObject);
var
  vname,vsurname,today,c,vidn,vprov,vmail,vdiv:string;
vage,year,i,age:integer;
bnotnull,bIDL,bmail,bage,byoung,valid,idrepeated:boolean;
dt:tdatetime;
begin
vname:=edtname.Text;
vsurname:=edtsurn.Text;
vidn:=edtidn.Text;
vdiv:=cbdiv.Text;
vprov:=cbprov.Text;
vmail:=edtmail.Text;

//booleans
bnotnull:=false;
bIdL:=false;
bmail:=false;
byoung:=false;
idrepeated:=false;
valid:=false;

//check if id entered is not in table already
if unit5.frmadmin.ADODetails.Locate('ID number',vidn,[]) then
begin
  idrepeated:=true;
  showmessage('ID Number already exists');
end;

//null check
if (vname<>'')and(vsurname<>'')and(vidn<>'')and(vprov<>'')and(vmail<>'')and(vdiv<>'') then
begin
  bnotnull:=true;
end
else
begin
  Showmessage('Complete All Fields!');
end;

//get current date
dt:=now;
year:=strtoint(formatdatetime('yyyy',dt));
c:=copy(vidn,1,2);
//calculate age from id number
if (strtoint(c)>=0) and (strtoint(c)<=22) then
begin
age:=year-(2000+strtoint(c));

end
else
begin
  age:=year-(1900+strtoint(c));
end;
//ID length validation
if (length(vidn)=13) then
begin
  bidl:=true;
end;

//check if contestant is not too young
if age<6 then
begin
showmessage('Contestant too young, cannot compete');
byoung:=true;
end;
//check if email is correct format
for i := 1 to length(vmail)do
  begin
    if vmail[i]='@' then
    begin
      bmail:=true;
  end;
  end;
  //error message for email check
  if bmail=false then
  begin
    showmessage('Incorrect Email Format');
  end;

  if bidl=false then
  begin
   showmessage('ID Number must be 13 characters');
  end;

//checks if all the conditions are met and if so we can then upload to database

if (bnotnull=true) and (bidl=true) and (byoung=false)and (bmail=true)and (idrepeated=false) then
begin
 valid:=true;
end;

if valid=true then
begin

unit5.frmadmin.ADODetails.Append;
unit5.frmadmin.ADODetails['Name(s)']:=vname;
unit5.frmadmin.ADODetails['Surname']:=vsurname;
unit5.frmadmin.ADODetails['ID Number']:=vidn;
unit5.frmadmin.ADODetails['Age']:=age;
unit5.frmadmin.ADODetails['Province']:=vprov;
unit5.frmadmin.ADODetails['Email']:=vmail;
unit5.frmadmin.ADODetails.Post;

unit4.frmcontest.ADOLead.Insert;
unit4.frmcontest.ADOLead['ID Number']:=unit4.frmcontest.DBComboID.Text;;
unit4.frmcontest.ADOLead['Name(s)']:=unit4.frmcontest.DBCombonme.Text;
unit4.frmcontest.ADOLead['Division']:=vdiv;

unit4.frmcontest.ADOLead.Post;

showmessage('Details Uploaded');

 frmupload.Hide;
end;

//clears all inputs
edtname.Clear;
edtsurn.Clear;
edtidn.Clear;
cbdiv.Text:='';
cbprov.Text:='';
edtmail.Clear;

end;

procedure Tfrmupload.Label7Click(Sender: TObject);
begin
frmupload.Hide;
end;

end.

A: I think we need to see a sample database record that was saved to database with false conditions. Beside you can take precaution by applying Trim() function to the input from edit boxes
vname:=Trim(edtname.Text);
vsurname:=Trim(edtsurn.Text);
vidn:=Trim(edtidn.Text);
vdiv:=Trim(cbdiv.Text);
vprov:=Trim(cbprov.Text);
vmail:=Trim(edtmail.Text);

You may also check the length of variable vidn
If Length(vidn) < 4 then
//or
If Length(vidn) < 2 then

A: The mistake is pretty obvious. You have strtoint(aka STRING to INT) but you give it a formatted datetime.
year:=strtoint(formatdatetime('yyyy',dt));

I don't understand why you take the year the way you do it when you can just give the value of 2022 to the integer, but if you insist on doing it that way, you can first format dt, then use datetimetostr and then strtoint. Another thing which will reduce the code and your work and make everything much more easier is DB-aware components. What they do is, once you connect them to the db and the table and column you're working with, they automatically make updates or inserts. All you need to do is TMSQuery.Insert and then TMSQuery.Post when adding new rows and TMSQuery.Edit and TMSQuery.Post when changing values.