text:
Q: YouTube dropped #t start time support in direct URL and embed videos? Recently, one could use #t=2m0s or #t=120 to set start time for direct links:
http://www.youtube.com/watch?v=Fk2bUvrv-Uc#t=2m30s

as well as for embed videos:

Now it seems YouTube dropped #t start time support and the above doesn't work anymore. How can I now place reference to videos with particular start time?

A: Embed videos
Looks like a different parameter is used now - start=<number of seconds> (see this blog and documentation).
Example:

Direct links
For direct links, it is enough to simply replace # for &:
http://www.youtube.com/watch?v=Fk2bUvrv-Uc&t=2m30s

A: YouTube dropped #t start time support for embed videos. Now we need ether directly use start=N&end=M parameters in seconds according to their new API, or write some extra code witch transforms our old #t=(n)m(n)s notation into new API-compatible style.

A: I was able to get the video clip to work based on the start and end, but the exact code needs to be as follows:
?start=x&end=y
where x is the start time in seconds and y the end time in seconds
if the '?' isn't present it doesn't work.  Also the code needs to be placed directly after the  URL WITHOUT any space or it doesn't work.

A: You can use &t= instead of #t=

A: I had a large number of videos chapterised using this method with a JQuery plugin. I've adapted the plugin so that you can continue using the (n)m(n)s notation.  You could change this fairly easily to grab the #t value from the URL instead of the data attribute that I'm storing it in.
(function( $ ) {
    $.fn.videoChapters = function(iframeID) {
        if(typeof window.orig_video === 'undefined') {
            window.orig_video = [];
        }
        window.orig_video[iframeID] = $('#'+iframeID).clone();

        var chapterContainer = this;
        $(this).find('a').on('click', function(e) {
                e.preventDefault();
                $('#'+iframeID).remove();
                $(chapterContainer).prevAll('.video-iframe').first().find('h3').after(window.orig_video[iframeID]);

                var video = $('#'+iframeID);
                if(typeof window.video_source === 'undefined') {
                    window.video_source = [];
                }

                if(typeof window.video_source[iframeID] === 'undefined') {
                    window.video_source[iframeID] = $(video).attr('src');
                }
                /*  to use it with a normal anchor change this to something like the below, of course it will vary for URL
                 *  so it'd be better to use a regex, but I'll let someone else worry about that.
                 *
                 *   var str = $(e.target).attr('href').split('#t')[1];
                 *   var nstr = $(str).split("s")[0];
                 *   var mstr = $(nstr).split("m");
                 *   var min = Number(mstr[0]);
                 *   var sec = Number(mstr[1]);
                 *
                 * */

                var seconds = $(e.target).data('seconds');

                /* youtube dropped old min/secs format, now we convert what's there to pure seconds */
                var splsec = seconds.split('m');
                var min = Number(splsec[0]);
                var sec = Number(splsec[1].split('s')[0]);

                min = min * 60;

                var total = min + sec;

                var newSource = window.video_source[iframeID] + "?start="+total+"&autoplay=1&rel=0";
                $(video).attr('src', newSource);
        });

    };
})( jQuery );

A: The start and end time using iframe embed code doesn't work from my test. What works for me is this code:
From:
http://www.youtube.com/embed/[VIDEOID]
To:
http://www.youtube.com/v/[VIDEOID]&start=[SECONDS]&end=[SECONDS]
<object width="640" height="385">
<param name="movie" value="http://www.youtube.com/v/[VIDEOID]&start=100&end=500" />
<param name="allowscriptaccess" value="always" />
<embed src="http://www.youtube.com/v/[VIDEOID]&start=100&end=500" type="application/x-shockwave-flash" allowscriptaccess="always" width="640" height="385" />
</object>

A: It seems to work (again?) with the #t= , at least for direct URLs.
The stated URL:
https://www.youtube.com/watch?v=Fk2bUvrv-Uc#t=2m30s
works, that is: it jumps to 2min 30sec.
I tested this on FF, Chrome, IE11.
But probably better to use &t= , & is the common URL argument concatenating character.

A: Use
/watch?v=<videoID>&t=<s>

with
<videoID>=id of the video
<t>=number of seconds to skip

Examples :
https://m.youtube.com/watch?t=58&v=9W35QxCZnK4

Video starts at 58 seconds
or
https://www.youtube.com/watch?t=120&v=9W35QxCZnK4

Video starts at 2 minutes


text:
Q: Circ above $D^3$ in a nice way I want to denote the interior of $D^3$, so I use $\overset{\circ}{D^3}$. This looks like this:

However I find this kind of ugly, and would rather have the circ just above the $D$, but then $\overset{\circ}{D}^3$ is giving even stranger things, like this:

Is there a way to have what I want? This would be basically the \circ as in the second image, and the 3 as in the first.

A: You should use \mathring{...}, rather than \overset{\circ}{...}.
\documentclass{article}
\usepackage{amsmath}

\begin{document}

\[
\mathring{D^{3}}
\qquad
\mathring{D}^{3}
\]

\end{document}

The amsmath package is not really necessary for this, but it's recommended for any math document.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make a model automatically reload and fetch data when the data in the DB changes? How to automatically reload the model after the data in ember-mirage has changed?
I mean: After performing a $.post() operation on ember mirage data, schema is changed. This has to be reflected in the template. But, since the model for the template is already run, the model hook is not run again!
I am using ember-cli-mirage for the past few days.

A: If you're using Ember Data (which I would strongly recommend), you'll need to use 'model.set' and 'model.save' for the model to be automatically updated.
If you're not, and you '$.post' some changes to the server, you'll need to refetch whatever data you changed.


text:
Q: "help center" magic link isn't click-friendly There's a magic link I use all the time: [help/on-topic]. If you didn't know it, when posted in a comment, it renders as help center - which is great!
Except for one thing: from a UX perspective, it's wrong.
"Help Center" sounds really daunting. Not something I want to click and browse for hours. "Help Center" is basically a sub-site, with a TON of information, including a page that explains what is and what isn't on-topic on the site.
When I link to [help/on-topic], I'm posting a (often canned) comment that tells the OP why I'm hammering their question, and kindly invite them to read up the site rules.
Of course, the site rules are in the help center. But I'm not linking to the entire help center and telling the OP to read the whole entire darn thing, I'm linking to one specific page that contains the specifically relevant information.
But the link doesn't render as What topics can I ask about here? as the actual page title says - it renders as "help center", which is terribly vague and misleading.
Can the rendering of the [help/on-topic] magic link be changed to "What topics can I ask about here?"
[What topics can I ask about here?](http://site.stackexchange.com/help/on-topic)

Also.. are there any stats about how often the OP actually clicks these links? 50%? 10%? 1%? 0.0001%? If so, it would be interesting to compare before/after implementing this feature request.


text:
Q: A Higher r-squared always implies a reduction in MAE and RMSE? I apply 2 different machine learning models in my data, a Multiple Linear Regression and Random Forest. The results were bellow:

Why the MAE and RMSE are higher for a higher R-squared? Both models were tested in the same test set but with different input varibales

A: What you've described can't happen in math, so there's either a missing detail, a bug in your code causing you to input something other than what you intend to input, or something wrong with the Python function (the last of which I find unlikely).
I disagree with this Python implementation of $R^2$, but for the same data set, $R^2_{1,sklearn}>R^2_{2,sklearn}\iff MSE_2>MSE_2\iff R^2_{1,Dave}>R^2_{2,Dave}$. This is because $R^2$, either in the implementation you use or that way I prefer, is a strictly decreasing function of MSE.
$$R^2=1-\dfrac{MSE}{denominator}$$
(This denominator is some kind of sum of squares that is related to a model that predicts the same value every time. Your function and I disagree on what the one value should be, but you could pick $5$ or $17$ or $\pi$ as the denominator, and MSE and that definition of $R^2$ should move in opposite directions.)
If you evaluate the $R^2$ of two different models but on the same data, the denominator stays the same. Thus, increasing/decreasing $R^2$ corresponds to decreasing/increasing MSE.
(If your implementation of an MSE calculation involves an $n-p$ denominator instead of $n$ or $n-1$, then the above does not apply. This could be the kind of missing detail I mentioned in the last sentence of my first paragraph.)
MAE is a totally different metric that need not increase/decrease with an increase/decrease in MSE or a decrease/increase in $R^2$. In this linked answer of mine, I give examples where an MSE increase/decrease is accompanied by an MAE decrease/increase.


text:
Q: Order in dataframe generation Could you explain to me why the Properties column was the third column and not the first one? As you can see I insert it as the first in pd.DataFrame, but when I do print(df), it appears as the third column.
import pandas as pd

df = pd.DataFrame({'Properties':[1, 2, 3,4],
                   'Latitude':[-24.930473, -24.95575,-24.924161,-24.95579],
                   'Longitude':[-24.930473, -24.95575,-24.924161,-24.95579],
                   'cluster': (1,2,1,2)})

print(df)

    Latitude  Longitude  Properties  cluster
0 -24.930473 -24.930473           1        1
1 -24.955750 -24.955750           2        2
2 -24.924161 -24.924161           3        1
3 -24.955790 -24.955790           4        2

A: Try using columns argument to assign the order of columns:
import pandas as pd
df = pd.DataFrame({'C1':[1, 2, 3,4],
                   'C2':[-24.930473, -24.95575,-24.924161,-24.95579],
                   'C3':[-24.930473, -24.95575,-24.924161,-24.95579],
                   'C4': (1,2,1,2)}, columns=['C1', 'C3', 'C2', 'C4'])

This gives:
   C1         C3         C2  C4
0   1 -24.930473 -24.930473   1
1   2 -24.955750 -24.955750   2
2   3 -24.924161 -24.924161   1
3   4 -24.955790 -24.955790   2


text:
Q: iText combining rowspan and colspan - PDFPTable Working on a calendar projcet and using iText to generate a pdf to print appointments. I can plot a cell with a colspan, and a cell with a rowspan, but I can't combine it. Table has width of 4 cells. I want to achieve something like this:
(A)(B)(C)(C)
(D)(E)(C)(C)
so  (1,1), (1,2) and (2,1) (2,2) are regular cells. But there should be a cell in (1,3) covering (1,3) (1,4) (2,3) and (2,4) thus having a colspan of 2 AND a rowspan of 2.
Current code:

PdfPTable table = new PdfPTable(4);
PdfPCell cell = new PdfPCell(new Phrase(" 1,1 "));
table.addCell(cell);
cell = new PdfPCell(new Phrase(" 1,2 "));
table.addCell(cell);
PdfPCell cell23 = new PdfPCell(new Phrase("multi 1,3 and 1,4"));
cell23.setColspan(2);
cell23.setRowspan(2);
table.addCell(cell23);
cell = new PdfPCell(new Phrase(" 2,1 "));
table.addCell(cell);
cell = new PdfPCell(new Phrase(" 2,2 "));
table.addCell(cell);
// 2,3 and 2,4 should be filled because 1,3 has rowspan 2 and colspan 2.
//table.completeRow(); //no effect

However that generates an error:

ExceptionConverter: java.io.IOException: The document has no pages.

If i don't start creating the second row, it just plots fine ( 1 row, and cell on (1,3) has a colspan of 2. Since there is no second row, the rowspan(2) has no effect.
Any help is appreciated. Thanks

A: At first sight, I'd say: you get a "document has no pages" exception because you're not adding any content to the document. I don't see:
document.add(table);

anywhere in your code snippet.
I have copy/pasted your code into a full example and I posted the full example here: ColspanRowspan. The resulting PDF looks like this:

This seems to be the desired behavior. I can only think of two differences: (1) you're forgetting to add the actual table (which was my initial answer), or (2) you are using a mighty old version of iText in which rowspan wasn't fully supported.


text:
Q: App crashes when there is no image Swift 4 My app which I have made in swift 4 crashes when a news provider does not have an image! So when I scroll over an article which does not have an image it crashes and I get the error:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Here is my code for the image:
let imageCache = NSCache<AnyObject, AnyObject>()

extension UIImageView {
    func downloadImage(from url: String){
    let urlRequest = URLRequest(url: URL(string: url)!)
    image = nil
    if let imageFromCache = imageCache.object(forKey: url as AnyObject) as? UIImage {
        self.image = imageFromCache
        return
    }
    let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
        if error != nil {
            print(error!)
            return
        }
        DispatchQueue.main.async {
            let imageToCache = UIImage(data: data!)
            imageCache.setObject(imageToCache!, forKey: url as AnyObject)
            self.image = imageToCache
        }
    }
    task.resume()
    }
}


text:
Q: How to Delete a excel file xlsx from the directory I´m trying deleted a excel file , but I don´t know how to delete it.
I saw APache Poi API but i don´t found any method or class for it.
the only one way that I did was it:
File f1 = new File("D:\\exceltest1.xlsx");
f1.delete();

with this code didn´t work, I think it working only with .txt file.
Can anyone help me with it, please?

A: Do you have some exceptions?
The method delete return TRUE if the file deleted and FALSE if not deleted.
You can use this case:
File f1 = new File("D:\\exceltest1.xlsx");
if (f1.delete()) {
    System.out.println("File " + f1.getName() + " is deleted.");
} else {
    System.out.println("File " + f1.getName() + " not found.");
}


text:
Q: Can I generate private key from the last public key using puttygen? I have generated public key earlier forgot to generate private key. Can I generate private key for earlier public key using puttygen?

A: You cannot generate private key from public key but you can generate public key from the private key using puttygen. As @alfasin mentioned if you could generate the private key from public key then  RSA would be useless and this would make you vulnerable to attack.FYI the public key is used for encryption and private key is used for decryption.
this wikipedia page will help you better understand the reason.

A: If you were able to do that, RSA would have been vulnerable to a "puttygen" attack...


text:
Q: How can I wait all XHR request to be loaded? I have a method for our website's search field.When I type a word into search field, server gives me a response.These responses sometimes can be a log so I have to wait for all XHRs to be loaded not a specific response.Tried waitForLoadState seems not working.Tried below code but it only returned one response not other requests?
async searchTextWithWait(value: string) {
      await(await this.page.waitForSelector("//span[contains(@class,'search-input')]/input")).type(value,{delay:80})
      await this.page.waitForResponse(response => {
        return response.status() == 200
    });

  }

A: Maybe this solution can help you:
const selector = "//span[contains(@class,'search-input')]/input";
await this.page.locator(selector).waitFor();
await Promise.all([
  this.page.waitForLoadState('networkidle'), // wait until there are no network connections for at least 500 ms.
  this.page.locator(selector).type(value,{delay:80}),
]);


text:
Q: Geometric intuition and computation for Cartier theory I am learning Cartier theory of commutative formal groups by the book of Zink. It is a powerful tool but I don't understand it's motivation. The Cartier module of a formal group $G$ over a $\mathbb{Z}_{(p)}$-algebra is $\mathcal{H}om(\widehat{W},G)$ which are $p$-type curves. I think it is a generalization of the tangent space and hence contains enough information of the group. But why the formal Witt vectors(or $\Lambda$ for global case) work?
It seems we can compute formal groups through Witt vectors: assume $m_1,\cdots,m_n$ is a $V$-base of $M=M_G$, and $Fm_i=\sum_{i,j}V^n[c_{n,i,j}]m_j$, we have an exact sequence
$$\mathbb{E}_p^n\rightarrow \mathbb{E}_p^n\rightarrow 0$$
then by the equivalence of category we get
$\widehat{W}\otimes_{\mathbb{E}_p}\mathbb{E}_p^n\rightarrow\widehat{W}\otimes_{\mathbb{E}_p}\mathbb{E}_p^n\rightarrow M_G\rightarrow 0.$
If we choose the curvilinear coordinate system of $G$ by $m_1,\cdots ,m_n$, how can we compute the group laws from the Witt vectors?


text:
Q: how to wait in observable RxJS So basically, i have a ionic mobile application that retrieves data from Firebase.
this is the code for html that displays data which comes from travalList$ that is an observable.
  <ion-list *ngFor="let item of travelList$ | async">
<ion-card (click)="itemTapped($event, item)" *ngIf="item.userId != currentUserId">
  <ion-card-header>

{{item.firstname}} {{item.lastname}} ({{item.email}})

  </ion-card-header>
  <ion-card-content>

{{item.fromAddress}}

at {{item.fromDate}}

To

{{item.toAddress}}

at {{item.toDate}}

  </ion-card-content>
</ion-card>

code for initializing items to be displayed. this is called at the constructor,so the getTravelList() retrieves data from firebase.
   initializeItems(){
this.travelList$ = this.plsdala.getTravelList()
.snapshotChanges()
.map(
  changes => {
    return changes.map(c=>({
      key: c.payload.key, ...c.payload.val()
    })).slice().reverse();
    console.log(this.travelList$); //to reverse order
  });

}
i wanted to put the retrieved data in an array but how do i wait the observable?
i need the array for search function.


text:
Q: Anaconda - Spyder is very slow to start on Windows 8 (checking for updates?) On my windows 8.1 laptop, the startup time for Spyder is:
1min 50 sec.... when I am connected to the internet
<25 sec .... when disconnected
I have already unchecked check updates at startup in advanced settings. Either that setting is ignored or perhaps there is another config file to edit?
Any ideas?

A: I have a solution which works at least for now.
Just run spyder --reset from a terminal. Warning: you have to change the any interface settings all over again. But the startup time is now ~20 sec irrespective of an internet connection or whether check updates was selected.
(from)
https://groups.google.com/a/continuum.io/forum/#!topic/anaconda/MwJrkinW2To


text:
Q: Simple_form and globalize gem I am developing an application with Ruby on Rails (4.1) and I use the Globalize gem (version 4.0.1) to store various translations of my data. The problem is that when I use the "globalize_fields_for" method of simple_form in order to generate the form fields for the various locales, I get the following error:
undefined method `globalize_fields_for' for #<SimpleForm::FormBuilder:0x00000106824928>

Here is my view (haml):
h3.title New Static Page
%hr

= simple_form_for [:admin, @static_page] do |f|
  %dl.tabs{ "data-tab" => "" }
    - @locales.each_with_index do |lang, index|
      - klass = index == 0 ? 'active' : ''
      %dd{ class: klass }= link_to t("admin.languages.#{lang}"), "#panel2-#{index + 1}", class: "#{lang} flag"
  .tabs-content
    - @locales.each_with_index do |lang, index|
      - klass2 = index == 0 ? 'active' : ''
      .content{ class: klass2, id: "panel2-#{index + 1}"}
        = f.globalize_fields_for lang.to_sym do |g|
          = g.input :title, label: "Title"
          = g.cktext_area :body, rows: 15, class: 'ckeditor'

    = f.button :submit, t('admin.buttons.submit'), class: 'new-submission'

the "@locales" variable has my locales (['el', 'en', 'ru'].
My model is as follows:
class StaticPage < ActiveRecord::Base

  extend FriendlyId
  friendly_id :title, use: [:slugged, :history]

  # Validations

  validates :title, presence: true, length: { maximum: 100 }
  validates_presence_of :body

  # Associations
  translates :title, :body
  has_many :translations
  accepts_nested_attributes_for :translations
end

If I use the "simple_fields_for" helper, then I get an error that says that I have undefined attribute "el" (or any other of the locales that I have created) which is valid as there is none declared in my model.
I am stuck for a couple of hours on this so any help/suggestion will be appreciated :)

A: You can use gem globalize3_helpers. Use helper globalize_fields_for_locales [:en, :ru, :el]


text:
Q: Group by count over a collection of nested json array documents in MongoDB I have data in mongo collection in the following format:
{
  "response":[
      {
          "_responsedata":{
              "Error":{
                  "message":"BMERROR001 - Something went wrong. Please check the error logs",
                  "statusCode":"400",
                  "reasonCode":"BMERROR001"
              }
          },
          "_responsemeta":{
              "status":"400"
          }
      },
      {
          "_responsedata":{
              "Error":{
                  "message":"BMERROR001 - Something went wrong. Please check the error logs",
                  "statusCode":"400",
                  "reasonCode":"BMERROR001"
              }
          },
          "_responsemeta":{
              "status":"400"
          }
      },
      {
          "_responsedata":{
              "Error":{
                  "message":"BMERROR002 - Something went wrong. Please check the error logs",
                  "statusCode":"400",
                  "reasonCode":"BMERROR002"
              }
          },
          "_responsemeta":{
              "status":"400"
          }
      },
      {
          "_responsedata":{
              "name":"name1",
              "col1":"value1"
          },
          "_responsemeta":{
              "status":"204"
          }
      },
      {
          "_responsedata":{
              "name":"name2",
              "col1:":"value2"
          },
          "_responsemeta":{
              "status":"201"
          }
      },
      {
          "_responsedata":{
              "Error":{
                  "message":"BMERROR003 - Something went wrong. Please check the error logs",
                  "statusCode":"400",
                  "reasonCode":"BMERROR003"
              }
          },
          "_responsemeta":{
              "status":"400"
          }
      }
  ]
}

This ihe format of one documents and I have many documents in the same format. Now for making this documents in a format, which can be visualized using D3, I need to group them based on the reasonCode field. So I need something like this as a result :
{
    "errors": [
        {
            "code":"BMERROR001",
            "count":2
        },
        {
            "code":"BMERROR002"
            "count":"1"
        },
         {
            "code":"BMERROR003"
            "count":"1"
        }
     ]
}

I tried with the following aggregation, but it is giving the reason as an array and the count.
[{$group: {
  _id:{
    "reason":"$response._responsedata.Error.reasonCode"
  },
  count:{$sum:1}
}}]

How can I take the count grouped by the reasonCode properly ?

A: You need to $unwind the response array first then you can apply $group on nested reasonCode.
[
  { $unwind: "$response" },
  {
    $group: {
      _id: {
        reason: "$response._responsedata.Error.reasonCode"
      },
      count: { $sum: 1 }
    }
  }
]

A: For those having a deep-nested arrays, you can do it like so:
{
  "pets": [
    "dogs": [
      "name": "douge",
      "quantity": 5
    ]
  ]
}

query
[
  { $unwind: "$pets" },
  {
    $unwind: {
     path: "$pets.dogs",
     preserveNullAndEmptyArrays: true
    }
  },
  {
    $group: {
     _id: null,
     sum: { $sum: "$pets.dogs.quantity" }
    }
  }
]


text:
Q: Appcelerator Titanium: Facebook Graph API empty Friends list another problem with the Facebook connection from Titanium.
I make an request to Facebook with Graph API, but I only get an empty result:

SUCCESS; {"data":[]}

This is my code:
Ti.App.fb.requestWithGraphPath('me/friends', false, 'GET', showRequestResult);

I've also tried to use the request example from KitchenSink, but that's not working, because the method is turned for my FB SDK.
So, I've tried to update the permissions for facebook with "user_friends" but if I log in, it's not asking for this permission.
Any Ideas?
Thanks for your help.

A: The reason why it doesn't work was that i have to get the Facebook permission "user_friends".


text:
Q: equivalence class and partially ordered sets question the question is -
1.we have 4 sets $A,B,C,D$ , if $AΔB⊆D$ and $BΔC⊆D$ then $AΔC⊆D$
2.given the power set $P$({1,2,3}) and given two relations $A,B∈$P$({1,2,3})$ $ARB$ if and only if $AΔB⊆$ {1,2} and $ASB$ if and only if AΔ{1,2}⊂BΔ{1,2}. which one of the sets is an equivalence relation ? prove it and find its classes

*which one is a partially ordered set / total order set?

my tries:
i will start with the second part . ARB is the equivalence relation , because it is reflexive $AΔA⊆∅$ and $∅⊆${1,2} (not sure about this) . ARB is symmetric because $AΔB=BΔA$ and it is Transitive because if  $AΔB$ and $BΔZ$
then we can do ($AΔBΔBΔZ$)=$AΔZ$ as for equivalence classes what i got was ∅ , {1} , {2} and $N$/{1},{2} (im not sure about this one)
first part i didn't know how to do it but it feels like transitive relation but i could not figure out how to prove this  and for the third part anti reflexive is AΔ{1,2}⊂AΔ{1,2} should be AΔ{1,2}⊆AΔ{1,2}if it is reflexive transitive is the same as we did in the second part and we also need to check if it is comparable but i did not know how to how can i check if i can compare(not sure if it is the right word in English i searched but couldn't find)?
thanks for any help and explanation! and sorry if there are translation mistakes i will edit if there is

A: For the relation $\mathcal{R}$, there are two equivalence classes here: the class of subsets that contain 3 and the class of subsets that don't contain 3. Indeed, $A\Delta B\subset\{1, 2\} \Longleftrightarrow 3\notin A\Delta B$. Note that an equivalence class is never empty. So, here the classes are
\begin{equation}
Cl_\emptyset =\{\emptyset, \{1\},\{2\}, \{1, 2\} \}
\end{equation}
and
\begin{equation}
Cl_{\{3\}} = \{\{3\}, \{1, 3\},\{2, 3\}, \{1, 2, 3\} \}
\end{equation}
For the relation $\mathcal{S}$, it is only a partial order because
\begin{equation}
\{1\}\Delta \{1, 2\} = \{2\}\quad \text{and} \quad \{1,2,3\}\Delta \{1, 2\} = \{3\}
\end{equation}
so that $\{1\}$ and $\{1, 2, 3\}$ are not comparable.


text:
Q: Charging a battery project There is this voltage source that generates different types, it is not a sine wave properly (A), then passing it to a full bridge rectifier, the outcome is like B, then you use a smoothing capacitor and the outcome is like C, what do you use to generate a steady voltage? I tried with a 5V voltage regulator, but it is not working, and the inputs are usually higher than 5V. It is to charge a battery (3.7 V), do you strictly require constant DC?

A: As long as the voltage doesn't exceed the safe voltage for the battery then a precise DC supply isn't too important - depends on the battery technology/chemistry.
In fact having a lead-acid battery being charged in parallel was a common way of smoothing DC before solid-state DC-DC regulators.
But 3.7v suggests you are trying to charge a Lithium-Ion battery, this can get dangerous if you overcharge it. You really need a charger-controller IC for Li-Ion, or at the least a protected cell

A: 1) A sufficient filter built of capacitors and inductors will smooth the signal. Look into the "pi shaped filter" of two capacitors with an inductor between them. If you are still seeing bad power, then add higher capacitance and inductance (or get a better power source.)
2) If the ouptut of your power source is > 5V, then a 3.3V regulator, or a 1.25V regulator with adjustable output, should be able to be set to the output voltage you want. As long as input voltage - regulator drop is > desired voltage, you're good.
3) If you're charging LiPo based batteries, GET A REAL CHARGER. LiPo batteries that are not strictly controlled when charging have burned down houses. This danger is real. A "B6" style charger can be had on eBay for < $15.
That being said, if you can guarantee that the output voltage will never go above 3.9V, it may be less dangerous to charge the LiPo, because it may never saturate at that voltage, and end up "floating" in the middle. However, it will also not fully charge the battery, and will end up wearing it out in the end.
So, big filter, plus adjustable-voltage regulator, should generate the voltage you want. A boost/buck DC DC converter can be used to accept a large range of input voltages and provide a constant output voltage, as long as the input current is sufficient for the load power. Pololu sells some reasonable-cost ones.

A: At first - I want to point out that Li-Ion and Li-Po batteries should be charged only with well designed chargers. Battery voltage, current, and temperature changes (caused by power disspated on internal resistance) must be always under control while charging.
For chemical point of view - constant and stable DC is not required by batteries. However you HAVE TO control that voltage and be sure, that maximum voltage on battery is below maximum voltage for your battery type.

For example - Li-Ion batteries are highly vulnerable to voltages above 4.2V. Irreversible chemical reaction happens and battery looses capacity permanently.

Voltage "shape" is not that important. You can use your [B] or [C] "shapes" and charge battery with pulses with peak voltage always below maximum cell voltage.


text:
Q: javascript onclick event in global custom text in views fields I am not able to apply onclick event in global custom text field.
This is what i'm adding in custom field:
Changed & send password

and this is what view is result is :
Changed & send password

A: Make a display tpl of the view and using string replace, replace click by onclick

A: in your view uid is probably used as string, not inserted as a variable
for MVC3 it would be something like @uid
Updated after your edit:
The result shows "Click=" .. that must be "onclick= "


text:
Q: Read/Write Google Sheets from within a Cloud Function I am trying to call the Sheets API from within a google cloud function in order to read from Google Sheets and Write to Google Sheets.  My credentials to access are stored within a google storage bucket called creds_bucket in a file called my_creds.json.  The two spreadsheets I'm using both have the 'my_creds' email linked to them and all the relevant APIs have bee enabled for project.
Here is my code....  I get a KEY error that says it doesn't recognise the creds_bucket  .  What would be driving this?
import httplib2
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import os
import json
from google.cloud import storage

def main(data, context):

    blob = storage.Client().get_bucket(os.environ['creds_bucket']).get_blob('my_creds.json').download_as_string()

    parsed_json_creds = json.loads(blob)

    scope = ['https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/spreadsheets']
    credentials = ServiceAccountCredentials.from_json_keyfile_name(parsed_json_creds, scope)

    service = build('sheets', 'v4', http=credentials.authorize(httplib2.Http()))

    spreadsheet_id_input = 'spreadsheetinput_ID'
    range_input = 'Sheet1!A1:D10'

    spreadsheet_id_ouput = 'SPREADHEET_Output_ID'
    range_ouput = 'Sheet1!A1:D10'

    # pull data from input google sheet
    response = service.spreadsheets().values().get(spreadsheetId=spreadsheet_id_input, range=range_input).execute()
    # export pulled data from input sheet to output sheet
    request2 = service.spreadsheets().values().update(spreadsheetId=spreadsheet_id_ouput, range=range_ouput, body=response)
    response2 = request2.execute()

  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 383, in run_background_function
    _function_handler.invoke_user_function(event_object)
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 217, in invoke_user_function
    return call_user_function(request_or_event)
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 214, in call_user_function
    event_context.Context(**request_or_event.context))
  File "/user_code/main.py", line 10, in main
    blob = storage.Client().get_bucket(os.environ['creds_bucket']).get_blob('my_creds.json').download_as_string()
  File "/env/lib/python3.7/os.py", line 678, in __getitem__
    raise KeyError(key) from None
KeyError: 'creds_bucket'

A: The KeyError error you are getting is caused by the os.environ function not finding any environment variable called "creds_bucket".
To fix it try attaching an environment variable with that name to the function, to do that you can:
Edit the function in the Console and adding a variable in the "Environment" section
Or
Redeploy the functions using the gcloud command with the "--update-env-vars" flag


text:
Q: Retrieve and display comments/queries from database I'm developing in php/sql a web application where users will be able to post items that they'd like to sell ( kinda like ebay ). I want non-members to be able to comment on the items or ask queries about items.
My problem is I want to display each item as well as any comment/query made about that item, in a similar manner as the way Facebook wall works.
I want to "append comments"(if any) to each item. The comments table is linked to the items table via column item_id. And the items table is linked to users table via column user_id. I have left joined users table with items table to display item details, i tried to left join comments table as well so that there are 3 joined tables.
That fails because no comments are displayed and only one item is displayed, despite there being multiple entries in each table. Here is the code i,m using.
$database->query
    ('
    SELECT sale.*, query.*, users.id AS userid, users.username as user
    FROM sale
    LEFT JOIN users ON sale.user_id = users.id
    LEFT JOIN query on sale.id = query.item_id
    where category = "$category" ORDER BY sale.id DESC
    ');

    $show = " "; //variable to hold items and comments

    if ($database->count() == 0) {

      // Show this message if there are no items

      $show .= "
There are currently no items to display.
" ;

    } else {

        $show .= "
";

        while ( $items = $database->statement->fetch(PDO::FETCH_ASSOC) )
        {

            $show .= "
                //show item details in html
               ";

            while( $query = $database->statement->fetch(PDO::FETCH_ASSOC) )
            {

                $show .= "
                  //show queries below item details
                        ";
            }

      $show .= "
" ;
        }

A: Welcome to Stackoverflow!
I recommend you taking a look at pdo. If you are already using mysql_ functions, then I recommend you switch. More on that can be found here.

Now that your pointed to the direction of to what functions to use when connecting/running queries, you now should create your tables. I use phpmyadmin for managing my database, I find it very good, but it's up to you what you use. Once you've decided on the service you use to manage your database, you should then learn how to use it by doing some google searches.

Now you need to set up your table and structure it correctly. If you say you're having items, then you should make a table called items. Next create the columns to the properties of the items. Also I recommend reading about Database Normalization, which is a key aspect of setting up your SQL tables Etc.

Once you have everything set up, you've connected to your database successfully Etc. You now need to set up the "Dynamic Page". What I mean by this is, there's only one page, say called 'dynamic', then a variable is passed to the url. These are called GET HTTP requests. Here's an example of what one would look like: http://example.com/item?id=345.
If you've noticed, you'll see the ? then the id variable defined to 345. You can GRAB this variable from the url by accessing the built in PHP array called $_GET[]. You can then type in your variable name you want to fetch into the []'s. Here's an example.
<?php
$data = $_GET['varname']; // get varname from the url
if(isnumeric($data)){ // is it totally made out of numbers?
    $query = "SELECT fieldname FROM table WHERE id=:paramname";
    $statement = $pdo->prepare($query); // prepare's the query
    $statement->execute(array(
        'paramname'=>$data // binds the parameter 'paramname' to the $data variable.
    ));
    $result = $statement->fetch(PDO::FETCH_ASSOC); // grabs the result of the query
    $result = $result['fieldname'];
    echo 'varname was found in the database with the id equal to:'.$data.', and the             result being: '.$result;
}
?>

So now you can see how you can grab the variable from the url and dynamically change the content with-in the page from that!
Hope this helped :)


text:
Q: Aggregation of coordinates in a grid I'm using these coordinates (raster) in order to plot them above an empty image.
rm(list = setdiff(ls(), lsf.str()))
mydata=structure(list(Position_X = c("95", "80", "43", "29", "92", "106",
"95", "105", "80", "78", "74", "109", "91", "125", "110", "46",
"48", "57", "54", "34", "76", "136", "82", "75", "130", "132",
"134", "136", "130", "130", "78", "93", "79", "127", "113", "113",
"128", "117", "97", "80", "132", "88", "114", "51", "122", "97",
"120", "85", "103", "154", "161", "165", "164", "207", "185",
"207", "165", "193", "184", "160", "247", "207", "208", "209",
"230", "211", "154", "168", "214", "189", "186", "207", "242",
"197", "200", "163", "214", "189", "246", "217", "167", "199",
"167", "186", "162", "161", "201", "186", "134", "221", "146",
"177", "164", "158", "163", "249", "136", "176", "257", "308",
"357", "372", "295", "311", "342", "309", "360", "355", "311",
"312", "370", "316", "358", "1450", "352", "337", "378", "340",
"296", "334", "342", "308", "312", "312", "303", "374", "267",
"327", "340", "376", "389", "341", "368", "262", "353", "343",
"338", "354", "311", "352", "358", "356", "302", "406", "448",
"452", "476", "392", "422", "480", "405", "416", "458", "406",
"487", "480", "437", "411", "450", "464", "449", "467", "477",
"484", "406", "406", "487", "473", "464", "435", "418", "470",
"480", "504", "515", "467", "441", "422", "422", "380", "474",
"428", "481", "482", "415", "497", "479", "419", "405", "385",
"449", "479", "488", "477", "479", "364", "412", "378", "572",
"568", "555", "566", "557", "556", "522", "556", "513", "555",
"558", "564", "558", "555", "541", "555", "534", "557", "557",
"557", "558", "522", "525", "519", "520", "569", "556", "516",
"581", "540", "512", "535", "536", "556", "523", "533", "541",
"557", "523", "537", "557", "524", "542", "517", "558", "509",
"543", "590", "618", "660", "706", "697", "618", "679", "646",
"639", "670", "625", "660", "620", "697", "636", "667", "703",
"686", "679", "730", "728", "661", "692", "674", "677", "675",
"624", "624", "696", "661", "712", "626", "683", "695", "672",
"621", "700", "672", "632", "610", "631", "683", "636", "647",
"629", "655", "688", "614", "663", "795", "753", "811", "786",
"793", "850", "841", "788", "822", "810", "794", "808", "734",
"792", "815", "731", "821", "805", "807", "809", "837", "809",
"835", "839", "835", "782", "841", "839", "850", "852", "741",
"824", "830", "843", "808", "823", "824", "787", "872", "848",
"839", "810", "813", "790", "819", "957", "919", "846", "919",
"903", "924", "867", "843", "861", "953", "925", "869", "908",
"899", "1016", "1060", "1075", "1084", "1035", "992", "977",
"958", "975", "908", "913", "962", "1063", "1008", "908", "958",
"1056", "1013", "860", "851", "1001", "909", "891", "1034", "953",
"958", "916", "953", "1021", "1027", "1035", "906", "956", "980",
"1017", "1061", "925", "1044", "1051", "1050", "1048", "918",
"1042", "1052", "1053", "1063", "1030", "1051", "1049", "998",
"959", "1048", "979", "1003", "984", "1002", "1048", "992", "1016",
"1042", "1039", "874", "1033", "917", "958", "863", "1048", "1107",
"1104", "1105", "1133", "1152", "1109", "1009", "953", "1120",
"1178", "1154", "1102", "976", "1057", "1191", "1195", "955",
"1022", "986", "958", "621", "864", "882", "1106", "1177", "1197",
"1062", "898", "1033", "916", "1115", "1196", "1057", "1103",
"1058", "1170", "1168", "921", "917", "1151", "1129", "1197",
"1065", "1156", "1160", "1115", "1121", "1176", "1108", "1127",
"1073", "1175", "1085", "1419", "1156", "1154", "1375", "1376",
"1508", "1126", "1341", "1441", "1470", "1381", "1325", "1462",
"1463", "1360", "1262", "1505", "1404", "1178", "1177", "1395",
"1373", "1313", "1386", "1388", "1518", "1285", "1248", "1229",
"1181", "1465", "1328", "1103", "1392", "1501", "1465", "1410",
"1397", "1375", "1328", "1456", "1459", "1323", "1159", "1166",
"1508", "1303", "1329", "1454", "1459", "1147", "1228", "1421",
"1316", "1456", "1340", "1341", "1397", "1447", "1309", "1400",
"1483", "1253", "1303", "1296", "1302", "1299", "1150", "1228",
"1470", "1526"), Position_Y = c("46", "43", "50", "35", "75",
"78", "38", "44", "64", "62", "65", "33", "34", "52", "44", "44",
"44", "43", "64", "58", "63", "43", "63", "36", "70", "68", "68",
"68", "68", "66", "63", "80", "67", "40", "80", "75", "48", "59",
"50", "41", "43", "70", "74", "33", "73", "78", "77", "39", "73",
"51", "42", "84", "48", "53", "72", "45", "77", "72", "87", "48",
"52", "55", "54", "76", "75", "74", "47", "73", "50", "52", "79",
"48", "80", "81", "51", "77", "51", "53", "81", "50", "52", "52",
"74", "78", "44", "83", "44", "77", "82", "80", "50", "73", "53",
"46", "81", "86", "50", "53", "54", "80", "67", "82", "68", "89",
"83", "85", "59", "87", "56", "51", "94", "43", "86", "58", "85",
"56", "98", "44", "55", "92", "93", "76", "86", "52", "85", "96",
"87", "50", "55", "96", "63", "91", "51", "51", "90", "86", "87",
"66", "74", "86", "60", "60", "61", "91", "98", "96", "53", "57",
"97", "51", "56", "95", "95", "57", "52", "97", "53", "95", "95",
"52", "96", "96", "96", "52", "57", "59", "52", "97", "96", "53",
"95", "53", "96", "52", "103", "53", "102", "96", "52", "101",
"97", "98", "96", "95", "43", "51", "96", "48", "57", "63", "47",
"46", "53", "96", "46", "55", "57", "63", "87", "61", "81", "74",
"71", "81", "74", "72", "95", "77", "85", "61", "81", "82", "66",
"72", "59", "70", "81", "84", "88", "73", "73", "55", "73", "85",
"62", "81", "56", "57", "82", "82", "83", "54", "83", "60", "82",
"68", "87", "90", "66", "91", "82", "52", "71", "98", "65", "65",
"57", "54", "49", "97", "92", "99", "55", "50", "97", "94", "96",
"55", "98", "95", "55", "49", "48", "102", "96", "102", "55",
"96", "55", "95", "56", "56", "97", "52", "56", "101", "56",
"100", "52", "96", "94", "101", "102", "49", "91", "98", "101",
"49", "55", "50", "50", "98", "92", "95", "86", "54", "83", "67",
"86", "86", "65", "66", "81", "65", "88", "86", "54", "92", "91",
"96", "94", "58", "65", "62", "99", "72", "80", "69", "93", "88",
"83", "66", "87", "85", "56", "66", "70", "68", "88", "68", "69",
"60", "63", "89", "63", "67", "63", "66", "62", "59", "90", "90",
"70", "98", "85", "88", "96", "64", "84", "85", "63", "79", "59",
"58", "72", "63", "57", "91", "53", "98", "85", "87", "81", "70",
"86", "83", "96", "72", "70", "85", "97", "94", "68", "95", "94",
"72", "95", "83", "67", "90", "76", "62", "98", "60", "82", "58",
"63", "93", "68", "95", "55", "62", "63", "66", "86", "60", "85",
"59", "70", "60", "65", "63", "103", "91", "104", "64", "96",
"96", "94", "62", "106", "63", "63", "63", "88", "71", "61",
"69", "88", "93", "67", "91", "82", "66", "86", "92", "60", "94",
"99", "102", "96", "62", "92", "67", "100", "53", "62", "62",
"85", "62", "60", "60", "95", "59", "61", "50", "93", "93", "59",
"61", "80", "103", "63", "95", "91", "71", "98", "95", "80",
"61", "68", "56", "95", "57", "65", "99", "57", "101", "59",
"67", "62", "60", "60", "96", "96", "97", "51", "93", "54", "63",
"97", "56", "67", "81", "78", "91", "62", "51", "88", "64", "59",
"65", "94", "54", "50", "77", "49", "104", "94", "61", "63",
"65", "64", "91", "68", "61", "93", "91", "88", "96", "50", "104",
"68", "64", "86", "67", "63", "94", "65", "67", "55", "90", "56",
"50", "104", "100", "68", "55", "50", "99", "52", "98", "78",
"50", "60", "60", "60", "75", "78", "69", "94", "70", "100",
"55")), .Names = c("Position_X", "Position_Y"), row.names = c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L,
16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L,
29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L,
42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L, 50L, 51L, 52L, 53L, 54L,
55L, 56L, 57L, 58L, 59L, 60L, 61L, 62L, 63L, 64L, 65L, 66L, 67L,
68L, 69L, 70L, 71L, 72L, 73L, 74L, 75L, 76L, 77L, 78L, 79L, 80L,
81L, 82L, 83L, 84L, 85L, 86L, 87L, 88L, 89L, 90L, 91L, 92L, 93L,
94L, 95L, 96L, 97L, 98L, 99L, 100L, 101L, 102L, 103L, 104L, 105L,
106L, 107L, 108L, 109L, 110L, 111L, 112L, 113L, 114L, 115L, 116L,
117L, 118L, 119L, 120L, 121L, 122L, 123L, 124L, 125L, 126L, 127L,
128L, 129L, 130L, 131L, 132L, 133L, 134L, 135L, 136L, 137L, 138L,
139L, 140L, 141L, 142L, 143L, 144L, 145L, 146L, 147L, 148L, 149L,
150L, 151L, 152L, 153L, 154L, 155L, 156L, 157L, 158L, 159L, 160L,
161L, 162L, 163L, 164L, 165L, 166L, 167L, 168L, 169L, 170L, 171L,
172L, 173L, 174L, 175L, 176L, 177L, 178L, 179L, 180L, 181L, 182L,
183L, 184L, 185L, 186L, 187L, 188L, 189L, 190L, 191L, 192L, 193L,
194L, 195L, 196L, 197L, 198L, 199L, 200L, 201L, 202L, 203L, 204L,
205L, 206L, 207L, 208L, 209L, 210L, 211L, 212L, 213L, 214L, 215L,
216L, 217L, 218L, 219L, 220L, 221L, 222L, 223L, 224L, 226L, 227L,
228L, 229L, 230L, 231L, 232L, 233L, 234L, 235L, 236L, 237L, 238L,
239L, 240L, 241L, 242L, 243L, 244L, 245L, 246L, 247L, 248L, 249L,
250L, 251L, 252L, 253L, 254L, 255L, 256L, 257L, 258L, 259L, 260L,
261L, 262L, 263L, 264L, 265L, 266L, 267L, 268L, 269L, 270L, 271L,
272L, 273L, 274L, 275L, 276L, 277L, 278L, 279L, 280L, 281L, 282L,
283L, 284L, 285L, 286L, 287L, 288L, 289L, 290L, 291L, 292L, 293L,
294L, 295L, 296L, 297L, 298L, 299L, 300L, 301L, 302L, 303L, 304L,
305L, 306L, 307L, 308L, 309L, 310L, 311L, 312L, 313L, 314L, 315L,
316L, 317L, 318L, 319L, 320L, 321L, 322L, 323L, 324L, 325L, 326L,
327L, 328L, 329L, 330L, 331L, 332L, 333L, 334L, 335L, 336L, 337L,
338L, 339L, 340L, 341L, 342L, 343L, 344L, 345L, 346L, 347L, 348L,
349L, 350L, 351L, 352L, 353L, 354L, 355L, 356L, 357L, 358L, 359L,
360L, 361L, 362L, 363L, 364L, 365L, 366L, 367L, 368L, 369L, 370L,
371L, 372L, 373L, 374L, 375L, 376L, 377L, 378L, 379L, 380L, 381L,
382L, 383L, 384L, 385L, 386L, 387L, 388L, 389L, 390L, 391L, 392L,
393L, 394L, 395L, 396L, 397L, 398L, 399L, 400L, 401L, 402L, 403L,
404L, 405L, 406L, 407L, 408L, 409L, 410L, 411L, 412L, 413L, 414L,
415L, 416L, 417L, 418L, 419L, 420L, 421L, 422L, 423L, 424L, 425L,
426L, 427L, 428L, 429L, 430L, 431L, 432L, 433L, 434L, 435L, 436L,
437L, 438L, 439L, 440L, 441L, 442L, 443L, 444L, 445L, 446L, 447L,
448L, 449L, 450L, 451L, 452L, 453L, 454L, 455L, 456L, 457L, 458L,
459L, 460L, 461L, 462L, 463L, 464L, 465L, 466L, 467L, 468L, 469L,
470L, 471L, 472L, 473L, 474L, 475L, 476L, 477L, 478L, 479L, 480L,
481L, 482L, 483L, 484L, 485L, 486L, 487L, 488L, 489L, 490L, 491L,
492L, 493L, 494L, 495L, 496L, 497L, 498L, 499L, 500L, 501L, 502L,
503L, 504L, 505L, 506L, 507L, 508L, 509L, 510L, 511L, 512L, 513L,
514L, 515L, 516L, 517L, 518L, 519L, 520L, 521L, 522L, 523L, 524L,
525L, 526L, 527L, 528L, 529L, 530L, 531L, 532L, 533L, 534L, 535L,
536L, 537L, 538L, 539L, 540L, 541L, 542L, 543L, 544L, 545L), class = "data.frame")

library(ggplot2)
library(png)
library(dplyr)
setwd("/Users/Folder/")
resize.win <- function(Width=6, Height=6)
{
    dev.off();
    windows(record=TRUE, width=Width, height=Height)
}
resize.win(1552,300)
#Replace the directory and file information with your info
img <- readPNG("plan3.png")
height<-dim(img)[1]
width<-dim(img)[2]
mypath <- file.path("C:/Users/Folder/img)
png(filename = mypath, width = 1552, height = 300)
#Set up the plot area
par(bty = 'n')
plot(1:1, type='n', main="", xlab="", ylab="", xaxt='n', yaxt='n', ann=FALSE, xlim=c(1,1552),ylim=c(1,112))
#recuperation des infos
lim <- par()
rasterImage(img,0,0,width,height)
lines(mydata$Position_X, mydata$Position_Y, col = "red" ,type="p", pch=16,lwd=2, cex = 1.8)
par(xpd=NA,oma=c(17.9,25,11,10))
legend(par("usr")[1],par("usr")[3],legend = "red" ,text.font=2, fill="red", ncol = 3,bty = "n", cex = 0.8,lty=0,xjust=0, yjust=1.8)
dev.off()

The result is here :

Now, I want to aggregate these coordinates in order to have a more macroscopic representation, let's say every 3px*3px there's aggregation of points (coordinate) with different colors of aggregation's number.
It is possible to do this, and how ? Thanks a lot.
EDIT 1 : Use of DBSCAN
 mydata$Position_X=as.numeric(mydata$Position_X)
    mydata$Position_Y=as.numeric(mydata$Position_Y)
    df=mydata
    library("fpc")
    # Compute DBSCAN using fpc package
    set.seed(123)
    db <- fpc::dbscan(df, eps = 0.15, MinPts = 5)
    # Plot DBSCAN results
    plot(db, df, main = "DBSCAN", frame = FALSE)

Problem : This code only make plot of my points, no aggregation. Why I couldn't use mydataset in this way ?
EDIT2 : Raster
    coordinates(mydata) = ~Position_X+Position_Y
library(raster)
r <- raster(xmn=0, ymn=0, xmx=416, ymx=73, res=5)
r[] <- 0
xy <- mydata
tab <- table(cellFromXY(r, xy))
r[as.numeric(names(tab))] <- tab
plot(r)
points(xy, pch=20)

A: I write directly what I had in mind with raster::rasterize, which does directly fill a raster with the counts.
Note that I used a resolution of 10 pixels, but you can choose anything else.
# Libraries ----
library(sp)
library(raster)
library(dplyr)
library(ggplot2)
library(rasterVis)

# Convert data to numeric ----
mydata <- mydata %>%
  mutate(Position_X = as.numeric(Position_X),
         Position_Y = as.numeric(Position_Y))

# ==== With raster ====
mydata.sp <- mydata
coordinates(mydata.sp) <- ~Position_X+Position_Y

r <- raster(xmn = xmin(mydata.sp), ymn = ymin(mydata.sp),
            xmx = xmax(mydata.sp), ymx = ymax(mydata.sp),
            res = 10)
r[] <- 0
plot(r)
points(mydata.sp, pch = 20)

# raster with classical plot
mydata.r <- rasterize(mydata.sp, r, fun = 'count')
plot(mydata.r, col = rev(topo.colors(10)))

# raster with ggplot2
rasterVis::gplot(mydata.r) +
  geom_tile(aes(fill = value)) +
  scale_fill_gradient(low = 'yellow', high = 'blue') +
  coord_equal()

Retrieve frequencies in the raster
# Get all data of the raster as a matrix
m <- as.matrix(mydata.r)

# Retrieve frequencies in more usable way
# /!\ Be careful, `Var1=1` corresponds to `row=1`
# you can retrieve real coordinates with `xFromCol` or `yFromRow`
m2 <- as.data.frame.table(
  as.matrix(mydata.r),
  base = list(as.character(1:max(xmax(mydata.sp), ymax(mydata.sp))))) %>%
  filter(!is.na(Freq))

There is also a solution with ggplot2::geom_bin2d directly on the original dataframe.
# ==== Direct with ggplot2 ====
ggplot(mydata, aes(Position_X, Position_Y)) +
  geom_bin2d(binwidth = c(10, 10)) +
  scale_fill_gradient(low = 'yellow', high = 'blue') +
  coord_equal()


text:
Q: Spinner inside a fragment using kotlin: none of the following functions can be called with the arguments supplied I've been trying to put a spinner inside a fragment, codying with kotlin , but I haven't made it yet.
This is how I've been trying.
I hope you guys could help me.
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val binding: RutinaBinding =
            DataBindingUtil.inflate(inflater, R.layout.rutina, container, false)
        binding.check.setOnClickListener{view : View ->
            Navigation.findNavController(view).navigate(R.id.action_rutina_to_menu_final)

        }

        val numero_series = resources.getStringArray(R.array.number_series_string)

        if (binding.numSeries != null) {
            val adapter = ArrayAdapter<String>(this ,
                android.R.layout.simple_spinner_item, numero_series)
            binding.numSeries.adapter = adapter

        return binding.root
    }

}

A: ArrayAdapter takes a Context as its first parameter, but a Fragment is not a Context. You should use the requireContext() method to get a Context
val adapter = ArrayAdapter<String>(requireContext(),
            android.R.layout.simple_spinner_item, numero_series)


text:
Q: Data screaping based on Search engines Is it possible to scrap the web based on Keywords using Search engines in PHP?
Like when some put keyword, the script will search google and render the results and then render the pages and scrap/extract the line that includes the matched keywords?
Any idea or library to refer to?

A: You can use php function call
file_get_contents('web url goes here');
example file_get_contents('http://www.google.com');
That function will get the html returned from the url, then you can use xpath to extract the element of html to get the data that you want.
You can see example and more explanation url below.
https://gist.github.com/anchetaWern/6150297
I personally have done something similar of your question, but it's in ruby on rails, you can explore the project here.
https://github.com/dvarun/gextract
the xpath that I used is here:
https://github.com/dvarun/gextract/blob/master/app/jobs/fetch_keyword_job.rb

A: You can do that using google api https://developers.google.com/custom-search/json-api/v1/overview and a related php client https://github.com/google/google-api-php-client.
Later on you need to write a web scraper to download the websites (curl) and parse the html parser (i.e. https://github.com/paquettg/php-html-parser).
I would, however, not recommend php for the latter task. There are much more sophisticated scraping tools available for python (i.e. BeautifulSoup or Scrapy) that will make your life much MUCH easier than using php.


text:
Q: Merge 2nd line of txt files together I have a few hundred txt files with 2 lines each.
To merge them, I would generally do:
cat *.txt > final.txt

however, I only need to do that for 2nd line of each file so the final output is like
2nd line of 1st file
2nd line of 2nd file
2nd line of 3rd file
(and so on..)

Any ideas how I can accomplish this?

A: 1st solution: Could you please try following with GNU awk. nextfile is very nice option in GNU awk which will skip all lines in current Input_file when a condition is MET.
awk 'FNR==2{print;nextfile}' *.txt > output_file

2nd solution: In case you don't have GNU awk try. Here since we are assuming there is NO nextfile in awk so I am creating a flag on each file's 2nd line and when it is TRUE simply going next line/skipping them and trying to save sometime. NOTE that this flag value will be RESET on each file's first line too.
awk 'FNR==1{flag=""} FNR==2{print;flag=1} flag{next}'  *.txt > output_file

3rd solution: Adding while and find approach too here with head and tail. AFAIK head and tail shouldn't read whole file.
while read line
do
  head -n +2 "$line" | tail -1
done <  <(find -type f -name "*.txt") > "output_file"

A: With GNU sed:
sed -n -s 2p *.txt > final.txt

or
sed -s '2!d' *.txt > final.txt

From man sed:

-s: consider files as separate rather than as a single continuous long stream.

A: find . -name "*.txt" -type f -exec awk 'NR==2' {} \;

A: Use awk
awk 'FNR == 2 { print; nextfile }' *.txt > final.txt

FNR contains the line number within the current file. When it's on line 2, it will print the line and then go to the next file.

A: Using Perl
 perl -ne ' if($.==2) { print ; close(ARGV) } ' *.txt

with sample files
$ cat allison1.txt
line1 in file1
line2 in file1

$ cat allison2.txt
line1 in file2
line2 in file2

$ cat allison3.txt
line1 in file3
line2 in file3

$  perl -ne ' if($.==2) { print ; close(ARGV) } ' allison*txt
line2 in file1
line2 in file2
line2 in file3

$


text:
Q: What are the benefits of IntegerCache while using Integer? In Integer class, there is private static class IntegerCache.
What is the use of this class?
What are the benefits of it while using Integer?

A: Values between -128 and 127 are cached for reuse. This is an example of the flyweight pattern, which minimizes memory usage by reusing immutable objects.

Beyond being an optimization, this behaviour is part of the JLS, so the following may be relied upon:
Integer a = 1;
Integer b = 1;
Integer c = 999;
Integer d = 999;
System.out.println(a == b); // true
System.out.println(c == d); // false

A: IntegerCache caches value between -128 to +127 to optimise Autoboxing.
You can set upper bound greater than 127 using -XX:AutoBoxCacheMax=NEWVALUE or -Djava.lang.Integer.IntegerCache.high=NEWVALUE

A: Look at its implementation:
private static class IntegerCache {
   static final int high;
   static final Integer cache[];
   static {
      final int low = -128;
      int h = 127;
      if (integerCacheHighPropValue != null) {
          int i = Long.decode(integerCacheHighPropValue).intValue();
          i = Math.max(i, 127);
          h = Math.min(i, Integer.MAX_VALUE - -low);
      }
      high = h;
      cache = new Integer[(high - low) + 1];
      int j = low;
      for(int k = 0; k < cache.length; k++)
      cache[k] = new Integer(j++);
   }
   private IntegerCache() {}
}

256 values are cached to be used again, they'll be loaded when you create the first Integer object.
So when you use the == operator to check the equality for two Integers on the range of [-127,128], you'll get it as if you where comparing two ints. But if you compare two Integers out of this range using ==, you'll get false, even if they have the same value.


text:
Q: Android: Custom Tab Icon Size Ok, I am going to building some custom tab icon images as explained in the following post.  But I just need to know what size do I need to build my tab icons?  I keep on guessing and then putting them in this demo and they get squashed or changed.  What ratio in pixels do I need to create my tab icons so that they appear right?
SOLUTION:
I will give sandy the best answer, especially since he is the only answer at this point, and because I did eventually use a 9 patch image.  But I tell you what, for someone who is new to the graphic editing game, 9 patch images were a pain in the butt to use.  I eventually just download someone else 9 patch image then edited the image for what I needed.  If you look at my other question here.  You can see the image I use as the background behind example 1 and example 2 are 9 patch images.  And that works great because everything looks perfect when you move it to landscape mode as well.

A: You need to create a 9 - patch image.. for more see here


text:
Q: How to customize Nihilo.css? One of the available themes in Dijit  is Nihilo.  I am using dijit/layout/.. for displaying  some charts and graphs . I want to change some of the styles being used. Can any one tell me how to customize Nihilo.css and use the customized version?

A: Don't change nihilo.css, create another CSS file and put the link tag for the second file after the link tag for nihilo.css.
This way, if you upgrade Dojo, you will not have to merge your changes back in.

A: If you need to customize nihilo, I would suggest to have a look at this official guide Customizing a Theme.
Basically the idea is to build your theme, based on nihilo leaving the original nihilo untouched,.


text:
Q: Guarantees on the evaluation order of recursive relationship match in Cyher/Neo4j For a match like MATCH (node0 {id: 1})-[:REL*]->(nodeN),
are there any guarantees on:

*

*match being Depth-First / Breath-First?

*match branching from one node through one relation or another?

Experimenting on this, for the same data set (created from integration tests with entities created in the same order each time), two Neo4j instances (one in docker ran through github action, another on docker desktop) seems to have:

*

*the same Depth-First semantics

*different branching order

Is there any Cypher parameters to influence 1) DFS vs. BFS behaviour 2) order of traversal from one node i.e. based on a relation property
I know there are traversal (i.e. tree-spanning) algorithms that do a similar thing but I don't want to explore them yet for the reason they are more restrictive in regard to property filtering (being able to filter only by labels)

A: I don't think there are any parameters right to do any of these things.

*

*DFS vs BFS -> Path matching is DFS only. For the query MATCH (node0 {id: 1})-[:REL*]->(nodeN), first cypher will obtain a nodeN, at one hop distance. Then it will traverse from that node and go forward. A good way to notice this is by looking at the output of the following query:
MATCH (n{id: 1})-[r:REL*]->(nodeN) return n, nodeN, r

*We can't influence the traversal order using some property. There is no such keyword, the WHERE clause will filter out the results, and ORDER BY will order the final results, but nothing right now can influence the traversals internally.

A: I don't think you can do it in pure Cypher. But if you need to have predictable results from your MATCH, you may try something like this, using an identifying property (internal ids will not work for your case I guess, since you're running two dbs)
MATCH (p) = (node0 {id: 1})-[:REL*]->(nodeN)
WITH p
ORDER BY length(p), nodeN.ID     // ORDER BY  nodeN.ID,length(p)

so you have at least the results in always the same order.


text:
Q: Why is this code an infinite loop? Before completing this code, I just tested it by mistake and realized that it will not stop:
$var = "any";
for ($i=1; $i < 2; $i++){
    $var.$i = "any";
}

Why does this produce an infinite loop? And why doesn't PHP produce an error?

A: I did a simple test :
echo $i;
 $var.$i = "any";
var_dump($var);

Result :
1string(3) "any"
anzstring(3) "any"

So $i get transformed to "anz" and doesn't pass the validation to get out of the loop.
$var.$i = "any"; is not really correct, i don't know what you are trying to do, but if you want to fill and array you should do something more like :
$var = array();
for ($i=1; $i < 2; $i++){
 $var[] = "any";
}

If you want to change your string letter by letter :
$var = "any";
    for ($i=1; $i < 2; $i++){
     $var[$i] = "a"; // asign a new letter to the string at the $i position
    }

A: When you do the following $var.$i = 'any' you set the $i variable and the $var variable.
So the the loop never stop running because var_dump($i < 1) returns true.
$var = 'var';
$i = 1;
$var.$i = 'var';

var_dump($i);

Returns string(3) "var".
This loop will never stop because $i is always reset to 'var', which is smaller than 1.

A: This is incorrect $var.$i = "any"; because this expression is equivalent to:
 $var.($i = "any");

Which assigns $i to new value, therefore the condition of which the while loops checks will always be true.

A: PHP5.4+.
You will get 'anz' result, after $i++, when $i == 'any'.
$i == 'any', after assignment and that is, actually, what it should get.
Trick is in "$i='any'" part of line. Even when "=" has lower precedence then ".", why do you think that it shouldn't put 'any' inside $i?
Try this instead:
$var = "any";
for ($i=1; $i < 2; $i++){
 $i.$var = "anything";
}

And your loop will work. And $var will get "anything" value. This doesn't look like a bug. Just unexpected behaviour for somebody.


text:
Q: Why do I seem to get different results from `base64`? I need to use base64 encoded credentials for an API call. From a web UI interface for the API I have gotten the credentials in base64 encoded form. For the sake of showing my issue I have saved the credentials to a file creds and the base64 encoded credentials from the web ui in a file creds64.
Then, running the script below:
#!/bin/bash

CREDS=$(cat creds)
BASE64_CREDS=$(cat creds64)

if [[ $CREDS == $(base64 -d creds64) ]]; then
  echo "the original credentials were the same as the decoded base64 credentials"
else
  echo "the original credentials were NOT the same as the decoded base64 credentials"
fi

if [[ $(base64 creds) == $BASE64_CREDS ]]; then
  echo "the encoded original credentials were the same as the base64 credentials"
else
  echo "the encoded original credentials were NOT the same as the base64 credentials"
fi

The resulting output is
the original credentials were the same as the decoded base64 credentials
the encoded original credentials were NOT the same as the base64 credentials

I don't understand how the base64 decoded credentials can equal the "plain" credentials, but comparing the result of base64 creds with the already encoded credentials can be not equal.
What am I misunderstanding here?

A: If the raw binary data contains null bytes, the shell basically cannot handle it. Compare
bash$ var=$'\0hello'
bash$ echo "$var"

bash$

The lack of quoting is also problematic; see When to wrap quotes around a shell variable
Keeping the data in a variable is unnecessary anyway. The following should work robustly regardless of any null characters.
if base64 -d creds64 | cmp - creds; then
    :

Finally, as Robby Cornelissen notes in a comment, the base64 command probably adds line breaks to keep the lines in the output below 80 characters. Your web client's result might not have line breaks at all, or could have them at a different line width.
You can fix this by trimming any newlines anywhere:
if [[ "$(base64 creds | tr -d '\n') = "$(tr -d '\n' <creds64)" ]]; then
    :

The use of [[ is a Bashism, so not portable to POSIX sh. You can switch to [ instead if you need portability. Somewhat similarly, cmp might not support specifying - to mean standard input on all platforms; Bash lets you use /dev/stdin instead, or /dev/fd/0 on some platforms.


text:
Q: segue to next ViewController and pass data if condition is valid I am trying to segue from first viewcontroller to the second one and pass the value of var dateAndTime = NSDate() to the second view controller.
My first approach was to segue from the first viewcontroller itself to the second one, define the name of the segue in Attributes inspector.
Next, I link a button @IBAction func nextButtonToFifthViewController in the first viewcontroller, use an if else statement and prepareForSegue, but the code does not compile because I am not allowed to override prepareForSegue.
@IBAction func nextButtonToFifthViewController(sender: AnyObject) {
    if timeRestricted.contains(hourComponents){
        self.label.text = "Please choose a time betwen 7:00 - 19:00"
    } else {

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        var destViewController:FifthViewController = segue.destinationViewController as! FifthViewController
        destViewController.dateAndTimeSelected = dateAndTime    }
       }

My second approach was to use performSegueWithIdentifier, but I wont be able to pass data to the next view controller because dateAndTimeSelected is not available for use in first view controller.
@IBAction func nextButtonToFifthViewController(sender: AnyObject) {
    if timeRestricted.contains(hourComponents){
        self.label.text = "Please choose a time betwen 7:00 - 19:00"
    } else {

        performSegueWithIdentifier("toFifthViewController", sender: self)
  dateAndTimeSelected = dateAndTime
}

A: Note that performSegueWithIdentifier and prepareForSegue methods should be used together. First you call performSegueWithIdentifier when you already sure that you need move to new view controller, then you may configure your new view controller in prepareForSegue
@IBAction func nextButtonToFifthViewController(sender: AnyObject) {
    if timeRestricted.contains(hourComponents){
        self.label.text = "Please choose a time betwen 7:00 - 19:00"
    } else {
        performSegueWithIdentifier("toFifthViewController", sender: self)
    }
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "toFifthViewController" {
        if let destViewController = segue.destinationViewController as? FifthViewController {
            destViewController.dateAndTimeSelected = dateAndTime
        }
    }
}


text:
Q: Xpath Attributes Hello I have the following XML sample
<?xml version="1.0" encoding="UTF-8"?>

<Data>
<x>3</x>
<Document1 id="123" filename="/test/dev/fileA.txt"/>
<Document2 id="123" filename="/test/dev/fileB.txt"/>
<Document3 id="123" filename="/test/dev/fileC.txt"/>
<Document4 id="123" filename="/test/dev/fileD.txt"/>
</Data>

I need with Xpath 1.0 to be able to retrieve a specific filename using the x variable.
Something like:
/Data/Document[x]/@filename

I need to be able to retrieve a specific filename base on the value of x.  Is it possible?  Please let me know if you need any more info.
Thanks in advance

A: Yes, it is possible. But why do you want to design your input xml format like this? It would be much better to use the id attribute to select the right document rather than the element name, for many reasons.
Reasons include:

*

*the xpath expression evaluates faster (/Data/Document[@id=/Data/x]/@filename)

*you could create an XSD schema for it

I also question why you would want to put the variable <x> in the same document as the other data - if you already know in the input document which 'Document' element you need, why not remove the others?
Having said that, an xpath expression that does what you are asking for is:
/Data/*[local-name() = concat('Document', /Data/x)]/@filename


text:
Q: How do you refresh System path/variables after installing programs? I have a python script which will install an application:
os.system("path/to/my.exe /VERYSILENT")

When i do this, for example I would install Git.
Later on, the application will call:
os.system("git --version")

which fails to call because it doesnt know what git is.
From what it looks like, the System variables etc are all grabbed when you import os so could I just after installing the application reimport os somehow and then carry on?
My desired end state is to refresh CMD, similar to how you would close a terminal and open a new one.

A: Sub-shells (as in os.system(..)) cannot effect the execution environment of the parent process (it would be a huge security hole).  You can update the permanent user environment with e.g. Powershell ([environment]::SetEnvironmentVariable($key, $val, "User")). Any processes started afterwards will see the new environment variable (this is why you need to close your cmd window and start a new one.


text:
Q: Codeigniter return unsigned zerofill id from database I am using this method to get the last inserted id:
$this->db->insert_id();

for example the inserted id in the database is 000055, but this function returns me only 55, how can I get the full unsigned zerofill id?

A: Assuming you're using MySQL - the $this->db->insert_id() method uses mysql_insert_id function - which returns an integer.
So, without changing the ./system/database/drivers/mysql/mysql_driver.php file, I don't think there's a way.

A: why are your ID's zero filled? This could cause problems if it returns 1's because it will think it is a binary number rather than a zero filled int. There could even be a rare chance to be hex as well. If you just want your ID's zero filled for the application then handle that in a library or helper for when you render it to a view because since PHP is loosely typed it could think you are doing a bit comparison or dealing with hex or binary and not an int.
If you really want to do this you will need to extend CI_DB_mysqli_driver (or whatever db driver you are using) and overwrite insert_id() and make sure it returns a string and then make sure you always treat it as a string. Still, I would strongly advise you from doing logic on zero filled ints.


text:
Q: repast simphony relogo tutorial Zombies; Has anyone come across the following warnings I came across the following warnings while taking the step by step tutorial for Zombies on Relogo within Repast Simphony 2.0 Beta
The warnings are:

*

*Description   Path    Resource    Location    Type
TrackingEdge is a raw type. References to generic type TrackingEdge should be parameterized  /Zombies/src/zombies/style  TrackingLinkStyle.java  line 31 Java Problem

*Description   Path    Resource    Location    Type
BaseLink is a raw type. References to generic type BaseLink should be parameterized  /Zombies/src/zombies/style  LinkStyle.java  line 28 Java Problem

*Description   Path    Resource    Location    Type
Unnecessary @SuppressWarnings("unchecked")  /Zombies/src/zombies/style  TrackingLinkStyle.java  line 29 Java Problem
They do not interrupt the simulation but as I would be developing other models in the future I was wondering if any one knew what they meant, and if possible how to take care of them
Thanks

A: On behalf of the repast simphony mailing list feedback
This is the answer to the question above
Hello Victoria,
Those are simply warnings and in no way affect your model.
If you're curious and would like to learn more about the first two sets of warnings, you can read up on Java Generics: http://docs.oracle.com/javase/tutorial/java/generics/index.html
If you're curious about the last warning, try searching for Java Annotations online: http://docs.oracle.com/javase/tutorial/java/javaOO/annotations.html
Best,
Jonathan


text:
Q: Why Java jni call on linux is slow as compare to windows? I am using java JNI having same code for windows and linux(Ubuntu) platform but facing a strange issue that the speed/performance of JNI call on linux(Ubuntu) is too slow as compare to windows. Following are the platform information
 - Window's-8 64-bit intel corei-7 machine with jdk 1.8.0, MinGW gcc 4.8.0
 - Ubuntu-15 64-bit intel corei-7 machine with jdk 1.8.0, Linux gcc 4.8.0
Any help in this regard will be highly appreciated.


text:
Q: How many types of stack are there in a running JVM program? the question is pretty obvious. As I am ready JVM specification I came across Java Stacks

"2.5.2 Java Virtual Machine Stacks"
Each Java Virtual Machine thread has a private Java Virtual Machine
  stack, created at the same time as the thread. A Java Virtual Machine
  stack stores frames (§2.6). A Java Virtual Machine stack is analogous
  to the stack of a conventional language such as C: it holds local
  variables and partial results, and plays a part in method invocation
  and return. Because the Java Virtual Machine stack is never
  manipulated directly except to push and pop frames, frames may be heap
  allocated. The memory for a Java Virtual Machine stack does not need
  to be contiguous.

So apart from thread stack is there any types of stacks that are used or that we can classify?

A: Some types of the stacks from the specification are:
1) Operand Stacks: Each frame contains a last-in-first-out (LIFO) stack known as its operand stack. The maximum depth of the operand stack of a frame is determined at compile-time and is supplied along with the code for the method associated with the frame.
2) Native Method Stacks: An implementation of the Java Virtual Machine may use conventional stacks, colloquially called "C stacks," to support native methods (methods written in a language other than the Java programming language). Native method stacks may also be used by the implementation of an interpreter for the Java Virtual Machine's instruction set in a language such as C. Java Virtual Machine implementations that cannot load native methods and that do not themselves rely on conventional stacks need not supply native method stacks. If supplied, native method stacks are typically allocated per thread when each thread is created.
3) Java Virtual Machine Stacks: you mentioned in the question.


text:
Q: Save object name into ForeignKey field on child object - Django I have these models:
class MyModel1(models.Model):
    field1 = models.CharField(max_length=128, blank=True, null=True)
    fieldrelated1 = models.OneToOneField('MyModel2', max_length=128, blank=True, null=True, related_name='mymodel2')
    fieldrelated2 = models.OneToOneField('MyModel3', max_length=128, blank=True, null=True, related_name='mymodel3')
    fieldrelated3 = models.OneToOneField('MyModel4', max_length=128, blank=True, null=True, related_name='mymodel4')

class MyModel2(models.Model):
    field2 = models.CharField(max_length=128, blank=True, null=True)
    myfk = models.ForeignKey(MyModel1, max_length=128, blank=True, null=True)

class MyModel3(models.Model):
    field3 = models.CharField(max_length=128, blank=True, null=True)
    test = models.CharField(max_length=128, blank=True, null=True)

class MyModel4(models.Model):
    field4 = models.CharField(max_length=128, blank=True, null=True)
    test = models.CharField(max_length=128, blank=True, null=True)

Then, this method:
def create_child_objects(instance, created, rad, **kwargs):
    if not created or rad:
        return
        field1 = instance.field1

    if not instance.fieldrelated1_id:
        fieldrelated1, _ = MyModel2.objects.get_or_create(field1=field2)
    instance.fieldrelated1 = fieldrelated1

    if not instance.fieldrelated2_id:
        fieldrelated2, _ = MyModel3.objects.get_or_create(field1=field3)
    instance.fieldrelated2 = fieldrelated2

    if not instance.fieldrelated3_id:
        fieldrelated3, _ = MyModel4.objects.get_or_create(field1=field4)
    instance.fieldrelated3 = fieldrelated3

    instance.save()

models.signals.post_save.connect(create_child_records, sender=MyModel1, dispatch_uid='create_child_objects')

So far, this method works to save the parent and save particular fields on child creation.
My problem comes when I want to, for example, instead of saving a parent's CharField into a child CharField, I want to save the actual parent instance into a child's ForeignKey field, like this:
def create_child_objects(instance, created, rad, **kwargs):
    if not created or rad:
        return
    field1 = instance.__str__

    if not instance.fieldrelated1_id:
        fieldrelated1, _ = MyModel2.objects.get_or_create(field1=myfk)
    instance.fieldrelated1 = fieldrelated1

    if not instance.fieldrelated2_id:
        fieldrelated2, _ = MyModel3.objects.get_or_create(field1=field3)
    instance.fieldrelated2 = fieldrelated2

    if not instance.fieldrelated3_id:
        fieldrelated3, _ = MyModel4.objects.get_or_create(field1=field4)
    instance.fieldrelated3 = fieldrelated3

    instance.save()

models.signals.post_save.connect(create_child_objects, sender=MyModel1, dispatch_uid='create_child_records')

The parent object is saved into db with a method like this:
    def __str__(self):
        return ('{}: {}: {}'.format(self.field1, self.field2, self.field3))

So, after the second create_child_objects it throws me this:
TypeError at /admin/mymodel/instance/add/
int() argument must be a string, a bytes-like object or a number, not 'method'

So, how can I save the parent object descriptor into a ForeignKey field to the parent object?
EDIT
What is saved on this myfk field is the id of MyModel1, so, it would be sufficient to save this, but when I try like this field1 = MyModel1.id
It says:
ValueError at /admin/mymodel/instance/add/
Cannot assign "98": "MyModel2.field1.id" must be a "MyModel1" instance.

A: field1 = instance.__str__

change to
field1 = instance.__str__()

or
field1 = str(instance)

__str__ is a method so your assignment makes field1 pointing to this method, not method's result.
UPD
All the MyModel[2-4].objects.get_or_create(field1=field2) lines are wrong:

*

*those model don't have field1 field, so correct filter would be field[2-4]=field1

*anyway, I assume it will never match anything because __str__ method is a combination of those IDs and this string must be parsed first; only extracted values would match

And I don't understand how your __str__ method works since this model does not have field2, field3 and field4.
I suggest you to rethink the approach. Have a look at generic relations.


text:
Q: Manual t-test in R, Tail test I've been trying to make a manual t test of a statistic that I calculated in r. I've seen some people recommend to use the function dt but that had not worked. I know because I'm comparing my results of R with my results in STATA (the last ones I'm sure I've got them correct). This is the code with which I'm trying to do this
pvalue<-dt(3.141523, df=8)

Where 3.141523 is my calculated t statistic and df is degrees of freedom. Thank you for your help!

A: I think you want to use the pt() function instead of dt(). dt() is the density while pt() is the distribution.
> pt(3.141523, df = 8)
[1] 0.9931132


text:
Q: How to get the paypal customerid(subscriber_id) I am using cakephp2.0 framework. I am doing recurring payment. I am not getting the customer_id and other variables. And I also send the Recurring to Y.
Here is my code:
$paypalParams = array(
    'paymentAction' => "Sale",
    'amount' => $_POST['amount'],
    'currencyCode' => "USD",
    'creditCardType' => $_POST['card_type'],
    'creditCardNumber' => trim(str_replace(" ","",$_POST['card_number'])),
    'expMonth' => $_POST['expiry_month'],
    'expYear' => $_POST['expiry_year'],
    'cvv' => $_POST['cvv'],
    'firstName' => $firstName,
    'lastName' => $lastName,
    'city' => $city,
    'zip'    => $zipcode,
    'countryCode' => $countryCode,
    'recurring' => 'Y',
    'billingPeriod' => $session_details['paymentType'],
    'billingFrequency' => "1",
    'totalBillingCycles' => "0",
);
echo "<pre>"; print_r($paypalParams);
$response = $paypal->paypalCall($paypalParams);

When I call paypalCall function:
public function paypalCall($params){
    /*
     * Construct the request string that will be sent to PayPal.
     * The variable $nvpstr contains all the variables and is a
     * name value pair string with & as a delimiter
     */
    $recurringStr = (array_key_exists("recurring",$params) && $params['recurring'] == 'Y')?'&RECURRING=Y':'';
    $nvpstr = "&TOTALBILLINGCYCLES=".$params['totalBillingCycles']."&BILLINGFREQUENCY=".$params['billingFrequency']."&BILLINGPERIOD=".$params['billingPeriod']."&PAYMENTACTION=".$params['paymentAction']."&AMT=".$params['amount']."&CREDITCARDTYPE=".$params['creditCardType']."&ACCT=".$params['creditCardNumber']."&EXPDATE=".$params['expMonth'].$params['expYear']."&CVV2=".$params['cvv']."&FIRSTNAME=".$params['firstName']."&LASTNAME=".$params['lastName']."&CITY=".$params['city']."&ZIP=".$params['zip']."&COUNTRYCODE=".$params['countryCode']."&CURRENCYCODE=".$params['currencyCode'].$recurringStr;
    //echo "<pre>"; print_r($nvpstr); die;
    /* Make the API call to PayPal, using API signature.
       The API response is stored in an associative array called $resArray */
    $resArray = $this->hashCall("DoDirectPayment",$nvpstr);
    echo "<pre>"; print_r($resArray); die;
    return $resArray;
}

When I print this array($resArray) it gives only these parameters:
enter code here
<pre>Array
(
[TIMESTAMP] => 2016-12-29T09:05:26Z
[CORRELATIONID] => 42743fa743c6
[ACK] => Success
[VERSION] => 65.1
[BUILD] => 24616352
[AMT] => 19.99
[CURRENCYCODE] => USD
[AVSCODE] => X
[CVV2MATCH] => M
[TRANSACTIONID] => 9A3464215B244930U
)

There is no customerid(subscriber_id).
Could anyone help me to see what I am doing wrong?


text:
Q: memcpy function in c Why this below code gives segmentation fault?
int main()
{
        char *t = "Working on RedHat Linux";
        char *s;

        s = malloc (8000 * sizeof(char));
        memcpy(s,t,7000);
        printf("s = %s\nt = %s\n",s,t);
        free(s);
}

I have allocated 8000bytes for 's'. And copying only 't' to s untill 7000bytes. Though I have allocated 8000 bytes for 's', why its giving segmentation fault?

A: Your program exhibits undefined behavior: for memcpy() to work, both the source and the destination must be addressable for the number of bytes you've specified.
You've satisfied the destination, but not the source part.
Also, you can remove sizeof(char) as it is defined by the standard to always be 1.

A: Use:
memcpy(s, t, strlen(t) + 1);

to avoid memcpy reading past the string literal array.
The C standard says regarding string functions (memcpy is a string.h function) (C99, 7.21.1p1).

"If an array is accessed beyond the end of an object, the behavior is
  undefined."

A: The segmentation fault is because t points to a region smaller than 7000 bytes.
You are probably trying to read into an area when no readable page is mapped (after the end of string literal "Working on RedHat Linux").
You should limit your memcpy to sizeof("Working on RedHat Linux") bytes.

A: t points to a String buffer of length 24, but in memcpy you are trying to copy more than that (7000) which do not exist.
You are trying to access memory beyond what is allocated.
So it is giving a segmentation fault


text:
Q: Assign single element to an IntArray value attribute in Kotlin annotations I have a custom annotation declared as
@Target(AnnotationTarget.FUNCTION)
annotation class Anno(val value: IntArray, val attr2: Int = 0)

For a single element declaration, I'm able to use the above annotation in a Java class as
@Anno(1)

but while writing the same in a Kotlin class, I have to put enclosing brackets
@Anno([1])

Aren't the brackets unnecessary in this case or am I declaring the annotation wrong? I am using Kotlin version 1.2.0-rc-39

A: Yes, square brackets (Kotlin 1.2+) or arrayOf (Kotlin 1.2-) are required.
But as long as this is your annotation, written in Kotlin, you can do fancy things with it, like taking lambdas or varargs, so you can try to tune the resulting syntax for your need. For example, this will be valid syntax, even in Kotlin 1.2-:
@Target(AnnotationTarget.FUNCTION)
annotation class Anno(
    val attribute: String,
    vararg val value: Int
)

@Anno("test", 1, 2, 3)
fun test() = 42

You'll need to put vararg parameter at the end.


text:
Q: Nested JSON access / assigning values to UITextField I am making a small app that allows users to catalogue books by looking up the ISBN on OpenLibrary. The idea is that the ISBN search takes the returned JSON data and uses it to populate UITextFields that the user can then further edit before saving.
I'm having issue accessing the nested JSON data and putting it into a UITextField. Accusing the top level of the dictionary and putting it into the UITextFields works fine, but when I try to go deeper, I get the error:

Cannot assign a value of type String? to value of type 'String!'.

The JSON data it's taking is here: https://openlibrary.org/api/books?bibkeys=0586057242&f&jscmd=data&format=json
Below is the code:
import UIKit

class ItemViewController: UIViewController {

    @IBOutlet weak var titleField: UITextField!
    @IBOutlet weak var authorField: UITextField!

    var session: NSURLSession!
    var items = NSObject()

    var lookUpID = "0586057242" // This will eventually get passed in from elsewhere.

    required init (coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        session = NSURLSession(configuration: config, delegate: nil, delegateQueue: nil)

        fetchItem()
    }

    func fetchItem() {
        let requestString = ("https://openlibrary.org/api/books?bibkeys=" + lookUpID + "&f&jscmd=data&format=json")
        if let url = NSURL(string: requestString) {
            let req = NSURLRequest(URL: url)

            let dataTask = session.dataTaskWithRequest(req) {
                (data, response, error) in
                if data != nil {
                    var error: NSError?
                    if let jsonObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary  {

                        if let itemDictionary: AnyObject  = jsonObject["\(self.lookUpID)"]{
                            if let id = itemDictionary as? NSObject {
                                self.items = id

                                println("\(self.items)")

                                // Works.
                                self.titleField.text = itemDictionary["title"] as? String

                                // Does not work.
                                self.authorField.text = itemDictionary["authors"]["name"] as? String

                            }

                        }
                    } else {
                        if let error = error {
                            println("Error parsing JSON: \(error)")
                        }
                    }
                } else {
                    println("Error fetching Item: \(error.localizedDescription)")
                }
            }
            dataTask.resume()
        }
    }

}

I don't at all understand why it doesn't work, am I doing something wrong with the way I'm accessing the values?

A: If you check the JSON again. Author node is returning array not dictionary. So, firstly you will have to get the dictionary from array then you should try to get name node from that dictionary.
So, think you try this:
self.authorField.text = itemDictionary["authors"][0]["name"] as? String

instead of using below line
self.authorField.text = itemDictionary["authors"]["name"] as? String

A: you should cast itemDictionary["authors"] as an array of authors and get individual author name like this:
let authors = itemDictionary["authors"]
for author in authors {
   self.authorField.text = author as! String
}

or for the first record
self.authorField.text = itemDictionary["authors"][0]["name"] as! String

A: You might try something like this:
var names = [String]()
if let authors = itemDictionary["authors"] as? NSArray {
    for author in authors {
        if let author = author as? NSDictionary,
            let name = author["name"] as? String {
                names.append(name)
        }
    }
}
self.authorField.text = join(",", names)

Hope this helps


text:
Q: Messages consumed late in JMS point-to-point model I have a JMS application running on WebLogic MQ, WebLogic 8.1.
The producer and consumer model handles around 50k orders a day, 24 hours. There is 1 producer and 4 consumers configured.
Problem is, sometimes a small handful of 5-8 messages are only picked up by the consumer 15 hours later. Amd these missed messages which were picked up by the consumer at around the same time altogether. This is causing an issue and I am not sure why this happens.


text:
Q: clear screen using exec() in linux I am trying to write a code that will clear the screen by using fork() through exec. But by referring http://man7.org/linux/man-pages/man3/exec.3.html manual i am confuse why this is not placing new image at the screen( i mean clearing the screen).
here is my attempt:
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
# include <curses.h>
#define NUMARGS 2

void main(int argc,char* argv[])
{
    pid_t pid;
    char * child_args[NUMARGS] = {0,0};

    if((pid=fork())==0){

        exec();// clear the screen

    }
    else{

        wait();

    }

}

Kindly correct me if its wrong so that i can solve this problem.

A: You seems to be confused about two different, unrelated things:

*

*exec*() and fork()

*Clearing the screen

fork create a new child process, duplicating the state of the current process at the same time.
exec is a family of related functions, whose job is to replace the current process by another.
On unix systems, clearing the screen is usually done via ANSI escape codes. Please do NOT print newlines in a loop instead, that's totally cheap. If you need portability between terminal emulators, you can use libraries to abstract this task, such as termcaps or (n)curses.

You mentioned using a child process to clear the screen, I suspect you're trying to create some kind of shell. Anyway, you can use fork() to create the child, waitpid() it in the parent function, and clear the screen from the child, either directly, for example with fputs(stdout, "\033[2J"), or by exec*() 'in another executable.

I really don't know why you don't just clear the screen from the parent, however.


text:
Q: LWJGL Determining the location of a 3D object on screen Quick question (maybe so).  Is it possible to efficiently calculate the (x,y) location of 3D vertices?  For example, I have a cube which is 1x1x1 in size and lies at the origin (0,0,0).  While it is on screen, what would the on-screen coordinates of each of the cube's 8 vertices?

A: Yes. Just matrix multiply your 3d vectors with the view matrix and in case of perspective projection divide by the homogenous coordinate. See Wikipedia on 3D projection, for the mathematical details. Which also provides a decomposition of the matrix so you dont need to deal with matrices if you wish.


text:
Q: Is substituting the same as equating two functions Maybe a silly question here, but I want to check my understanding. I am looking into the number of intersections between a line and a curve, and finding said number through the discriminant. The steps I've been told are:

*

*Equate the two functions

*Move everything to LHS

*Find the discriminante for resultant quadratic

*Depending on number of answers we know the number of intersections.

This all makes sense to me. However, one of the solved examples is:
Find the range of values of q for which the line x + 2y = q meets the curve  x(x + y) + 8 = 0
And the first thing they do is rearrange the linear equation for x and then substitute into the quadratic. Once this is done I understand the rest of the process.
But here's my question. Is this substitution the same as the concept of equating the functions? I'm guessing it is but I'd like to make sure I'm not just making it suit the problem I'm looking at if the reason why the substitution works is another one.
Thanks for your help!

A: Quoting @Amaan M: Imagine you have two functions, y=f(x) and y=g(x). Since f(x)=y, you can substitute f(x) into y=g(x) in place of y, which is how you get to f(x)=g(x). So, equating two functions is the same as substitution.

A: *

*Further to your self-Answer, do be aware that there may be no
quadratic discriminant to apply your suggested procedure to, since
you will not necessarily obtain a quadratic in Step 1.

*And even if you do obtain a quadratic form, its number of
solutions isn't necessarily the number of intersections of the two
given graphs. For example, consider the pair
$$y=-e^{3-2x},\\y=2e^{3-x}+e^3.$$ Applying your procedure, we
eventually obtain $$(e^{-x})^2+2(e^{-x})+1=0.$$ So far, so good.
However, it would be invalid to conclude that because this resultant
quadratic form has discriminant $0,$ the graphs have exactly $1$
intersection point; in fact, they have
none.

The reason, of course, is that $e^{-x}={-}1\implies x\notin\mathbb R.$


text:
Q: Advanced WiFi network settings are not per-network? Like most people, I move often with my laptop, and thus I also often switch WiFis networks. There is a WiFi network I often connect to which requires the IP to be entered manually.
So I opened Network Preferences, picked WiFi, clicked Advanced..., TCP/IP, and I told it to "Configure IPv4: Manually". I entered all the info and it connected just fine.
But now I am back home, where I always get the IP using DHCP. To my surprise, the "Configure IPv4" stayed at "Manually". Why didn't it revert to DHCP?
In short, why isn't the "Configure IPv4" option per-network as it should be? What's the idea behind making it a global setting for all networks?
And finally, can I make it a per-network setting?

A: You can change your location in the apple button in the menubar, that way you won't have to open the system preferences, there are apps to change system preferences according to wi-fi connection: at the bottom of this post some are mentioned

A: Create a new location using the Network preference panel for the manual/static IP network rather than changing and re-changing the settings for Automatic.


text:
Q: Sum grouped by multiple columns in MySQL I have the following table
color       shape         material       value    qt
----------------------------------------------------
green       cylinder      plastic         12       2
white       cube          wood            5        1
green       cylinder      plastic         6        2
white       cube          wood            5        2
green       cylinder      plastic         2        2

I want to have the sum of values that have the same criteria. I want something like the following.
color       shape         material       sum
-----------------------------------------------
green       cylinder      plastic        28
white       cube          wood           15
green       cylinder      plastic        12

I have a lot of colors, shapes and materials so I would like a dynamic query. I don't know where to start.
EDIT
There is other characteristics that makes every record different

A: If it as simple as your description makes it sounds
SELECT color, shape, material, SUM(value)
FROM SomeTable
GROUP BY color, shape, material

But not sure your example output table ties up with your description and original data

A: select color, shape, material, sum( value * qt )
from tbl
group by color, shape, material


text:
Q: Script executes slower on different servers This is just a question to have some ideas of where I am doing it wrong.
I have a classic ASP application deployed on two environments (Test and Integration). The problem is that on the Test environment it takes about 10 seconds to load a certain page, as on the INT environment, the same page, takes about one minute. The difference between them is that I have different databases for Test and INT and that on the Test environment there is one server but on the INT environment there are two servers that are doing some balancing.
Also, on my ASP page I use the Response.Buffer property, but there is not Response.Flush() or Response.Clear() method called on the page. Maybe this is also a problem, but I am not sure.
Any ideas from where this delay may come from ?
Unfortunately this is all the code that I can share.
Thank you

A: what is the page doing, reading from a database?
if it is, you should run the querys directly in the databases first and if they are as fast, start thinking about IIS or ASP as the problem. If not the problem is at the databases and asp has nothing to do with it.