How to get all images of hashtag in Instagram without API?

Question: This is the code that I used to get images of hashtag without API. I do not want to use any credentials. It does not require me to add either client_id or access token. But I only get 15 images. How can I get all the images?

    <form action='#' method='post'>
    <input type='input' name='txttag' />
    <input type='submit' value='Get Image' />
    </form>

    <?php
    function scrape_insta_hash($tag) {
        $insta_source = file_get_contents('https://www.instagram.com/explore/tags/'.$tag.'/'); // instagrame tag url
        $shards = explode('window._sharedData = ', $insta_source);
        $insta_json = explode(';</script>', $shards[1]);
        $insta_array = json_decode($insta_json[0], TRUE);
        return $insta_array; // this return a lot things print it and see what else you need
    }

    if(isset($_POST['txttag']))
    {
        $tag =$_POST['txttag']; // tag for which ou want images
        $results_array = scrape_insta_hash($tag);
        $limit = 15; // provide the limit thats important because one page only give some images then load more have to be clicked
        $image_array= array(); // array to store images.
            for ($i=0; $i < $limit; $i++) {
                $latest_array = $results_array['entry_data']['TagPage'][0]['tag']['media']['nodes'][$i];
                $image_data  = ''; // thumbnail and same sizes
                //$image_data  = ''; actual image and different sizes
                array_push($image_array, $image_data);
            }
            foreach ($image_array as $image) {
                echo $image;// this will echo the images wrap it in div or ul li what ever html structure
            }
            //https://www.instagram.com/explore/tags/your-tag-name/
    }
    ?>

Comment: Great this is still working thank you
Answer: Easily way is request with ?__a=1 like https://www.instagram.com/explore/tags/girls/?__a=1 and receive JSON without parsing HTML and window._sharedData =
In json you can see page_info scope with end_cursor:
"page_info": {
    "has_previous_page": false,
    "start_cursor": "1381007800712523480",
    "end_cursor": "J0HWCVx1AAAAF0HWCVxxQAAAFiYA",
    "has_next_page": true
},

use end_cursor to request next portion of images:
https://www.instagram.com/explore/tags/girls/?__a=1&max_id=J0HWCVx1AAAAF0HWCVxxQAAAFiYA
UPD:
<?php

$baseUrl = 'https://www.instagram.com/explore/tags/girls/?__a=1';
$url = $baseUrl;

while(1) {
    $json = json_decode(file_get_contents($url));
    print_r($json->tag->media->nodes);
    if(!$json->tag->media->page_info->has_next_page) break;
    $url = $baseUrl.'&max_id='.$json->tag->media->page_info->end_cursor;
}

Comment: Works brilliant! I never heard about the `?__a=1` tag. For others who are looking to understand how to extract info from JSON data, have a look at this guy's article: `http://www.picssel.com/build-a-simple-instagram-api-case-study/`
Comment: Let's hope that Instagram doesn't notice this for a while…
Comment: @jigsparmar you need to request each video post by shortcode like ``https://www.instagram.com/p/BM39M3XBz-F/?__a=1`` (change ``BM39M3Xbz-F`` to shortcode of post you want and you will receive json with video url)
Comment: @ilyapt how did you know this method? It's awesome! Would you point us to the documentation link?
Comment: Any ideas how to get JSON (or other format of data) for list of Followers and Following?
Comment: @Emkey instagram's official site uses this method for ajax requests. There are a lot of interesting requests for scraping instagram data. I just saw how to work that site with chrome developer tools.
Comment: @BenCoffin, yes, I know how to get it, but this is not easy way.

First you do request to:
```https://www.instagram.com/graphql/query/?query_id=17888483320059182&variables=%7B%22id%22%3A%22_put_owner_id_here_%22%2C%22first%22%3A12%7D```

just replace _put_owner_id_here_ to "owner id" you want and you receive 12 posts posted this user, then make request with any post shortcode, like

```https://www.instagram.com/p/_put_post_shortcode_here_/?__a=1```

replace _put_post_shortcode_here_ to shortcode from 1st step and check in received json owner object contains "owner username"
Comment: Can you please tell me how to print more than 20 images with your code.
Comment: i not get the url for vedio. can you help?
Comment: did you know how to get vedio?
Comment: @ilyapt would you teach us where exactly it can be seen in the developer tools?
Comment: how can I get posts using various hashtags in my android app?
Comment: `caption: "..."
code: "..."
comments: Object { count: 0 }
comments_disabled: false
date: 1510945307
dimensions: Object { height: 1080, width: 1080 }
display_src: "https://..."
is_video: false
likes: Object { count: 31 }
owner: Object { id: "123456789" }`

..any idea how to get the "owner name" by ID?
Comment: &max_id= does not work on https://www.instagram.com/salehmosleh/?__a=1&max_id=1569828694092266307 .
Comment: i never comment just for thanks, but man thanks. 1 upvote is not enough for you.
Answer: The Answer from Legionar was great but it is not working anymore. I had to update the code in my working Environment here is how it works for me:
function scrape_insta_hash($tag) {
  $insta_source = file_get_contents('https://www.instagram.com/explore/tags/'.$tag.'/'); // instagrame tag url
  $shards = explode('window._sharedData = ', $insta_source);
  $insta_json = explode(';</script>', $shards[1]);
  $insta_array = json_decode($insta_json[0], TRUE);
  return $insta_array; // this return a lot things print it and see what else you need
}

$tag = "my_hashtag";
$results_array = scrape_insta_hash($tag);

$limit = 18; // provide the limit thats important because one page only give some images then load more have to be clicked

for ($i=$limit; $i >= 0; $i--) {
  if(array_key_exists($i,$results_array['entry_data']['TagPage'][0]["graphql"]["hashtag"]["edge_hashtag_to_media"]["edges"])){
    $latest_array = $results_array['entry_data']['TagPage'][0]["graphql"]["hashtag"]["edge_hashtag_to_media"]["edges"][$i]["node"];

      $newPosting = [
        "image"=>$latest_array['display_url'],
        "thumbnail"=>$latest_array['thumbnail_src'],
        "instagram_id"=>$latest_array['id'],
        "caption"=>$latest_array['caption']['edge_media_to_caption']['edges'][0]["node"]["text"],
        "link"=>"https://www.instagram.com/p/".$latest_array['shortcode'],
        "date"=>$latest_array['taken_at_timestamp']
      ];

      echo "
";
      print_r($newPosting);
      echo "/
";

  }
}

You may need to change the "newPosting" array depending on what you need but at least for now you can get the instagram data with this method. Also there is more data inside $latest_array . Different image-sizes, comments and likes for example.
Comment: Can you expand a little bit more on $limit variable? Are you using it to limit the calls to the instagram servers?
Comment: Hey the $limit variable in this case does nothing important. We do one request  when calling: file_get_contents("..."), than we transform the result into an array we can work with.

Then we just go over the array until the "limit" is reached. I dont know how many posts are usually stored in such a request but normaly you want to show like the latest 15 images or so...
Answer: This one works for me perfectly.
I only needed the thumbnails. You can easily change it to full size image.
This example does not solve pagination, but you can do that from @ilyapt answer.
$tag = 'coronavirus';
$json = json_decode(file_get_contents("https://www.instagram.com/explore/tags/$tag/?__a=1", true));

$i = 0;
foreach($json->graphql->hashtag->edge_hashtag_to_media->edges as $key => $value) {
    $img = $value->node->thumbnail_resources[0]->src;
    echo "";
    if (++$i == 9) break; // limit to the 9 newest posts
}

Comment: Thanks, this works as of '20. Literally laughed at the tag choice.
Answer: @olaf answer worked great for me!
@Tomas The limit is the number of posts that will be returned by the function so that it doesn't return all of them.
Also: this function puts the Instagram posts in order from oldest to newest.  If you want the latest to be first and go backwards to the limit number:
Change
for ($i=$limit; $i >= 0; $i--)

to
for ($i=0; $i < $limit; $i++)


Why does $\alpha \|{x}\|_1 < \|{x}\|_2 < \beta \|{x}\|_1$ show equivalence of norms?

Question: I am reading a book on Hilbert space ("Introduction to Hilbert Space by Debnath and Mikusinski")  and I came across a proof for equivalence of norms that I do not understand. $E$ is a vector space and a non empty set, elements of $E$ are vectors. $\alpha,\beta$ are positive numbers and $x\in E$. Then:
$$\alpha \|{x}\|_1 < \|{x}\|_2 < \beta \|{x}\|_1. \tag{1}\label{first}$$
The proof starts off saying that this "clearly" implies the equivalence of norms $\|{\cdot}\|_1$ and $\|{\cdot}\|_2$:
Question 1: Why does $\ref{first}$  imply that $\|{\cdot}\|_1$ and $\|{\cdot}\|_2$ are equivalent?
Comment: How do you define the equivalence of two norms? E.g. for me, $1$ is actually the definition of equivalence
Comment: I think it is unfortunate that you've put a bounty on this question without answering the comment. Unfortunately, it is not possible to give you an honest answer without your definition of equivalence of norms.
Comment: I suppose one can explain the motivation for why equivalence of norms is defined that way (i.e. equivalent norms induce the same topology on the vector space), though that's not the question as stated.
Comment: $\lim_{x\rightarrow \infty}\| x_1 - x \| _1 = \lim_{x\rightarrow \infty}\|_2 - x \| _2$
Comment: It must be $\alpha \|{x}\|_1 \le  \|{x}\|_2 \le  \beta \|{x}\|_1.$ The strict inequality doesn't satisfy if $x=0.$ Anyway, as asked in other comments, can you say what do you understand by equivalence of norms?
Comment: This question deserves "unclear what you are asking" closing if not for the bounty.
Answer: I hope that this can help you:
For two norms $||·||_{1},||·||_{2}$ defined in a vectorial space $X$ the following two statements are equivalent:
i) $\exists \rho\in \mathbb{R}$ (constant) such that $||x||_{2}\le \rho ||x||_{1}$ $\forall x\in X$.
ii) The topology of $||·||_{2}$ is included of the topology of $||·||_{1}$.
Notation: $B_{i}(x,r)$ is the open ball of center $x\in X$ and radius $r>0$ with the norm $||· ||_{i}$, $i=1,2$
$i)\Rightarrow ii)$ If $U$ is an open set with the norm $||·||_{2}$ , for each $x\in U$ $\exists \epsilon>0$ such that $B_{2}(x,\epsilon)\subset U.$ From i) we deduce that $B_{1}(x,\epsilon / \rho) \subset B_{2}(x,\epsilon) \subset U$, then $U$ is an open set with the norm $||·||_{1}$ as we want.
$ii)\Rightarrow i)$ As $B_{2}(0,1)$ is open with $||·||_{2}$, it will be open with $||·||_{1}$ too, then exists $\delta >0$ such that $B_{1}(0,\delta)\subset B_{2}(0,1)$. Taking $\rho=1/\delta>0$ we have the inequality.
Indeed, if $x\in X$ verify that $||x||_{2}>\rho ||x||_{1}$, taking $y=x/||x||_{2}$ we have
$$||y||_{1}=\frac{||x||_{1}}{||x||_{2}}<\frac{1}{\rho}=\delta$$
Where $||y||_{2}<1$ , which is a contradiction, $||y||_{2}=1$ . So $||x||_{2}\le \rho ||x||_{1}$ $\forall x\in X$.
Then in the equivalence of norms you have both inequalities and both inclusions at the topologies.
Comment: I hate my life.
Comment: It could be worse.


How to mount Windows 2008 shared folder on SHMZ 6.6 (CentOS) client?

Question: We have a Windows Server 2008 with a shared folder. It is needed to mount this shared folder in SHMZ 6.6 Linux (FreePBX, CentOS).
I tried the "Even-better method" from https://wiki.centos.org/TipsAndTricks/WindowsShares - didn't work: when I try to cd to mounted folder - terminal freezes.
Tried mount.cifs - freezes right after the command is executed.
Tried connecting using smbclient - successfully connects, I am able to browse subfolders.
Please help to fix this.
Answer: Adding sec=ntlm,servern=SERVERNAME to mount options worked!


Decouple unit of work from services or repo

Question: I am trying to decouple my unit of work from my services or repository so that I wont have to touch the UoW code whenever I wish to add a new service. How do I do this?
_categoryService = _unitOfWork.Get<ICategoryService>();

so instead of
_unitOfWork.CategoryService.Add(category)

I can just say;
_categoryService.Add(category);

Comment: Can you elaborate more about your scenario? It seems to me that you are talking about injection of dependency (your code depends on ICategoryService and you want to inject it automatically), but it is not clear from your question.
Comment: Hi! I have an MVC4 test project to study the UoW pattern. I have a controller, a service class that references the repository. But as you can see I have this CategoryService in my UoW as a property. Then I realized that whenever I create a new service for something in the future I'd have to add this service to the UoW class I have. I am trying to find a way to just have a Get function that returns a service type based on what interface i passed to it. Im not even sure if this is the right way to go about this. Thanks!
Comment: What are you using for UoW container? You should use some of the IoC's, check this page for nice list: http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx Most of them have .Resolve() method, or similar, and you can register most of them as default dependency resolver in asp.net mvc, so you just add IService as parameter to your controller. Is this what are you asking?
Answer:
I am trying to decouple my unit of work from my services or
  repository so that I won't have to touch the UoW code whenever I wish
  to add a new service

Well, that's a good start!  ;-)
The solution I am presenting is not the one and only possible solution, there are several good ways to implement UoW (Google will help you out). But this should give you the big picture.
First, create 2 interfaces: IUnitOfWork and IRepository
public interface IUnitOfWork : System.IDisposable
{
  IRepository<TEntity> GetRepository<TEntity>() where TEntity : class;
  void Save();
}

public interface IRepository<T> : IDisposable where T : class
{
  void Add(T entity);
  void Delete(T entity);
  void Update(T entity);
  T GetById(long Id);
  IEnumerable<T> All();
  IEnumerable<T> AllReadOnly();
  IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
}

The implementations are quite straightforward (I removed all my comments for readability purpose, but do not forget to add yours  ;-) )
public class UnitOfWork<TContext> : IUnitOfWork where TContext : IDbContext, new()
{
  private readonly IDbContext _ctx;
  private Dictionary<Type, object> _repositories;
  private bool _disposed;

  public UnitOfWork()
  {
    _ctx            = new TContext();
    _repositories   = new Dictionary<Type, object>();
    _disposed       = false;
  }

  public IRepository<TEntity> GetRepository<TEntity>() where TEntity : class
  {
    if (_repositories.Keys.Contains(typeof(TEntity)))
      return _repositories[typeof(TEntity)] as IRepository<TEntity>;

    var repository = new Repository<TEntity>(_ctx);
    _repositories.Add(typeof(TEntity), repository);
    return repository;
  }

  public void Save()
  {
     try
     {
       _ctx.SaveChanges();
     }
     catch (DbUpdateConcurrencyException ex)
     {
       ex.Entries.First().Reload();
     }
  }

  …
}

public class Repository<T> : IRepository<T> where T : class
{
  private readonly IDbContext _context;
  private readonly IDbSet<T> _dbset;

  public Repository(IDbContext context)
  {
    _context = context;
    _dbset   = context.Set<T>();
  }

  public virtual void Add(T entity)
  {
    _dbset.Add(entity);
  }

  public virtual void Delete(T entity)
  {
    var entry = _context.Entry(entity);
    entry.State = EntityState.Deleted;
  }

  public virtual void Update(T entity)
  {
    var entry = _context.Entry(entity);
    _dbset.Attach(entity);
    entry.State = EntityState.Modified;
  }

  public virtual T GetById(long id)
  {
    return _dbset.Find(id);
  }

  public virtual IEnumerable<T> All()
  {
    return _dbset.ToList();
  }

  public virtual IEnumerable<T> AllReadOnly()
  {
    return _dbset.AsNoTracking().ToList();
  }

  public IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
  {
    return _dbset.Where(predicate);
  }

}

As you can see, both implementations make use of IDbContext interface. This interface is just for easy testing purpose:
public interface IDbContext
{
  DbSet<T> Set<T>() where T : class;
  DbEntityEntry<T> Entry<T>(T entity) where T : class;
  int SaveChanges();
  void Dispose();
}

(As you can see, I'm using EntityFramework Code First)
Now that the whole plumbing is set up, let's have a look at how this could be used in a service.
I have a base service that looks like this:
internal class Service<T> where T : class
{
  internal Service(Infrastructure.IUnitOfWork uow)
  {
    _repository = uow.GetRepository<T>();
  }

  protected Infrastructure.IRepository<T> Repository
  {
    get { return _repository; }
  }

  private readonly Infrastructure.IRepository<T> _repository;
}

And all my services inherit from this base service.
internal class CustomerService : Service<Model.Customer>
{
  internal CustomerService(Infrastructure.IUnitOfWork uow) : base(uow)
  {
  }

  internal void Add(Model.Customer customer)
  {
    Repository.Add(customer);
  }

  internal Model.Customer GetByID(int id)
  {
    return Repository.Find(c => c.CustomerId == id);
  }

}

And that's it!
Now, if you want to share the same UoW to several services, in a facade method or somewhere else, it could just look like this:
using (var uow = new UnitOfWork<CompanyContext>())
{
  var catService = new Services.CategoryService(uow);
  var custService = new Services.CustomerService(uow);

  var cat = new Model.Category { Name = catName };
  catService.Add(dep);

  custService.Add(new Model.Customer { Name = custName, Category = cat });

  uow.Save();
}

Hope this helps!
Comment: Thanks again!! I'll look those articles. One more question, in the method GetRepository of the UnitOfWork class you get new repositories by this line of code: "get var repository = new Repository(_ctx);". Is there a way to remove the reference to the Repository class so that it could be injected?? How could it be done? Or you have to explicitly tell your DI container to give you an instance for an IRepository type??
Comment: Sorry, I just got back from a very long vacation. I'll try this out. Thanks a lot!
Comment: Max, let me ask you a question. You defined Repository methods as virtual so you could override them. Where would you override them if you don't have any class that inherits from Repository (maybe I want a repository to delete in a particular way). I don't like the idea of extension methods but it's a way out. Would it be a way to work with classes that inherit from Repository (CustomerRepository for example) and override some methods and add new ones without the need of extension methods??
Comment: @snekkke Thanks for your feedback. Actually, you're right. Virtual is quite useless here. One way to customize things would be to add specific methods to your `services`. Adding that kind of methods could do the job: `internal Model.Customer  GetByExternalIdAndChannelAsReadOnly(string externalCode, ChannelId channel)
        {
            var cust = Repository.Find(c => c.ExternalCode == externalCode && c.ChannelId == (byte)channel).SingleOrDefault();
            return cust ;
        }`
Comment: Thanks Max, right now i'm trying to architect my app and i can´t find the architecture that makes me happy. I´m trying to use a service layer, unit of work, repositories, domain classes...but i can´t put all of them to work together....each time i added a new layer or new pattern i end up with something new (for example now i think i can't make any progress without a DI container)...do you have any thoughts on how could an acceptable architecture could be composed??
Comment: Well, it's quite impossible to decide or even advise you on what architecture to choose. The reason is that an architecture needs to address a business need. Without knowing your business I can't help you that much. What I can tell you, though, is to keep things simple. Start simple, then if needed, add some more abstraction and refactor. However, have a look at Jeffrey's Palermo Onion Architecture. I also answered to a lot of [SO Onion Architecture related questions](http://stackoverflow.com/search?tab=votes&q=user%3a1660523%20%5bonion-architecture%5d).


Evaluation of $\int_{0}^{1}\frac{x^4(1-x^2)^5}{(1+x^2)^{10}}dx$

Question:
Evaluation of $\displaystyle \int_{0}^{1}\frac{x^4(1-x^2)^5}{(1+x^2)^{10}}dx$

$\bf{My\; Try::}$ Let $$I = \int_{0}^{1}\frac{x^4(1-x^2)^5}{(1+x^2)^{10}}dx$$
Now Put $x=\tan \theta\;,$ Then $dx = \sec^2 \theta d\theta$ and changing limits, We get
$$I = \int_{0}^{\frac{\pi}{4}}\frac{\tan^4 \theta\cdot \left(1-\tan^2 \theta\right)^5}{(1+\tan^2\theta)^{10}}\cdot \sec^2 \theta d\theta = \int_{0}^{\frac{\pi}{4}}\sin^4 \theta\cdot \cos^4 \theta \left(\cos 2 \theta\right)^5 d\theta$$
So $$I = \frac{1}{16}\int_{0}^{\frac{\pi}{4}}(\sin 2\theta)^4\cdot (\cos 2 \theta)^4\cdot \cos 2 \theta d\theta$$
Now Put $\sin 2 \theta = t\;,$ Then $2\cos 2 \theta d\theta = dt$ and changing limits, We get
$$I = \frac{1}{64}\int_{0}^{1}t^4(1-t^2)^2 dt$$
Now after expanding , We can integrate it,
My question is can we solve it any other way, If yes then plz explain here
Thanks
Comment: If it's any help, you can try partial fractions; the integrand can be written as

$$-144\, \left( {x}^{2}+1 \right) ^{-9}+272\, \left( {x}^{2}+1 \right) ^
{-8}- \left( {x}^{2}+1 \right) ^{-3}+32\, \left( {x}^{2}+1 \right) ^{-
10}+170\, \left( {x}^{2}+1 \right) ^{-6}-61\, \left( {x}^{2}+1
 \right) ^{-5}+12\, \left( {x}^{2}+1 \right) ^{-4}-280\, \left( {x}^{2
}+1 \right) ^{-7}$$
Comment: $$\sin^22\theta=u$$ will make things a little easier
Comment: The only other way is partial fraction but it is a pain in the butt.
Comment: Juan, there was an error in arriving at the last integral in the OP.  The factor outside the integral should be $\frac{1}{32}$, not $\frac{1}{64}$.  Now, I posted a solution that begins there and uses the Beta and Gamma functions to quickly arrive at a solution.  -Mark
Comment: The change of variables $t=\frac{2x}{1+x^2}$.
Answer:
There was a small error in the development in the OP.  The integral $I$ should be $$I=\frac{1}{32}\int_0^1 t^4(1-t^2)^2\,dt$$

We can evaluate the integral of interest in terms of the Beta function, $$B(x,y)=\int_0^1 t^{x-1}(1-t)^{y-1}\,dt$$and its relationship to the Gamma function, $$B (x,y)=\frac{\Gamma(x)\Gamma(y)}{\Gamma(x+y)}$$
Note that
$$\begin{align}
I&=\frac{1}{32}\int_0^1 t^4(1-t^2)^2\,dt\\\\
&=\frac{1}{64}\int_0^1 t^{3/2}(1-t)^2 \,dt\,\,\dots\text{enforcing the substitution}\,\,t\to \sqrt{t}\\\\
&=\frac{1}{64}B(5/2,3)\\\\
&=\frac{1}{64}\frac{\Gamma(5/2)\Gamma(3)}{\Gamma(11/2)}\\\\
&=\frac{1}{64}\frac{\left(3\frac{\sqrt{\pi}}{4}\right)\,(2!)}{945\frac{\sqrt{\pi}}{32}}\\\\
&=\frac{1}{1260}
\end{align}$$
Comment: Juan, there was an error in arriving at the last integral in the OP.  The factor outside the integral should be $\frac{1}{32}$, not $\frac{1}{64}$.  Now, I posted a solution that begins there and uses the Beta and Gamma functions to quickly arrive at a solution.  -Mark
Answer: $$\begin{align*}
& \int_0^1 \frac{x^4(1-x^2)^5}{(1+x^2)^{10}} \, dx \\
&= \int_0^1 \frac{\frac{(1-y)^2}{(1+y)^2} \left(1-\frac{1-y}{1+y}\right)^5}{\left(1+\frac{1-y}{1+y}\right)^{10}} \, \sqrt{\frac{1+y}{1-y}} \frac{dy}{(1+y)^2} \tag1 \\
&= -\frac1{32} \int_0^1 y^5 \left(1-y^2\right)^{3/2} \, dy \\
&= \frac1{32} \int_0^1 (1-z)^{5/2} z^{3/2} \, \frac{dz}{2(1-z)^{1/2}} \tag2 \\
&= \frac1{64} \int_0^1 (1-z)^2 z^{3/2} \, dz \\
&= \frac1{64} \int_0^1 \left(z^{3/2} - 2z^{5/2} + z^{7/2}\right) \, dz \\
&= \frac1{64} \left(\frac25 - \frac47 + \frac29\right) = \boxed{\frac1{1260}}
\end{align*}$$

$(1)$ : substitute $x=\sqrt{\dfrac{1-y}{1+y}}$
$(2)$ : substitute $y=\sqrt{1-z}$


python: simple dbus example- os.fork() in service routine?

Question: I am trying to write dbus server where I want to run some external shell program (grep here) to do the job.
when I do:
prompt$ server.py
then:
prompt$ client.py # works fine, ie. runs grep command in child process.
prompt$ client.py # ..., but second invocation produces following error message:
DBusException: org.freedesktop.DBus.Error.ServiceUnknown: The name org.example.ExampleService was not provided by any .service files
I am stuck. Are You able to help me?
here is server.py (client.py thereafter):
import gtk, glib
import os
import dbus
import dbus.service
import dbus.mainloop.glib
import subprocess

messages_queue=list()
grep_pid=0

def queue_msg(message):
    global messages_queue
    messages_queue.append(message)
    return

def dequeue_msg():
    global messages_queue,grep_pid
    if grep_pid != 0:
        try:
            pid=os.waitpid(grep_pid,os.P_NOWAIT)
        except:
            return True
        if pid[0] == 0:
            return True
        grep_pid=0

    if len(messages_queue) == 0:
            return True
    else:
            tekst=messages_queue.pop(0)

        cmd="grep 'pp'"

        print cmd
        #works fine, when I do return here
        #return True

    grep_pid=os.fork()
    if grep_pid != 0:
        return True
    os.setpgid(0,0)
    pop=subprocess.Popen(cmd,shell=True,stdin=subprocess.PIPE)
    pop.stdin.write(tekst)
    pop.stdin.close()
    pop.wait()
    exit(0)

class DemoException(dbus.DBusException):
    _dbus_error_name = 'org.example.Exception'

class MyServer(dbus.service.Object):

    @dbus.service.method("org.example.ExampleInterface",
                         in_signature='', out_signature='')
    def QueueMsg(self):
            queue_msg("ppppp")

    @dbus.service.method("org.example.ExampleInterface",
                         in_signature='', out_signature='')
    def Exit(self):
        mainloop.quit()

from dbus.mainloop.glib import threads_init

if __name__ == '__main__':
        glib.threads_init()

        threads_init()

        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

        session_bus = dbus.SessionBus()
        name = dbus.service.BusName("org.example.ExampleService", session_bus)
        object = MyServer(session_bus, '/My')

        glib.timeout_add_seconds(1, dequeue_msg)
        mainloop = glib.MainLoop()
        print "Running example service."
        mainloop.run()

now client.py:
import sys
from traceback import print_exc
import dbus

def main():
    bus = dbus.SessionBus()

    try:
        remote_object = bus.get_object("org.example.ExampleService",
                                       "/My")

    except dbus.DBusException:
        print_exc()
        sys.exit(1)

    iface = dbus.Interface(remote_object, "org.example.ExampleInterface")

    iface.QueueMsg()

    if sys.argv[1:] == ['--exit-service']:
        iface.Exit()

if __name__ == '__main__':
    main()

Comment: I've been researching how to integrate an application with dbus-python and came across your post.  There is a section in this [link](http://developer.gnome.org/glib/2.31/glib-The-Main-Event-Loop.html) if you scroll down a little, called 'Customizing the main loop iteration'. Its about customizing the glib mainloop ;) and how it is incompatible with `fork` on *nix systems.
Answer: You usually get this error message when you try to access a service that is no longer available. Check if your server is still running.
You can use d-feet to debug your dbus connections.
Answer: The error message about the missing .service file means that you need to create a service file in dbus-1/services.
For example:
# /usr/local/share/dbus-1/services/org.example.ExampleService.service
[D-BUS Service]
Name=org.example.ExampleService
Exec=/home/user1401567/service.py

A lot of tutorials don't include this detail (maybe .service files didn't use to be required?)  But, at least on Ubuntu 12.04, dbus services can't be connected to without it.
Comment: could you please add some tutorial resource? I cannot find it via web search (my bad i guess). It used to work for me without any of these .service files but now suddenly stopped working - not sure why. (or perhaps even better, provide me with the right search keyword, so next time i will have more success searching :)?)


Residues of $ \frac{z^4}{1+z^6} $

Question: I am trying to compute all 6 the residues of $ \frac{z^4}{1+z^6} $. I tried the straightforward way first of finding all the points where the denominator is 0 etc but it became way too complicated. Any ideas?
Comment: the denominator is zero when $z$ is a sixth root of $-1$
Comment: I know, I found all these points, but finding the residues based on that using the methods I tried was too complicated.
Comment: Have you tried "If $g$ has a simple zero at $z_0$, then $\operatorname{Res}\bigl( \frac{f}{g}; z_0\bigr) = \frac{f(z_0)}{g'(z_0)}$"? (Where of course $f$ and $g$ are supposed to be holomorphic at $z_0$.)
Comment: Oh jesus I just now realized the zeros are all simple! For some reason I had convinced myself they were all of order 6 and I couldn't shake it off... This is what happens when you've been solving complex analysis for 6 hours straight... Thanks for helping point me to the right direction!
Answer: Let $a$ be a pole of $f(z)=z^4/(z^6+1)$. Then $a^6=-1$. Also $a$ is a simple pole.
The residue is thus
$$\lim_{z\to a}(z-a)f(z)=\lim_{z\to a}\frac{z^4(z-a)}{z^6-a^6}
=\frac{a^4}{\lim_{z\to a}\frac{z^6-a^6}{z-a}}.$$
But
$$\lim_{z\to a}\frac{z^6-a^6}{z-a}=g'(a)$$
when $g(z)=z^6$ etc.
Comment: Hmmm alright, but the sum of all the residues is then 0, right? The reason this is concerning to me is that I am using it to calculate an integral that shouldn't be 0.
Comment: Sorry, I'm dumb, I was using the wrong formula, nothing concerning, thanks!
Answer: $z^6 + 1$ has roots $e^{\frac {(2k+1)\pi }{6}i}$
We might factor the denominator like this.
$(z-e^{\frac {\pi}{6} i})(z^5 + z^4e^{\frac {\pi}{6}i} + z^3e^{\frac {2\pi}{6}i} + z^2e^{\frac {3\pi}{6}i} + ze^{\frac {4\pi}{6}i} + e^{\frac {5\pi}{6}i})$
$\lim_\limits{z\to  e^{\frac {\pi}{6}i}} \frac {z^4}{z^6+1} (z-e^{\frac {\pi}{6}i}) = \lim_\limits{z\to  e^{\frac {\pi}{6}i}} \frac {z^4}{(z^5 + z^4e^{\frac {\pi}{6}i} + z^3e^{\frac {2\pi}{6}i} + z^2e^{\frac {3\pi}{6}i} + ze^{\frac {4\pi}{6}i} + e^{\frac {5\pi}{6}i})}$
As $z$ approaches $e^{\frac {pi}{6} i},$ each term in the denominator approaches $e^{\frac {5\pi}{6}i}$
$\lim_\limits{z\to  e^{\frac {\pi}{6}i}} \frac {z^4}{z^6+1} (z-e^{\frac {\pi}{6}i})=\frac {e^{\frac {4\pi}{6} i}}{6e^{\frac {5\pi}{6}i}} = \frac {e^{-\frac {\pi}{6}i}}{6}$
Now that we have one residue, the rest get easier.  To find the residue at $e^{\frac {3\pi}{6}i}$ we can quickly jump through the algebra above to
$\lim_\limits{z\to  e^{\frac {3\pi}{6}i}} \frac {z^4}{z^6+1} (z-e^{\frac {3\pi}{6}i}) = \frac {e^{\frac {12\pi}{6}i}}{6e^{\frac {15\pi}{6} i}} = \frac {e^{-\frac {3\pi}{6}i}}{6}$
And the pattern becomes more obvious.  The rest of the residues are:
$\frac {e^{-\frac {5\pi}{6}i}}{6}, \frac {e^{-\frac {7\pi}{6}i}}{6},\frac {e^{-\frac {9\pi}{6}i}}{6}, \frac {e^{-\frac {11\pi}{6}i}}{6}$
Comment: That is what I tried to do at first but there is a simpler way, which is to simply use the formula someone mentioned in the comments beneath my post.
Comment: It is a worthwhile exercise.  Once you have done it once or twice, you start to see the patterns.

Residues of $ \frac{z^4}{1+z^6} $


Why can I state $ \left| 3-y \right|=e^{ -4t }$ iff $3-y=e^{ -4t } $?

Question: I have this differential equation problem.
$$ \frac { dy }{ dt } =\quad 12-4y,\quad y\left( 0 \right) \quad =\quad 0 $$
Walking through my steps.
$$ \frac { dy }{ dt } =\quad -4\left( y-3 \right) \\ \frac { 1 }{ \left( y-3 \right)  } dy\quad =\quad -4dt\\ \int { \frac { 1 }{ \left( y-3 \right)  } dy } \quad =\quad -\int { 4dt } \\ \ln { \left( \left| 3-y \right|  \right)  } \quad =\quad -4t+c\\ { e }^{ \ln { \left( \left| 3-y \right|  \right)  }  }=\quad { e }^{ -4t }+c\\ \left| 3-y \right| \quad =\quad { e }^{ -4t }+c $$
Now my teacher has stated that we can assume the LHS is always going to be positive. She attempted to explain this to me but I was unable to understand  the proof/logic behind  stating the following two steps
$$
\left| 3-y \right| \quad =\quad { e }^{ -4t } +c\\ \quad 3-y\quad =\quad { e }^{ -4t }+c
$$
How can I show that $$ { e }^{ -4t } $$ is always positive?
Comment: The equivalence is false since it is possible that $3-y=-e^{-4t}$.
Comment: Right. That is my question. How can I show, that?
Comment: There are a lot of errors in your work. Maybe they have something to do with your issue. The problems are in factoring out $-4$ and simplifying $e^{-ln|3-y|}$.
Comment: You missed the constant of integration. This gives $3 - y(t) = Ae^{-4t} $$ for some $A \neq 0$.
Comment: There are several mistakes still in your work. I will try to make my answer below more inclusive.
Answer: When you integrate $-4dt$ you should get
\begin{equation}
-\ln(|3-y|) = -4t + A_1
\end{equation}
where $C$ is an unknown constant. So your solution should be $|3 - y| = A_2e^{-4t}$ where $A_2 = e^{A_1}$. Therefore $3 - y = \pm A_2 e^{-4t}$ and we can just absorb $\pm$ into the constant $A_2$ and write $y = 3 + Ae^{-4t}$. The conclusion is you should get more than one solution for your ODE. Why is that? Because an ODE doesn't give a unique solution unless you have an initial condition $y(0) = $ something. Once an initial condition is known you can solve for $A$.
EDIT: Since $y(0) = 0$ we should have $A = -3$ ie. $y = 3 - 3e^{-4t}$.
Comment: updated my question. Thanks for your feedback.
Answer: Given $\dfrac{dy}{dt}=12-4y=4(3-y),\quad y(0)=0$.
$$\int\dfrac{1}{3-y}\,dy=\int4\,dt$$
$$-\ln\vert 3-y\vert=4t-c_0$$
$$ \ln\vert 3-y\vert=c_0-4t $$
$$ \vert3-y\vert=e^{c_0}e^{-4t}=c_1e^{-4t} $$
$$3-y = \pm c_1{ e }^{ -4t }=ce^{-4t}$$
$$ y=3-ce^{-4t}$$
is the solution
$y(0)=3-c\cdot1=0$ so $c=3$. Therefore $y(t)=3-3e^{-4t}$.
Comment: Just factored out a -4, you can multiply it back in to get the same expression.
Comment: No, when you multiply it out you get $-12+4y$ not $12-4y$.
Comment: sorry those were errors. in my latex


On alternative training in case you can not practice a violin for a long time

Question: On alternative training in case you can not practice a violin for a long time?
I have been playing the violin for about 25 years.
I am doing it as a hobby, but I play it at least once every two days on weekdays.
This time, overseas business trips for one year are decided, during that time you will not be able to practice at all.
(It is impossible to play in a business trip destination)
I think that my arm will fall considerably if I do not touch musical instruments for a year as expected.
I'm not want to degradation of performance technique as much as possible, what are the workarounds?
I am considering muscular strength training by its own weight so as not to drop the minimum necessary muscle strength.
Please tell me if you have any other ideas.
Comment: If all else fails and you cannot physically practice to stay in shape, then consider ear training: It can be done with a smartphone and earphones.  It won't keep you physically in form, but at least it's musical learning.
Answer: You haven't explained why you can't play while you're on the trip, but I'll assume it's because it will be too loud.
If that's the case, consider a "silent" electric violin. The concept is the same as the electric guitar: minimal acoustic sound is amplified by electronic pickups. For performances, it is played through an amplifier/speaker system, but you can get a very small portable amplifier for your electric violin (there are many such devices for guitar, they would probably work just as well for violin) and play through headphones. I used to practice electric bass that way when I went to visit relatives:
Here are some informative videos about silent electric violins - there is plenty of material out there:

Here's what they call a "plug amp", designed for guitar. (I have one for bass):
Vox amPlug 2 Clean Headphone Guitar Amp
Answer: When I can't play, I keep my hands and arms in shape by using a medium sized soft rubber ball. I squeeze it repeatedly until my hand feels strained, and then change hands and do it again. That takes care of the hands. Musically I can look at the music and imagine myself actually performing the piece as I read the music, this goes a long way towards keeping the music fresh in my mind. When you think about it, you see that is what you're doing when you are actually playing your fiddle.


MVC c# List from string in ViewBag

Question: I am retrieving a string from a MS Sql table, it could be just one name or delimited names:  For example Tom or Speaker 1, Speaker 2.
I convert the string to list in the controller using:
                    Event cevent = db.Events.Find(id);
                    string speakers = cevent.Speakers;
                    ViewBag.speakers = "";
                    if (!String.IsNullOrWhiteSpace(speakers) &&
                    speakers.Contains(","))
                    {
                        ViewBag.speakers = speakers.Split(',').ToList();
                    }
                    else
                    {
                        ViewBag.speakers = speakers;
                    }
                    return View(cevent);

In the view I use the following to display the list:

            @foreach (var item in ViewBag.speakers)
            {

 @item

            }

Works great with the list, I get:
• Speaker 1
• Speaker 2

However, if the ViewBag has just one item, I get:
• T
• o
• m

Comment: var list=ViewBag.speakers as List(); and check if the list.count >0 use foreach else bind the normal item
Comment: or you can modify string to list, so no need of further process in view.  if speakers as a string then,  List obj1 = new List();
            obj1.Add(speakers); ViewBag.speakers = obj1 ;
Answer: You might consider always passing an enumerable speaker object to the view regardless of whether or not there are one or more than one speaker.
In your view, you are enumerating over the speakers object, which, in the case of the "Tom", is a list of chars. You might try something like this, instead:
In the controller:
ViewBag.speakers = new List<string>();
string speakers = cevent.Speakers;
var listOfSpeakers = speakers.Split(',').ToList();

foreach (var speaker in listOfSpeakers)
{
    ViewBag.speakers.Add(speaker)
}

If you need to format the HTML output differently depending on whether more than one speaker is passed to the view, you can use if(ViewBag.speakers.Count > 1) on the speaker list in a conditional block and handle the output differently in that case.
Comment: I get error 'string' does not contain a definition for 'Count'
Comment: @hncl Yes, you can only call count on an enumerable object. You may want to always pass a list to the view, even if it only contains one element. I have edited to suggest changes to controller.
Comment: I should clarify, .Count() is a LINQ extension method, and works on IEnumerable types, but .Count is a property and part of the List object itself.
Comment: thank you.  I got this error in the controller:
System.Collections.Generic.List' does not contain a definition for 'add'
Comment: .Add() with capital A.

MVC c# List from string in ViewBag


Closed immersions and complete linear systems

Question: Let $X$ be a local complete intersection subscheme in $\mathbb{p}^n$ for some integer $n>0$. Denote by $i:X \to \mathbb{P}^n$ the induced closed immersion, $\mathcal{O}_X(1):=i^*\mathcal{O}_{\mathbb{P}^n}(1)$ and $N:=h^0(\mathcal{O}_X(1))$. Does there exist a closed immersion of $X$ into $\mathbb{P}^N$ via the complete linear system $H^0(\mathcal{O}_X(1))$, which factors through $i$?
Answer: I always get confused about what the phrase "factors through" means, so let me describe the setup and you can decide if this is what you wanted or the opposite.
We have an exact sequence of sheaves on $\mathbf P^n$ of the form
$$ 0 \rightarrow I_X(1) \rightarrow O_{\mathbf P^n} (1) \rightarrow O_X(1) \rightarrow 0 $$
where $I_X$ is the ideal sheaf of $X$. Let's assume $X$ isn't contained in a hyperplane. (If it is, replace $n$ by $n-1$ and repeat). Then the first sheaf has no global sections, so taking cohomology above we get the exact sequence
$$ 0 \rightarrow H^0 (O_{\mathbf P^n} (1)) \rightarrow H^0(O_X(1)) \rightarrow H^1(I_X(1))$$
So $H^0 (O_{\mathbf P^n} (1))$ is a subspace of $H^0(O_X(1))$.
Suppose we choose a basis $\{s_0,\ldots, s_N\}$ for $H^0(O_X(1))$ such that $\{s_0,\ldots, s_n\}$ is the standard coordinate basis for $H^0 (O_{\mathbf P^n} (1))$. Then the immersion $X \rightarrow \mathbf P^N$ you want is given simply by $x \mapsto [s_0(x), \ldots, s_N(x)]$, while your given map $i: X \rightarrow \mathbf P^n$ is just$x \mapsto [s_0(x), \ldots, s_n(x)]$.
So there is a diagram
$$X \rightarrow \mathbf P^N \dashrightarrow^\pi \mathbf P^n$$
where $\pi$ is projection away from a linear subspace (or if you like, forgetting the last $N-n+1$ coordinates) and the composite is equal as a rational map to $i$.
To me this situation would be described as saying that $i$ factors through the new immersion, rather than the other way around.
Remark: You might wonder if I'm making a mountain out of a molehill here, but I claim I am not: there are indeed subvarieties $X \subset \mathbf P^n$ for which $H^1(I_X(1)$ is nonzero, and so the factorisation is nontrivial. Indeed, the property that $H^1(I_X(1)=0$ is interesting enough to get its own name: such an $X$ is called linearly normal. Searching this site for that phrase will give examples of subvarieties which fail to be linearly normal.
Comment: @Dubh: Thank you very much for the answer. It is very helpful. However, by factoring through, I think I meant something a little different. I question was: does there exist a closed immersion $i_0$ of $X$ into $\mathbb{P}^N$ such that there exists a $j:\mathbb{P}^n \to \mathbb{P}^N$ for which $i_0=j \circ i$.


Weierstrass theorem and compactness

Question: On my book the statement of Weierstrass theorem is: If $f$ is a continuous function $f:A\subseteq X\rightarrow \mathbb{R}$ defined on a compact set $C$, where $A$ is the domain of $f$ and $X$ is a metric space, then argmax$f$ and argmin$f$ are non-empty and compact sets.
I have a couple of proof to demonstrate that argmin and argmax are nonempty but I cannot understand why they are also compact sets.
Have you any hint/proof to see that?
Comment: A point is a closed set. Also you have that $f$ is continous and $C$ compact. By the way what is $A$?
Comment: I added the info you need. I've forgotten to describe the sets
Comment: When $A$ is the domain of $f$ and $f$ is defined on the compact set $C$, what's the difference between $A$ and $C$?
Comment: Since it is in the chapter about optimization, I think that $C$ has to be interpreted as the constraint in a constrained optimization problem, whereas $A$ is the domain of the function.
Answer:
Argmin$(f)$ and Argmax$(f)$ are closed (continuous preimages of point sets, which are closed).
Argmin$(f)$ and Argmax$(f)$ are subsets of $C$.
$C$ is compact
Closed subsets of compact sets are compact. (x)

Thus, Argmin$(f)$ and Argmax$(f)$ are compact.

Weierstrass theorem and compactness


Como centralizar layout

Question: Quero centralizar esse panel, mesmo quando a tela for maximizada, quero que ele continue centralizado. E não como está.
Comment: use as propriedades Achor. Se quiser que ele aumente de acordo com o form, deixe todas marcadas, caso contrario desmarque todas
Comment: Eu não quero que aumente, quero que permaneça centralizado e do mesmo tamanho.
Comment: por isso o "caso contrário, desmarque todas." Como o colega respondeu abaixo, deixe como 'none'
Comment: De certo! Muito obrigado!
Answer: Nas propriedades do elemento, você irá localizar a opção Layout e definir o Anchor para None.
Comment: Deu certo! Muito Obrigado!
Answer: você tbm pode fazer via código:
Sabendo que o centro do Contêiner localiza-se na metade de sua largura .Width / 2 e na metade da sua altura .Heigth / 2
controle.Top = (Contêiner.Heigth / 2) - (controle.Heigth - 2);
controle.Left = (Contêiner.Width / 2) - (controle.width - 2);
Obs.: o Contêiner nada mais é, que seu recipiente.

Como centralizar layout


Whether limit of a function exists

Question: Let $f:[0,\infty) \rightarrow \mathbb R$ be a function such that for any positive $a$ the sequence $f(an)$ converges to zero.Does the limit $lim_{x\rightarrow \infty} f(x)$ exist?
My problem is should I look for a counter example or try to prove it in which I have not succeeded till now.
Comment: Did you forget to include the condition that $f$ is continuous? If this is not a requirement, then the statement is false (define $f(\sqrt{p})=1$ for any prime number $p$, $f(x)=0$ otherwise).
Comment: Generally, if you are unsure if something is true, you should spend half your time trying to prove it, and the other half trying to disprove it. Eventually you will succeed.
Answer: When you add the condition that $f$ also be continuous, it turns out to that $f(x)\to0$. Here is a sketch of the proof.
Suppose $\lim_{x\to\infty}f(x)\neq 0$. Then there will be some $\epsilon>0$ and a sequence of points $x_k\to\infty$ for which $f(x_k)>2\epsilon$. Since $f$ is continuous, there is a closed interval $I_k$ around each point where $f(x)>\epsilon$ for $x\in I_k$.
For any $E\subset \mathbb{R}$, $c\in\mathbb{R}$, let $c\cdot E$ denote $\{cx\,|\,x\in E\}$.
Let $E_0=[0,1]$. Define a sequence of closed intervals $E_n$ for $n\ge1$ recursively as follows: choose some integer $m$ large enough so that, for some $k$, $(m\cdot E_{n-1})\cap I_k$ is a nontrivial closed interval (not just a point). You can show such an $m$ exists. Then, for that $k$, define $E_n=\frac1m\cdot(  (m\cdot E_{n-1})\cap I_k)$. You may have to also insist if you use $I_k$ you choose for $E_n$ was not used for any previous $E_m$.
Since the $E_n$ are nested closed intervals, their intersection is nonempty. You can then show that, for any point $e$ in their intersection, the sequence $f(e),f(2e),f(3e)\dots$ will not approach zero, since the sequence $e,2e,3e\dots$ will hit infinitely many intervals $I_k$.
Answer: I don't believe this is true.
Let $\{x_n\}$ be a sequence of distinct real numbers greater than 1 which are not multiples of each other and let $f(x_i*n) = 1$ if $i \le n$ and $f(x_i*n) = 0$ if $i \gt n$. Now suppose there was an $L$ such that $|f(x)| < \epsilon$ if $x > L$, this is not possible because for any $L$ we would have some $x_i*n \gt L$ where $f(x) = 1$.
Comment: err, is this even continuous?
Comment: Does it have to be?
Comment: for some reason I thought it had to be, I guess not

Whether limit of a function exists


A priori publication of statistical analysis plan (SAP) for clinical trials

Question: This is somewhat of a regulatory question, rather than statistical question. But I assume that the readership of this community will be the most knowledgeable on this matter.
Question:
Is there any regulatory agency that actually documents submission of a statistical analysis plan (SAP) for clinical trials prior to the final clinical database lock and treatment unblinding?
What surprised me a bit is that there appears to be no obligation to actually submit a statistical analysis plan a priori. Could someone please tell me that I am incorrect about this and that a priori SAPs are always available to the public?
Here are some examples of rather vague suggestions:
ICH E9 Statistical Principles for Clinical Trials:
"The plan should be reviewed and possibly updated as a result of the blind review of the data and should be finalised before breaking the blind."
U.S. FDA, Guidance for Industry Developing Medical Imaging Drug and Biological Products, June 2004:
"We recommend that sponsors [...] submitted to the protocol before images have been collected."
Specific Background:
Recently, a "positive" phase III trial result has been published for a disease in my area of expertise. However, the are several "red flags" in my opinion:

Actual results are not reported
Only mixed model for repeated measures (MMRM) estimates were reported, but it is rather unclear what co-variates were used for "adjustment" in the model [on clinicaltrials.gov, there is no mentioning of "adjustment" for co-variates]
The outcome variable was transformed [on clinicaltrials.gov, there is mentioning of transformation of the outcome variable]

Having worked on natural history data for this disease before, it is obvious that one can easily find "significant" between-group differences by iterating across combinations of outcome transformations (no transformation, sqrt, log10) and co-variates combinations (age, gender, baseline lesion size). For obvious reasons, I suspected that a statistical analysis plan must be deposited somewhere a priori. However, the specific study did not publish the statistical analysis plan on clinicaltrials.gov.
Comment: It may make a difference whether you're asking about established tradition or recent practice. // Recently, IMHO in the US and elsewhere, a combination of factors has led to some departures from traditional standards of governmental oversight of clinical trials, and of premature announcements of claimed results that have not been peer reviewed. // As for Covid vaccines, I recently got my first shot and scheduled my 2nd anyhow.
Comment: Thank you for the response. Would you have some more specific information regarding "legal documents"? (For the COVID trials BTW, information on the data and SAPs appears to be given [e.g., https://clinicaltrials.gov/ct2/show/NCT04368728], so this is not so much my concern.)
Answer: Focusing on Phase 3 studies only:

SAPs are submitted to regulatory authorities along with the the protocol, informed consent documents, letters of intent, etc. etc. etc. for approval prior to the first patient initiated. The regulatory authorities may reject the submission if the SAP is not clearly aligned with the objectives.

SAPs may be made publicly available after the database lock or publication of top-line results. There are many examples on clinicaltrials.gov.

When submitting the CSR for regulatory approval by the respective agencies in accord with the ICH E9 guidance, the SAP is a controlled document meaning the cumulative revision history and the timeline are kept, and should match with the protocol. You cannot modify the SAP after database lock (OK you can but it's 99.9% likely to result in a rejection). If any aspect of the CSR is not in alignment with the SAP it is a major finding.

It makes sense that the number of examples are relatively few. The authorities are hesitant to mandate that SAPs (or protocols even) are made publicly available. This is because the authorities are perceived as an immense hurdle in the drug approval process - a necessary one at that. I believe the authorities feel that if "successful" (meaning led to approval) study examples were too widely circulated, others would so closely copy the template they would fail to ever present or challenge new ideas, even when necessary. Indeed, you often hear that the FDA "won't approve a drug without a blinded controlled study" or "hates R and loves SAS" or "doesn't approve Bayesian trial designs but only frequentist". The opposite is true. But these new ideas need to be defensible to a number of highly experienced, cross-functional, and educated agents.
Comment: Thank you very much for this helpful response. Just to understand: If I still have the suspicion that an analysis was designed to benefit from vibration effects (through vagueness regarding variable transformations and co-variates) and authors responded to an email of me that the SAP can not be shared due to IP issues, what would be the next steps?  (1.) forget about it, because U.S. FDA and EMA are well functioning, or (2.) letter to the editor regarding the journal article to highlight the vague aspects of the Methods section, (3.) something else


PHP mPDF problemas com código de barras

Question: Eu recebo uma URL de um boleto gerado em ASP, uso a classe mPDF para enviar esse boleto pro servidor, recupero o boleto gerado e envio por e-mail com PHPMailer. O que acontece é que no gmail o código de barras do boleto está diferente de quando eu acesso diretamente pela URL
SEGUE UM EXEMPLO DO CÓDIGO DE BARRAS DO BOLETO EM ASP

CÓDIGO DE BARRAS DO BOLETO GERADO COM mPDF

esses são os mesmos boletos, porém com código de barras diferente. Segue um exemplo do código onde eu gero o boleto com mPDF:
<code>$location = '/usr/local/se/web/wwwroot/temp/';

$url = file_get_contents($path);

$mpdf = new \Mpdf\Mpdf(['mode' => 'utf-8', 'format' => 'A4', [197, 296]]);
$mpdf->allow_charset_conversion = true;
$mpdf->SetDisplayMode('fullpage');
$mpdf->writeHTML($url);

ob_clean();

$pathArchive = $location . createRandomOID() . '.pdf';

$mpdf->Output($pathArchive);

return $pathArchive;
</code>
alguma dica de como posso resolver? Já li a documentação do mPDF e nada resolveu.
Answer: RESOLVIDO
eu resolvi com a função str_replace do PHP, alterei a largura dos pixels do código de barras, dessa forma:
$url = file_get_contents($path);
<code>//troca os pixels de largura do código de barras do boleto
$new_url = str_replace(array('img src=http://boletos.schulze.com.br/p.gif width=1 height=50 border=0','img src=http://boletos.schulze.com.br/b.gif width=1 height=50 border=0'), array('img src=http://boletos.schulze.com.br/p.gif width=1.5 height=50 border=0','img src=http://boletos.schulze.com.br/b.gif width=1.5 height=50 border=0'), $url);
</code>
e assim o arquivo PDF foi anexado com todas as barras no email.

PHP mPDF problemas com código de barras


What is the best way to forward visitors to my homepage to an external site but leave the backlinks accessible?

Question: Maybe not distinctly a Drupal question, I have an older Drupal 7 site that I want to leave up for backlinks, but any new visitors I want to redirect to a new external website.  So domain.com would redirect to newdomain.com but domain.com/node/6 is still accessible.
Update: Server is nginx and I don't have access to server settings and routes.
Comment: Sounds potentially like an htaccess rule. You could write one that matches the domain directly, and that should allow non-homepage URLs to keep working. Maybe something like this in your .htaccess file: https://stackoverflow.com/questions/42493408/redirect-root-but-not-subfolders this should redirect any home request to the new domain, but anything not matching should continue to work. It _might_ need a little massaging for Drupal, but I don't have a way to test this out at the moment. Initial tests here tell me it will work. https://htaccess.madewithlove.be/
Comment: Sorry, updated the question it is an nginx server and I don't have access to the nginx routes/settings files.
Answer: It sounds like one thing you could do is edit the themes template.php file and do something like:
/**
 * Implements template_preprocess_html().
 */
function mytheme_preprocess_html(&$variables) {
  if (drupal_is_front_page()) {
    $url = 'http://newdomain.com';
    drupal_goto($url, ['external' => TRUE], 301);
    // perhaps alternatively you could use header();
  }
}

Outside of doing this at the web server level, it might be the smallest change to do it.


In the Bash prompt, why does Control+x and Backspace clear the current line?

Question: I discovered this by mistake: Control+x followed by Backspace
Does anyone know why this clears the line? Any documentation?
Answer: Yes. From man bash:

   Killing and Yanking
       kill-line (C-k)
              Kill the text from point to the end of the line.
       backward-kill-line (C-x Rubout)
              Kill backward to the beginning of the line.

Answer: This is the equivalent of a cut in Windows. You can paste it back with Ctrl+Y.
Comment: It's actually the magic of readline.
Comment: I didn't even know that Bash has clipboard-like functionality! Nice to know!
Comment: True but the end result is about the same.
Comment: @timbrigham: Yes, but it means that it also works in other programs using readline, and for those that don't, you might be able to use `rlwrap`.
Answer: As noted, it is in the man page. More precisely, the key-combinations in question are from EMACS, which is the default key-binding for Bash in a number of Linux distributions. If you need to use vi instead under Bash, you can use:
set -o vi

To switch it back to EMACS:
set -o emacs

Answer: bash supports something called the readline library, which allows you to do a completely amazing number of things with your shell. One of those things is that readline comes configured with a large number of default keyboard shortcuts, such as:
Ctrl-b  Move the cursor one character   ⇦ to the left
Ctrl-f  Move the cursor one character   ⇨ to the right
Alt-b   Move the cursor one word    ⇦ to the left
Alt-f   Move the cursor one word    ⇨ to the right
Ctrl-a  Move the cursor     ⇤ to the start of the line
Ctrl-e  Move the cursor     ⇥ to the end of the line
Ctrl-x-x    Move the cursor      ⇤⇥ to the start, and to the end again
Ctrl-d  Delete  the character   underneath the cursor
Ctrl-u  Delete  everything  ⇤ from the cursor back to the line start
Ctrl-k  Delete  everything  ⇥ from the cursor to the end of the line
Alt-d   Delete  word    ⇨ untill before the next word boundary
Ctrl-w  Delete  word    ⇦ untill after the previous word boundary
Ctrl-y  Yank/Paste  prev. killed text   at the cursor position
Alt-y   Yank/Paste  prev. prev. killed text at the cursor position
Ctrl-p  Move in history one line    ⇧ before this line
Ctrl-n  Move in history one line    ⇩ after this line
Alt->   Move in history all the lines   ⇩ to the line currently being entered
Ctrl-r  Incrementally search the line history   ⇧ backwardly
Ctrl-s  Incrementally search the line history   ⇩ forwardly
Ctrl-J  End an incremental search
Ctrl-G  Abort an incremental search and restore the original line
Alt-Ctrl-y  Yank/Paste  arg. 1 of prev. cmnd    at the cursor position
Alt-.
Alt-_   Yank/Paste  last arg of prev. cmnd  at the cursor position
Ctrl-_
Ctrl-x
Ctrl-u  Undo the last editing command; you can undo all the way back to an empty line
Alt-r   Undo all changes made to this line
Ctrl-l  Clear the screen, reprinting the current line at the top
Ctrl-l  Clear the screen, reprinting the current line at the top
Completion  TAB Auto-complete a name
Alt-/   Auto-complete a name (without smart completion)
Alt-?   List the possible completions of the preceeding text
Alt-*   Insert all possible completions of the preceeding text
Ctrl-t  Transpose/drag  char. before the cursor ↷ over the character at the cursor
Alt-t   Transpose/drag  word before the cursor  ↷ over the word at/after the cursor

Here's some good information on customizing readline as well.


Considering the coordinates $x = \sinh u \sin v$, $y = \sinh u \cos v$, how do I show that these coordinates are orthogonal?

Question: I know that orthogonal means meeting at right angles, but I'm unsure about how to go about computing it.
Also, how do I find $\nabla f$ for these coordinates?
Comment: What is their inner product?
Answer: Given coordinates
$$(x,y) = (\sinh u \sin v, \sinh u \cos v)$$
Calculate scale factors/metrics
$$h_u=\sqrt{x_u^2+y_u^2}=\sqrt{\cosh^2 u\sin^2 v+\cosh^2 u\cos^2 v}=\cosh u
$$
$$h_v=\sqrt{x_v^2+y_v^2}=\sqrt{\sinh^2 u\cos^2 v+\sinh^2 u(-\sin v)^2}=\sinh u
$$
thus $$\nabla= \left(\frac1{h_u}\frac{\partial }{\partial x},\frac1{h_v}\frac{\partial }{\partial y}\right)=
\left(\frac1{\cosh u}\frac{\partial }{\partial x},\frac1{\sinh u}\frac{\partial }{\partial y}\right)$$


R: "family" and "degree" specification in loess fitting

Question: I can't understand the difference between the possible specifications of the family option in the loess command in R. This is what I found in the help of the loess command:

For the default family, fitting is by (weighted) least squares. For family="symmetric" a few iterations of an M-estimation procedure with Tukey's biweight are used. Be aware that as the initial value is the least-squares fit, this need not be a very resistant fit.

Is it a matter of robustness?
About the degree: can I use the same loess command with degree = 0 to obtain the k-nearest neighbors algorithm for regression? Or is it necessary to specify something else (e.g. uniform kernel, weights, ...)?
Answer: Loess iteratively estimates the smoothing function. Part of the iteration involves a regression procedure to estimate the parameters of a smoothing spline as a predictive function. The option "degree" is the polynomial degree of the smoothing spline. As noted in the help file, family has to do with how the polynomial is estimated. With gaussian, you are essentially performing OLS, which hopefully is straightforward.
The M-estimator is a more general root-finding procedure. Note with M-estimation, you also get the OLS model if you use the normal score equations as the $\rho$ function and solve them analytically. Tukey's biweight function is locally linear but with tails that taper down to 0 reducing the influence of outliers.
Essentially yes, you can say this is procedure which is "robust to outliers". But that also means it excludes high influence, high leverage points even when they're the right value. On the topic of outliers, basic stat education says very little except that one "looks for outliers" in an analysis, and indeed one should. Where we've gone terribly wrong is inferring, therefore, that they should be excluded and the data omitting these values should be reported as final with minimal description of the methods. Consider however:

Loess is concerned with a mean response over time. For a skewed error distribution, excluding outliers will lead to biased, inconsistent estimates of the mean
Confidence and prediction intervals are underestimated when excluding outliers, since in replications of the study, one does not guarantee the same outlying results will necessarily be excluded
Excluding outliers outright as an automated routine yields little in the manner of sensitivity analysis. Loess does not report which values are effectively excluded according to the biweight function.

So the parameters of the spline that are estimated provide a solution to the system of equations:
$$ \theta: \sum_{i=1}^n \psi (\hat{y} -y) = 0$$

$\psi(x)= x(1-(x^2)/(c^2))^2$   for $|x|<c$; $0$   for $|x|>c$
Where $\theta$ is the vector of parameters to the smoothing spline used to predict $y$, ($\hat{y})$.
https://mathworld.wolfram.com/TukeysBiweight.html
Comment: Thank you a lot. Let me check if I understood the main point: if I specify `family = gaussian` the procedure won't be robust towards outliers. The opposite if `family = symmetric` is specified (with all the related observations you did). I didn't understand if you answered also the question about knn in the first part, sorry.
Comment: Yes. Someone can correct me if I'm wrong, but KNN is an unsupervised learning technique whereas LOESS is supervised. They aren't related at all. The closest analogue as a smoothing technique would be a boxcar filter, but still it's a regression routine that fits a line rather than consider random variables in two-space.
Comment: @AdamO kNN is supervised; you may be thinking of k-means? I think loess with degree 0 is a version of kNN, where predictions are weighted by distance?
Comment: @BenReiniger Oh, yes, that's true. KNN is supervised, I'm pretty sure about it. Thanks for the review.


Can I compare two conditions with one sample t-test?

Question: I am reading a paper and in the methods section of the supplementary material, they describe how they compared the two conditions (stimulated and unstimulated) by saying.

Statistical analysis of signaling responses in manually gated bone
  marrow was performed as follows: For each experimental condition, the
  arcsinh-transformed median intensity of each of 18 intracellular
  antibodies was compared to the distribution of the arcsinh-transformed
  median intensities of unstimulated replicates (n=5) in each of 24
  manually gated cell populations (resulting in a total of 432
  observations per condition). Independent one-sample t-tests were
  performed with 4 degrees of freedom and p-values were adjusted for 432
  multiple comparisons (Bonferroni). All signaling responses with
  adjusted p-values below 0.05 are listed in Table S3.

I am not able to understand how they compared stimulated and unstimulated conditions by doing a one-sample t-test?
Both the conditions are performed on the same subject for sure, but they are two different samples (or tubes), so does that mean that they have included the median intensities of the stimulated and unstimulated replicates in the same vector and performed the t-test?
For example in R like t.test(x)
Any clarification would be helpful. Thanks.
Comment: Could it be that they paired the samples and did a t-test on the paired differences? Would that be consistent with the rest of the article?
Answer: Your general understanding of one sample t-tests is correct. I haven't studied biology since high school, but a few thoughts...

The antibodies and replicates are somehow the same, and the t-test is a paired t-test between each treated and untreated similar 'thing', and a paired t-test is a one sample t-test.
In a lot of biological work I know multiple hypothesis testing is a big thing, and when trying to decide what to even analyze, instead of analyzing a million things, you only keep those that have significant signals. So maybe that one-sample t-test is referring to some part of the process where they decide which signals to keep by just comparing the signal effect to some mean (and thus each is a one sample t-test?)
It's in the supplementary methods, so could be a typo or a mistake. If you understand the biology and that doesn't make sense, and it's not 1 or 2, I would email the authors and ask! There's nothing wrong with doing that!
Answer: I haven't read the whole paper, but (as a biologist) I would understand it to be what @doubled explains in point 2: for each ab stain and for each cell population, they compare what they get in the stimulated sample vs unstimulated and ask if it is significantly different.


When creating a view based on order products in ubercart, only people with access to all orders can see it

Question: I've created a view based on order products in ubercart, but only those with admin role, who have permissions to see all orders can see the view.
Now this is problematic, as the view is a most popular products grid, which is meant for anonymous users who visit the webshop.
My question is: can I somehow restrict access to anonymous and authenticated users to see all the orders but at the same time allow them to see that one view, based on order products?
Hope my question was clear, and thanks in advance,
Huba
Answer: In the view's advanced settings, go to 'SQL Settings', and check 'Disable SQL rewriting'.
Drupal modules can hook in to SQL queries and alter them before they are executed. The Ubercart module automatically adds a permission check to queries that touch the Order table, to implement the 'view own orders' permission. Individual views can opt out of this rewriting mechanism, but that will prevent any module from altering the query. Be sure to thoroughly test that the view does not leak any sensitive information.
Comment: Thank you! It was just what I was looking for! Yes, I got the Drupal warning, do you suggest, that simply making sure, that no field containing sensitive information is added to the view? Can you give me some hints, as to what else to look for, if there's something else? Thank you again!


Difference between hypotenuse and larger leg in a Pythagorean triple

Question: I've been number crunching irreducible Pythagorean triples and this pattern came up: the difference between the hypotenuse and the larger leg seems to always be n² or 2n² for some integer n. Moreover, every integer of the form n² or 2n² is the difference between hypotenuse and the larger leg for some irreducible Pythagorean triple. Is there a simple proof for that?
There is a result listed on Wikipedia that looks kinda, sorta related: that the area of a Pythagorean triangle can not be the square or twice the square of a natural number.
EDIT: Actually, the statements are correct only for odd n² (but also by any 2n² as stated) as John Omielan demonstrated below.
Comment: Are you aware of the formula $(p^2-q^2, 2pq, p^2+q^2)$ where $p,q$ are coprime and have opposite parity?
Comment: By the way, what is an example of an irreducible Pythagorean triple in which the difference between the hypotenuse and larger leg is $2^2$?
Comment: @DavidK The difference of 4 is impossible as proved in the answers below.
Comment: Yes, that was a hint that the $n^2$ differences would occur only for odd $n.$
Answer: As explained in Pythagorean triple, for integers $m \gt n \gt 0$, Euclid's formula of
$$a = m^2 - n^2, \; \; b = 2mn, \; \; c = m^2 + n^2 \tag{1}\label{eq1A}$$
generates all primitive (i.e., irreducible) Pythagorean triples, specifically

Every primitive triple arises (after the exchange of $a$ and $b$, if $a$ is even) from a unique pair of coprime numbers $m$, $n$, one of which is even.

Note \eqref{eq1A} results in
$$c - a = (m^2 + n^2) - (m^2 - n^2) = 2n^2 \tag{2}\label{eq2A}$$
$$c - b = (m^2 + n^2) - 2mn = (m - n)^2 \tag{3}\label{eq3A}$$
Regarding your second part, to help avoid confusion with $n$ above, let's call the values $k^2$ and $2k^2$ instead. With the first one, it uses \eqref{eq3A} so $k = m - n$. However, since one of $m$ and $n$ is even and the other is odd, their difference is odd, so only odd $k$ will work. For any such $k$, set $n = k + 1$ and $m = 2k + 1$ (note $m$ and $n$ are coprime, with $n$ even) to get
$$m^2 - n^2 = (4k^2 + 4k + 1) - (k^2 + 2k + 1) = 3k^2 + 2k \tag{4}\label{eq4A}$$
$$2mn = 2(2k + 1)(k + 1) = 2(2k^2 + 3k + 1) = 4k^2 + 6k + 2 \tag{5}\label{eq5A}$$
This shows $2mn \gt m^2 - n^2$, so $2mn$ is the longer leg. Thus, the difference would result in \eqref{eq3A}.
For the $2k^2$ case, choose $n = k$ and $m = 3k + 1$ (note $m$ and $n$ are coprime, with one of them even). Therefore,
$$m^2 - n^2 = (9k^2 + 6k + 1) - k^2 = 8k^2 + 6k + 1 \tag{6}\label{eq6A}$$
$$2mn = 2(3k + 1)k = 6k^2 + 2k \tag{7}\label{eq7A}$$
This means $m^2 - n^2 \gt 2mn$, so $m^2 - n^2$ is the longer leg. Thus, the difference would result in \eqref{eq2A}.
Comment: +1: (also) to your answer, as presenting a more complete answer to the question than my answer did.
Comment: You also proved my statement is wrong. Not all squares can be the "personality" (I'm calling [c - larger leg] that) of a primitive Pythagorean triple. The double of any square can and is, though.
Comment: Also, the statement applies to both c-a and c-b regardless of which is the "personality" (i.e., the largest).
Comment: @user2661923 Thanks for the response & upvote. I was about to press the Post button with just the first part answered, similar to your answer, when I happened to look at the question again to notice it had a second part as well. So I also missed that part initially.
Answer: Counter example is $(9, 12, 15)$.
Edit
In addition to overlooking the 2nd part of the OP's question, as indicated in my 2nd edit (below), I also overlooked that in the first part of the OP's question, he is (also) specifically focusing on irreducible Pythagorean triplets.

I've been number crunching irreducible Pythagorean triples

However, if the pythagorean triplet is presumed irreducible, then the problem is completely resolved by this article which indicates that the product will either have form
$[(m^2 + n^2) - (m^2 - n^2)] = 2n^2$
or will have form
$[(m^2 + n^2) - (2mn)] = (m - n)^2.$
Edit
After reading John Omielan's answer, and then re-reading the question, I realized that my answer is incomplete.  However, there is no point in my trying to complete my answer, since John Omielan's answer covers the exact same ground.
Answer: We have $a^2+b^2=c^2$, hence $(c-b)(c+b)=a^2$. Since the triple is irreducible, the GCD of $c-b$ and $c+b$ is at most $2$: any divisor of both $c-b$ and $c+b$ would also have to be a divisor of $(c+b)-(c-b)=2b$, and $GCD(c-b, b)=GCD(c+b,b)=GCD(b,c)=1$. So we can say the following about $c-b$ and $c+b$:

The product of these two numbers is a square. That is, the power of each prime factor of their product is even.
The two numbers do not share any prime factors apart from, possibly, $2$.

This means that, with a possible exception of $2$, every prime factor's power of both $c-b$ and $c+b$ is even. If the numbers are odd (their GCD is 1), the same holds for $2$ (its power is $0$), so each of them is a perfect square. If the numbers are even (their GCD is 2), divide both by $2$ first, and then similarly conclude that $(c-b)/2$ as well as $(c+b)/2$ is a square.
As for the second part of the question, just find any solution to either $c-b=n^2$ or $c-b=2n^2$ for an arbitrary $n$. In particular, the triples $(n^2+2n, 2n+2, n^2+2n+2)$ and $(2n^2+2n, 2n+1, 2n^2+2n+1)$ respectively satisfy the condition.
Note though that for even $n$ there are no irreducible triples with $c-b=n^2$: since $c+b$ has to be a square of the same parity, both $c-b$ and $c+b$ are divisible by $4$, then $2b=(c+b)-(c-b)$ and $2c=(c+b)+(c-b)$ are divisible by $4$, which means $b$, $c$, and consequently $a$ are all even.
Answer: If we replace the usual $(m,n)$ of Euclid's formula with
$(2n-1+k,k)$, we get
\begin{align*}
  A=(2n-1)^2+                     & 2(2n-1)k      \\
  B=  \qquad\quad\quad   & 2(2n-1)k+ 2k^2\\
  C=(2n-1)^2+                    & 2(2n-1)k+ 2k^2\\
\end{align*}
which produces the mostly-primitve table of Pythagorean triples below. Notice that half of  all triples have $A>B$ and half have $B>A$.
\begin{array}{c|c|c|c|c|c|}
n & k=1 & k=2 & k=3 & k=4 & k=5   \\ \hline
Set_1 & 3,4,5 & 5,12,13& 7,24,25& 9,40,41& 11,60,61  \\ \hline
Set_2 & 15,8,17 & 21,20,29 &27,36,45 &33,56,65 & 39,80,89 \\ \hline
Set_3 & 35,12,37 & 45,28,53 &55,48,73 &65,72,97 &  75,100,125  \\ \hline
Set_{4} &63,16,65 &77,36,85 &91,60,109 &105,88,137 &119,120,169  \\ \hline
Set_{5} &99,20,101 &117,44,125 &135,72,153 &153,104,185 &171,140,221  \\ \hline
Set_{6} &43,24,145 &165,52,173 &187,84,205 &209,120,241 &231,160,281  \\ \hline
\end{array}
From the formula we can see that $\quad C-A=2k^2\quad$ and that $\quad C-B=(2n-1)^2.\quad $ The first case it is twice the square of any natural number and the second is an odd number squared.


A way to completely close the keyboard without losing textfield focus

Question: Is there a way to completely close the keyboard without losing textfield focus? I'm using textfield to capture the result provided by a physical barcode reader built into the smartphone, it's in the return value, but I want to hide the keyboard. I tried many methods, but I couldn't find a good solution.
Your final solution was the following code. However, since there is no state management in the application, the keyboard opens and closes quickly every time the page is refreshed.
 @override
 Widget build(BuildContext context) {

  SystemChannels.textInput.invokeMethod("TextInput.hide");
  return Scaffold(..

Answer: To hide the keyboard and keep the cursor visible, set readOnly to true and show the cursor to true
TextFormField(
  showCursor: true,
  readOnly: true),

See flutter/issues/#16863
Comment: This is not a solution for me. Because the barcode reading process functions like a keyboard operation. I can't read barcode if I just do read as true.
Answer: You can set keyboardType: parameter to TextInputType.none. This will retain focus. Keep access as the TextField is still editable but no keyboard is shown.
Comment: TextInputType.none not working for me..
Comment: You could try [this solution](https://stackoverflow.com/a/70539470/14388778)


Switching from a short-scale bass to a 'normal' one - Tips please?

Question: I've been playing bass in my bedroom for a while now. I have a pretty but pretty crappy 1970s Yamaha semi-acoustic (SA70, I think). I've been thinking of branching out into some new styles and techniques (slap, dub/reggae etc.) Physically and because of its old electrics, my bass isn't good for much apart from the soul/Motown style lines I play with my fingers. The bass isn't 'bassy' enough for reggae and slapping it isn't feasible either and its beginning to feel limiting.
So I had a look at various P and Jazz bass clones. And briefly tried playing a few. The frets seemed miles apart and the strings felt unwieldy.
Does anyone have experience of switching to a long-scale bass? Are there any tips or tricks you can share? Also any recommendations of suitable instruments would be very welcome.
Comment: Do you happen to still have the SA70 by chance?
Comment: I'm surprised you can't get it bassy enough for reggae. http://music.stackexchange.com/questions/4212/what-are-the-disadvantages-of-buying-a-short-scale-bass-guitar suggests that short-scale basses are less trebly. Have you considered running it through an amp modeler like the Zoom B1 to boost the signal and get some tone?
Comment: I think the lack of 'bassiness' has more to do with the ancient pickups and electrics although that question also mentions the 'flappy' attack and lack of sustain my poor old bass suffers from.

I have tried running it through various different bits of software, the signal from the amp isn't great but while it is possible to transform the sound somewhat, the physical limitations of the instrument itself seems to have a greater negative impact.
Comment: Fair enough. After reading the answers to that question, I bought a Gretsch short-scale, and I love it. No idea how suitable it is for slapping, but it's definitely capable of dubby reggae bass.
Comment: I wish I could afford a Gretsch :-(
Comment: The Gretsch Electromatic range is very affordable.
Comment: Yes I do. I'm still playing it because I haven't upgraded since asking this question :-(
Comment: Wait! Before you switch basses, try a new set of strings first to see if they'll achieve what you want. New strings can make a WORLD of difference, especially if you switch from flats or halfwounds to roundwounds or something similar. New strings might also be stiffer, which may help the sound as well.
Answer: I switched when I first started as a kid, and my advice is to just go for it. If you are used to playing with four fingers on your left hand (i.e., assuming your left hand is on the neck) then you may have to re-learn the low neck positions where you typically don't use all four fingers unless you have a good stretch, but beyond that it is really no different. And you will learn to appreciate the longer scale for better sound in general and longer sustain.
Have fun!
Answer: On the full-scale bass, warm up your hands and fingers by starting out playing scales and patterns at the 5th fret. Then repeat the same scales and patterns starting at the 4th fret, then the 3rd, then the 2nd, then the 1st, then in open position. You'll gradually increase your reach and strengthen your hand and finger muscles.
Answer: My main advise when switching to a regular / long scale bass from a short scale would be to avoid stretching too much with your fretting hand.
I try to play one finger per fret when I'm playing above the 5th fret but when you're down below the 5th move your hand instead of stretching.
For example when going from a low F (1st fret on the E string) to an octave up (3rd fret on the D string) maybe use your index finger for the low F and pinky for the octave instead of index on the low F and ring finger on the octave.


How do I make my HTML background colour reach the sides of the page?

Question: I'm trying to create a navigation bar (made up of two horizontal lists) that has a black background. The problem is that the background color doesn't reach the outer border of the page even when I set the width and height of my ul element to 100% and margin and padding to 0px.
I also tried making the body and HTML's margin and padding 0px but that also failed. I was able to get a result close to what I was looking for by making the HTML background color black but that gave the webpage a black border as well. Thank you if you're able to help me. My code is below.

body {
  font-family: helvetica;
  background-color: gray;
}
#nav {
  display: flex;
}
img{
  width: 100px;
  height: 100px;
}
#left{
color: black;
font-size: 24px;
}
#left li{
  padding: 10px;
  padding-top: 14px;
  padding-bottom: 6px;
  float: left;
  display: block;
}
#left_list{
  width: 70%;
  clear: right;
}
#right{
  color: black;
  font-size: 24px;
}
#right li{
  padding: 22px;
  padding-bottom: 26px;
  padding-top: 16px;
  float: right;
  display: block;
}
#right_list{
  width: 30%;
  float: right;
  clear: left;
}
ul{
  list-style-type: none;
  margin: 0px;
  padding: 0px;
  overflow: hidden;
  background-color: black;
  width: 100%;
  height: 100%;
  }
#nav a:link{
  color: white;
  display: block;
  margin-top: 25px;
}
#nav a:hover{
  color: hotpink;
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Home

Contact

Comment: Using the inspector, I can see that the `` has 8px margin, which would inset it from the root html element. Setting `margin: 0;`  in your CSS for _body_ got rid of it.
Answer: I also tried making the body and HTML's margin and padding 0px but that also failed
Seems not when I just add
* { margin:0; padding:0; }

* { margin:0; padding:0; }
body {
  font-family: helvetica;
  background-color: gray;
}
#nav {
  display: flex;
}
img{
  width: 100px;
  height: 100px;
}
#left{
color: black;
font-size: 24px;
}
#left li{
  padding: 10px;
  padding-top: 14px;
  padding-bottom: 6px;
  float: left;
  display: block;
}
#left_list{
  width: 70%;
  clear: right;
}
#right{
  color: black;
  font-size: 24px;
}
#right li{
  padding: 22px;
  padding-bottom: 26px;
  padding-top: 16px;
  float: right;
  display: block;
}
#right_list{
  width: 30%;
  float: right;
  clear: left;
}
ul{
  list-style-type: none;
  margin: 0px;
  padding: 0px;
  overflow: hidden;
  background-color: black;
  width: 100%;
  height: 100%;
  }
#nav a:link{
  color: white;
  display: block;
  margin-top: 25px;
}
#nav a:hover{
  color: hotpink;
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Home

Contact

Answer: if you put margin: 0 for body your problem will solved

body {
  font-family: helvetica;
  background-color: gray;
  margin: 0;
}
#nav {
  display: flex;
}
img{
  width: 100px;
  height: 100px;
}
#left{
color: black;
font-size: 24px;
}
#left li{
  padding: 10px;
  padding-top: 14px;
  padding-bottom: 6px;
  float: left;
  display: block;
}
#left_list{
  width: 70%;
  clear: right;
}
#right{
  color: black;
  font-size: 24px;
}
#right li{
  padding: 22px;
  padding-bottom: 26px;
  padding-top: 16px;
  float: right;
  display: block;
}
#right_list{
  width: 30%;
  float: right;
  clear: left;
}
ul{
  list-style-type: none;
  margin: 0px;
  padding: 0px;
  overflow: hidden;
  background-color: black;
  width: 100%;
  height: 100%;
  }
#nav a:link{
  color: white;
  display: block;
  margin-top: 25px;
}
#nav a:hover{
  color: hotpink;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Home

Contact


Jetpack compose Drawing over shapes

Question: I have this interesting problem in a project, where user should be able to draw the same shape over the defined shape, i have achieved this so far, but i want to check if he/she drawn over the shape correctly in ONE GO. if the finger goes outside the sqaure the current drawing should reset and put a toast message as unsucssesfull else says succesfull, How do i check if the drawing is on the Square?

The white square is drawn with drawRect() Method and drawing over it is by the user itself, achieved by Drawpath().
code is given below

class DrawingActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyDrawing()
        }
    }
}
@Composable
fun MyDrawing() {
    val actionIdle = 0
    val actionDown = 1
    val actionMove = 2
    val actionUp = 3
    //Path, current touch position and touch states
    val path = remember { Path() }
    var motionEvent by remember { mutableStateOf(actionIdle) }
    var currentPosition by remember { mutableStateOf(Offset.Unspecified) }
    val canvasColor: Color by remember { mutableStateOf(Color.LightGray) }
    val drawModifier = Modifier
        .fillMaxWidth()
        .fillMaxHeight()
        .background(canvasColor)
        .clipToBounds()
        .pointerInput(Unit) {
            forEachGesture {
                awaitPointerEventScope {

                    val down: PointerInputChange = awaitFirstDown().also {
                        motionEvent = actionDown
                        currentPosition = it.position
                    }
                    do {
                        val event: PointerEvent = awaitPointerEvent()

                        var eventChanges =
                            "DOWN changedToDown: ${down.changedToDown()} changedUp: ${down.changedToUp()}\n"
                        event.changes
                            .forEachIndexed { index: Int, pointerInputChange: PointerInputChange ->
                                eventChanges += "Index: $index, id: ${pointerInputChange.id}, " +
                                        "changedUp: ${pointerInputChange.changedToUp()}" +
                                        "pos: ${pointerInputChange.position}\n"

                                pointerInputChange.consumePositionChange()
                            }

                        //gestureText = "EVENT changes size ${event.changes.size}\n" + eventChanges

                        //gestureColor = Color.Green
                        motionEvent = actionMove
                        currentPosition = event.changes.first().position
                    } while (event.changes.any { it.pressed })

                    motionEvent = actionUp
                    //canvasColor = Color.LightGray

                    //gestureText += "UP changedToDown: ${down.changedToDown()} " + "changedUp: ${down.changedToUp()}\n"
                }
            }

        }

    Canvas(
        modifier = drawModifier
            .padding(20.dp)
            .size(500.dp)
    ) {
        val canvasWidth = size.width
        val canvasHeight = size.height
        val line = 1.5
        val squareSize = canvasWidth/line

        drawRect(
            color = Color.White,
            topLeft = Offset(center.x - canvasWidth / 3, center.y - canvasHeight / 6),
            size = Size(width = squareSize.toFloat(), squareSize.toFloat()),
            style = Stroke(
                width = 50.dp.toPx()
            ),
        )

        when(motionEvent){
            actionDown->{
                path.moveTo(currentPosition.x,currentPosition.y)
            }
            actionMove->{
                if (currentPosition!= Offset.Unspecified){
                    path.lineTo(currentPosition.x,currentPosition.y)

                }
            }
            actionUp->{
                path.lineTo(currentPosition.x,currentPosition.y)
                motionEvent = actionIdle

            }
            else-> Unit
        }

       drawPath(
           color = Color.Cyan,
           path = path,
           style = Stroke(width = 5.dp.toPx(), join = StrokeJoin.Round)
       )

    }

}
Answer: You can either get Rect of your Path using path.getBounds(), and compare it with user's current touch position.
Here i add a sample for this. I don't check if it got error or finish in one touch you can implement that. This one checks in which bound we are currently, if we are in green rect we are in correct bounds
@Composable
private fun CanvasShapeSample() {

    // This is motion state. Initially or when touch is completed state is at MotionEvent.Idle
    // When touch is initiated state changes to MotionEvent.Down, when pointer is moved MotionEvent.Move,
    // after removing pointer we go to MotionEvent.Up to conclude drawing and then to MotionEvent.Idle
    // to not have undesired behavior when this composable recomposes. Leaving state at MotionEvent.Up
    // causes incorrect drawing.
    var motionEvent by remember { mutableStateOf(MotionEvent.Idle) }
    // This is our motion event we get from touch motion
    var currentPosition by remember { mutableStateOf(Offset.Unspecified) }
    // This is previous motion event before next touch is saved into this current position
    var previousPosition by remember { mutableStateOf(Offset.Unspecified) }

    val innerPath = remember { Path() }
    val outerPath = remember { Path() }

    // Path is what is used for drawing line on Canvas
    val path = remember { Path() }

    var isError by remember { mutableStateOf(false) }

    val drawModifier = Modifier
        .fillMaxSize()
        .background(Color.LightGray)
        .pointerMotionEvents(
            onDown = { pointerInputChange: PointerInputChange ->
                currentPosition = pointerInputChange.position
                motionEvent = MotionEvent.Down
                pointerInputChange.consume()
            },
            onMove = { pointerInputChange: PointerInputChange ->
                currentPosition = pointerInputChange.position
                motionEvent = MotionEvent.Move
                pointerInputChange.consume()
            },
            onUp = { pointerInputChange: PointerInputChange ->
                motionEvent = MotionEvent.Up
                pointerInputChange.consume()
            },
            delayAfterDownInMillis = 25L
        )

    Canvas(modifier = drawModifier) {

        val canvasWidth = size.width
        val canvasHeight = size.height

        val outerShapeWidth = canvasWidth * .8f
        val innerShapeWidth = canvasWidth * .6f

        if (innerPath.isEmpty) {

            innerPath.addRect(
                Rect(
                    offset = Offset(
                        (canvasWidth - innerShapeWidth) / 2,
                        (canvasHeight - innerShapeWidth) / 2
                    ),
                    size = Size(innerShapeWidth, innerShapeWidth)
                )
            )
        }

        if (outerPath.isEmpty) {
            outerPath.addRect(
                Rect(
                    offset = Offset(
                        (canvasWidth - outerShapeWidth) / 2,
                        (canvasHeight - outerShapeWidth) / 2
                    ),
                    size = Size(outerShapeWidth, outerShapeWidth)
                )
            )
        }

        when (motionEvent) {
            MotionEvent.Down -> {
                path.moveTo(currentPosition.x, currentPosition.y)
                previousPosition = currentPosition
                isError = !isInBound(innerPath = innerPath, outerPath = outerPath, currentPosition)
            }

            MotionEvent.Move -> {
                path.quadraticBezierTo(
                    previousPosition.x,
                    previousPosition.y,
                    (previousPosition.x + currentPosition.x) / 2,
                    (previousPosition.y + currentPosition.y) / 2

                )
                previousPosition = currentPosition
                isError = !isInBound(innerPath = innerPath, outerPath = outerPath, currentPosition)
            }

            MotionEvent.Up -> {
                path.lineTo(currentPosition.x, currentPosition.y)
                currentPosition = Offset.Unspecified
                previousPosition = currentPosition
                motionEvent = MotionEvent.Idle
            }

            else -> Unit
        }

        drawPath(color = Color.Green, path = outerPath)
        drawPath(color = Color.Yellow, path = innerPath)

        drawPath(
            color = Color.Red,
            path = path,
            style = Stroke(width = 4.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round)
        )

        drawCircle(
            color = if (isError) Color.Red else Color.Green,
            center = Offset(100f, 100f),
            radius = 50f
        )
    }
}

private fun isInBound(innerPath: Path, outerPath: Path, position: Offset): Boolean {
    val innerRect = innerPath.getBounds()
    val outerRect = outerPath.getBounds()

    return !innerRect.contains(position) && outerRect.contains(position)
}

Result

If your shape is complex what you can do is getting path segments and check if they are out of bounds of your complex shape
        val segments: Iterable<PathSegment> = path.asAndroidPath().flatten()

pathSegment has start and end PointF values. If user moves pointer fast it might not create enough pathSegments but it would proabably be an edge case.
This tutorial has section about path segments checking it and sample above would give an idea. But this will probably very difficult for complex shapes which might require you to ask question for algorithm for detection if a position is inside a Path
https://github.com/SmartToolFactory/Jetpack-Compose-Tutorials#6-1-5-canvas-path-segments

I see that you use my code for drawing over canvas i mentioned here. I simplified it you can check these gestures to see how simple it's now. You don't need all that code.
Comment: Hi, Yes, I have used your code :), This is a bit confusing since this is my very first drawing/compose project. If you could some code here based on my code. That would be great.
Comment: okay i will try to add some tomorrow. You want user to draw inside white square right?
Comment: Yes, wonderful, I managed to get val pathOfDrawing = path.getBounds(). but struggling to get that with the shape.
Comment: Actually without bounds, you can just use the currentPosition from down and move events. Just check it with Rectangle. Rect has a `rect.contains(Offset)` method. on each gesture compare it with the bounds if your shape is always be a Rect.
Comment: it won't be always rect apparently
Comment: I mean have 2 rectangles, ok? First one, is inner one that you don't want your offset to be in and the white one that you want it to be in.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/246414/discussion-between-thracian-and-mohamed-rimshad).
Comment: hello, may i know which version of dependency you are using for the code you provided, lot of the things are unresolvable, such as Down,Up,size,position, fillMaxSize
Comment: `pointerMotionEvents ` and `MotionEvent` are from this library https://github.com/SmartToolFactory/Compose-Extended-Gestures. `com.github.SmartToolFactory:Compose-Extended-Gestures:2.0.0`.
Comment: Works great, was wondering if you have a medium blog or youtube channel, excited to do some experiments with your github repo :)
Comment: Unfortunately i don't have a blog or youtube channel. You can follow github if you want to. Tutorial covers gestures, custom layouts, canvas and many other things. Your question is pretty interesting and difficult btw. My answer is just a tool. Finding an algorithm to detect if drawing is in valid path not going back, not intersecting will be hard. One of my coworker had worked in a similar project for indoor to keep user on path and it was quite hard. You need to search algorithms to find a good solution and if you do apply it other areas either
Comment: Maybe you can create a third path between outer and inner path and check closest distance your current position to path if it's out of desired threshold then show an error when your shapes get more complex. This is something you should ask with `algorithm` tag i guess

Jetpack compose Drawing over shapes


If n $\geq2$, does G necessarily have an element of order $p^2$? Justify your answer.

Question: If n $\geq2$, does a group G of order $p^n$ necessarily have an element of order $p^2$? Justify your answer.
p is a prime number.
n is an integer.
I can't seem to find a counterexample, but I think it is false.
Comment: What is $G$, what is $p$?
Comment: Also, what is $n$?
Comment: That $n$ and $p$ just has no relationship with $G$?
Comment: To be more precise: What are the relations between $G$, $p$ and $n$?
Answer: My guess is that $G$ is a group, $p$ is a prime number dividing $n$, and $n$ is the order of the group $G$.  (not true, but close; the counterexample still works)
Consider $G = \Bbb{Z}/2\Bbb{Z}\times \Bbb{Z}/2\Bbb{Z}$. Then $G$ has order $4=2^2$, but it has no element of order $p^2$ (the only possible choice of $p$ is $2$).
Comment: @John Yes, but the counterexample still works :)
Comment: sorry for the lack of information. i have edited my post
Comment: Your guess is wrong ^^.
Comment: Ar..... You are right!
Answer: The group $C_p \times \cdots \times C_p$ has no element of order $p^2$. In fact, all nontrivial elements have order $p$.


Tag is not working in React js between elements

Question: in below code the
 tag is not working.  I'm working in vscode, building reactjs app.
function Main()
{
    return(
    <>

                Your Height:

            <input type="text" id="height" placeholder="Centemeters"></input>

 /*This Tag is not working*/

               Your Weight   /*this statement is showing side by side with above ones*/

            <input type="text" id="weight" placeholder="KG"></input>

    </>
    );
}

Answer: That's because you have display: flex; on the container that holds the elements.

Comment: How is this an answer? There is no solution to it, your only line of code is identical as part of the (*malfunctioning*) code the OP gave.
Comment: It is an answer! The "d-flex" class probably contains "display: flex;" property, witch by default has "flex-direction: row;" .That's why the  tag isn't working. If the class is removed it will work!


Downgrade to specific IE version (IE 9.0.24)

Question: I follow the instructions on how to downgrade IE. But my version now is 9.0.25 and client has 9.0.24. And there are, of course, some errors that are not in 9.0.25... Is it possible to get this exact version?
Answer: I never tried this solution, but Microsoft proposes free Virtual Machines : https://dev.windows.com/en-us/microsoft-edge/tools/vms/windows/
Maybe you can choose specific version of IE9 in it ?
Otherwise, as it is written, these virtual machines expire after 90 days. So take a snapshot when you first install the virtual machine which you can roll back to later.