text:
Q: draw the pushdown automaton How can I draw the pushdown automaton for language $L = \{ bin(n) \text{#} bin(3n)^{R} | n \in  \mathbb{Z}, n \geq 0 \}$ when bin(n) is binary notation of $n$ without leading zeros. Alphabet is $\{ 0, 1, \text{#} \}$

A: Design it to mimic ordinary long multiplication by $3$ in binary. I'll outline what's needed.
The key is to recognize that multiplying a binary number by $3$ is just adding the number to the result of shifting it one place to the left, as in this example of $185\cdot3$:
            10111001
                  11
            --------
            10111001
           10111001
           ---------
          1000101011

The automaton should stack the input until it reads a $\#$. At that point the top element of the stack will be the least significant bit of $n$. If the input is in $L$, that bit should agree with the next bit of input. The basic processing cycle from this point on is:

*

*Use the bit at the top of the stack and the current state to determine what the next bit of input ought to be and whether there should be a carry into the next 'column';

*If the next input bit is correct, pop one bit off the stack and go to one of four states, depending on the popped bit, the present state, and whether or not there is a carry to the next 'column'. The states keep track of whether the popped bit was $0$ or $1$ and whether there is an outgoing carry.

Of course if the next input bit is not correct, the input is not in $L$.

A: Here is how our PDA works :

*

*if the first symbol is not 1 reject (except if the string is # , see edge cases down)

*push all symbols to stack till you read # , do not push # (this step is pushing all symbols of bin(n) to stack)

*now using the stack we can read bin(n) from right to left , the input we receive from this point is supposed to be bin(3n)r , meaning we can read also bin(3n) from right to left

*Now we consider the symbol at top of stack x , the symbol we read w , and make transitions for valid x & w to states that correspond to the carry

*ex 1, after reading # , if x = 0 , 0*3 = 0 , carry = 0 , so if x = 0 , we expect w = 0 , and we head to state carry = 0 , that is 0,0;ε to carry 0

*ex 2, if we are in state carry 1 , and x = 0 , 0*3 + 1 = 1 and carry = 0 , so if x = 0 , and we are in carry 1 , we expect w = 1 , and we go to state carry = 0 , that is 1,0;ε to carry 0

*Now continue this way and you should be able to construct the PDA , you will find that you will need another state for carry 2 , for each state think about valid x & w to make a transition and what carry will they cause to know which state you will head to , continue this way till you finish the PDA

*if we are in state carry 0 , and stack is empty , we non-deterministically guess that input has finished and head to accept state

Hopefully these steps help you build your own PDA , after you try , you can check your answer , here is the PDA :

edge cases :
here we explain how the transition 1,\$;\$ acts like 1,0;ε for ex : if bin(n) = 1 , you see how bin(3n) = 10 , bin(3n)r = 01 , after reading bin(n) the stack will have \$1 after reading 0 from bin(3n)r the stack will be $ and we are in carry 1 , usually we need to pop a 0 to go to carry 0 , but since we read \$ , we know this is the end of bin(n) and so we treat \$ as if it was a leading 0 ( which does not change bin(n) ) , we pop \$ as if we would have popped a 0 , then push it again for the test of emptiness of stack , if you think about it you can make the same transition to the accept state instead of carry 0 , both are the same
in case n = 0 , bin(0) = 0 , since we do not allow leading 0s , the string will end up being just # , so we guess whether n = 0 or not , if n is not 0 we check if b(n) starts with 1


text:
Q: Like query string in codelgniter My view page has the following fields
id,name,email,gender etc..

I have a search box , and i want to perform search in all the above fields
How to write the query string in CI way
Controller
public function search()
    {

        $sql = "SELECT * FROM users";

        $this->form_validation->set_rules('search_term', 'Search_term', 'trim|xss_clean');

        if ($this->form_validation->run() == TRUE)
        {
             $keyword = $this->input->post('search_term');

             $sql.= "WHERE name like '{$keyword }'";
             $sql.= "OR email like '{$keyword }'";
             $sql.= "OR gender like '{$keyword }'";

        }

        $query = mysql_query($sql);
    }

A: read  CI Like  like query
    $keyword = $this->input->post('search_term');
    $this->db->select('*');
    $this->db->like('name', $keyword);
    $this->db->or_like('email', $keyword);
    $this->db->or_like('gender', $keyword);
    $res = $this->db->get('users');

redpajama_set_name: RedPajamaStackExchange


text:
Q: Site is continuously accessing by several IPs I have high traffic wordpress blog, but for last two days i am constantly getting the error "Error establishing a database connection".  I have called to my hosting customer care and they are saying that my blog is constantly accessing by some IPs addresses and they are blocking those ips.
But after 4 or 5 hours i am facing the same issues, this time spammers are attacking from other ips, every time i cannot call to my customer care to block ips.
Do we have any word press plugin or any solution for this ?
Thank you
-siva

A: Any restriction on IP based on wp-admin panel ? Try to restrict Login LockDown plugin to restrict admin panel.


text:
Q: Permutation of String in java The below code gives redundant permutation values in case of string having length 4.But if we replace line 1,2,3 of swap function by the code written below it(in comment) then no redundant result get printed.Why could this is happening?
package dspermutation;

import java.util.Scanner;

public class DSPermutation {
String s;
char[] c;
int n;

    public static void main(String[] args) {
        DSPermutation ds=new DSPermutation();
        ds.input();
    }

    private void input() {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the string");
        s=sc.next();
        c=s.toCharArray();
        n=c.length;
        permutation(c,n-1,0);
    }

    private void permutation(char[] cc,int nn,int ii) {
        if(ii==nn)
        {
          System.out.println(cc);

        }
        else
        {
            for(int j=ii;j<=nn;j++)
            {
                swap(cc[ii],cc[j]);
                permutation(cc,nn,ii+1);
                swap(cc[ii],cc[j]);
            }
        }

    }

    private void swap(char p, char c0) {
        int x=s.indexOf(p);
        int y=s.indexOf(c0);
        /*1*/char temp=c[x];
        /*2*/c[x]=c[y];
        /*3*/c[y]=temp;

       /*c[x]=c0;
       c[y]=p;
       s=String.valueOf(c)*/

    }
}

A:
Call-by-reference

{
        private void permutation(char[] cc,int nn,int ii) {
        ...
        ...
        for(int j=ii;j<=nn;j++)
        {
            swap(cc[ii],cc[j]);

            // Here you are passing reference of cc[ii] to swap method.
            // and  then if you remove the comment from swap method,
            // cc[ii] and cc[j] are getting exchanged from that method.

            permutation(cc,nn,ii+1);
            swap(cc[ii],cc[j]);
        }
    }
 ...
 ...
      private void swap(char p, char c0) {

      int x=s.indexOf(p);
      int y=s.indexOf(c0);
      char temp=c[x];
      c[x]=c[y];
      c[y]=temp;

      }
}


text:
Q: Proving $a^{-2}bcd+b^{-2}cda+c^{-2}dab+d^{-2}abc\geqslant a+b+c+d$
If $a,b,c,d$ are positive real numbers, then prove that $$\frac{bcd}{a^2}+\frac{cda}{b^2}+\frac{dab}{c^2}+\frac{abc}{d^2}\geqslant a+b+c+d$$

Attempt:
$$\frac{bcd}{a^2}+\frac{cda}{b^2}+\frac{dab}{c^2}+\frac{abc}{d^2} = \frac{abcd}{a^3}+\frac{abcd}{b^3}+\frac{abcd}{c^3}+\frac{abcd}{d^3}$$
Using AM-GM inequality:
$$abcd\big[a^{-3}+b^{-3}+c^{-3}+d^{-3}\big]\geqslant4abcd(abcd)^{-\frac{1}{4}}$$
Could anyone help me?

A: We'll replace $a\rightarrow\frac{1}{a}$ and similar.
Thuse, we need to prove that
$$a^3+b^3+c^3+d^3\geq abc+abd+acd+bcd,$$
which is AM-GM or Muirhead.
For example
$$\sum_{cyc}a^3=\frac{1}{3}\sum_{cyc}(a^3+b^3+c^3)\geq\frac{1}{3}\sum_{cyc}3\sqrt[3]{a^3b^3c^3}=\sum_{cyc}abc$$
and we are done!


text:
Q: Open a link in web browser using flash swf I am new to flash coding and didn't know much more.
I want to make a flash file that send URL to web browser to open particular link.
I've made such file it execute properly but after making swf file, it does not open the link.
Any one help me regarding this small problem.

A: Check out navigateToURL(): http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/package.html#navigateToURL()
Note that it won't work unless it's triggered by a user action; i.e. a mouse click or a key press


text:
Q: jquery load function not working properly I'm trying to load partial content after page load with using jQuery and ASP.NET MVC 4 but it is not displaying loaded content on DOM. I have searched internet but couldn't found any solution. I'm sharing what i have done.
jQuery:
$(function () {
    var site = site || {};
    site.baseUrl = site.baseUrl || "";
    $(document).ready(function (e) {
        $(".partialContents").each(function (index, item) {
            var url = site.baseUrl + $(item).data("url");
            if (url && url.length > 0) {
                $.get(url, function (data) {
                    $(item).append(data);
                })
            }
        });
    });
});

HTML:
<div class="partialContents" data-url="/Home/GetAds">
</div>

I'm loading Advertisements scripts with jQuery.


text:
Q: Cloudfront and multiple Country code top-level domains I did deploy a Next.js application on aws-amplify and everything works fine.
Additionally I started to add six custom domains to my application on amplify (mysite.at, mysite.de, mysite.com, mysite.uk, mysite.it and mysite.ch).
This works well too.
Now I wanted to use the i18n feature, which nextjs provides.
module.exports = {
  generateEtags: false,
  i18n: {
    locales: ['en-US', 'it-IT', 'de-AT', 'de-DE', 'de-CH', 'en-UK'],
    defaultLocale: 'en-US',
    localeDetection: false,

    domains: [
      {
        domain: 'www.mysite.com',
        defaultLocale: 'en-US',
      },
      {
        domain: 'www.mysite.it',
        defaultLocale: 'it-IT',
      },
      {
        domain: 'www.mysite.ch',
        defaultLocale: 'de-CH',
      },
      {
        domain: 'www.mysite.at',
        defaultLocale: 'de-AT',
      },
      {
        domain: 'www.mysite.de',
        defaultLocale: 'de-DE',
      },
      {
        domain: 'www.mysite.uk',
        defaultLocale: 'en-UK',
      },
    ],
  },
}

It's possible to call www.mysite.com/de-DE and it shows me the page for Germany, ww.mysite.com/it-IT for the italian content and so on.
But when I call www.mysite.at (which should render the content for Austria de-AT) I always get the content from the first call which was made after deployment.
In this case I always get the content for Germany.(on every machine I try)
When I empty the cloudfront cache, and call www.mysite.uk I get the content for uk, but when I call www.mysite.de afterwards, I get the uk content again.
When I request with a parameter eg. www.mysite.de/?dsjskdjsaj it does work.
So I think the cloudfront CDN (Lambda@Edge) is the problem in this case.
Is it possible to cache the content for each domain?
I know there is only one cloudfront distribution for my project, but maybe there is a solution.


text:
Q: Extract port number from netstat command I have the following output of the command netstat:
netstat -taunp | grep hgd
tcp        0      0 10.1.1.1:601            10.1.1.2:935            ESTABLISHED 842/hgd
tcp        0      0 10.1.1.1:55394          10.1.1.2:3490           ESTABLISHED 842/hgd

I want to extract from this output the port number 601.
please note that this port is random and port 935 is hard coded and exists in many netstat lines
any suggestion?

A: Awk is the tool for what you want :
netstat -taunp | grep <your_grep> | awk '{print $4}' | awk -F ':' '{print $2}'

A: Here is how I like to do it:
netstat -taunp | awk '/hgd/ && $5~/:935$/ {split($4,a,":");print a[2]}'

grep is not needed, since awk can find hgd by it self:

*

*/hgd/ && $5~/:935$/ find line with hgd and fifth field ends with :935then do:

*split($4,a,":") split 4 filed inn to array a using : as separator

*print a[2] print second part of array a where the ports are.

A: You may use
netstat -taunp | awk -F'[:[:space:]]+' '/hgd/ && $7 == "935" { print $5 }'

See the online demo
Details

*

*-F'[:[:space:]]+' - sets the field separator to one or more occurrences of : and/or whitespace

*'/hgd/ && $7 == "935" - if the line contains hgd and Field 7 is equal to 935 then

*{ print $5 }' - print Field 5.


text:
Q: Solution for process.env.TZ = 'UTC' in Node for Windows? I was trying to test my Postgres database to make sure everything was being added properly and would include a hardcoded date in this format 2029-01-22T16:28:32.000Z.
Here is the table for it:
CREATE TABLE blogful_articles (
    id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    title TEXT NOT NULL,
    content TEXT,
    date_published TIMESTAMP DEFAULT now() NOT NULL
);

I expect to get back 2029-01-22T16:28:32.000Z but get back 2029-01-23T00:28:32.000Zbecause Windows would automatically adjust it for the timezone difference and my test would fail.
It should automatically adjust for daylight savings time but here is my solution:
function adjustingForTimezone(dateToAdjust) {
  const offsetInMilliseconds = dateToAdjust.getTimezoneOffset() * 60000;
  const theDateWithOffsetAdded =
    Date.parse(dateToAdjust) - offsetInMilliseconds;
  const adjustedTime = new Date(theDateWithOffsetAdded);
  return adjustedTime;
}

Here is how I used it:
app.get("/articles", (req, res, next) => {
  const knexInstance = req.app.get("db");
  ArticlesService.getAllArticles(knexInstance)
    .then(articles => {
      const os = process.platform

      function adjustingForTimezone(dateToAdjust) {
        const offsetInMilliseconds = dateToAdjust.getTimezoneOffset() * 60000
        const theDateWithOffsetAdded = Date.parse(dateToAdjust) - offsetInMilliseconds
        const adjustedTime = new Date(theDateWithOffsetAdded)
        return adjustedTime
      }

      res.json(
        articles.map(article => ({
          id: article.id,
          title: article.title,
          style: article.style,
          content: article.content,
          date_published: os === "win32" ? adjustingForTimezone(article.date_published) : new Date(article.date_published)
        }))
      );
    })
    .catch(next);
});

I made the adjustingForTimezone function that should adjust it automatically, is there any way that I could improve it?  What are the potential pitfalls of using this in my code?

A: The approach used to "adjust" for time zone doesn't actually adjust.  Instead, it creates a different point in time.  It's common to think that one can just subtract an offset to account for time zones, but those are two very different concepts.
The Date object has only one actual value stored within it, which is the numeric timestamp that you see when calling getTime, valueOf, parse, etc.   Any other functions that use the local time zone (such as toString), or a named time zone (such as the timeZone option of toLocaleString) will expect that the internal timestamp is UTC-based.  If it's not, then you may get incorrect results.
Where this matters in your code is where you call getTimezoneOffset.  The point in time you are asking for should be UTC-based, but since you need to adjust then it is already the wrong point in time.  You can test this near date/time of a DST transition and you'll see that it switches offsets slightly too early or slightly too late.
So let's go back to the original problem - you're getting a timestamp out of Postgres that has been shifted by the local time zone.  This is the culprit:
date_published TIMESTAMP DEFAULT now() NOT NULL

Here's what's probably happening:

*

*The now() function returns a TIMESTAMP WITH TIME ZONE (aka TIMESTAMPTZ), using the session time zone in effect when you insert the row.  In your example, it is returning 2029-01-23T00:28:32.000+08:00.  Thus the session time zone is probably the default, which is pulling from the server's time zone setting.  (UTC+8 - used in China, Australia, and a few other places.)

*Then you pass it to a TIMESTAMP, which in Postgres is not aware of time zone.  So it strips off the offset and stores 2029-01-23T00:28:32.000.  Thus your timestamp is not stored in UTC but in local time.

*Later when you query, the session time zone is set to UTC, so you get back 2029-01-23T00:28:32.000Z, which is incorrect.
There are a few different ways you could fix this:

*

*You could ensure the session time zone was set to UTC during the row insert.
  SET TIME ZONE 'UTC'; INSERT INTO ...

*You could explicitly convert to UTC before storing your timestamp when defining your table:
  date_published TIMESTAMP DEFAULT (now() AT TIME ZONE 'UTC') NOT NULL

*You could define your date_published field as a TIMESTAMPTZ instead of a TIMESTAMP.  (This is arguably the best approach.)
  date_published TIMESTAMPTZ DEFAULT now() NOT NULL

*You could ensure the session time zone at time of query is the same local time zone as at time of insert.  However, I don't recommend this one because you will have discrepancies if the server's time zone ever changes or if you are using a time zone that transitions between offsets for daylight saving time.
With any of these in place, you can delete your adjustingForTimezone function and directly use the timestamp returned from the query.


text:
Q: How to make my JAX-RS webservice remember my login? I created a very simple REST webservice in Java by using JAX-RS. And have a client make Ajax calls to that webservice to login and get the login information.
JAX-RS Code
@Path("/netsuite")
public class myRESTWebService{
   @GET
   @Path("/login/{userName}")
   public String login(@PathParam("userName") String userName){
      //here I have to save that userName in some session so that I can use it in below function
   }

   @GET
   @Path("/getUserName")
   public String getUserName(){
      //here I have to return the above username
   }
}

I know REST webservices are stateless, how can I make it stateful. I tried Google search whole day, didn't helped me much.
How can I make it stateful ?

A: You can access the HttpSession and store the username like this:
@GET
@Path("/login/{userName}")
public String login(@PathParam("userName") String userName, @Context HttpServletRequest servletRequest) {
    HttpSession session = request.getSession();
    session.setAttribute("userName", userName);
}

But I strongly recommend to rethink why you need state in a stateless application and take a look at Java EE Security Concepts.
Unrelated: Classes in Java always start with a capital Letter.


text:
Q: Half of a derivative? How could a half derivative be computed? Not that I have found a use for what I wish I could call partial derivatives, but they are still interesting. Taking the nth derivative of the $m^{th}$ derivative of $f(x)$ is the $(n+m)^{th}$ derivative of $f(x)$. My real question is how to compute the nth derivative where $n$ is any real number, but I'll settle for just half derivatives for now. How do you find the half derivative of $x^p$?

A: A natural requirement for a half-derivative operator $H : \mathcal{F} \to \mathcal{F}$ on some suitable space $\mathcal F$ of functions on some interval in $\Bbb R$ is that $$H^2 = D ,$$ where $D$ denotes the usual derivativce.
Here's a conceptual approach to constructing such an operator: Formally writing $H = D^{1 / 2}$ and demanding that the Laplace transform identity $\mathcal L \{D^k f\}(s) = s^k \mathcal L \{f\}(s)$ for integer $k$ hold also for noninteger values imposes that
$$\mathcal L \{Hf\}(s) = s^{1 / 2} \mathcal L \{f\}(s) ,$$
and so we can set---again for the functions to which we can apply $\mathcal L$---
$$(Hf)(t) := \mathcal L^{-1} \{s^{1 / 2} \mathcal L\{f\}\}(t) .$$
Then using that $\mathcal L$ maps convolutions to products lets us rewrite this formula, at least formally, as
$$(Hf)(t) := \frac{1}{\sqrt{\pi}} \frac{d}{dx} \int_0^x \frac{f(t) \,dt}{\sqrt{x - t}} ,$$
which recovers a special case of a formula due to Cauchy. (The coefficient is a consequence of the fact that $\Gamma\left(\frac{1}{2}\right) = \sqrt{\pi}$, where $\Gamma$ is the Gamma function.) The map $f \mapsto Hf$ is evidently linear (over $\Bbb R$).
Example For a power function $p(x) = x^k$ evaluating the latter formula gives
$$(H p)(x) = \frac{\Gamma(k + 1)}{\Gamma(k + \frac{1}{2})} x^{k - \frac{1}{2}}.$$
Computing then gives
$$(H^2 p)(x) = (H(Hp))(x) = \frac{\Gamma(k + 1)}{\Gamma\left(k + \frac{1}{2}\right)} \cdot \frac{\Gamma\left(k + \frac{1}{2}\right)}{\Gamma(k)} x^{((k - \frac{1}{2}) - \frac{1}{2})} = k x^{k - 1} ,$$
so $H^2 p = D p$ as expected. Linearity then implies that $H^2 q = D q$ for all polynomials $q$.
It's evident how to extend this at least some formally to fractions (or even real numbers) other than $\frac{1}{2}$, but formulas must be interpreted with some care must be taken for "powers" outside $(0, 1)$. For negative "powers" one recovers fractional integral operations, which in some ways are better behaved than fractional derivatives.
The formal Laplace transform approach is not nearly the only possible one, nor is it (I think) the most general. See the Wikipedia article on Fractional calculus for much more.


text:
Q: Compare one row of a table to every rows of a second table I am trying to retrieve the number of days between a random date and the next known date for a holiday. Let's say my first table looks like this :
date | is_holiday | zone
9/11/18 | 0 | A
22/12/18 | 1 | A

and my holidays table looks like this
start_date | end_date | zone
20/12/18 | 04/01/18 | A
21/12/18 | 04/01/18 | B
...

I want to be able to know how many days are between an entry that is not a holiday in the first table and the next holiday date.
I have tried to get the next row with a later date in a join clause but the join isn't the tool for this task. I also have tried grouping by date and comparing the date with the next row but I can have multiple entries with the same date in the first table so it doesn't work.
This is the join clause I have tried :
SELECT mai.*, vac.start_date, datediff(vac.start_date, mai.date)
FROM (SELECT *
      FROM MAIN
      WHERE is_holiday = 0
     ) mai LEFT JOIN
     (SELECT start_date, zone
      FROM VACATIONS_UPDATED
      ORDER BY start_date
     ) vac
     ON mai.date < vac.start_date AND mai.zone = vac.zone

I expect to get a table looking like this :
date | is_holiday | zone | next_holiday
9/11/18 | 0 | A | 11
22/12/18 | 1 | A | 0

Any lead on how to achieve this ?

A: It might get messy to do it in SQL but if in case you are open to doing it from code, here is what it should look like. You basically need a crossJoin
Dataset<Row> table1 = <readData>
Dataset<Row> holidays = <readData>

//then cache the small table to get the best performance

table1.crossJoin( holidays ).filter("table1.zone == holidays.zone AND table1.date < holidays.start_date").select( "table1.*", "holidays.start_date").withColumn("nextHoliday", *calc diff*)

In scenarios where one row from table1 matches multiple holidays, then you can add an id column to table1 and then group the crossJoin.
// add unique id to the rows
table1 = table1.withColumn("id", functions.monotonically_increasing_id() )

Some details on crossJoins:
http://kirillpavlov.com/blog/2016/04/23/beyond-traditional-join-with-apache-spark/


text:
Q: Must know vs. should know
Mrs. Woods ....... New York very well. She has lived there all her life.
a. must have known
  b. must know
  c. should have known
  d. should know

The test answer key says b is the right option. But I think both b and d can be correct.

A: Must X means X is required to or has to happen, without a doubt.
Should X means X is expected to happen, but there could be a small chance it doesn't - or the information is second hand so you don't actually 100% know for sure.

Mrs. Woods must know New York very well. She has lived there all her life.

We are saying that Mrs. Woods has to know New York very well.

Mrs. Woods should know New York very well. She has lived there all her life.

We are saying that we expect Mrs. Woods to know New York very well.  Perhaps we haven't met Mrs. Woods personally or for some other reason there's a bit (even if just a tiny, tiny bit) of doubt.  Other conversation would have to establish this doubt.

This is a tricky test question, but in test questions, you are supposed to go by the information in the question.  So this is why the test says must know because there's nothing casting doubt in the provided information of the question.

A:
It's a stupid test. Although the relevant contexts are less likely, there certainly are situations where a and c would be perfectly valid. And even for the most likely contexts, it's ridiculous to suppose that d is any "better, more right" than b.


text:
Q: Dynamically Create Posts Via XML File I'm new to wordpress/php and I'm trying to create new posts dynamically through a xml file.
The xml I'm working with is this one.
The file get updated periodically during the day in a FILO fashion (new item are added at the top and the bottom one get push out) and right now we have someone manually creating new posts every few hours by grabbing a few value in each items.
So what I'm wondering is if I can automate this process?
Whenever this file is updated. Wordpress will create a new post with the new item only.
I'm able to pull values out of the xml file, but I'm having trouble creating a post dynamically and also set it so it will only create the new items, so I won't have any duplicates.
Also I'm not sure if this will effect much of the code, but I'm using the ACF plugin, so there are some custom fields in the post as well.
Thanks in advance.

A: Yes.  From your description, it appears that all of the requirements to automate this process are in place.
The data is provided via XML which can be parsed with PHP to the necessary title, body, meta components.  [search]
WordPress supports programmatic post insert/delete/edit functions so that part is fairly simple.  [WP Codex]
Now you just need a PHP developer to write the code to your specs.

A: I figured it out on how to create post dynamically. I don't know if it's optimal, but it gets the job done.
I put all the necessary info in variables/arrays and added them into a for loop that does the insertion. It goes through the entire xml file, but will stop and break out of the loop if it comes to a post with the same title (I know this probably wont be the best unique identifier), this way it won't create multiple of the same post. once it break it tells the user how many post has been created:
$flag = true;
for($i=0; $i<24; $i++){
if(!get_page_by_title($b[$i]->title, OBJECT, post)){

    //check what category it's in.
    if(stristr($feedKeywordsArray[$i],"news")){
        $category = 3;
    }
    elseif(stristr($feedKeywordsArray[$i], "live")){
        $category =4;
    }
    elseif(stristr($feedKeywordsArray[$i], "insider")){
        $category =5;
    }
    elseif(stristr($feedKeywordsArray[$i], "local")){
        $category =6;
    }
    elseif(stristr($feedKeywordsArray[$i], "spotlight")){
        $category =7;
    }
    else{
        $category=1;
    }

    $my_post = array(
        'post_title'    => $b[$i]->title,
        'post_content'  => $b[$i]->description,
        'post_status'   => 'publish',
        'post_author'   => 1,
        'post_category' => array($category),
        'tags_input' => $feedKeywordsArray[$i]
    );

// Insert the post into the database.
    $post_id = wp_insert_post( $my_post );
    echo "
 Post: '" . $b[$i]->title . "' added
";

    if($post_id>0){
        update_field('excerpt', (string)($b[$i]->description), $post_id);
        update_field('vamp-thumbnail', (string)($thumbnail[$i]), $post_id);
        update_field('vamp-video', str_replace("#autostart=on;", "#autostart=off;hidecompanion=on;autoadv=off;",(string)($a[$i][0])), $post_id);

    }
}
else{
    $flag = false;
    echo "
 Coming Out of the for loop after creating " . $i . " successful post(s).
";
    break;
}
}

if($flag){
echo "Created all post";
}

?>


text:
Q: Different RoutePrefix, same controller name I'm having a problem with splitting my web-api application into different areas (not mvc areas), using namespaces and RoutePrefix
The application is hosted using Owin Self Host, and in my Startup class I have the following.
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
app.UseWebApi(config);

And my two controllers that I tested with
[RoutePrefix("api/test")]
public class TestController : ApiController
{
    [Route("")]
    public IHttpActionResult Get()
    {
        return Ok("api");
    }
}

[RoutePrefix("sync/test")]
public class TestController : ApiController
{
    [Route("")]
    public IHttpActionResult Get()
    {
        return Ok("sync");
    }
}

These two controllers live in two different namespaces, Api and Sync.
When I try to access the two controllers with
http://localhost/api/test and http://localhost/api/sync I get a 404.
But If I rename one of the controllers to e.g. TestApiController then both works.
Someone having a good idea if it's possible to do what I want?

A: Unfortunately, Web API finds controllers by class name, ignoring the namespace. This is a known issue and is not unique to attribute-based routing.
The easiest work-around by far is to avoid the problem and use unique controller names. But if you don't mind getting a little fancy, here's a solution:
https://blogs.msdn.microsoft.com/webdev/2013/03/07/asp-net-web-api-using-namespaces-to-version-web-apis/


text:
Q: Stack implementation of DFS. All test cases work except the first From https://structy.net/problems/largest-component
Write a function, largestComponent, that takes in the adjacency list of an undirected graph. The function should return the size of the largest connected component in the graph.
The problem is this code works for all test cases except the first one. And i do not want to solve this with the recursive DFS method i want to use the stack or queue DFS method.
The main function
const largestComponent = (graph) => {
    //init the largest count variable to 0
    let largest=0;
    // use a global set data structure to keep track of visited nodes
    let visited =  new Set();

    //loop through graph object and send each node to DFS function
    for (node in graph) {
        //if node has been visited then skip to next node
        if(visited.has(String(node))) continue;

        let currentCount = DFS(graph, node, visited);

        // get largest count per iteration
        largest = Math.max(largest, currentCount);

    }
    // return result
    return largest;
}

The depth first search function
const DFS = (graph, node, visited) => {

    // initiate count for neighbors of current node but also count current node so init to 1
    let currentCount = 1;

    // populate stack with node
    let stack = [node];

    //loop for as long as stack isn't empty
    while(!!stack.length){

        // get current node from stack
        let current = stack.pop();

        // mark node as visited
        visited.add(String(current));

        // loop through neighbors of node
        for( neighbor of graph[current]){

            // if neighbors have been visited already then skip them
            if(visited.has(String(neighbor))){
                continue;
            } else {
                // add neighbor to count
                currentCount++;

                // add the next neighbor to stack
                stack.push(neighbor);
            }
        }
    }
    // return count of connected components for current node
    return currentCount;
}

Test case 1
console.log(largestComponent({
  0: ['8', '1', '5'],
  1: ['0'],
  5: ['0', '8'],
  8: ['0', '5'],
  2: ['3', '4'],
  3: ['2', '4'],
  4: ['3', '2']
})) // should give -> 4

Test case 2
console.log(largestComponent({
  1: ['2'],
  2: ['1','8'],
  6: ['7'],
  9: ['8'],
  7: ['6', '8'],
  8: ['9', '7', '2']
})); // should give  -> 6

Test case 3
console.log(largestComponent({
  3: [],
  4: ['6'],
  6: ['4', '5', '7', '8'],
  8: ['6'],
  7: ['6'],
  5: ['6'],
  1: ['2'],
  2: ['1']
})); // should give -> 5

Test case 4
console.log(largestComponent({
  0: ['4','7'],
  1: [],
  2: [],
  3: ['6'],
  4: ['0'],
  6: ['3'],
  7: ['0'],
  8: []
})); // should give -> 3

A: Cause
What happens in Test case 1 is that you are counting 8 twice (once when current is 0 and once when current is 5).
Step by step:

*

*Current node is 0, currentCount=1, stack=[], visited=[]

*

*Mark 0 as visited -> [0]

*Add to stack: 8, 1, 5 -> [8, 1, 5]

*Current count becomes: 1 + 3

*Current node is 5, currentCount=4, stack=[8, 1] (pop 5), visited=[0]

*

*Mark 5 as visited -> [0, 5]

*Add to stack: 8 (0 is visited, but 8 still not) -> [8, 1, 8]

*Current count becomes: 4 + 1  here is the problem
Solution
This can be solved changing three things:

*

*Count nodes when visited (not when checking neighbors).

*As a consecuense of point 1, start the currentCount variable at 0.

*Check if the current node poped from stack hasn't been visited.

Code
The final code will be like this:
const largestComponent = (graph) => {
    //init the largest count variable to 0
    let largest=0;
    // use a global set data structure to keep track of visited nodes
    let visited =  new Set();

    //loop through graph object and send each node to DFS function
    for (node in graph) {
        //if node has been visited then skip to next node
        if(visited.has(String(node))) continue;

        let currentCount = DFS(graph, node, visited);

        // get largest count per iteration
        largest = Math.max(largest, currentCount);

    }
    // return result
    return largest;
}

const DFS = (graph, node, visited) => {

    // count starts at 0, `node` will always be counted in the first iteration
    let currentCount = 0;

    // populate stack with node
    let stack = [node];

    //loop for as long as stack isn't empty
    while(!!stack.length) {

        // get current node from stack
        let current = stack.pop();

        // if current node has been visited then skip to next node
        if (visited.has(String(current))) continue;

        // mark node as visited and count it
        visited.add(String(current));
        currentCount++;

        // loop through neighbors of node
        for( neighbor of graph[current]){

            // if neighbors have been visited already then skip them
            if(visited.has(String(neighbor))){
                continue;
            } else {
                // add the next neighbor to stack
                stack.push(neighbor);
            }
        }
    }
    // return count of connected components for current node
    return currentCount;
}


text:
Q: Why does Python char binding to C fails in c function? I need to use in Python C-coded translation of string to reverse polish notation and calculation of it.
For this I do next:
import ctypes

input_string = bytes(memoryview("2 + 3.2 + 4".encode()))
result = str(self.model.functions['equal'](input_string))

where equal function is in:
    def init_functions(self):
        equal = self.c_lib.equal
        equal.restype = ctypes.c_double
        equal.argtypes = [ctypes.c_char_p]
        self.functions.update({'equal': equal})

Where function in C is:
double equal(char *input) {
    stack S = parseInput(input);
    stack polish = toReversePolishNotation(&S);
    return calculate(&polish);
}

It does calculation perfectly fine in C (checked with tests and memory leaks), always delivering the right answer.
But when I use this function in Python, it occasionally delivers some wrong output.
Sometimes it is 0, sometimes it is some strange number, sometimes it is endless cycle.
For example:
C result
Some random Python result
Strictly the next after random result in Python
More of it, my beloved example is "39.9 - 52.0". In C it is always as stated. But Python passes this string to C as "39.9 - 52.9".
I tried to set input_string = '' in Python, tried to memset char* input by '\0', tried to use different implementations of input_string:
input_string = ctypes.c_char_p("2 + 3.2 + 4".encode('utf-8'))
input_string = bytes("2 + 3.2 + 4", encoding='utf-8')

Python never delivers right answer consequently. It always fails. I don't know, if I need to free input_string somehow or something else is wrong.

A: The C code expects a pointer to mutable memory (probably for some tokenization). For that you need to use create_string_buffer.
input_string = ctypes.create_string_buffer(b"2 + 3.2 + 4")

See the documentation and tutorial


text:
Q: Want to set Parent of portfolioitem/feature I am trying to set Parent for portfolioitem/feature object, using set() method and then commit(). But Parent attribute is not set. ANy suggestions on this. Thanks in advance
genericInnerCopy: function(_childObj) {
   that = _childObj;
   console.log("parent MMF object", _newParent);
   var record = Ext.create(this.model, {
     Name: that.get('Name'),
     //Parent: _newParent,
   });
   record.save({
     callback: function(result, operation) {
     if(operation.wasSuccessful()) {
       result.set('Parent', _newParent);
       result.commit();
     }
     else{
       console.log("error");
     }
     }
   });
},

A: It depends what _newParent contains. It should be a _ref of the object, not the whole object or anything else:
/portfolioitem/initiative/1234567

See a full example of creating a feature and setting its initiative parent in this github repo.
In your code you may not be able to do _newParent.get('_ref') and instead _newParent.data._refdepending on how you arrived at the object.


text:
Q: Loop through SqlDataSource result if underlying SP returns more than one Table I have Asp.net application with SqlDataSource ojbect that calls t-sql sctored procedure. It returns more than one table (it returns aboout 20 different tables in format:
1.table -> event1 data
2.table -> event2 participation data

3.table -> event2 data
4.table ->event2 participation data
etc.

Everything works fine. However, I do not understand how to get all those tables from SqlDataSource result. I do not need any GridView or Repeater. I need to manually loop through SqlDataSource results. I do not know how.
When I was searching on how to convert SqlDataSource to DataSet, it suggests SqlDataSource.Select -> get DataView -> convert toTable, but this works only for one table.

A: Try this
DataSet ds;
myAdap.Fill(ds);
if(ds.tables.count >0){
if(ds.tablles[0]..rows.cout >0){
  foreach(datarow dr in ds.tables[0].rows){  //do someting with table 1}
}
if(ds.tables[1].rows.count>0){
  foreach(datarow dr in ds.tables[1].rows){  //do seomthing with table 2}
}
}
ds.dispose();

<asp:SqlDataSource
     ID="SqlDataSource1"
     runat="server"
     ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
     DataSourceMode="DataSet"
     SelectCommand="SELECT TOP 25 ProductID, ProductName, UnitPrice FROM Products"
     >
</asp:SqlDataSource>


text:
Q: Disk quota after file removal I have an account on some free ssh accessed linux server. The disk per user quota is 100MB. Recently I've downloaded a file abot 80MB and next tried to unzip it. And then an error occured saying the disk quota is being exceeded (I forgot about the quota limitation before the whole operation). Now I've deleted the compressed 80MB leaving in my home dir several really small files but even after the big file removal when i check my quota it says about 90MB even if, as i've said i removed the big archive file. What can i do to "reset" the quota? I really need the disk space.

A: Review the space your files are using. Any number of tools to do this. For an interactive view of utilization try:
ncdu ~

100 MB cannot uncompress a 80 MB file. Likely the uncompressed copy alone is larger than 100 MB. Plus, you need the compressed copy until it is extracted.
You value more space. Pay to rent an instance with larger disks from your favorite provider.


text:
Q: XSLT line break problem I am trying to produce html output according to the fields in xml file with xslt. And I name them according to grandparent-parent-child-grandchild relation in xml
For instance:
<root>
  <node1>
      <node2>
         <node3>Data</node3>
      </node2>
  </node1>

What i need is creating let's say textbox, with name node1__node2__node3
What i did so far is this
<input type="text" name="node1__
        node2__
        node3__"

But what i want to is:
<input type="text" name="node1__node2__node3__"/>

So it is useless. My xslt to produce this useless output is:
<xsl:template name="chooseNameID">
    <xsl:param name="currentNode"/><!-- in this case currentNode is node3 -->
    <xsl:variable name="fieldNames">
        <xsl:for-each select="$currentNode/ancestor::*">
                <xsl:value-of select="name(.)"/>__
        </xsl:for-each>
    </xsl:variable>

    <xsl:attribute name="name">
        <xsl:value-of select="$fieldNames"/>
    </xsl:attribute>

</xsl:template>

I guess the problem is in <xsl:value-of but i cannot find any solution to that.
Thanks

A: This transformation:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node3">
    <xsl:variable name="vName">
     <xsl:for-each select=
      "ancestor-or-self::*[not(position()=last())]">
        <xsl:value-of select="name()"/>
        <xsl:if test="not(position()=last())">__</xsl:if>
     </xsl:for-each>
    </xsl:variable>

    <input type="text" name="{$vName}"/>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:
<root>
    <node1>
        <node2>
            <node3>Data</node3>
        </node2>
    </node1>
</root>

produces the wanted, correct result:
<input type="text" name="node1__node2__node3"/>

Do note: The use of AVT (Attribute Value Template) to generate the required output in one short line.

A: The unwanted whitespace, including newlines, is part of a text node literal in the loop.
In the stylesheet document, whitespace-only text nodes are ignored except within xsl:text. However whitespace adjacent to other text is part of that text.
Literal whitespace in the stylesheet can be managed with xsl:text.
    <!-- change this -->
    <xsl:for-each select="$currentNode/ancestor::*">
        <xsl:value-of select="name(.)"/>__
    </xsl:for-each>

    <!-- to this -->
    <xsl:for-each select="$currentNode/ancestor::*">
        <xsl:value-of select="name(.)"/>__<xsl:text/>
    </xsl:for-each>

    <!-- or this -->
    <xsl:for-each select="$currentNode/ancestor::*">
        <xsl:value-of select="name(.)"/>
        <xsl:text>__</xsl:text>
    </xsl:for-each>

A: As normal, after asking a question you find a solution.
Changing <xsl:value-of select="$fieldNames"/> line with this <xsl:value-of select="normalize-space($fieldNames)" worked for me.


text:
Q: Html: 2 td's, how to align them center? below is the code for Submit and Cancel button. When i have 3 buttons, i aligned the middle one as center. So all the 3 buttons looked good on center. But for something like this, with 2 buttons. How can i align them in the center of tr. With this code it shows on bit left side. Thanks!!

        <asp:ImageButton ID="imgbtnSubmit" runat="server"
             ImageUrl="~/images/submitnew.gif"
             OnClick="imgbtnSubmit_Click" ValidationGroup="valCC"
             TabIndex="21" />

          <asp:ImageButton ID="imgbtnCancel2" runat="server"
              ImageUrl="~/images/cancel.gif"
              OnClick="imgbtnCancel2_Click" CausesValidation="false"
              ImageAlign="AbsMiddle"
              ValidationGroup="valCC" />

A: You assign hard widths to both cells. That should force them to the left.  If you want things centered, best to leave the sizes off and let the browser figure out what size is best.
Further, Using tables for formating a rookie mistake, as it usually ends up with problems like you're having.  Try:

    <asp:ImageButton ..... />

    <asp:ImageButton ..... />

A: Put them in one cell (with colspan=2) and center them there:

        <asp:ImageButton ID="imgbtnSubmit" runat="server" ImageUrl="~/images/submitnew.gif"
             OnClick="imgbtnSubmit_Click" ValidationGroup="valCC" TabIndex="21" />
          <asp:ImageButton ID="imgbtnCancel2" runat="server" ImageUrl="~/images/cancel.gif"
              OnClick="imgbtnCancel2_Click" CausesValidation="false" ImageAlign="AbsMiddle"
              ValidationGroup="valCC" />


text:
Q: When the code is ran on VS2010 in windows10 OS, application buttons are not visible. But the same code works fine in windows7 VS2010 We have moved from Win 7 to Win 10 recently.
Visual Studio 2010 is installed on Win 10. Code build using .net framework v4.0. while running the code in local few buttons on the application are not visible when we run the code.
The same code is published then deployed on the server and ran, buttons are visible.
I have checked the IE compatibility, ran the application on different browser but still no result. tried to check the properties of the solution.
no error message occurred. only buttons not visible while running in local.
I have checked the IE compatibility, ran the application on different browser but still no result. tried to check the properties of the solution.
no error message occurred. only buttons not visible while running in local.
Public Shared Function ButtonVisibleCheck(ByVal Id As String, ByVal Num As Integer) As Boolean
    Dim retVal As Boolean = False
    Dim cmd As OracleCommand
    Dim SHOW_BUTTON_SQL As String = "DECLARE v_status BOOLEAN; BEGIN v_status := xx_pkg.button_show(:p_app_number,:p_page_number ,:p_button_id); if v_status THEN :p_return_val := 'Y'; ELSE :p_return_val := 'N'; END IF;  END;"

    Try
        cmd = New OracleCommand
        cmd.CommandText = SHOW_BUTTON_SQL
        cmd.CommandType = CommandType.Text
        cmd.Parameters.Add(New OracleParameter("p_return_val", OracleType.VarChar, 1)).Direction = ParameterDirection.Output
        cmd.Parameters.AddWithValue("p_app_number", ApplicationDAO.AppId).DbType = DbType.Int32
        cmd.Parameters.AddWithValue("p_page_number", PageNumber).DbType = DbType.Int32
        cmd.Parameters.AddWithValue("p_button_id", ButtonId).DbType = DbType.AnsiString

        OracleCommandProcessor.ExecuteNonQueryInContext(cmd)

        retVal = IIf(DbUtilities.Nvl(cmd.Parameters("p_return_val").Value, "N") = "Y", True, False)

    Catch ex As Exception
        retVal = "Error while processing Validation Check"
    Finally
        cmd = Nothing
    End Try

    Return retVal
End Function

IIf(DbUtilities.Nvl(cmd.Parameters("p_return_val").Value, "N") = "Y", True, False) In this line "p_return_val").Value is always coming as Null in  windows 10 . But in windows 7 it will return Y.
IIf(DbUtil.Nvl(cmd.Parameters("p_return_val").Value, "N") = "Y", True, False) In this line "p_return_val").Value is always coming as Null in  windows 10 . But in windows 7 it will return Yand based on that we are displaying button visible true or False.


text:
Q: Selenium Webdriver enter multiline text in form without submitting it I have a multiline text and when I am simply putting the whole text into a form using sendKeys, the form gets submitted on each line break.
I tried replacing the newline with carriage return this way:
String myText="Some Multiline Text....";
myText=myText.replace("\n","\13");

This simply removed the newlines and I could not see the newline in output text.
Also below did not work(it also submits form at line breaks):
String myText="Some Multiline Text....";
myText=myText.replace("\n","\r");

So how do I go about with newlines in sendkeys without submitting the form?

A: What worked for me using python 3 was make use of ActionChain as Tamas said and @Arount posted on Python and Selenium - Avoid submit form when send_keys() with newline
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome()
driver.get('http://foo.bar')

inputtext = 'foo\nbar'
elem = driver.find_element_by_tag_name('div')
for part in inputtext.split('\n'):
    elem.send_keys(part)
    ActionChains(driver).key_down(Keys.SHIFT).key_down(Keys.ENTER).key_up(Keys.SHIFT).key_up(Keys.ENTER).perform()

A: This is not a Selenium issue, pressing enter in a text field often submits the form. Usually you can bypass it by using Shift+Enter to insert a new line. Try this:
String myText = "first line\nsecond line";
myText = myText.replace("\n", Keys.chord(Keys.SHIFT, Keys.ENTER));
myElement.sendKeys(myText);

A: You can also use the following method for selenium. I added 2 samples. Msgbox and sendkeys
Dim myText As String = "hello\nYes"
myText = myText.Replace("\n", Environment.NewLine)
MsgBox(myText)
exDriver.FindElement(By.TagName("input")).SendKeys(myText)

Output
imgur output


text:
Q: Rails HABTM relationship not working with polymorphic relationship I have two models: Student and Project.  A student HABTM projects and a Project HABTM students.  Here are the two models:
class Student < User
    has_many :relationships, dependent: :destroy
    has_many :employers, through: :relationships
    has_and_belongs_to_many :projects, join_table: :projects_students
end

class Project < ActiveRecord::Base
    has_many :relationships
    belongs_to :employer
    has_and_belongs_to_many :students, join_table: :projects_students
end

As you can see, Student uses polymorphic inheritance from User (The user table has a type column, one of the values is Student).  Here is the controller that creates projects:
def create
    @project = current_user.projects.new(project_params)

    respond_to do |format|
        if @project.save
            format.html { redirect_to @project, notice: 'Project was successfully created.' }
            format.json { render action: 'show', status: :created, location: @project }
        else
            format.html { render action: 'new' }
            format.json { render json: @project.errors, status: :unprocessable_entity }
        end
    end
end

def project_params
    params.require(:project).permit(:title, :category, :location, :budget,
       :description, :projectdoc)
end

Project and Student are connected through the join_table :projects_students:
create_table "projects_students", force: true do |t|
  t.integer "student_id"
  t.integer "project_id"
end

add_index "projects_students", ["project_id"], name: "index_projects_students_on_project_id", using: :btree
add_index "projects_students", ["student_id"], name: "index_projects_students_on_student_id", using: :btree

The problem is that when a project is created, the student_id is not being passed to the projects_students table.  How can I fix this?

A: I think you mean to say that Student uses "single table inheritance" rather than "polymorphic inheritance" of which there is no such thing.
That said, since the HABTM association is on users and not students, I'd check in the console to see if this works:
Student.first.projects << Project.first

Next thing I'd do is to use "build" instead of "new" when instantiating the project:
@project = current_user.projects.build project_params

I suppose this is only for creating new projects, and that there is a different route for adding students to projects.

A: I think you're thinking about this wrong.  Generally the _id is reserved for foreign keys to a related table.  Since there is no Student table, rails may be unable to link the student_id in your join table appropriately.
Try changing your join table:
create_table "projects_users", force: true do |t|
  t.integer "user_id"
  t.integer "project_id"
end

add_index "projects_users", ["project_id"], name: "index_projects_users_on_project_id", using: :btree
add_index "projects_users", ["user_id"], name: "index_projects_users_on_user_id", using: :btree

Your join table shouldn't care about your STI setup.  You can handle that in your models.
So then just cleanup the associations:
class Student < User
    has_many :relationships, dependent: :destroy
    has_many :employers, through: :relationships
    has_and_belongs_to_many :projects, join_table: :projects_users, foreign_key: :user_id
end

class Project < ActiveRecord::Base
    has_many :relationships
    belongs_to :employer
    has_and_belongs_to_many :students, join_table: :projects_users, class_name: 'Student', association_foreign_key: :user_id
end


text:
Q: src folder not included in exported .jar messing up resource paths (Eclipse) So I have a project that runs perfectly within Eclipse, but when I export it as a runnable .jar the paths to my .png resource files won't work anymore as the src folder is not included in the exported .jar.
createTexture("resources/grass.png", 0);

This is where I use the path.
public static void createTexture(String path, int index){
    try (InputStream inputStream = Drawer.class.getClassLoader().getResourceAsStream(path)){
        textureDecoder = new PNGDecoder(inputStream); [...]

now I get the error
Exception in thread "main" java.lang.NullPointerException
at de.matthiasmann.twl.utils.PNGDecoder.readFully(PNGDecoder.java:802)
at de.matthiasmann.twl.utils.PNGDecoder.<init>(PNGDecoder.java:112)
at workers.Drawer.createTexture(Drawer.java:80)
at workers.Drawer.openglSetup(Drawer.java:44)
at jonta.Main.setUp(Main.java:41)
at jonta.Main.main(Main.java:121)

OLD:
This is obviously the error I get when I try to run the .jar:
java.io.FileNotFoundException: src\resources\grass.png

I'll of course include more code/configurations I've made if that would be relevant.
EDIT: Problem solved, thanks!

A: Use:
InputStream inputStream = className.class.getClassLoader().getResourceAsStream(path);

A: In Eclipse, after selecting "Export ..." and "JAR File", there is checkbox for "Export Java source files and resources". You need to click that checkbox.


text:
Q: Null Reference Exception , But it is NOT a null value I yesterday started working on my first .NET c# MVC project.
Now I receive a null reference when i try to POST but before that when i try to read from that same value it works fine.
What I mean is that when the page loads, it loads the value correctly, but when i press the submit button it throws the exception .
@model QnA_WebApp_MVC.Models.Block
@{
    Block block = (Block)@TempData["block"];
}

User: @block.user_id

And the thing is that the block.user_id is not even among the posted values.

A: Anyway I found the solution my self. I changed the
Block block = (Block)@TempData["block"];

To
Block block = new Block();
block = ViewBag.block;

In a previous attempt i had tried
Block block = ViewBag.block;

and it was not working -> null reference exception
I believe that the solution was that i first declared the block as a new Block() but i am not 100%. Anyway now it works so i am moving on


text:
Q: Comparing with previous passwords For security reasons, I need to force the user to change his password quite often and something I don't want is a password really close to the previous one, for obvious security reasons.
But for security reason as well, I can't keep the real password in the DB (ie: I need to hash it or any other method).
But I don't think comparing the hashes will help.
Is there a way to compare 2 passwords in order to know if they are close to each other?
Ex: password and password1 are too close to each other.

A: At the time of making the user choose a new password, you make him/her enter his/her old password. This allows you to compare the new password to the old password without having to store the old password in plaintext.

A: When a user logs in normally you are storing a hash of the password in your database. You compare the password typed to the hash by hashing what they typed and if the resulting hash is the same as the hash in the database it is accepted.
To compare against old passwords you would do the same thing. You could save the last password (or the last 5, 10 ...x passwords) in the database by just copying the password hash field to old-password1 (shifting each password over one column if you want to keep them from reusing it after some number of changes, old-password1 becomes old-password2 etc) Then when they type in the new password you can compare the same way you always do, but against the old hashes. If it matches an old hash you reject it with a message saying that it cannot be one of the last X passwords they used.
You are not storing any clear-text passwords, and you can keep as many old hashes as you want.


text: Q: Is there any analogue of mathcal which also works with Greek letters? I have noticed that the font category mathcal does not work with Greek letters as inputs, probably because nobody has created any sort of "calligraphic Greek font family". Is there any sort of font package or environment which does this?


text:
Q: WPF prism: using command on toggleswitch I want to use a delegate command with a Horizontaltoggleswitch that is fired when the switch is toggled. I use delegate commands with button and also with textboxes (where the Event is fired when the enterkey is pressed), but I cant find how to solve that with toggleswitch? I tried this:
XAML:
        <toggleSwitch:HorizontalToggleSwitch CheckedContent="Open" UncheckedContent="Closed" IsChecked="{Binding SubstrateValveOpen,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
            <toggleSwitch:HorizontalToggleSwitch.InputBindings>
                <KeyBinding Command="{Binding SubstrateCommand}" Key="??"/>
            </toggleSwitch:HorizontalToggleSwitch.InputBindings>
        </toggleSwitch:HorizontalToggleSwitch>

ViewModel:
        private bool _substrateValveOpen;
        public bool SubstrateValveOpen
        {
            get => _substrateValveOpen;
            set => SetProperty(ref _substrateValveOpen, value);
        }

         public DelegateCommand SubstrateCommand => new DelegateCommand(Substrate, CanSubstrate);

         ...

but I dont really know what to do with the Event.
thanks for any idea!

A: The command is completely superfluous here. The property should do everything here.
Reminder: a property ist not just a field with PropertyChanged...
private bool _substrateValveOpen;
public bool SubstrateValveOpen
{
    get => _substrateValveOpen;
    set
    {
        if (value && !_substrateValveOpen && !CanSubstrate())
            return;
        if (SetProperty(ref _substrateValveOpen, value) && value)
            Substrate();
    }
}


text:
Q: proof of $\frac{\frac{1}{n}}{\sqrt{x^2+\frac{1}{n}}+x}\leq\frac{1}{\sqrt{n}}$ for large $n$ I'm trying to conclude this question in which I just need to prove that:
$$0<\frac{\frac{1}{n}}{\sqrt{x^2+\frac{1}{n}}+x}\leq\frac{1}{\sqrt{n}}$$
and then I'll have that, for large $n$:
$$\begin{align}
\left\lvert\cos\left(\sqrt{x^2+\frac{1}{n}}\right)-\cos(x)\right\rvert &= \left\lvert2\sin\frac{\sqrt{x^2+\frac{1}{n}}-x}{2}\sin\frac{\frac{\frac{1}{n}}{\sqrt{x^2+\frac{1}{n}}+x}}{2}\right\rvert\\
&\leq
2\sin\frac{\sqrt{x^2+\frac{1}{n}}-x}{2}\sin\frac{1}{2\sqrt{n}}\xrightarrow[n\to\infty]{} 0
\end{align}$$
because $\sin\frac{1}{2\sqrt{n}}\to 0$ and $\sin\frac{\sqrt{x^2+\frac{1}{n}}-x}{2}$ is bounded.
I liked the answers given in the question but I really need to solve it this way, I'm trying to investigate the inequation. I know that, the worst case is for $n$ so large that $\frac{1}{n}$ in the LHS of the inequality goes to $0$, and the best case is when $n=1$ and therefore we have:
$$\sqrt{x^2}+x<\sqrt{x^2+\frac{1}{n}}+x<\sqrt{x^2+1}+x\le\sqrt{2}+1$$
*for $0\le x\le 1$
but it doesn't help, I think.

A: Well, as $x$ is positive, by monotonicity of the square root
$$\sqrt{x^2+\frac1n}+x \geq \sqrt{x^2+\frac1n}+\geq \sqrt{\frac1n}=\frac1{\sqrt{n}}$$
Thus
$$\frac{\frac{1}{n}}{\sqrt{x^2+\frac1n}+x}\leq \frac{\frac{1}{n}}{\sqrt{x^2+\frac1n}}\leq \frac{\frac{1}{n}}{\frac1{\sqrt{n}}}=\frac{1}{\sqrt{n}}$$

A: Outline: setting $\alpha=\frac{1}{\sqrt{n}}$, you want to prove
$$
\frac{1}{\sqrt{x^2+\alpha^2}+x} \leq \frac{1}{\alpha}, \qquad \forall x\geq 0\tag{1}
$$
Let us prove it for all $\alpha > 0$: this will then be equivalent to proving that for all $x\geq 0$
$$
\sqrt{x^2+\alpha^2}+x \geq \alpha, \qquad \forall x\geq 0
$$
that is, removing $x$ from each side and squaring, this will be equivalent* to showing that
$$
x^2+\alpha^2 \geq x^2+\alpha^2 - 2\alpha x, \qquad \forall x\geq 0.
$$
Now, why is that the case?

${}$* You may want to check that this is indeed equivalent, since we square... but yes, it is, as if the original RHS is negative then there is nothing to prove (the LHS is always positive).

A: Cross-multiply, square, subtract ${1\over n}$ from both sides to get
$$
0\le 2x^2+2x\sqrt{x^2+{1\over n}}
$$
Assuming $x\in[0,1]$ the above identity is trivial as each term on the RHS is non-negative. Now backtrack and get your desired identity.


text:
Q: How to parse JSON-C in .net I cannot use the Youtube APIs since they are not supported on WP so I opted to just use the JSON response. Seems like Youtube has changed there response type to JSON-C, how can I parse this?
https://www.googleapis.com/youtube/v3/search?part=snippet&order=relevance&q=lil+b&key=AIzaSyACjwJrIBICZxPb1x3JRq-FQ8iaei7LqXA&alt=json
I've tried Newtonsoft JSON but it does not support it either, any advice? Thanks!

A: Can you try the below code. I have saved the json data as text file. Using jsonCsharp you can generate the model class. http://json2csharp.com/
var json = System.IO.File.ReadAllText(@"C:\json.txt"); //get json data
var result = JsonConvert.DeserializeObject<RootObject>(json);

public class PageInfo
{
    public int totalResults { get; set; }
    public int resultsPerPage { get; set; }
}

public class Id
{
    public string kind { get; set; }
    public string channelId { get; set; }
    public string videoId { get; set; }
}

public class Default
{
    public string url { get; set; }
}

public class Medium
{
    public string url { get; set; }
}

public class High
{
    public string url { get; set; }
}

public class Thumbnails
{
    public Default @default { get; set; }
    public Medium medium { get; set; }
    public High high { get; set; }
}

public class Snippet
{
    public string publishedAt { get; set; }
    public string channelId { get; set; }
    public string title { get; set; }
    public string description { get; set; }
    public Thumbnails thumbnails { get; set; }
    public string channelTitle { get; set; }
}

public class Item
{
    public string kind { get; set; }
    public string etag { get; set; }
    public Id id { get; set; }
    public Snippet snippet { get; set; }
}

public class RootObject
{
    public string kind { get; set; }
    public string etag { get; set; }
    public PageInfo pageInfo { get; set; }
    public string nextPageToken { get; set; }
    public List<Item> items { get; set; }
}


text:
Q: stringWithContentsOfURL gives null value Hi I'm trying to get a number from a text file in my server but i'm getting a null value this is the code... I have reed many similar posts trying to solve the problem but non of them has been useful
NSURL *url = [NSURL URLWithString:@"http://www.trailrunningcamp.cl/version.txt"];
NSError* error = nil;
NSString *content = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];

NSLog(@"Content = %@", content );

I have added this code to my plist but still got the same result
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
   <dict>
     <key>trailrunningcamp.cl</key>
      <dict>
        <!--Include to allow subdomains-->
         <key>NSIncludesSubdomains</key>
         <true/>
         <!--Include to allow HTTP requests-->
        <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
     <true/>
      <!--Include to specify minimum TLS version-->
     <key>NSTemporaryExceptionMinimumTLSVersion</key>
     <string>TLSv1.1</string>
     </dict>
   </dict>
 </dict>

I'm using Xcode 7.2.1 and OS X El Capitan 10.11.3.... before that code worked fine (a year ago) but with the new Xcode does not work... Is it a missconfiguration or a code error?


text:
Q: Updating excel file using Apache POI I am trying to update an existing excel file using Apache POI. Every time I run my code I receive an error as shown below. I have also tried FileInputStreamNewFile thing.
Exception in thread "main" java.lang.NullPointerException
    at com.gma.test.WriteExcelTest.writeXLSXFile(WriteExcelTest.java:26)
    at com.gma.test.WriteExcelTest.main(WriteExcelTest.java:44)

Please find the code below. Appreciate your help.
package com.gma.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteExcelTest {

    public static void writeXLSXFile(int row, int col) throws IOException {
        try {
            FileInputStream file = new FileInputStream("C:\\Anuj\\Data\\Data.xlsx");

            XSSFWorkbook workbook = new XSSFWorkbook(file);
            XSSFSheet sheet = workbook.getSheetAt(0);
            Cell cell = null;

            //Update the value of cell
            cell = sheet.getRow(row).getCell(col);
            cell.setCellValue("Pass");

            file.close();

            FileOutputStream outFile =new FileOutputStream(new File("C:\\Anuj\\Data\\Data.xlsx"));
            workbook.write(outFile);
            outFile.close();

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

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        writeXLSXFile(3, 3);
    }

}

A: Thanks Jelle Heuzel for getting a good example.
I just wanted to add the resulting working code so other can incorporate it in their code faster.
I also had to use XSSFRow instead of HSSFRow but other than that it works fine for me.
package stackoverflow.appachePOI;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteExcelTest {

    public static void writeXLSXFile(int row, int col) throws IOException {
        try {
            FileInputStream file = new FileInputStream("C:\\Users\\Sam\\files\\Masterproef lca\\lca-analysebeheer\\Test-Files\\exceltemplates\\template.xlsx");

            XSSFWorkbook workbook = new XSSFWorkbook(file);
            XSSFSheet sheet = workbook.getSheetAt(0);
            Cell cell = null;

            //Retrieve the row and check for null
            XSSFRow sheetrow = sheet.getRow(row);
            if(sheetrow == null){
                sheetrow = sheet.createRow(row);
            }
            //Update the value of cell
            cell = sheetrow.getCell(col);
            if(cell == null){
                cell = sheetrow.createCell(col);
            }
            cell.setCellValue("Pass");

            file.close();

            FileOutputStream outFile =new FileOutputStream(new File("C:\\Users\\Sam\\files\\Masterproef lca\\lca-analysebeheer\\Test-Files\\exceltemplates\\Output.xlsx"));
            workbook.write(outFile);
            outFile.close();

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

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        writeXLSXFile(3, 3);
    }

}

A: If you replace
//Update the value of cell
cell = sheet.getRow(row).getCell(col);
cell.setCellValue("Pass");

With
//Retrieve the row and check for null
HSSFRow sheetrow = sheet.getRow(row);
if(sheetrow == null){
    sheetrow = sheet.createRow(row);
}
//Update the value of cell
cell = sheetrow.getCell(col);
if(cell == null){
    cell = sheetrow.createCell(col);
}
cell.setCellValue("Pass");

It will work!

A: i tried with this and work for XLSX and XSSF
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TestStackOver {

    public static void writeXLSXFile(int row, int col) throws IOException {
        try {
            FileInputStream file = new FileInputStream(Constante.ruta);
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            XSSFSheet sheet = workbook.getSheetAt(0);
            Cell cell = null;
          //Retrieve the row and check for null
            XSSFRow sheetrow = sheet.getRow(row);
            if(sheetrow == null){
                sheetrow = sheet.createRow(row);
            }
            //Update the value of cell
            cell = sheetrow.getCell(col);
            if(cell == null){
                cell = sheetrow.createCell(col);
            }
            cell.setCellValue("Pass");

            file.close();

            FileOutputStream outFile =new FileOutputStream(new File(Constante.ruta_salida));
            workbook.write(outFile);
            outFile.close();

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

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        System.out.println("inicio");
        writeXLSXFile(1, 14);
        System.out.println("terminado");
    }

}


text:
Q: Using score field with SolrNet I'm using SolrNet and have a problem where the score field is conflicting with documents being added or updated in the index.
The class representing my documents looks something like this
class MyDoc
{
    [SolrUniqueKey("doc_id")]
    public string DocId { get; set; }

    [SolrField("foo")]
    public string Foo { get; set; }

    [SolrField("bar")]
    public string Bar { get; set; }

    [SolrField("score")]
    public double Score { get; set; }
}

In the query being issued to Solr, I've added the 'score' field to the fl parameter, and the score value is returned and set correctly on this class.  However, when adding or updating documents, I'm getting an error about the score field not existing in my index, which it doesn't, and shouldn't as this is a dynamic field.
The code doing the add/update is fairly simple:
Startup.Container.GetInstance<ISolrOperations<MyDoc>>().Add(doc);

It looks like I need the score property to be ignored by SolrNet (or Solr) when adding or updating documents, and only use it when retrieving documents.
Is there any way to achieve this?

A: I have accomplished this by having two separate classes. One that maps to documents being retrieved from the index as search results and another class that is used to add items to the index. So in this scenario you could do the following:
 class MyDoc
 {
      [SolrUniqueKey("doc_id")]
      public string DocId { get; set; }

      [SolrField("foo")]
      public string Foo { get; set; }

      [SolrField("bar")]
      public string Bar { get; set; }
 }

 class MyDocResult
 {
      [SolrUniqueKey("doc_id")]
      public string DocId { get; set; }

      [SolrField("foo")]
      public string Foo { get; set; }

      [SolrField("bar")]
      public string Bar { get; set; }

      [SolrField("score")]
      public double Score { get; set; }
 }

Be sure you initialize both classes pointing to the same solr url.
      Startup.Init("http://localhost:8983/solr");
      Startup.Init("http://localhost:8983/solr");
Then you can add with:
  ServiceLocator.Current.GetInstance<ISolrOperations<MyDoc>>().Add(doc);

And Query with:
  var solr ServiceLocator.Current.GetInstance<ISolrOperations<MyDocResult>>();
  var results = solr.Query("foo bar");

You could also look into using the Dynamic or Fully Loose Mapping options for SolrNet if you do not want to create two separate classes.

A: If you make your POCO class have the Score as nullable you can use the same object for indexing and results
[SolrField("score")]
public double? Score { get; set; }


text:
Q: помогите улучшить архитектуру кода: изменить модель, отделить логику от UI, разбить на файлы (c# + winforms) Привет
Я сделал тестовое задание, хотел бы попросить поревьюить код, что бы его улучшить.
Нужно:
    - улучшить архитектуру: изменить модель данных, правильно разбить код на файлы
    - полностью развязать модель и UI
    - внедрить другие паттерны проектирования
    - внедрить MVC (если нужно)
Задание 3. Модель автоматического аппарата быстрого питания.
Необходимо выполнить реализацию задачи с максимальным использованием преимуществ объектно-ориентированного подхода и, по возможности, реализовать подходящие архитектурные шаблоны проектирования приложений.
В качестве результата нужно предоставить UML-диаграмму классов предметной области или приложение реализующее работу вышеупомянутого аппарата или и то и другое.
Создать объектную модель аппарата по быстрому приготовлению напитков и еды со следующими допущениями:

*

*Латте – это эспрессо + молоко

*Капучино – эспрессо + молоко + молочная пенка

*Молоко можно добавлять к следующим напиткам: эспрессо, латте, чай черный, чай зеленый

*Сахар можно добавлять ко всем напиткам. Количество порций сахара указывается пользователем (от 0 до 5).

*Ветчину, сыр можно добавлять к хлебу и булочке (получается бутерброд)

*Комплекс – это набор из напитка и еды по фиксированной цене. При этом можно выбрать любой элемент из категории «Напиток» + один элемент из «Добавки к напиткам», аналогично с едой: 1 элемент из категории «Еда» + 1 элемент из категории «Добавки к еде».
Задание.

*Аппарат должен считать стоимость выбранного заказа и выводить в окно со стоимостью.

*После нажатия на кнопку выдать, в диалоговом окне выводить строку с составом заказа, например, Капучино (Эспрессо+Молоко+Сахар)
Бутерброд (Хлеб+Ветчина).
В случае реализации приложения учитывать следующее ограничение:
Язык реализации: C#
Уровень представления: Windows Forms или Web-приложение
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static WindowsFormsApp1.CoffeeMachine;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private CoffeeMachine coffeeMachine = new CoffeeMachine();
        public Form1()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            radioButtonEspresso.Text = new Espresso().Name + new Espresso().GetCost() + " руб";
            radioButtonLatte.Text = "Латте - " + coffeeMachine.GetLatte().GetCost() + " руб";
            radioButtonCapuchino.Text = "Капуччино - " + coffeeMachine.GetCapuchino().GetCost() + " руб";
            radioButtonBlackTea.Text = new BlackTea().Name + new BlackTea().GetCost() + " руб";
            radioButtonGreenTea.Text = new GreenTea().Name + new GreenTea().GetCost() + " руб";
            radioButtonWater.Text = new Water().Name + new Water().GetCost() + " руб";

            radioButtonBread.Text = new Bread().Name + new Bread().GetCost() + " руб";
            radioButtonRoll.Text = new Roll().Name + new Roll().GetCost() + " руб";
            radioButtonChips.Text = new Chips().Name + new Chips().GetCost() + " руб";
            radioButtonCookie.Text = new Cookie().Name + new Cookie().GetCost() + " руб";

            Meals blankObject = new Espresso();
            checkBoxMilk.Text = new Milk(blankObject).Name + new Milk(blankObject).Cost;
            checkBoxSugar.Text = new Sugar(blankObject).Name + new Sugar(blankObject).Cost;
            checkBoxSyrop.Text = new Syrop(blankObject).Name + new Syrop(blankObject).Cost;
            checkBoxHam.Text = new Ham(blankObject).Name + new Ham(blankObject).Cost;
            checkBoxCheese.Text = new Cheese(blankObject).Name + new Cheese(blankObject).Cost;
            checkBoxJam.Text = new Jam(blankObject).Name + new Jam(blankObject).Cost;

            checkBoxComplex.Text = "Комплекс (1 напиток с любой добавкой + 1 еда с любой добавкой на выбор)";
            labelComplexCost.Text = "90 руб";

            radioButtonBread.Checked = true;
        }

        private void ShowCost(int cost)
        {
            textBoxCost.Text = cost.ToString();
        }

        private void RecountMealsCost()
        {
            Dictionary<Meals, bool> beverageChoice = new Dictionary<Meals, bool>()
            {
                {new Espresso(), radioButtonEspresso.Checked},
                {coffeeMachine.GetLatte(), radioButtonLatte.Checked},
                {coffeeMachine.GetCapuchino(), radioButtonCapuchino.Checked },
                {new BlackTea(), radioButtonBlackTea.Checked},
                {new GreenTea(), radioButtonGreenTea.Checked},
                {new Water(), radioButtonWater.Checked }
            };
            RecountBeverageCost(beverageChoice.FirstOrDefault(x => x.Value == true).Key);

            Dictionary<Meals, bool> foodChoice = new Dictionary<Meals, bool>()
            {
                { new Bread(), radioButtonBread.Checked},
                { new Roll(), radioButtonRoll.Checked},
                { new Chips(), radioButtonChips.Checked},
                { new Cookie(), radioButtonCookie.Checked}
            };
            RecountFoodCost(foodChoice.FirstOrDefault(x => x.Value == true).Key);

            int totalCost = coffeeMachine.BeverageCost + coffeeMachine.FoodCost;
            ShowCost(totalCost);
            buttonGiveOrder.Enabled = coffeeMachine.IsComplexOrderEnabled(checkBoxComplex.Checked, totalCost);
        }

        private void RecountBeverageCost(Meals meal)
        {
            if (meal.GetType().Name != "Milk")
            {
                meal =  coffeeMachine.AddAdditionIfChecked(checkBoxMilk.Checked, meal, new Milk(meal));
                checkBoxMilk.Enabled = true;
            }
            else
            {
                checkBoxMilk.Enabled = false;
            }

            for (int i = 0; i < numericUpDownSugarPieces.Value; i++)
            {
                meal = coffeeMachine.AddAdditionIfChecked(checkBoxSugar.Checked, meal, new Sugar(meal));
            }
            meal = coffeeMachine.AddAdditionIfChecked(checkBoxSyrop.Checked, meal, new Syrop(meal));
            coffeeMachine.BeverageCost = meal.GetCost();
        }

        private void RecountFoodCost(Meals meal)
        {
            if (meal.GetType().Name == "Bread" || meal.GetType().Name == "Roll")
            {
                meal = coffeeMachine.AddAdditionIfChecked(checkBoxHam.Checked, meal, new Ham(meal));
                meal = coffeeMachine.AddAdditionIfChecked(checkBoxCheese.Checked, meal, new Cheese(meal));
                checkBoxHam.Enabled = true;
                checkBoxCheese.Enabled = true;
            }
            else
            {
                checkBoxHam.Enabled = false;
                checkBoxCheese.Enabled = false;
            }

            meal = coffeeMachine.AddAdditionIfChecked(checkBoxJam.Checked, meal, new Jam(meal));
            coffeeMachine.FoodCost = meal.GetCost();
        }

        private void radioButton_Clicked(object sender, EventArgs e)
        {
            RecountMealsCost();
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            RecountMealsCost();
        }

        private void checkBox_CheckedChanged(object sender, EventArgs e)
        {
            RecountMealsCost();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string caption = new Order().GetInfo(groupBox1, groupBox2, groupBox3, groupBox4).Caption;
            string message = new Order().GetInfo(groupBox1, groupBox2, groupBox3, groupBox4).Message;
            MessageBox.Show(caption, message, MessageBoxButtons.OK);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp1
{
    public class CoffeeMachine
    {
        public int BeverageCost { get; set; }
        public int FoodCost { get; set; }
        private int complexCost = 90;

        public abstract class Meals
        {
            public Meals(string name)
            {
                this.Name = name;
            }
            public string Name { get; protected set; }
            public abstract int GetCost();
        }

        public class Espresso : Meals
        {
            public Espresso() : base("Эспрессо - ")
            { }

            public override int GetCost()
            {
                return 60;
            }
        }

        public class BlackTea : Meals
        {
            public BlackTea() : base("Чёрный чай - ")
            { }
            public override int GetCost()
            {
                return 25;
            }
        }

        public class GreenTea : Meals
        {
            public GreenTea() : base("Зелёный чай - ")
            { }
            public override int GetCost()
            {
                return 25;
            }
        }

        public class Water : Meals
        {
            public Water() : base("Вода - ")
            { }
            public override int GetCost()
            {
                return 20;
            }
        }

        public abstract class MealsDecorator : Meals
        {
            protected Meals meals;
            protected int cost;
            protected string name;
            public MealsDecorator(string name, Meals meals) : base(name)
            {
                this.meals = meals;
            }
        }

        public class Milk : MealsDecorator
        {
            public Milk(Meals meals)
                : base(meals.Name, meals)
            { }

            public string Name { get; set; } = "Молоко - ";
            public int Cost { get; set; } = 10;

            public override int GetCost()
            {
                return meals.GetCost() + Cost;
            }
        }

        public class MilkFroth : MealsDecorator
        {
            public MilkFroth(Meals meals)
                : base(meals.Name + "Молочная пенка - ", meals)
            { }

            public override int GetCost()
            {
                this.cost = 10;
                return meals.GetCost() + this.cost;
            }
        }

        public class Syrop : MealsDecorator
        {
            public Syrop(Meals meals)
                : base(meals.Name, meals)
            { }

            public string Name { get; set; } = "Сироп - ";
            public int Cost { get; set; } = 5;

            public override int GetCost()
            {
                return meals.GetCost() + Cost;
            }
        }

        public class Sugar : MealsDecorator
        {
            public Sugar(Meals meals)
                : base(meals.Name, meals)
            { }

            public string Name { get; set; } = "Сахар - ";
            public int Cost { get; set; } = 5;

            public override int GetCost()
            {
                return meals.GetCost() + Cost;
            }
        }

        public class Ham : MealsDecorator
        {
            public Ham(Meals meals)
                : base(meals.Name, meals)
            { }

            public string Name { get; set; } = "Ветчина - ";
            public int Cost { get; set; } = 15;

            public override int GetCost()
            {
                return meals.GetCost() + Cost;
            }
        }

        public class Cheese : MealsDecorator
        {
            public Cheese(Meals meals)
                : base(meals.Name, meals)
            { }

            public string Name { get; set; } = "Сыр - ";
            public int Cost { get; set; } = 10;

            public override int GetCost()
            {
                return meals.GetCost() + Cost;
            }
        }

        public class Jam : MealsDecorator
        {
            public Jam(Meals meals)
                : base(meals.Name, meals)
            { }

            public string Name { get; set; } = "Джем - ";
            public int Cost { get; set; } = 7;

            public override int GetCost()
            {
                return meals.GetCost() + Cost;
            }
        }

        public Meals GetLatte()
        {
            return new Milk(new Espresso());
        }

        public Meals GetCapuchino()
        {
            return new MilkFroth(new Milk(new Espresso()));
        }

        public class Bread : Meals
        {
            public Bread() : base("Хлеб - ")
            { }
            public override int GetCost()
            {
                return 10;
            }
        }

        public class Roll : Meals
        {
            public Roll() : base("Булочка - ")
            { }
            public override int GetCost()
            {
                return 15;
            }
        }

        public class Chips : Meals
        {
            public Chips() : base("Чипсы - ")
            { }
            public override int GetCost()
            {
                return 34;
            }
        }

        public class Cookie : Meals
        {
            public Cookie() : base("Печенье - ")
            { }
            public override int GetCost()
            {
                return 29;
            }
        }

        public Meals AddAdditionIfChecked(bool isControlChecked, Meals meal, MealsDecorator decorator)
        {
            if (isControlChecked)
            {
                meal = decorator;
            }
            return meal;
        }

        public bool IsComplexOrderEnabled(bool controlStateToEnable, int cost)
        {
            if (controlStateToEnable == true && cost > complexCost)
                return false;

            return true;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    class Order
    {
        public string BeverageName { get; set; }
        public string[] BeverageAdditionsNames { get; set; }
        public string FoodName { get; set; }
        public string[] FoodAdditionsNames { get; set; }
        public Order(string beverageName,
                     string[] beverageAdditionsNames,
                     string foodName,
                     string[] foodAdditionsNames)
        {
            BeverageName = beverageName;
            FoodName = foodName;
            BeverageAdditionsNames = beverageAdditionsNames;
            FoodAdditionsNames = foodAdditionsNames;
        }

        public string Message { get; set; }
        public string Caption { get; set; }
        public Order(string message, string caption) {
            Message = message;
            Caption = caption;
        }

        public Order() { }

        public Order Get<T1, T2, T3>(T3 beverages, T3 beverageAdditions,
                                     T3 foods,     T3 foodAdditions)        where T1: RadioButton
                                                                            where T2: CheckBox
                                                                            where T3: GroupBox
        {
            Func<Control, string> GetName = x => { return x.Text.Split(new string[] {" -"}, StringSplitOptions.None)[0]; };
            Func<T1, bool> RadiobuttonChecked = x => { return x.Checked == true; };
            Func<T2, bool> CheckboxChecked = x => { return x.Checked == true; };
            Func<T2, bool> CheckboxEnabled = x => { return x.Enabled == true; };

            var beverage = GetControls<T1>(beverages).Where(RadiobuttonChecked).Select(GetName).SingleOrDefault();

            var beverageAddition = GetControls<T2>(beverageAdditions).Where(CheckboxChecked).Select(GetName).ToArray();

            var food = GetControls<T1>(foods).Where(RadiobuttonChecked).Select(GetName).SingleOrDefault();

            var foodAddition = GetControls<T2>(foodAdditions).Where(CheckboxChecked).Where(CheckboxEnabled).Select(GetName).ToArray();

            return new Order(beverage, beverageAddition, food, foodAddition);
        }

        private IEnumerable<T> GetControls<T>(GroupBox source)
        {
            return source.Controls.OfType<T>();
        }

        public Order GetInfo<T>(T beverages, T beverageAdditions, T foods, T foodAdditions) where T: GroupBox
        {
            Order order = Get<RadioButton, CheckBox, GroupBox>(beverages, beverageAdditions, foods, foodAdditions);
            string beverageDelimiter = ", ";
            string foodDelimiter = beverageDelimiter;
            string additionsDelimeter = beverageDelimiter;

            var chosenBeverageAdditions = string.Join(beverageDelimiter, order.BeverageAdditionsNames);
            var chosenFoodAdditions = string.Join(foodDelimiter, order.FoodAdditionsNames);

            if (chosenBeverageAdditions == string.Empty)
                beverageDelimiter = null;
            if (chosenFoodAdditions == string.Empty)
                foodDelimiter = null;

            string caption = "Заказ";
            string message = "Напиток: " + order.BeverageName + beverageDelimiter + chosenBeverageAdditions + "\n" +
                             "Еда: " + order.FoodName + foodDelimiter + chosenFoodAdditions;
            return new Order(caption, message);
        }
    }
}

A: Вы умеет кодировать (ну вот в коде я вижу дженерики например), но архитектуры в приложении я не вижу.
Во-первых, паттерн MVC говорит о том, что нужно разделять логику (доменную модель) от UI. Имея написанный слой доменной логики вы можете легко заменить проект с WebForms на скажем Asp.Net или что-то другое -- а домен при этом не поменяется.
А посмотрите на ваш класс Order. Это доменная логика, в ней нельзя ничего знать о UI, но в ваш класс Order просочилось знание о конкретной реализации UI: вы пишете button.Checked
Возьмите студию, создайте проект Domain и попробуйте написать предметную область, не подключая неймспейсы WinForm. Удалось - отлично, добавляйте в solution новый проект WinFormsUI, создавайте в нём ссылку на Domain и дописывайте недостающую конкретику в UI.
Второй момент связан с передачей зависимостей. Вы знаете о том, что такое зависимость, как её передать на конструктор и почему внутри метода не должно быть слова new (у вас 56 раз встретилось в проекте)? Если знаете, то почему не сделали?
Далее. О предметной области. Я могу подойти к аппарату и заказать что-то, не являющееся комплексным обедом? Я могу взять две чашки чая и один бутерброд, а потом нажать кнопку "рассчитать стоимость"? Или взять одну чашку чая нажать "рассчитать стоимость"?
Мне мнится, что в предметной области должен быть некоторый класс Order, который имеет метод AddToOrder и метод IsOrderComplex, который бы проверял текущий набор того, чего уже понадобавляли.
Я думаю, что класс "Еда", от которого вы наследуете нужно заменить на Product, потому что именно продукт имеет не только Title, но и Price.
И, мало ли, нужно будет расширить архитектуру на продажу непродовольственных товаров, например, продавать контейнер для еды, салфетки или что-то ещё.
Непонятно, зачем описывать кучу классов отнаследованных от Еды, когда можно было создать класс Продукт с конструктором принимающим Title и Price в качестве обязательных полей. Вы представляете реальное приложение, в котором программист добавляет в коде новый класс? Или кто-то в базе данных создаёт строчку, а вы можете создать массив продуктов, раз у вас базу не требуют или читать из конфиг-файла. Конфиг же более гибко, чем перекомпилировать приложение после добавления нового класса, верно?
Также мнится мне, что можно было бы продемонстрировать паттерн фабрика, который бы умел создавать Order из накликанного "нам два кофе чай и два бутерброда" или создавать сразу комплексный ордер. У вас же такой жесткий хардкод, что приложение получается строго по ТЗ "автомат для накликивания комплексных обедов", но архитектура не предусматривает расширяемости. Если надо взять два кофе и один бутерброд – мы будем переписывать приложение, а пока будем рекомендовать костыль "сделайте сначала один заказ, а потом другой"?
И ещё момент. У вас можно добавлять к заказу напиток и для некоторых напитков возможна добавка молоко. Вот как вы архитектурно реализуете эту бизнес-логику? Сейчас её нигде нет, тупо везде хардкод.
Гипотетически. Можно было бы сделать класс "напиток" с абстрактным "в_напиток_можно_добавлять_дополнительное_молоко". Создавая потомков переопределять: кому-то false, кому-то true. А фабрика, которая конструирует напитки будет работать с этим свойством и не даст возможность добавить допмолоко туда, куда нельзя добавить.
Вариантов куча: можно в продукт запилить продукт_тайп, например. Была бы другая архитектура.
Ради интереса сходите в макдональдс. Там не WinForms, а наверное веб-сайт, но есть интерфейс, в котором прекрасно виден UI - жмякнули "кола", нажали "кастом", выбрали "без льда и с молоком". И стоимость заказа считается на лету. Мне кажется, что у вас глядя на этот интерфейс появятся мысли что поменять в доменной модели и как можно построить UI на winforms.


text:
Q: Make csv file available for download which is generated by a python script Python script runs on click of button using ajax.The script generates a csv which i want to show to the user so that it could be downloaded.How can I achieve this?

A: One way would be for the python code to save the csv file with a unique filename (perhaps generated by some combination of the date and the user's name) in the "static" directory and then create a link string (as either a relative or absolute URL) with that filename to use something like this:
Click here to download CSV file
See https://www.w3schools.com/tags/att_a_download.asp for a clear explanation and demo of the download attribute of the  element.
You might need to mess with file permissions, but I think Django can serve a file from a static directory to a user client without any extra fuss. You probably also want to purge the CSV files older than some reasonable period. CRON could do that, or it could be part of a startup routine.


text:
Q: How to set a complex custom crontab in google-app-engine (java)? I am building an app for which I need to set up cron jobs. What I want to do is to set the specific minutes in a hour where specific crons should run. For instance:

*

*Task1 at 1st minute of the hour

*Task2 on every second minute of the hour

*Task3 every 2 minute only in the second half of the hour

Building this in the standard Unix cron format is reasonably straightforward, but could not figure out how to do it in the Google-App-Engine.
The documentation does not list any non-trivial examples. Any suggestions on how to do it? Examples would be excellent.

A: The documentation you linked to seems to indicate that it isn't possible to do what you want using only Cron for Java (unless they have an undocumented feature for it). In particular this doesn't appear to allow for multiple times.

time specifies the time of day, as HH:MM in 24 hour time.

The Python version says the exact same thing.
However, one solution (albeit somewhat more expensive in terms of CPU usage) would be to call a URL every minute, and from the handler for that URL, dispatch out to whatever other calls you need.
In other words, something like:
<?xml version="1.0" encoding="UTF-8"?>
<cronentries>
  <cron>
    <url>/run-scheduled-tasks</url>
    <description>Run all scheduled tasks</description>
    <schedule>every 1 minutes</schedule>
  </cron>
</cronentries>

Then in run-scheduled-tasks, check a database for when each task last run, and if your complex condition for triggering them has occurred since then.

A: If the documentation is correct you can't get as granular as you are wanting. Doesn't look like they support picking a particular minute of the hour. Or a subset of an hour.
You might have to get creative. Why do you need such specific timing?

A: This may seem silly. Write three servlet. And schedule them from another UNIX machine on the other part of the world :D. Or even you can write a java app to do it. enjoy

A: Have a look at Quartz and see if that'll solve your problem.


text:
Q: ¿Cómo puedo agregar un id a cada row? Alguien que me pueda ayudar, quiero agregarle un id a cada uno de los cuadros de mi tabla en este caso cada row, tengo mi tabla de la siguiente manera:

Y necesito agregarle un id a cada cuadrito que se encuentra con un guion -.  El id sera respecto a su posición, en este caso en Presentación seria id = 1-2, en Presentación (4ta posición) seria id = 1,3 y así sucesivamente y cuando sea otro renglón cambiaría a  id= 2-2 o id= 2-3 y así respectivamente.
Utilizo codeigniter, bootstrap-tables, JSON, javascrit.
Para crear la tabla utilizo el siguiente código:
$('#ejemplo').bootstrapTable({
      url:'<?= base_url(); ?>index.php/ejemplo/presentacion/datos',
      columns: [
        {field: 'mate',filter:{type:"input"}},
        {field: 'idMate',filter:{type:"input"}},
        {field: 'pres',filter:{type:"input"}}
      ],

      pagination: true,
      showFooter: true,
      showHeader: true,
      search: true,
      showExport:true,
      filter: true,
      method: 'post',
      showRefresh:true,

    });

El encabezado lo agrego directamente en htlm, al crear mi encabezado la Presentación se pone de manera dinamica dependiendo cuantas se traiga de mi base de datos.

     <?php
       $pres = explode(",",$presentacion);
         echo 'Materiales	';
         echo '	';
            for ($i=0; $i <count($pres) ; $i++) {
              echo ''.$pres[$i].'	';
            }
  ?>

Alguien que me pueda ayudar a realizar eso en javascript.

A: Pues se podría hacer con algo así:

var filas = document.getElementsByTagName("tr"), celdas;
 for (var i = 0; i < filas.length; i++){
  filas[i].firstElementChild.id = i+"-0";  //Sólo suponiendo que Materiales sea el primer td, de lo contrario
  celdas = filas[i].children;
  for (var j = 0; j < celdas.length; j++){
   let celda_actual = celdas[j];
   if(celda_actual.textContent == "-")//Sólo si llegasen a haber más celdas con contenido que no sea -
    celda_actual.id = i+"-"+j;
  }
 }

  -
  hola
  -
  -

  -
  hola
  -
  -

  -
  hola
  -
  -

  -
  hola
  -
  -