alertDialog com layout confuso em fragment

Question: Não consigo alterar o layout de um alertDialog() que herdou um layout não sei de onde. já tentei setar um customAlertDialogLayout também sem êxito. já tentei alterar o context e nada parece funcionar.
SedeFragment.java
package br.gov.rj.pmerj.policialoficialsv.fragments;

/**
 * A simple {@link Fragment} subclass.
 *
 */
public class SedeFragment extends Fragment implements RecyclerViewOnClickListenerHack {
  private RecyclerView mRecyclerView;
  private ImageButton mImageButton;
  private List < Sede > mList;
  //public LegislacaoDao legislacaoDao;
  Fragment fragment;
  public Bundle savedInstanceState;
  public SedeDao sededaoDaoselecionado;
  int mpId = 0;
  String exStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();
  String path = (exStoragePath + "/media/alarms/");
  public Sede sede;
  public SedeDao sedeDao;

  public SedeFragment() {
    // Required empty public constructor
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View view;

    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.fragment_sede, container, false);

    mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_list);
    mImageButton = (ImageButton) view.findViewById(R.id.imgrota);
    mRecyclerView.setHasFixedSize(true);
    GridLayoutManager llm = new GridLayoutManager(getActivity(), 1, GridLayoutManager.VERTICAL, false);
    mRecyclerView.setLayoutManager(llm);
    mRecyclerView.addOnItemTouchListener(new RecyclerViewTouchListener(getActivity(), mRecyclerView, this));
    // mRecyclerView.addOnItemTouchListener(new RecyclerViewTouchListener( getActivity(), mRecyclerView, this ));
    //GridLayoutManager llm = new GridLayoutManager(getActivity(), 1, GridLayoutManager.VERTICAL, false);
    mRecyclerView.setLayoutManager(llm);
    sedeDao = new SedeDao((MainActivity) getActivity());
    //LegislacaoDao legislacaoDao = new LegislacaoDao((MainActivity) getActivity());
    //mList = (ArrayList<Legislacao>) legislacaoDao.listar();
    mList = (ArrayList < Sede > ) sedeDao.listar();

    // SedeAdapter adapter = new SedeAdapter(getActivity().getApplicationContext(), mList);
    SedeAdapter adapter = new SedeAdapter(getActivity(), mList);

    mRecyclerView.setAdapter(adapter);

    return view;

  }
  @Override
  public void onLongPressClickListener(View view, int position) {

    // acao2(getActivity(),mList.get(position));
    //  return false;
    //saveas();
    //Toast.makeText(getActivity(), "onLongPressClickListener(): "+position, Toast.LENGTH_SHORT).show();
    // Toast.makeText(getActivity(), "onLongPressClickListener(): "+passaro.getCantoAudio(), Toast.LENGTH_SHORT).show();
    /*CarAdapter adapter = (CarAdapter) mRecyclerView.getAdapter();
    adapter.removeListItem(position);*/
  }
  @Override
  public void onClickListener(View view, int position) {
    switch (view.getId()) {
      case R.id.imgrota:
        sededaoDaoselecionado = new SedeDao(getContext());
        Bundle bundle = new Bundle();
        bundle.putInt("iditem", mList.get(position).getId());
        String s;
        s = mList.get(position).getEndereco();
        Toast.makeText(getContext(), mList.get(position).getOpm() + " - " + mList.get(position).getEndereco() + " - " + mList.get(position).getBairro() + " - " + mList.get(position).getMunicipio(), Toast.LENGTH_SHORT).show();

        break;
    }

    //   sededaoDaoselecionado = new SedeDao(getContext());

    //Toast.makeText(getContext(), "teste"+itemdaoDaoselecionado.buscarPorId(position).getId(), Toast.LENGTH_SHORT).show();
    // Toast.makeText(getContext(), "item unico selecionado" + mList.get(position).getId(), Toast.LENGTH_SHORT).show();
    // Toast.makeText(getContext(),  mList.get(position).getOpm() + " - " + mList.get(position).getEndereco() + " - " +  mList.get(position).getBairro()+ " - " +  mList.get(position).getMunicipio() , Toast.LENGTH_SHORT).show();
    // Toast.makeText(getActivity(), "onClickListener(): " + position, Toast.LENGTH_SHORT).show();
    //sededaoselecionado = new SedeDao(getContext());

    //Bundle bundle = new Bundle();
    // bundle.putInt("iditem", 10);
    //mList.get(position).getId()
    // bundle.putInt("iditem", itemdaoDaoselecionado.buscarPorId(position).getId());
    //bundle.putInt("iditem", mList.get(position).getId());
    //fragment = new LeiFragment();
    // fragment.setArguments(bundle);
    // replaceFragment();
    // }

    //URLEncoder.encode("your URL here", "UTF8")
    //String s;
    //Sede sd;
    //SedeDao sddao;
    //sd = new Sede;
    //s = mList.get(position).getEndereco();
    //s= URLEncoder.encode(" "+s, "UTF8")

    //Avallie
    /*
            String my_package_name;
            String url;
            my_package_name="com.google.android.apps.maps";
            try {
                //Check whether Google Play store is installed or not:
                view.getContext().getPackageManager().getPackageInfo("com.google.android.apps.maps", 0);

                url = "market://details?id=" + my_package_name;
            } catch ( final Exception e ) {
                url = "https://play.google.com/store/apps/details?id=" + my_package_name;
            }

*/

    //  Uri gmmIntentUri = Uri.parse("google.navigation:q="+s+","+mList.get(position).getBairro() +" "+  mList.get(position).getMunicipio());
    //Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
    //mapIntent.setPackage("com.google.android.apps.maps");
    //if (mapIntent.resolveActivity(getContext().getPackageManager()) != null) {
    //  startActivity(mapIntent);
    //}

  }

  public void alert(View v, String s) {
    final AlertDialog dialog = new AlertDialog.Builder(v.getContext())
      .setView(R.layout.custom_dialog_layout)
      .create();

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(v.getContext());
    //alertDialogBuilder.setView((R.layout.custom_dialog_layout));
    alertDialogBuilder.setMessage(s);
    // alertDialogBuilder.setView(R.layout.custom_dialog_layout);
    // AlertDialog alertDialog = alertDialogBuilder.create();
    // setView(mLayoutInflater.createView(R.layout.custom_dialog_layout, null));
    //  alertDialog.setView(v.);
    alertDialogBuilder.show();
  }

  private void replaceFragment() {
    FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
    fragmentManager.beginTransaction()
      .replace(R.id.container, fragment)
      .commit();
  }

  private static class RecyclerViewTouchListener implements RecyclerView.OnItemTouchListener {
    private Context mContext;
    private GestureDetector mGestureDetector;
    private RecyclerViewOnClickListenerHack mRecyclerViewOnClickListenerHack;

    public RecyclerViewTouchListener(Context c, final RecyclerView rv, RecyclerViewOnClickListenerHack rvoclh) {
      mContext = c;
      mRecyclerViewOnClickListenerHack = rvoclh;

      mGestureDetector = new GestureDetector(mContext, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public void onLongPress(MotionEvent e) {
          super.onLongPress(e);

          View cv = rv.findChildViewUnder(e.getX(), e.getY());

          if (cv != null && mRecyclerViewOnClickListenerHack != null) {
            mRecyclerViewOnClickListenerHack.onLongPressClickListener(cv,
              rv.getChildPosition(cv));
          }
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
          View cv = rv.findChildViewUnder(e.getX(), e.getY());

          if (cv != null && mRecyclerViewOnClickListenerHack != null) {
            mRecyclerViewOnClickListenerHack.onClickListener(cv,
              rv.getChildPosition(cv));
          }

          return (true);
        }
      });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
      mGestureDetector.onTouchEvent(e);
      return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {}

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
  }

}

item_legislacao.xml
 <
  android.support.v7.widget.CardView xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
xmlns: card_view = "http://schemas.android.com/apk/res-auto"
android: layout_gravity = "center"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
card_view: cardCornerRadius = "3dp"
card_view: cardElevation = "1.5dp"
card_view: cardUseCompatPadding = "true" >

  <
  LinearLayout
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: orientation = "vertical"
android: layout_margin = "18dp" >

  <
  TextView
android: textColor = "#000000"
android: id = "@+id/tv_model"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: textSize = "15sp" / >

  <
  TextView
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: id = "@+id/endereco"
android: textSize = "15sp"
android: textColor = "#000" / >

  <
  LinearLayout
android: orientation = "horizontal"
android: layout_width = "fill_parent"
android: layout_height = "30dp"
android: layout_gravity = "center_vertical"
android: gravity = "center"
android: layout_marginTop = "4dp" >

  <
  ImageButton
android: id = "@+id/imgrota"
android: theme = "@style/AppTheme.Button"
android: src = "@android:drawable/ic_dialog_map"
android: layout_height = "fill_parent"
android: layout_width = "0dip"
android: layout_weight = "1"
android: adjustViewBounds = "true"
android: padding = "2dp"
android: scaleType = "fitCenter" / >

  <
  ImageButton
android: id = "@+id/imgtel"
android: src = "@android:drawable/ic_menu_call"
android: theme = "@style/AppTheme.Button"
android: layout_height = "fill_parent"
android: layout_width = "0dip"
android: layout_weight = "1"
android: adjustViewBounds = "true"
android: padding = "2dp"
android: scaleType = "fitCenter" / >

  <
  ImageButton
android: id = "@+id/imginfo"
android: src = "@android:drawable/ic_dialog_info"
android: theme = "@style/AppTheme.Button"
android: layout_height = "fill_parent"
android: layout_width = "0dip"
android: layout_weight = "1"
android: adjustViewBounds = "true"
android: padding = "2dp"
android: scaleType = "fitCenter" /
  >

  <
  ImageButton
android: id = "@+id/imgshare"
android: src = "@android:drawable/ic_menu_share"
android: layout_height = "fill_parent"
android: layout_width = "0dip"
android: layout_weight = "1"
android: theme = "@style/AppTheme.Button"
android: adjustViewBounds = "true"
android: padding = "2dp"
android: scaleType = "fitCenter" / >

  <
  /LinearLayout>

  <
  /LinearLayout>

SedeAdapter.java
myViewHolder.btninfo.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {

    SedeFragment sedefragment;
    sedefragment = new SedeFragment();
    String s;
    s = (mList.get(position).getOpm() + "\n" + "\n" + "Endereço:" + " + mList.get(position).getEndereco() + "\
      n " +
      "Bairro:" + mList.get(position).getBairro() + "\n" + "Município:" + mList.get(position).getMunicipio() + "\n" + "\n" +
      "SOP/OF DE DIA:" + mList.get(position).getTel());
    sedefragment.alert(v, s);

  }
});

styles.xml


Joining three tables to get a list of tags

Question: I have these three tables:
user_submitted_value

  id | owner_id | value |
  -----------------------
   1 | 1        |  1337 |
   2 | 2        |  1337 |
   3 | 2        |  1337 |
   4 | 1        |  1337 |

tag

  id | owner_id |      text |
  ---------------------------
   1 | 1        |  'Tag 01' |
   2 | 1        |  'Tag 02' |
   3 | 1        |  'Tag 03' |
   4 | 2        |  'Tag 04' |

user_submitted_value_tag

  id | owner_id | tag_id | value_id |
  -----------------------------------
   1 | 1        |      1 |        1 |
   2 | 1        |      2 |        1 |
   3 | 1        |      3 |        1 |

So basically, users can submit values and enter any number of freetext tags to attach to that value. I need to store the tags as belonging to a specific user, and I need to be able to count how many times they've used each tag.
What I want to accomplish is a query that gets rows from user_submitted_value with the tags appended onto them. For example:

  Query value with id 1:

  id | owner_id | value |                         tags |
  ------------------------------------------------------
   1 | 1        |  1337 | "'Tag 01','Tag 02','Tag 03'" |

  Query all values belonging to user with id 1:

  id | owner_id | value |                         tags |
  ------------------------------------------------------
   1 | 1        |  1337 | "'Tag 01','Tag 02','Tag 03'" |
   4 | 1        |  1337 |                           "" |

I know I need to JOIN one or more times, somehow, but I am not comfortable enough with SQL to figure out exactly how.
Answer: This seems like a rather arcane data format -- particularly because owner_id is repeated in all the tables.
In any case, I think the basic query that you want to get the values and tags for a given user looks like this:
select usv.owner_id,
       group_concat(distinct usvt.value_id) as values,
       group_concat(distinct t.text) as tags
from user_submitted_value usv join
     user_submitted_value_tag usvt
     on usv.value_id = usvt.value_id and usv.owner_id = usvt.owner_id join
     tags t
     on usvt.tag_id = t.id and usvt.owner_id = t.owner_id
group by usv_owner_id;

Comment: Thanks! What changes would you suggest to the data format to be more efficient?
Comment: I found a problem with this query. It won't return values that have no tags. Having no tags is allowed behavior in my use-case.
Comment: Changing both the joins to LEFT JOIN appears to include the rows with no tags. Awesome. Now, how would I limit the query to either a specific user, or a specific user_submitted_value? IE where can I put a WHERE clause? I tried appending a WHERE to `from user_submitted_value` but that won't work.
Comment: @korona . . . Add a `where` clause before the `group by`.
Answer: Here's the final solution in my case. Heavily based on the answer submitted by Gordon Linoff.
      SELECT
        user_submitted_value.id,
        user_submitted_value.creator_id,
        user_submitted_value.value,
        group_concat(tag.text) AS tags
      FROM user_submitted_value
      LEFT JOIN user_submitted_value_tag
        ON user_submitted_value.id = user_submitted_value_tag.value_id
        AND user_submitted_value.creator_id = user_submitted_value_tag.creator_id
      LEFT JOIN tag
        ON user_submitted_valuetag.tag_id = tag.id
        AND user_submitted_value_tag.creator_id = tag.creator_id
        WHERE user_submitted_value.id = ?
      GROUP BY user_submitted_value.id

The WHERE clause on the second JOIN can be modified to get all values for a given user.


displaying dates in rails view

Question: I have the following date
start = "16/09/2014"

which I convert using "to_date" method to
Tue, 16 Sep 2014

How can I display above in my view as doing the following doesn't work?
= start.to_date
Answer: From the doc here:
 start.to_date.strftime('%a, %d %b %Y')

You have to choose your display options.

Another cool way to do it, is to add it to an initializer:
Time::DATE_FORMATS.update my_format: '%a, %d %b %Y'

Then you can do:
start.to_date.to_s(:my_format)

displaying dates in rails view


How to get Content Type by Name or ID?

Question: I'm trying to get a Content Type by the Name or the ID.
I'm using this code but it does not work.
SPContentTypeId eventTypeId = new SPContentTypeId("0x0102");
SPContentType eventType = web.AvailableContentTypes[eventTypeId];

Do you have any ideas?
Thanks.
Comment: Your code works for me and is the correct approach to load a SPContentType. What is the expception? What _does not work_?
Answer: Based On the the information you have provided in your question, I think what you are looking for is something like this:
SPContentType spct = web.AvailableContentTypes ["ContentTypeName"];

Good luck! :)
Comment: `web.AvailableContentTypes` returns all content types in the current site collection. This has nothing to do with a web application.
Comment: thanks Stefan for your correction, Just before noticing your comment I realized that I was unsure about the correctness of my statement and omitted the whole paragraph since it seemed unnecessary anyway.
Comment: Plus, you might want to elaborate on your examples. They do not really explain, solve the issues from the OP.
Answer: Just a note on the above. If you plan on making ANY changes to the content type then you don't want to use the above function. It will return read only versions. You want to be using:
web.ContentTypes["ContentTypeName"].

Instead of:
web.AvailableContentTypes["ContentTypeName"].

Just to save people a whole pile of time as the above answer is not really correct. It should include BOTH options as it really depends on the context and how they are using it. Although they don't give those sorts of details this is a top answer in google.
Comment: @JimYarbro Thanks I have done now ;-) did no know I could do that.

How to get Content Type by Name or ID?


Maximum modulus on the unit disc

Question: Q: Suppose that $f(z)$ is analytic in the unit disc $D = \lbrace z: |z|<1 \rbrace$ and continuous in the corresponding closed disc $\overline{D}=\lbrace z: |z| \leq 1 \rbrace$. Suppose also that $f(z)/z^5$ can be extended to be analytic analytic in all of D (including the origin). If $|f(z)| \leq 4$ in $\overline{D}$, what is the maximal value that $|f(0.6i)|$ can assume under these conditions?
I am having some trouble with this problem. The answer i have gotten is $|f(0.6i)|\leq 4\cdot(0.6^5)$, but this is returned as incorrect. Am I missing a way to get a better bound with these conditions?
Comment: Apply the MMT to the function $f(z)/z^5$.
Answer: The question makes no sense ! Let $n \in \mathbb N$ and consider $f_n(z)=nz^5.$
Then $|f_n(0.6i)|=n (0.6)^5$
Consequence: $|f(0.6i)|$ can made arbitrayly big.
Comment: Edited do include the entire question; all of it evidently didn't copy as one would expect!

Maximum modulus on the unit disc


errors in crontab file, can't install

Question: Me new in ruby on rails. I make schedule.rb by using the whenever gem, and write a code
set :environment, "development"
set :output, {:error => "log/cron_error_log.log", :standard => "log/cron_log.log"}

every '* * * * * *' do
  command "echo 'you can use raw cron syntax too'"
end

I already did whenever, but when I update crontab it gives following error
"-":3: bad command
errors in crontab file, can't install.
[fail] Couldn't write crontab; try running `whenever' with no options to
       ensure your schedule file is valid.

What is its solution?
Answer: The Unix crontab has 5 fields; minute, hour, day of month, month, day of week.
This line:
every '* * * * * *' do
       1 2 3 4 5 6 <- Error

You entered too many fields.
Comment: One more think if u know how can I see the output.....I did whenever --update-crontab and file updated....but output not shows
Comment: You mean how to look at the current crontab? Type `crontab -l`.

errors in crontab file, can't install


Commerce Kickstart 2 Need Rule To Apply Sales Tax To Shipping

Question: I need a Rule to apply sales tax to shipping on a sales order.
I tried the following code (borrowed from here: https://www.drupal.org/node/2307695) and it doesn't work for me:
<code>{ "rules_apply_sales_tax_to_shipping" : {
"LABEL" : "Apply sales tax to shipping",
"PLUGIN" : "reaction rule",
"WEIGHT" : "5",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_tax", "commerce_shipping" ],
"ON" : { "commerce_shipping_calculate_rate" : [] },
"DO" : [
{ "commerce_tax_calculate_by_type" : {
"commerce_line_item" : [ "commerce_line_item" ],
"tax_type_name" : "sales_tax"
}
}
]
}
}
</code>
Maybe there is a typo? There are only two tax_types on our site, sales_tax and VAT so I don't think so.
Do I need to add this as an Action onto our Sales Tax? I don't see how to do this... this does not appear in the drop down list of available Actions.
Comment: Do you have any conditions on the Rules component for the taxes in question?
Comment: No. At the risk of sounding stupid (again). There are no conditions in the Rule for Calculate Sales Tax on the product line items. Shouldn't I simply be able to clone -that- rule (CST) but point it to line items of type 'shipping'? I just don't know how to do it. FWIW: I can't figure out for the life of me how to address the variables through the UI. TIA --JC
Answer: don't know if you solved this yet (hope so). The trick is to set your tax rate and THEN apply is a calculation rule to shipping. Not the most intuitive way to do it, but it works.


Mod_ruid2 vs. SuPHP

Question: I'm setting up a new server and I'm in doubt whether I install php/apache with SuPhp or mod_ruid2. I'd a lot of troubles with SuPHP before and it's definitely slower than mod_ruid2. But is mod_ruid2 equal as secure as SuPHP? Do I have more security risks when I use mod_ruid2 than i'd have with SuPHP?
In other words: mod_ruid2 vs SuPHP. Who wins?
Answer: Lets deal with your security question first:
Mod_ruid2 is almost as secure as SuPHP. Both execute the scripts as a privledge isolated user. I give SuPHP the win by a wisker because it refuses to run files that are editable by everyone (666 and 777 perms), while mod_ruid2 will still execute this.
As long as you don't upload / setup insecure permissions mod_ruid2 is just as secure as SuPHP.
As for what I would use, that depends on a lot of factors. The better fit depends on more then just raw execution speed or security. You need to consider memory usage, the number of unique vhosts, etc.
mod_ruid2 is not compatible with a number of other apache modules and technologies that are also important from an overall performance perspective:

mod_cache (mod_disk_cache, mod_memory_cache, etc)
the newer apache mpms (mpm_event, mpm_worker, mpm_leader) that use threads instead of just processes.
FastCGI and other techniques that give you the same speed advantages as mod_ruid2.

If you are going to have a lot of different sites all doing PHP, then mod_ruid2 makes sense. If its a few sites, FastCGI makes a lot more sense.
Comment: Note that development of suPHP came to a halt: See the official [End of life](https://lists.marsching.com/pipermail/suphp/2013-May/002554.html) notice.
Comment: But mod_ruid2 will start as root then switch to the script owner, right (like mpm-itk)? So any vulnerability hitting before the setuid operation may allow an attacked to root the server. This don't happen with mod_php or suphp (as both run as non-root users).
Comment: mod_ruid2 starts as the apache user, just like mod_php and it changes to the vhost owner for each vhost request (i.e. before the script is loaded)

Mod_ruid2 vs. SuPHP


Forwarding a static website using Docker

Question: I have a website serving static HTML/client-side JS, running on a machine on my LAN. The website is accessible from 192.168.0.10:81, and there is no DNS.
I have another machine on the LAN which serves a number of internet-facing websites. These are accessible from 192.168.0.11:81-82, with each address having a DNS record. Each website exists in a Docker container, the the jwilder/nginx reverse proxy is used to map DNS to port addresses.
Is it possible to have a Docker container on the second machine 192.168.0.11:83, which serves out static content from 192.168.0.10:81 on the LAN? This would allow setting DNS environment variables from the docker-compose file. Is there a different approach to achieving this? A diagram of this situation:
Answer: On a reverse proxy I would add an record to website to forward specific traffic to machine a.
Or you can create another reverse proxy on machine b to forward traffic to A. But this is over kill, because of a same subnet of machine A, B and reverse proxy.


Qual regra posso usar para ter acesso administrador ao Firebase?

Question: Olá eu gostaria de saber se existe alguma regra no firebase firestore, onde apenas a conta do meu projeto possa ter acesso para modificação, isso sem ter que desenvolver um sistema de autenticação, ou seja, o simples fato de eu estar logado no google com minha conta do email já me dê permissão para tal feito...
https://firebase.google.com/docs/firestore/security/get-started?hl=pt-br
Procurei nesse documento, mas aparentemente nada que seja próximo do que eu quero.
Answer: você pode usar:
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.email == seu_email
    }
  }
}

no entanto eu recomendo utilizar customClaims, que são parâmetros que são gravados junto ao token de autênticacao do firebase.
para isso você precisa utilizar o firebase-admin
admin.auth().setCustomUserClaims(uid, {admin: true}).then(() => {
  // Os parâmetros irão se propagar tokens. talvez necessite de relogar com sua conta no app.
});

fazendo isto agora você pode utilizar as regras de segurança para o firestore (firestore rules):
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.token.admin == true
    }
  }
}

agora todos os documentos só poderão ser gravados e lodos pelo administrador.
mais informações em: https://firebase.google.com/docs/auth/admin/custom-claims#set_and_validate_custom_user_claims_via_the_admin_sdk
observação: para acessar o firebase-admin você precisará de uma conta de serviço. https://firebase.google.com/docs/admin/setup#initialize_the_sdk


jupyter notebook - ImportError: No module named 'bson'

Question: Trying to play with some jupyter notebook, I have an issue with the bson module which seams not available as reported in the error: "ImportError: No module named 'bson'"
I'm running jupyter notebook 4.3.0 over a python 2.7 kernel which is available in a dedicated virtual environment. I tried to install manually the bson module through a simple "conda install bson" but it's not in the official/standard repo so I had to install OpenMDAO/bson. Finally, it didn't change the issue. I understand that the module might come from the pymongo package so I tried to install with the same result.
Any hint here? What's the link between bson and pymongo?
Answer: You can advise this answer: import error: no module named bson
Which states that:

If you don't get the no module named bson error but the EPOCH_AWARE import error, this is due to a name clash between bson and pymongo.
  In this case, you should do these in order:

sudo pip uninstall bson
sudo pip uninstall pymongo
sudo pip install pymongo

In your case, try to start with a fresh virtualenv and do the above mentioned in the given order
That also answers the link between bson and pymongo.
Comment: Already seen that question and tested this. Tht'a why I created the question ;-). I didn't tried on a fresh virtualenv though.
Comment: Do that and comment if it goes as planed :)
Comment: Gave it another try and finally I got it to work by starting again from a fresh virtual env and triple checking this one was correctly installed within jupyter notebook with this http://help.pythonanywhere.com/pages/IPythonNotebookVirtualenvs
Comment: Good to know mate :) Happy coding!


Usual git workflow for a website with single functionality and two layouts

Question: I have a client that has a website which design is switched depending of the season (summer/winder). So basically it is the same functionality, but two versions of the template related files (css, JS, images etc.) I wonder what is the usual git workflow in such situations? I guess i need two branches, one for each design, but how to keep other files the same? Do I need to create submodule? If not, how to edit small file on both branches at once when i change something and that change needs to be commited to both branches?
Comment: What are you using for source control now and how are you managing the changes?
Comment: using git (mentioned in the caption) on a bitbucket account.
Comment: I guess you should create 3 projects : one main git repository for your main site, and two other for your themes (and have a command that can import one of the themes inside the main git repository). The themes shouldn't be in the same version control as the rest, as they seem to be completely separated.
Comment: what are you even trying to do?  Ofcourse you can do this via git , but just keep it for what its orginally meant to handle. Use two folders like summer and winter , keep the file name same since website is quiet simillar and just load files from 1 of them. You can even use 1 single css file to load other css files. And infact tbh summer and winter are far apart , you can do this manually per 5-6 months.
Comment: Ok, so you're using git now, how are you handling the theme switching currently?  Is that process not working for you?
Answer: Git is a tool to manage the source of one thing, and it is usually best practice to not put to many different things inside a git repository. For example, If you create a module that gives the possibility to add a payment method, create a new project for that (a git repository).
If the framework / CMS you use doesn't support having multiple themes installed and selecting one of them, you should consider the themes as being separate things, and separate them from the main project (into separate modules).
Answer: This is an issue of overall architecture, not one of source control (ab)use.  Trust me, you don't want multiple concurrent development streams.  All it will do is create headache.
Consider instead an abstraction which would allow you to factor the common resources out and enable a method of easily switching themes.  Consider using something like Less or Sass to help.


Remove orphaned module data after uninstall

Question: I have installed the xmlsitemap module, which is in alpha state. The module has an incomplete uninstall routine. Right now I am getting this error at /admin/config:

User warning: The following module is missing from the file system:
  xmlsitemap in drupal_get_filename() (line 240 of
  core/includes/bootstrap.inc). drupal_get_filename('module',
  'xmlsitemap') (Line: 263) drupal_get_path('module', 'xmlsitemap')
  (Line: 134) module_load_include('install', 'xmlsitemap') (Line: 93)
  module_load_install('xmlsitemap') (Line: 82) drupal_load_updates()
  (Line: 109) Drupal\system\SystemManager->listRequirements() (Line: 96)
  Drupal\system\SystemManager->checkRequirements() (Line: 102)
  Drupal\system\Controller\SystemController->overview('system.admin_config')
  call_user_func_array(Array, Array) (Line: 123)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
  (Line: 574)
  Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object)
  (Line: 124)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array,
  Array) (Line: 97)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
  call_user_func_array(Object, Array) (Line: 144)
  Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line:
  64) Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
  (Line: 57) Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1)
  (Line: 47) Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object,
  1, 1) (Line: 99)
  Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line:
  78) Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1)
  (Line: 47)
  Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1,
  1) (Line: 50)
  Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1,
  1) (Line: 23) Stack\StackedHttpKernel->handle(Object, 1, 1) (Line:
  656) Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

There are dozens of entries in my database, which are related to this module. Is there any quick way, to remove the module's orphaned data?
Answer: Use following database query to remove the module:
Drupal 8
DELETE FROM key_value WHERE collection='system.schema' AND name='module_name'

Drupal 7
DELETE from system where name = 'old_module1' AND type = 'module'

See: How to fix "The following module is missing from the file system..." warning messages.
Comment: That worked. The message is not appearing anymore. Apart from that there is orphaned data in the database, which must be cleaned manually.


given $a+b+c=3$ prove that $abc(a^2+b^2+c^2) \leq 3$

Question: I am preparing for inmo and I came accross this problem while solving a worksheet, but couldn't solve it, pl help me...
Problem-

Prove that if a,b,c are non negative real numbers such that a+b+c=3, then $abc(a^2+b^2+c^2)\leq3$ ... (0)

Developments-
Firstly applying am-gm on $a+b+c$ to get $abc\leq1$
Then applying quadratic mean arthematic mean to get
$a^2+b^2+c^2 \ge 3$
Then writing the expansion of $(a+b+c)^2$ we get
$a^2+b^2+c^2 = 9-2(ab+bc+ca)$ ...(I)
Thn applying am-hm on $ab+bc+ca$ to get
$ab+bc+ca \ge 3abc$
Then substituting in (I) we get
$a^2+b^2+c^2 \leq 9-6(abc)$
Then we substituting in (0)
$LHS \leq abc(9-6abc)$
Whose max value is $27/8$ but is not less than three, so I am stuck for this point onwards
Comment: $uvw$ kills it  as its lenear in $w^3$....
Comment: I didn't understand, I don't know any high level theorms, pl tell me what u mean In detail
Comment: You can use AM-GM here, like my solution.
Answer: WLOG $a\le b\le c$ so $\frac{b+c}{2}\ge 1$
let $$f(a,b,c)= abc(a^2+b^2+c^2)$$ now $$f(a,b,c)-f(a,\frac{b+c}{2},\frac{b+c}{2})=-\frac{1}{8} a (b - c)^2 (2 a^2 + b^2 - 2 b c + c^2)\le 0$$  let $t=\frac{b+c}{2}\ge 1$ So it suffices to show  $$f(a,t,t)\le 3 \iff f(3-2t,t,t)\le 3$$ but $$f(3-2t,t,t)-3=-3 (t - 1)^2 (4 t^3 - 6 t^2 + 2 t + 1)\le 0$$ which is true  because $4t^3-6t^2+2t=2t(t-1)(2t-1)\ge 0$
Done!
Comment: @tthnew your is also nice ,didnt think it was possible by AM-GM (+1)
Comment: Nice solution indeed!
Comment: Wow, MV method! Can you check my solution?
Comment: Thanks, +1 to you also.
Comment: Note that $f(a,b,c) \le f(a,\frac{b+c}{2},\frac{b+c}{2})$ together with the symmetry of $f$ and the domain already implies that the maximum is attained where $a=b=c$.
Comment: @MartinR can you elaborate ,if that is true my answer can be shortened ...
Comment: @AlbusDumbledore: Roughly: $f$ is continuous on the given domain and has a maximum. If that maximum is attained at some point $(a, b, c)$ with $b \ne c$ then the above inequality is strict and you obtain a contradiction.
Comment: @MartinR very interesting ,thank you!
Answer: Assume $a=\min\{a,b,c\} \rightarrow 0\le a \le 1.$
By AM-GM, we have $$abc\left(a^2+b^2+c^2\right) =\dfrac{1}{3} a\cdot
3bc\cdot\left(a^2+b^2+c^2\right)$$
$$\le \dfrac{1}{12} a \left[a^2+bc+\left(b+c\right)^2\right]^2\le \dfrac{1}{12} a \left[a^2+\dfrac{\left(3-a\right)^2}{4}+\left(3-a\right)^2\right]^2\le 3,$$
so it suffices to prove
$$\left( 9\,{a}^{2}-33\,a+64 \right)  \left(1-a \right) ^{3}\ge 0,$$
which is obvious since $0\le a\le 1.$
Done!
Answer: I will use a well known inequality for my solution -
$a^2b^2+b^2c^2+c^2a^2 \geq abc(a+b+c)$
$\implies (ab+bc+ca)^2 \geq 3abc(a+b+c) = 9abc$
Now using AM-GM,
$a^2+b^2+c^2+2 (ab + bc + ca) \geq 3 [(a^2+b^2+c^2)(ab+bc+ca)^2]^{1/3}$
$9 \geq 3[(a^2+b^2+c^2)(ab+bc+ca)^2]^{1/3}$
$3^3 \geq 9 abc(a^2+b^2+c^2)$
$3 \geq abc(a^2+b^2+c^2)$

On the inequality I used to answer comes from $(ab-bc)^2+(bc-ca)^2+(ca-ab)^2 \geq 0$.
Comment: +1 to be frank your solution is the best as it does not rely on crazy factorisation ,again,that substituiting in $(i)$ is confusing until second thought.I think your proof would be greatly simplified if you use the sub $p=a+b+c,q=ab+bc+ca,r=abc$ :)
Comment: What do you mean for substituting in (i) ?


Can we choose norms such that $\mathbb R^m\otimes\mathbb R^n\cong\mathbb R^{mn}$ is an isometry?

Question: $\mathbb R^m\otimes\mathbb R^n$ and $\mathbb R^{mn}$ are (algebraically) isomorphic. Is there a norm on $\mathbb R^{mn}$ such that this isomorphism is an isometry when $\mathbb R^m\otimes\mathbb R^n$ is equipped with the injective or projective tensor norm?
Answer: Yes, because these are finite-dimensional Hilbert spaces, the (Hilbert-Schmidt) norm on the tensor product is the standard one on $\mathbb R^{mn}$. Checking on a basis, or checking more abstractly, both succeed.
EDIT (in response to query from the original poster): what I would call the Hilbert-Schmidt norm on the algebraic tensor product of two Hilbert spaces $V,W$ is completely specified by
$$
\langle v\otimes w,\;v'\otimes w'\rangle \;=\; \langle v,v'\rangle_V\cdot \langle w,w'\rangle_W
$$
(This extends bilinearly to completely define the thing...)
Comment: How is the Hilbert-Schmidt norm defined for a tensor?
Comment: @0xbadf00d: please reread **your** question carefully and have a look at my answer to your question.
Comment: Thanks for editing. So, with "standard one" you mean the Frobenius norm on $\mathbb R^{mn}$, right?
Comment: Yes, what I call the Hilbert-Schmidt norm (for some Hilbert-space operator reasons) is also called the Frobenius norm, I believe.
Comment: @paulgarrett Afaik, that's correct. I think I haven't done a good job in writing my question; what I really want to know is if there is one of the "common" matrix norms such that the $\mathbb R^m\otimes\mathbb R^n\cong\mathbb R^{mn}$ holds isometrically when $\mathbb R^m\otimes\mathbb R^n$ is equipped with the injective norm.
Answer: Hint: if $A$ is isomorphic to $B$ as a vector space via some linear transformation $f: A \to B$ and if $B$ is equipped with a norm, there is a simple, obvious and unique way of equipping $A$ with a norm that makes $f$ an isometry.
Comment: Yes, maybe I should had state the question differently: If the tensor product is equipped with the injective norm, is that isomorphism an isometry when $\mathbb R^{mn}$ is equipped with one of the "common" norms (p-norm, Frobenius norm, etc.).


Loading ng-include partials from local pre-loaded (JST) template cache

Question: I have my template pre-loaded in a javascript string array, like var t = JST['firstTemplate'], where t would be like,

This scope has a value of {{value}}

How can I use this pre-loaded template in an ng-include directive?
Note that my template in this scenario can be more complex, with possible nested view and templates and their own nested scopes and controllers. So I am not sure if any of the ng-bind directives would help?
UPDATE:
Looking at the source of ng-include it appears that a good way to do this would be to decouple the template loading logic into a customizable provider.
The current default loading mechanism simply does a $http.get with $templateCache as the cache provider. It seems like I can inject my template content in JST['firstTemplate'] into the template cache, but I'd have to do that at startup time, for every template.
$templateCache.put('firstTemplate', JST['firstTemplate']);

and then have,

I could also write a custom directive that goes side-by side with every ng-include, that somehow does this pre-caching of templates. That again seem clunky.
UPDATE #2
I'm going to try overriding the templateCache, so that it uses my already pre-loaded JST hash. Will post the results if this works.
Comment: Just for the protocol: `` If you do not pass a string to ng-include, it tries to get the value from a scope variable with this name.
Answer: Here is the solution I found to work, and it's not a hack like I was thinking earlier (above :-) Basically, decorate the $templateCache.get method using standard $provide.decorator so that cache gets look in my local pre-loaded cache. It just works.
angular.module('app').config([
  '$provide',
  function($provide) {
    $provide.decorator('$templateCache', function($delegate, $sniffer) {
      var originalGet = $delegate.get;

      $delegate.get = function(key) {
        var value;
        value = originalGet(key);
        if (!value) {
          // JST is where my partials and other templates are stored
          // If not already found in the cache, look there...
          value = JST[key]();
          if (value) {
            $delegate.put(key, value);
          }
        }
        return value;
      };

      return $delegate;
    });

    return this;
  }
]);

If you're wondering why I have this stuff in JST, we use a rails backend and the rails asset pipeline to deliver all angular assets. The JST templates allow us to bundle all templates and load them into the app during initialization, and avoid additional server roundtrips that are normally required when fetching partials and other template content.
The above patch makes all of this works with angular.
Comment: Thank you for this patch also. I was using the raw JST Source. Now to play with this.
Answer: Instead of ng-include, use ng-bind-html:

On your controller, place the template on the $scope:
$scope.t = JST['firstTemplate'];

You will need to include ngSanitize as a submodule (don't forget to add angular-sanitize.js too):
angular.module('app', ['ngSanitize']);

Comment: From the documents, it looks like ng-bind-html does _not_ compile the template nor do other things ng-include does, like creating a new scope for it. I think want all that to happen. Am I mistaken on how ng-bind-html works?
Comment: You can use the `$compile` service for that.
Comment: Almost seems like we need an option on ng-include to tell it to use the template cache.
Answer: today i am faced with the same problem, here is my solution:
A custom directive, which return the JST"server/info" as template:
/* jstTemplate.js */

/**
 * @desc template loader for JST templates
 * @example

 */

angular
    .module('myApp')
    .directive('jstTemplate', jstTemplate);

function jstTemplate() {
    return {
        restrict: 'A',
        template: function(element, attrs) {
            return JST[attrs.jstTemplate]();
        }
    }
};

Usage:

The attrs.jstTemplate contains the value, we provided in the directive.
Cheers,
Niklas


Views to display recent content with user pictures

Question: I want to create a view displaying the recent content posted by users along with their respective pictures. I am able to Create the view displaying recent content but how to display the respective user picture who created the content along side the content.
Answer: Add a relation ship of the type content:author and use that relationship to add the user profile image.
Hope that helps.
EDIT : A description as per the comment
1) From RELATIONSHIPS(This would be in the advanced section on the right side) click on add. it will bring up a list of fields that you can add.
2) Add the Content: Author relation ship.
3) Now When you try to add the a field additional fields would be displayed related to the user you can select  User: Picture. The relationship author should be select.
Comment: Thanks for the fast reply...can u tell me how do i use the relationship content:authot to add the user profile image


Proving Dirac Delta property if the approximating functions aren't necessarily non-negative

Question: Here is my problem, as written:

A Dirac approximation sequence is a family of smooth functions $\{ \delta_1, \delta_2, \dots\}$ defined over $\mathbb R$  such that $\delta_n(x) = 0$ whenever $|x| > 1/n$, and for all $\epsilon$, there exists $N$ such that $\int_{-\epsilon}^{\epsilon} \delta_n(x)dx= 1 $ whenever $n>N$. Prove the sifting property of the Dirac delta: that if $f:\mathbb R\to\mathbb R$ is continuous, then $\displaystyle\lim_{n\to \infty} \int_{-\infty}^\infty \delta_n(x)f(x) dx = f(0).$

Here is a sketch of my approach: assume $f(0)=0$ by shifting. Now given fixed $\epsilon$, and for some $N$, we have for large $n>N$ that
$$ \left|\int_{-\infty}^{\infty} \delta_n(x) f(x) \right| = \left| \int_{-1/N}^{1/N} \delta_n(x) f(x)\right|.$$
Now since $f$ is continuous at $0$, if $N$ is chosen large enough, I can bound $|f|$ in $[-1/N,1/N]$ and find that the above is at most, say,
$$ \left|\int_{-\infty}^{\infty} \delta_n(x) f(x) \right| \leq \epsilon' \left| \int_{-1/N}^{1/N} \delta_n(x)\right|$$
where $\epsilon'$ is my chosen bound for $f$. So I need to bound the right expression with something independent of $n$: this could be done if $\delta$ is presumed to be non-negative (which, as far as I can tell, is how this question is answered elsewhere on this site). Presumably, I need to use the $\int \delta_n = 1$ property, but how can I continue without this non-negativity assumption?
Answer: Without non-negativity, it doesn't have to be true.
Let $\omega(x)$ be bump function: smooth, symmetric around $0$, $\omega(x) = 1$ when $|x| < 1/3$, $\omega(x) = 0$ when $|x| \geq 1$, $|\omega| \leq 1$, $\int\limits_{-1}^1 \omega(x)\, dx = 1$. Let $\delta_n(x) = \omega(n(x + 1/n)) \cdot n^2 - \omega(n(x - 1/n)) \cdot n^2 + \omega(nx) \cdot n$ - bumps around $-1/n$ and $1/n$ that compensate each other in integral, plus bump around $0$. Let $f(x) = x$. We have
$$\int_\mathbb R \delta_n(x) f(x)\, dx = \\
\int_{-2/n}^0 \omega(n(x + 1/n))\cdot n^2 \cdot x\, dx - \int_{0}^{2/n}\omega(n(x - 1/n))\cdot n^2 \cdot x\, dx + \int_{-1/n}^{1/n}\omega(nx) \cdot x\, dx = \\
-2\int_{0}^{2/n}\omega(n(x - 1/n))\cdot n^2 \cdot x\, dx < \\
-2\int_{2/(3n)}^{4/(3n)} 1 \cdot n^2 \cdot x\, dx < \frac{-2n}{3} \cdot \frac{2}{3n} = \frac{-4}{9}
$$
The problem is, even if $f$ is continuous, it can still break "balance" between parts that "compensated" each other in $\delta_n$ - in this case, by changing sign. Yes, for it $f$ has to be small near $0$, but the parts that "compensated" each other can be taken large enough so that even after multiplication by small value, their integral stays bounded away from $0$.
Comment: Thanks a lot: this is a really good answer.


SciPy instead of GNU Octave

Question: For my lab experiments I write small programs to help with the data analysis. I usually just need basic calculations, means, standard deviation, arbitrary weighted function fitting and plots with errorbars and fitted function.
With GNU Octave, I can do this. I started to read more into the language of it and I start to not like its inconsistencies and that I have to learn yet another language.
So I am thinking about using Python, which I am using for a while now, with SciPy and NumPy. Can I do those things with Python easily or is it more overhead to get the general purpose language Python to do what I intend to do?
Answer: Yes, the Python ecosystem makes it a viable platform for everyday data analysis tasks, especially using the IPython interface (but I'll stick to the standard one here.)  The "[not having] to learn yet another language" argument is a strong one, IMHO, and is one of the reasons why I tend to use Python for this stuff.
<code>>>> import numpy as np
>>> import scipy.optimize
</code>
"I usually just need basic calculations"
<code>>>> x = np.linspace(0, 10, 50)
>>> y = 3*x**2+5+2*np.sin(x)
</code>
"means, standard deviation"
<code>>>> y.mean()
106.3687338223809
>>> y.std()
91.395548605660522
</code>
"arbitrary weighted function fitting"
<code>>>> def func(x, a, b, c):
...     return a*x**2+b+c*np.sin(x)
...
>>> ynoisy = y + np.random.normal(0, 0.2, size=len(x))
>>> popt, pcov = scipy.optimize.curve_fit(func, x, ynoisy)
>>> popt
array([ 3.00015527,  4.99421236,  2.03380468])
</code>
"plots with error bars and fitted function"
<code>xerr = 0.5
yerr = abs(np.random.normal(0.3, 10.0))
fitted_data = func(x, *popt)

# using the simplified, non-object-oriented interface here
# handy for quick plots

from pylab import *
errorbar(x, ynoisy, xerr=xerr, yerr=yerr, c="green", label="actual data")
plot(x, fitted_data, c="blue", label="fitted function")
xlim(0, 10)
ylim(0, 350)
legend()
xlabel("time since post")
ylabel("coolness of Python")
savefig("cool.png")
</code>
Comment: Thank you very much for that detailed answer! That should get me started pretty quickly. I just have one little thing that I forgot to ask: How to handle the measurement and error tuples in a sane way. (I asked that [there](http://stackoverflow.com/q/12351837/653152).)

SciPy instead of GNU Octave


Add/hide blocks on user page

Question: I have some blocks for navigation and side bars that are appearing all over the site.
I want to hide the navigation and sidebars on the following urls:
node/78
node/19
user
messages

For some reason, drupal will hide the nav and side bars on node/78 and node/19 but not the user and messages pages.   How do I make it disappear from the user and messages page as well?
What I've done so far was click on Structure>Block, then go to the block I want, configure it, and list the paths for the blocks I want to hide.
Answer: I think your solution here is to also include user/* and messages/* in your list.
So the whole list would read:
node/78
node/19
user
user/*
messages
messages/*

Comment: Actually, it looks like `user` and `messages` aren't even necessary. Just include `user/*` and `messages/*` in your list on that block's configuration page.

Add/hide blocks on user page


Trying to use Apache Directory Studio to edit LDIF file results in "Permission Denied"

Question: I have created a Linux CentOS 7 VM, and on it, I've installed OpenLDAP.  Now, I need to modify the file olcDatabase={2}hdb.ldif. This is proving to be a challenge. I'd MUCH rather use a GUI tool than the command prompt. And a little bit of Google led me to Apache Directory Studio.
I think I have it installed correctly?  It doesn't show up anywhere under the "Applications" dropdown. (should it?)  I just extracted it into a new folder I named "Applicaitons", and I am able to execute it ok.
The file I need to open and edit is located here:
etc/openldap/slap.d/c=config

When I navigate there directly, I have to stop and enter my password when I get to slap.d

The problem I have is that when I try to open the file in question from within Apache Directory Studio using File > Open File, when I then try and drill into slap.d I get this error:

I've tried a few things that (might) work on windows, like looking for Right-Click > Run As Admin, etc.  I tried to execute Apache Directory Studio from a command prompt using sudo... that got me nowhere.
Not sure how to work around this.
Answer: With Apache Directory studio, you also don't change the files manually (which is what would happen if what you tried worked). Instead, it's a graphical tool that will help you to perform the LDAP operations to alter the config.
For this to work, you need to add an LDAP connection (bottom left, under "Connections"), point it to the LDAP server (whicht might be localhost in your case), and configure the Base DN as cn=config.
Offhand, I don't know the default values that a fresh OpenLDAP installation on CentOS creates for this. Maybe someone else can chime in here.
Comment: See also https://serverfault.com/questions/587721/basic-openldap-setup-using-slapd-d-configuration/587742#587742. This likely should work on CentOS 7 as well.
Comment: ok, thank you for this. The more I know, the more I know I don't know.  I need to spend more time looking at the docs for Apache Directory Studio.  I am flying so blind it's pathetic. I don't know the first thing about Linux or OpenLDAP.  As you say, I am going to need to figure out the default connection values for a fresh install.


Prevent cron from flushing the cache indiscriminately?

Question: I use Drupal 6 with the Cache Backport module, and all the available cache tables are configured to be stored in Redis (similar to Memcached in function for RAM caching). The caching works very well.
I have noticed that the amount of data stored in Redis gradually grows as the cache warms up, which is expected. However, the amount of stored data regularly drops suddenly to almost nothing.
I ran a test by loading up the cache by running a search for the word "the". Usually the amount of data stored in Redis will climb to between 20 and 40 MB on that query. Then, I ran the filter_cron job (I use the Ultimate Cron module and can run the different cron jobs selectively.) The Redis memory immediately dropped to almost nothing. After loading up the cache again to 20 - 40 MB, I ran the system_cron, which instantly resulted in Redis memory dropping even lower than it did on filter_cron. Both of these results are repeatable every time. So obviously both of the system and the filter cron jobs are indiscriminately flushing the Redis cache, which negates the purpose of a cache.
Can I prevent cron jobs from flushing the Redis cache, and if so, how? Is there not effective intelligent cache expiration logic on an individual key basis? Or would the cache system malfunction if I prevented it from being completely flushed by the cron job?
Thanks a lot for the help!
Answer: The cache is flushed by the system_cron() module, so basically the only way to stop it happening is to hack the core system module (very bad), or use something like Elysia Cron to schedule that particular cron job to run on a slower schedule. One of the module's features is:

Set the timings and frequencies of each cron task (you can run some jobs every day at a specified hour, other only monthly and so on...). For each task you can simply choose between some frequently used options ("once a day", "once a month" ...), or use a powerful "linux crontab"-like syntax to set the accurate timings. You can even define your frequently used options to speed up site configuration.

It's worth bearing in mind that system_cron() performs some other tasks as well (cleaning up deleted files, clearing the queue and batch tables, etc.), so using this method will slow down those tasks too.
Although it's a bit long winded, and not very future-proof, perhaps the only way to get to a satisfactory solution would be to implement a cron hook in your own module, which performs the tasks of system_cron() minus the cache flush. Then you can schedule the system_cron() to run on a slower schedule that suits your caching needs.
Comment: Thanks a lot for the reply. And do you know if the cache system will continue to perform in a sane manner using its own expiration logic? Or will it start serving up stale results?
Comment: I thought when cache_clear_all() gets called from system_cron(), just the expired entries are deleted b/c the first parameter is NULL.
Comment: Yes, that's what this says [here](http://drupal.org/node/1691116#comment-6352756), but it's clearly expiring everything, at least with my setup.


exim system filter foranyaddress condition wont work

Question: i am trying to setup exim system filter, it should be skipped for certain recipients, but condition always fails:
Filter looks like:
# Exim filter
if foranyaddress $h_to: ( $thisaddress contains "lists.example.loc" )
    then
        finish
    elif $h_X-SIGN-ADDED: is not contains "yes"
    then
        headers add "X-SIGN-ADDED: yes"
        seen pipe "/etc/mailsystem/sign/sign.py $sender_address $recipients"
endif

my test.msg is
Message-ID: <email@example.com>
Date: Mon, 25 Jun 2012 12:39:18 +0400
From: Hikaru <email@example.com>
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:13.0) Gecko/20120605 Thunderbird/13.0
MIME-Version: 1.0
To: <firstname.lastname@example.com>
 Subject: 1
 Content-Type: text/plain; charset=UTF-8; format=flowed
 Content-Transfer-Encoding: 7bit

 1

And command to run testing is:
exim -bF exim.filter -f firstname.lastname@example.com -bfd lists.example.loc <test.msg

Why it always runs pipe to script?
Thanks in advance
Answer: Seems to me, I found why it won't work: "foranyaddress" condition waits for list of addresses and won't work if there is only one recipient.
So, if "To:" header will be expanded to several addresses everything would work.


How to test differences of three categories within the same individuals?

Question: Suppose I can observe $Y_{ijt}$,  $i = 1,2,..., n$ , $j  = 1,2,3$ and $t = $ 3 weeks, 1 months, half a year and one year.
I am interested in whether

$E(Y|j=1,k) = E(Y|j = 2,k)= E(Y|j=3,k)$
$E(Y|j, k) = \alpha_j + \beta_j k $

At first, I thought it was a simple question that I can simply use ANOVA for different periods of time in the first case, and for the second I can run simple linear regression at given $j = 1,2,3$. Yet I realized that for each individual $i$ at given time period $t = k$, $Y_{i1k}$, $Y_{i2k}$ , $Y_{i3k}$ are likely correlated, which render ANOVA ineffective. I am what kind of model should I build to tackle these two questions that I want to tackle?
Answer: You can account for the covariance between time periods by using multilevel modeling. Marginal models directly model the population mean, so they may be most useful for you in this question of interest.
You could fit a marginal model such as this one (I'm assuming you meant t when typing k) and conduct the appropriate tests on coefficients.
$E(Y) = \beta_1 + \beta_2 I(j = 2) + \beta_3 I(j = 3) + \beta_4 t + \beta_5 I(j = 2) t + \beta_6 I(j = 3)t$
Marginal models can be fit using the nlme package (or gee for non-identity link functions) in R or PROC MIXED (PROC GENMOD for non-identity link functions) in SAS.
Comment: Hi, thx for the suggestion. The covariance not only exists between different time periods but also exists between different levels... for each individuals will have three different $y_{ij}$ corresponding to $j=1,2,3$, I don't think this model will be able to taken into account this unless I was mistaken something?


How to import tensorflow and keras

Question: from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
from tensorflow.keras import layers

model = Sequential([layers.Input((3, 1)),
                    layers.LSTM(64),
                    layers.Dense(32, activation='relu'),
                    layers.Dense(32, activation='relu'),
                    layers.Dense(1)])

model.compile(loss='mse',
              optimizer=Adam(learning_rate=0.001),
              metrics=['mean_absolute_error'])

model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=100)

I was able to run this in google colab.
My problem is when I downloaded the python file from colab and tried to run it using vscode and Jupyter I received the following error:
"Canceled future for execute_request message before replies were done
The Kernel crashed while executing code in the current cell or a previous cell. Please review the code in the cell(s) to identify a possible cause of the failure"
I then commented out the above code, and the rest of my code worked fine, but when I imported TensorFlow as tf (still leaving the code commented out) and changed nothing else, I received the same error again.
How do I fix this? I have done pip install tensorflow, removed
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
from tensorflow.keras import layers

changed all the layers. to tf.keras.layers. Nothing seems to be working. Any suggestions? New to TensorFlow, so I might be misunderstanding something.
Any help is greatly appreciated.
Comment: you are likely running out of memory or running a 32 bit python which has a limit of 4GB of memory.
Answer: It seems tensorflow has not installed in your system properly. Please follow the step by steps mentioned in this link to install tensorflow. Attached the same issue here for your reference,
You can run the .py file in jupyter notebook as command %run <filaname.py> after uploading the file in the same environment of jupyter notebook and can use <%load <filename.py> to load the entire file in jupyter notebook.
It could be more easy if you download the file in .ipynb format from Google Colab and can directly open the file in the jupyter notebook after uploading it into same folder where Anaconda has installed.

How to import tensorflow and keras


Criação de um site e um back-end com frameworks PHP

Question: Estou criando um site com sistema de back-end.
Sempre fiz este processo utilizando apenas um framework como Laravel ou Codeigniter, mas conversando com algumas pessoas mais experientes neste assunto, recomendaram utilizar Codeigniter ou Laravel só para o back-end e usar o silex que é uma micro framework.
A recomendação surgiu pelo fato de o silex ser mais rápido que estes macro frameworks. Gostaria de saber se isso realmente procede, ou posso continuar utilizando como venho fazendo?
Comment: Nunca use o codeigniter. Se quer desempenho use o [phalcon](https://phalconphp.com/) é um framework feito como uma extensão, agora o quanto mais rápido ele é não sei dizer.
Comment: @WallaceMaxters com motivo né ;)
Comment: Recomendar usar Codeigniter atualmente é como pedir para usarem clipper numa aplicação desktop :)
Comment: @rray concordo que `Codeigniter` é ruim, mas seu comentário demonstrou um grande teor de ódio pelo framework :D
Comment: Cara tomei -1 minha questão está para ser excluída, sendo que a minha pergunta é baseada na velocidade das frameworks...nossa cara!!! O que está acontecendo com o stack br??? A melhor resposta que tive foi a primeira que votei pq mostra gráficos....que absurdo isso!
Answer: De forma resumida, a afirmação de seus amigos procede. Grandes frameworks como Laravel ajudam o desenvolvedor a simplificar inúmeras tarefas tediosas do dia a dia, porém isso tem um custo. Eles carregam diversos pacotes que muita das vezes não são utilizados por sua aplicação,o que acaba gerando um overhead.
Já um microframework é mais rápido devido a quantidade pequena de pacotes que carrega intrinsecamente consigo, você terá que instalar manualmente algum pacote que não venha por padrão, o que gera um trabalho extra porém melhora na performasse.
Se você quer mesmo é velocidade, recomendo utilizar o Phalcon ele é um full-stack framework, porém como é escrito em C, sua velocidade e monstruosa. Abaixo segue um benchmark para você ter uma ideia do quão rápido ele é.
Answer: O que é mais importante para você? Execução da aplicação ou a velocidade de desenvolvimento?
Embora o micro framework seja naturalmente mais leve, ele não terá todos os recursos de um framework full stack, que já incluem tudo isso de forma bem integrada.
Você pode criar todas essas integrações em um micro framework, mas você quer ter que manter esse tipo de código na sua aplicação? As bibliotecas que sua aplicação utiliza podem sofrer atualizações e você vai precisar alterar esse código.
Tudo depende do objetivo do seu projeto. Muita gente recomenda os micro frameworks por estar em evidencia. E realmente faz sentido usar o micro framework se temos uma arquitetura em micro services, onde todos os recursos de um full stack se tornam dispensáveis.
Entretanto, qual a vantagem de começar com um micro framework e implementar 90% de um framework full stack e ter que manter toda essa integração?
Concluindo, os micro frameworks tem uma performance melhor, pois tem menos recursos. Porém a cada recurso ou integração que você precisar, mais overload será adicionado, chegando até a passar um full stack se não fizermos da melhor forma. Já com um full stack, você vai carregar coisas que não precisa, porém tudo que você precisa utilizar já está integrado e basta usar.


ERROR CODE 1215 - Você não pode add a chave estrangeira

Question: Tabela 1:

Tabela 2:
Comando: ALTER TABLE extras ADD FOREIGN KEY (login) REFERENCES usuario(login);
Resposta: Error Code: 1215. Cannot add foreign key constraint

Não é possível encontrar um índice na tabela referenciada onde as
  colunas referenciadas aparecem como as primeiras colunas, ou os tipos
  de coluna na tabela e a tabela referenciada não correspondem à
  restrição. Observe que o tipo de armazenamento interno de ENUM e SET
  mudou em

Não consigo identificar o motivo do erro. Alguém pode me ajudar?
Ps. como podem ver, os dois campos estão com o mesmo tipo ( varchar (15) )
Desde ja obrigado
Comment: Qual SGBD você está usando?
Comment: estou usando o Mysql
Answer: Aparentemente está certo sua estrutura, verifique se o tipo de tabela está como InnoDB mesmo, elas podem estar como MyISAM o que não permite criação de FK, segue script que criei à partir do seu print e funcionou normalmente:
CREATE TABLE IF NOT EXISTS `usuario` (
  `login` VARCHAR(15) NOT NULL,
  `nome` VARCHAR(40) NOT NULL,
  `senha` VARCHAR(10) NOT NULL,
  PRIMARY KEY (`login`))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `extras` (
  `idFunc` INT NULL,
  `login` VARCHAR(15) NOT NULL,
  `data` DATETIME NULL,
  `extra` TEXT NULL,
  INDEX `fk_extras_usuario_idx` (`login` ASC),
  CONSTRAINT `fk_extras_usuario`
    FOREIGN KEY (`login`)
    REFERENCES `usuario` (`login`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

Comment: As duas estão criadas como InnoDB.
Comment: Tentou rodar o script que postei?
Comment: Eu refiz as tabelas e deu certo. Geralmente gosto de tentar entender o erro, mas como estava sem tempo optei pela solução mais ágil


How To Alter Web Form Elements Permanently?

Question: Webform elements can be altered using the function MYMODULE_form_alter. However the changes are not permanent. For example, if you're changing the title of an element from '#title' => t('Old Title') to '#title' => t('New Title') ,the change will not affect source - the (View) Source page will still show '#title' => t('Old Title')
So my question is: Is it possible to alter the source (YAML) from code because that will make changes permanent.I have tried to locate weformX.yml for webformX inorder to alter it in code but I can not find.
Answer: You can alter the yaml source of a webform by loading the config entity and modify elements:
use Drupal\webform\Entity\Webform;
use Drupal\Core\Serialization\Yaml;

  $webform = Webform::load('contact');
  $elements = Yaml::decode($webform->get('elements'));
  $elements['name']['#title'] = 'Please fill in your name';
  $webform->set('elements', Yaml::encode($elements));
  $webform->save();

Comment: This is the right answer it is working.But somebody down-voted my question without a comment. I use this to populate cascaded dropdowns instead of hitting the db again and again in form_alter. This have improved the response time of the application
Comment: I think this is a very good question, because this is a special case. The yaml source of the form elements is not like normal configuration, it's embedded in the webform config entity. So you have to load the configuration and extract the value or if you export the configuration you have yaml embedded in yaml.


Check wordpress post for specific HTML tag . Else show post thumbnail

Question: I guess this question must have been asked here before, but i couldn't find the topic so bear with me.
I'm trying to achieve an if/else statement in PHP to find a specific HTML tag with a certain classname. If this HTML tag is found i want it to display the HTML tag otherwise if not found, i want it to show the post thumbnail.
All this needs to be done in a wordpress template (single.php).
So i have this:
if (strpos($post->post_content, ('img[.ngg_displayed_gallery]') === false)){
        $gallery = false;
          the_post_thumbnail('full');
          echo do_shortcode('[shareaholic app="share_buttons" id="390155"]');
        }
else{
    echo ('img[.ngg_displayed_gallery]');
    echo do_shortcode('[shareaholic app="share_buttons" id="390155"]');
    }

I'm pretty sure i screwed this code up so please help me. I'm very bad with PHP ;)
Thanks for the help!
Edit:
Ok.. i'll try to be more clear:
When someone edits a wordpress post and adds a Nextgen Gallery in the content editor there is this HTML string:

So basically i want to code something like this: When this HTML IMG string appears in the content field, show that INSTEAD of the post thumbnail (featured image).. If that HTML IMG string is NOT in the content field, show the post thumbnail (featured image).
Comment: `img[.ngg_displayed_gallery]` is a selector. `` is a html tag.
Comment: Meaning? I should right it down like so? if (strpos($post->post_content, ('') === false)){ ??
Comment: You need to describe what your trying to do more accurately, so we can help you.
Comment: I've added a more detailed description
Comment: Please... can someone provide an answer?
Answer: From what I understand from the question, you need to find a html tag in the contents of string, you are using strpos(). I want to let you know this is bad practice and alternative should be used instead, however, here is an example.
// First we must get the HTML formated content.
$content = apply_filters ("the_content", $post->post_content);

// We then must indentifie the needle in the heystack (content)
$needle = 'ngg_displayed_gallery';

if (strpos($content, $needle) === false)){
    $gallery = false;
    // No, there's no gallery present
    echo "NO, gallery not found";
} else {
    // Yes there is an gallery present
    echo "YES, gallery found";
}

Q1. Why is this bad practice?
We can find the id of gallery/image reliability, as each  is different in src, id and possible class


In linux every process is given a 4GB of virtual address space considering a 32-bit architecture

Question: Hi I am new to Linux Kernel Development. So want some clearity for the following statement.
*> In memory, every process is given a 4GB of virtual address space

considering a 32-bit architecture. The lower 3GB virtual addresses is
  accessible to the user space portion of the process and the upper 1GB
  is accessible to the kernel space portion.*

Does it mean that each process in linux is allocated that much memory space 1GB+3GB?
If yes then there are hundreds of process in linux , so 100*4GB space from where the system gets so much of memory space?
What it has relation with the kernel stack and user stack ?
Does every process in linux has kernel and user stack ?
Comment: You should learn how Virtual Memory is working. There is physical memory (actual RAM) and virtual memory (mappings to a RAM, which may exist or not). 4Gb is a limit of mappings (that is not necessary to be used entirely).
Answer: Intro
Linux, like most modern operating systems, uses virtual pages provided by most modern architectures, including the x86 family.
In a system with virtual memory, the physical memory (actual RAM resource) is abstract from the process running on the system. An address space is just all the numbers where memory could be.
Paging
Memory can be mapped (put at an address) in pages which is the architecture dependent size of a memory chunk. So if you want to put memory at some address so the process can use it, then you'd have to pick a page aligned number (a multiple of the page size) and place at least one page there.
Protection
Virtual memory also allows for memory protection which sets what permissions the process will have. When a process's executable memory is mapped (the instructions it executes to do stuff) it is read/execute only. This means that the processor can execute that memory, and you can read it, but you can't write to it.
When a process is loaded from disk (in Linux with the exec system call) it is placed in memory with several regions of memory already mapped. These regions are the executable code from the program, data sections, and stack. The process can request more memory to be mapped later by using the mmap or brk system calls.
When a process tries to access memory it does not have mapped, it triggers the infamous SEGFAULT error, and the kernel will kill your program. Other times, the hardware will fault but the program does have memory mapped, this is because the kernel unmapped it to save it until it is needed. What happens here is the process stops running, the kernel remaps the memory, and your process starts running again like nothing happened.
Address Space
So the size of the address space is just the upper limit of the memory you could have if the program had mapped every address it possibly could to actual RAM memory.
The one gig address space to the kernel part is about the process's meta-data that the kernel keeps track of. For instance, it will keep a listing of open files, and mapped memory in the process headers. It will also keep thread headers there. Again, all of it is not mapped, only what it needs.
Note that each process has its own universe of addresses, it never sees what another process has mapped at those addresses. This way, the process can act as if it is the only process on the machine, mapping memory to any address it chooses.
Also note, the 4gb number is because the hardware that does addressing supports only 32 bit numbers, the largest number one can hold in a 32 bit number is 2^32 = 4,294,967,296. This is 4 gb. So one can only map 4gb of addresses to memory.
This is just a crappy intro, please do some googling on virtual memory.
Comment: This much i now but my question is that there are many processes running at a time like firefox chrome running at same time in linux. But if 4 gb is allocated to chrome how firefox will get memory fot its operation.
Comment: Also what is the things that the kernel stack size is limites to 8KB. and what is its relation to the 1 GB of space.
Comment: @Dpk That's what I attempted to say. A process doesn't have 4gb of actual RAM allocated to it. Each process starts off with a very small amount of memory (a few pages, a page on x86_64 is 4kb), as it allocates more memory, more pages are added. Each process is running by itself (exclusively on its own core) and is swapped out for other processes, when it is swapped in (scheduled) the memory for that process is mapped in the address space. So each process gets its own 4gb address space that does not clash with other programs.
Comment: @Dpk as for the stack size. I think you may be thinking 8mb, and its the kernel's limit on stack size. When a program is launched, it is given some pages for stack. To save memory, it does not map all of the stack pages at once, and the stack will grow. The stack is positioned at a high address and grows down towards lower addresses. When your program tries to access memory lower than what memory the kernel has mapped, the kernel will map more memory (same thing as `SEGFAULT` hardware interrupt except the kernel will just map more memory). That is, until it reaches a limit (8mb).
Comment: @Dpk Remember that there are never really more than one process running at a time (on a core). And each core has its own hardware for mapping memory (MMU). This is why firefox and chrome are not competing for space in the same 4gb memory space, because they never see each other. Their address spaces will never collide.
Comment: @Dpk Also note that the kernel 1gb is mapped to the same kernel RAM memory (some is core specific) (not all of it may be mapped, the kernel may be smaller than 1gb, or some may not be paged in). Also note that the kernel can page in/out memory to disk. So that's what happens to memory that is unmapped between process switches. Some of it may stay in memory, some of it may be shared between many processes (e.g. shared libraries).
Comment: @Dpk If every process were to attempt to map a bunch of memory, many wouldn't be actually paged in until used. Once the available memory resources (RAM & Disk (swap)) ran out. The OOM (out of memory) killer comes into play and kills off processes. This actually happens a lot on smaller memory systems when too many chrome tabs kills off spotify or something. Also, more and more swap is used once the actual RAM memory runs out. (Sorry for the long comment chain)
Comment: One more question how to know the size of user stack of a process thread.

And if one process has some data of say 400MB and other of others of 800MB and other say some more processes so some more MBs of data.
So how OS stores temporary that data.
e.g. If one firefox swap in .. iw will think as 3GB is allocated to its self only
if chrome will come it will swap in and swap out firefox first.
so where the firefox data  willl be stored temporary so that the same can be used when it swap in again in future.
Comment: @Dpk If I understand correctly, you're asking what happens to the data stored in memory is one process is swapped for another. If both chrome and firefox are using almost all of the available memory ~3gb, then the OS can't just leave it in RAM but unmapped to the process like it would if there were RAM to spare. In this case, the OS swaps the memory out to disk, using a swap partition or swap file. That's why a process can use 3gb of memory if your system only has 2gb of RAM, the OS will swap to disk and back as needed (although swapping takes time, so it will be a bit slower).
Answer:
Does it mean that each process in linux is allocated that much memory space 1GB+3GB?

No. All processes share the same kernel space. In addition, these are the maximum theoretical limits. They can be further restricted by system settings, process settings, and the size of the page file. Even if a system allowed a process to grow to the maximum side, processes generally start small and have to grow to reach the maximum.

If yes then there are hundreds of process in linux , so 100*4GB space from where the system gets so much of memory space?

See above. If allowed, such memory space would be on disk in the page file (partition).

What it has relation with the kernel stack and user stack ?

They are separate stacks. The kernel stack is located in the kernel space and the user stack is in the user space. The processor uses the kernel stack when executing in kernel mode and the user stack while in user mode. The switch is automatic as part of hardware switch between modes.

Does every process in linux has kernel and user stack ?

Yes. There is one for each thread. Kernel stacks tend to be small.
Comment: what is the things that the kernel stack size is limites to 8KB. and what is its relation to the 1 GB of space.

Also how to know the size of user stack for the process ?
Comment: I believe Linux limits the kernel stack to 2 pages (8KB). The kernel stack does relatively simple things so it does not need to be large. All kernel stacks are within the 1GB of system space. The stack size for a thread or process can change.
Comment: How ot know the size of user stack for a process/thread in linux.


Denseness of the set $\{f: \int_0^1 x^\alpha f''(x) dx = \int_0^1 x^\beta f''(x) dx = 0 \}$ in $C[0,1]$

Question: Let $\alpha, \beta \in (-1,1) \setminus \{ 0 \}$. Is it true that the set
$$
\left\{f \in C^2[0,1]: \int_0^1 x^\alpha f''(x) dx = \int_0^1 x^\beta f''(x) dx = 0 \right\}
$$
is dense in $C[0,1]$? I think it is not, but have no idea how to prove it. In case $\alpha, \beta \geq 1$ it is quite easy since we can use integration by parts twice and rewrite the condition without derivatives, but I do not know what to do if $\alpha, \beta < 1$.
Answer: Your set seems to be indeed dense in $\mathcal C([0,1])$. Without loss of generality, assume that $\alpha\neq \beta$.
We need the following fact:
$\mathbf{Fact.}$ Given a compact set $K\subset\mathbb R^2$, there is a constant $C$ such that the following holds: for any $(p,q)\in K$ and $A>1$, one can find a function $\Phi\in \mathcal C^2([0,A])$ such that $\int_0^{A} \Phi''(t)t^\alpha dt=p$, $\int_0^{A}\Phi''(t)t^\beta dt=q$ and $\Vert\Phi\Vert_\infty\leq C$.
Assuming this has been proved, let us show that your set (call it $\mathcal A$) is dense in $\mathcal C([0,1])$.
By something like Weierstrass theorem, it is enough to approximate any $\mathcal C^2$ function; so let us fix $f\in\mathcal C^2([0,1])$ and $\varepsilon \in (0,1)$.
Put $L_\alpha(f)=\int_0^1 f''(x)x^\alpha dx$ and $L_\beta(f)= \int_0^1 f''(x)x^\beta dx$. Choose $\gamma >0$ such that $\gamma(1-\alpha)>1$ and $\gamma(1-\beta)>1$ By the above fact applied with $K=\{ (p,q);\; \vert p\vert\leq \vert L_\alpha(f)\vert\;{\rm and}\; \vert q\vert\leq  \vert L_\beta(f)\vert \}$, one can find a function $\Phi\in\mathcal C^2([0,{\varepsilon^{-\gamma}}])$ such that $\int_0^{{\varepsilon^{-\gamma}}} \Phi''(t)t^\alpha dt=\varepsilon^{\gamma(1-\alpha)-1}L_\alpha(f)$, $\int_0^{{\varepsilon^{-\gamma}}}\Phi''(t)t^\beta dt=\varepsilon^{\gamma(1-\beta)-1}L_\beta(f)$ and $\Vert\Phi\Vert_\infty\leq C$, where $C$ does not depend on $\varepsilon$. Now define $g$ on $[0,1]$ by $g(x)=f(x)-\varepsilon\, \Phi({\varepsilon^{-\gamma}}x)$. Then $g\in\mathcal C^2([0,1])$ and $\Vert g-f\Vert_\infty\leq C\varepsilon$. Moreover,
\begin{eqnarray*}\int_0^1 g''(x)x^\alpha\, dx&=&L_\alpha(f)-\varepsilon^{1-2\gamma}\int_0^1\Phi''({\varepsilon^{-\gamma}}x)x^\alpha dx\\
&=&L_\alpha(f)- \varepsilon^{1-\gamma+\gamma\alpha}\int_0^{\varepsilon^{-\gamma}}\Phi(t) t^\alpha\, dt\\&=&0\, ,
\end{eqnarray*}
and likewise $\int_0^1 g(x)x^\beta dx=0$. So $g\in\mathcal A$, and since $C$ does not depend on $\varepsilon$, this shows that $\mathcal A$ is dense in $\mathcal C([0,1])$.
To prove the fact, we first note that given $p,q\in\mathbb R$, one can find a quadratic function $\psi(x)=ax^2+bx+c$ such that $\int_0^{1} \psi(x)x^\alpha dx=p$, $\int_0^{1}\psi(x)x^\beta dx=q$, $\psi(1)=0$ and $\vert a\vert+\vert b\vert+\vert c\vert\leq M (\vert p\vert+\vert q\vert)$, where $M$ is a constant depending only on $(\alpha,\beta)$. Indeed, this amounts to solving the linear system
$$\left\{
\begin{matrix}\frac{1}{\alpha+3}& a&+&\frac{1}{\alpha +2}& b&+&\frac{1}{\alpha +1}& c&=&p\\
\frac{1}{\beta+3}& a&+&\frac{1}{\beta +2}& b&+&\frac{1}{\beta +1}& c&=&q\\
&a&+&&b&+&&c&=0
\end{matrix} \right. $$
whose matrix depend only on $(\alpha,\beta)$ and turns out to be invertible (I'm skipping some row manipulations here).
It follows that for any $(p,q)\in\mathbb R^2$ and any $A>1$, one can find a function $\varphi\in\mathcal C([0,A])$ such that $\int_0^A \varphi(t)
t^\alpha dt=p$, $\int_0^A\varphi(t) t^\beta dx=q$, $\varphi\equiv 0$ on $[1,A]$ and $\Vert\varphi\Vert_\infty\leq M(\vert p\vert+\vert q\vert)$ for some constant $M$ which does not depend on $(p,q)$: just define $\varphi$ to be equal to the above quadratic function $\psi$ on $[0,1]$ and $\varphi\equiv 0$ on $[1,A]$.
Now, let $K$ be an arbitrary compact subset of $\mathbb R^2$ and let $A>1$. For any $(p,q)\in K$, define $\Phi:[0,A]\to \mathbb R$ by $\Phi(t)=\int_1^t\int_1^s \varphi (u) du$, where $\varphi$ is as above. Then $\Phi\equiv 0$ on $[1,A]$, so $\Vert\Phi\Vert_\infty\leq C$ for some constant $C$ depending only of $K$; and $\Phi$ does the job.
Comment: Looks great! Thanks.
Comment: You're welcome!


How to draw conclusions based on Statistically Equal data sets?

Question: I just have a question about statistical significance that I can't wrap my mind around.
So lets say we put out a survey comparing male and females and their frustration levels doing any sort of tasks. from like lets say a scale of 1-5 with 5 being highest level of frustration/anger and whatever
The results come back and lets say....males have a mean score of like 4 while females have a lower mean score of lets say 2.
Now I want to compare the data from the sample of males and females and draw the conclusion that hey males have a higher frustration level on average to do whatever task. But first I complete a t-test lets say Welchs to make sure taht the data is okay to compare.
So I compute a tvalue of .264 and a t value at 90% confidence interval with whatever degrees of freedom of 1.943. Became my t90CI value is greater than my tvalue I draw the conclusion that the female and male data sets are statistically equal.
Does this now mean that I can now effective draw the conclusion from my data collection that "hey males experience significantly higher frustration levels on average"?
Sorry for making this post so long
Comment: a tvalue of .264 means you cannot say "males experience significantly higher frustration levels on average".
Comment: so if my t90CI value I calculate is less than my tvalue I can then say that the data is statistically difference and draw the conclusion i want right?
Comment: Whose CI will you calculate? difference of the means? If so, based on 0.264, the CI will include 0. So you still cannot get what you want. If you calculated you t value correctly (=0.264), absolutely, you cannot get what you want.
Answer: Your null hypothesis (assuming a two tailed test) is that the mean for the men $\mu_{m}$ equals the mean for the women $\mu_{w}$, that is
$H_{0}: \mu_{m}=\mu_{w}$ against the alternative $H_{1}: \mu_{m}\neq\mu_{w}$.
Your test statistic is calculated assuming the null hypothesis is true. Since you didn't get an "extreme" value for your test statistic you have little evidence that the null is actually false (that is your statistic isn't bigger than your critical value.) The same idea holds for a one sided test if that is actually what you are interested in. Essentially your data is not extreme enough to reject your null hypothesis. All you can conclude is that, "we failed to reject the null hypothesis with $\alpha = 0.1$".
Short answer: No you can't conclude that males and females are different.
Comment: thanks for the feedback. I have not taken statistics at all so im in the blue here. but is there another test to use besides Welch's t test to see if the results/mean are affected by male or female respondants. Or was this the right  approach?
Comment: @Tommy it depends on your sample size for the two groups among other things. How many responses did you have from men and from women? And what is your research hypothesis, that is what are you hoping is true, that their is a difference?
Comment: Sorry for the late response. Well my sample size for the male was 65 and female was 105. This was a survey where i got x and y results of like frustration level. But I am not sure if i can actually say hey the mean result of males is significantly higher than females. And was looking for a way to prove it. I am not sure if i am making any sense
Comment: @Tommy it seems like the correct approach, and the result was you just couldn't reject the null.


proving that closed subspace of complete metric space is complete

Question:
$4.9$ Let $A$ be a subset of a metric space $S$. If $A$ is complete, prove that $A$ is closed. Prove that converse also holds if $S$ is complete.

For the first part, I assumed $\{ a_n\}$ to a Cauchy sequence in $A$. And since $\{a_n\}$ converges in $A$, the limit point of $\{a_n\}$ also lies in $A$ making $A$ closed.
I need proof of the converse and example that it does not hold if $S$ is not complete.
Comment: See also [Showing that if a subset of a complete metric space is closed, it is also complete](https://math.stackexchange.com/q/244661) and [Proof that a subspace $A$ of a complete metric space $X$ is complete iff $A$ is closed](https://math.stackexchange.com/q/243199).
Answer: I would argue that you need to flesh out the first part a bit.  But, leaving that aside, let's look at the converse.
You want to show that if $S$ is a complete metric space and $A\subseteq S$ is closed, then $A$ is complete.  So, naturally, you want to consider a Cauchy sequence $(a_n)_{n\in\mathbb{N}}$ of elements in $A$.  Note that a sequence in $A$ is also a sequence in $S$, and $S$ is complete; also note that $A$ contains all of its limit points.  You should be able to put those together to finish the result.
As far as a counterexample: think about $S=\mathbb{Q}$, with its usual metric inherited from $\mathbb{R}$. Can you think of any sets that are closed in $\mathbb{Q}$ but which have possible limit points (from $\mathbb{R}$) missing?


Fubini-Study on $\mathbb CP^1$

Question: I am trying to prove that on $\mathbb CP1$ the Fubini-Study form $\omega_{FS}$ is a quarter of the standard form $\omega_{std}= d\theta\wedge dh$ on $S^2$, where we identify $S^2$ with $\mathbb CP^1$ through the stereographic projection.
My take on this:
Let $\psi: S^2\setminus\{N\}\to U_0$ (where $U_0=\{[z_0:z_1]\in\mathbb CP^1: z_o\neq 0\}$) such that $\psi(\theta, h)= [1: \frac{\cos\theta}{1-h}+ i\frac{sin\theta}{1-h}]$. We know that on $[1: x+iy]\in U_0$ the Fubini-Study form is $\omega_{FS}= \frac{dx\wedge dy}{1+x^2+y^2}$. So I tried to pull it back through $\psi$ and prove that $\psi^*\omega_{FS}= \frac14 \omega_{std}$ but I can only show that $\psi^*\omega_{FS}= \frac{d\theta\wedge dh}{(1-h)^2(2-h)}$.
Answer: Your formula for the Fubini-Study form is incorrect.  The correct formula is $\frac{dx\wedge dy}{(1+x^2+y^2)^2}$.  There is a similar formula for the metric, introduced already by Riemann in his 1857 address.
Comment: Is this for sure? I still cannot make it work...
Comment: You can see some details on page 227 of these lecture notes: http://u.cs.biu.ac.il/~katzmik/egreg826old3.pdf

Fubini-Study on $\mathbb CP^1$


What is the right attitude toward open source machine learning toolkits?

Question: There are lots of machine learning toolkits nowadays, such as weka, sklearn, R libs.  If we choose to use these toolkits, besides that it is convenient, sometimes we might lose control of what is really happening.
For example, in some learning methods the value of features should be scaled to $[0,1]$, but there may be lots of different methods which can achieve this. When we use a scaling function provided by a specific toolkit, we just don't know what's really happening, and this will cause trouble, say, when we want to check if different scaling would affect the performance of learning algorithms.
If the learning system is entirely implemented by ourselves, there could not be that much confusion, since we know exactly what happens.
So what is the right attitude toward open source machine learning toolkits?
Just use them for the first phase, and then implement manually without the help of learning toolkits in order to have more control over algorithms, or can we just rely on such kinds of learning toolkits?
Comment: My view is that good OS libraries should have sane, override-able, defaults. Scikit-Learn is a good example of this (Weka is poorer example). That way the programs are explicit only when required. To program your own just to have more control can be overkill in 90% of cases -- better is to fork to OS library and added in the pieces you want.
Answer: Related answer: https://stats.stackexchange.com/a/66420/25433

If we choose to use these toolkits, besides that it is convenient, sometimes we might lose control of what is really happening.

This is not at all specific to open source toolkits. In fact, in open source programs it's easier to make changes where and when necessary. Additionally, if you add fundamental functionality you can become a contributor for the package to get a win-win situation.

If the learning system is entirely implemented by ourselves, there could not be that much confusion, since we know exactly what happens.

Probably. On the other hand, implementing from scratch takes a lot of knowledge, time and effort, especially if you want to do proper unit testing and what not (which most popular open source software solutions do provide). Also note that machine learning practitioners are often not software engineers, which makes (re)implementation far from trivial.

So what is the right attitude towards open source machine learning toolkits Just use them for the first phase, and then implement manually, without the help of learning toolkits in order to have more control over algorithms, or we can just rely on such kinds of learning toolkits?

The most important thing in my opinion is to be aware of what exists (for example here and here). More often than not, you can find what you need in open source (maybe after some fiddling here and there). Don't reinvent the hot water.
Never assume that open source software (or any software for that matter) is bug-free. If you get weird results, question the tools you used. The larger the userbase of a given package, the safer you are from critical bugs in the software. Users are inevitably the best testing bed for any software system. You can assume to be fairly safe from major issues in popular packages like weka, shogun, opencv, ...
This is another related question that might be particularly relevant for machine learning. A lot of academic open-source software is released as a proof-of-concept. Such implementations -- often at the cutting edge of algorithms with fairly few users -- should be treated with care. The smaller the userbase, the less scrutiny software has received.


How to use #selector correctly in Swift?

Question: I'm adding a reload button for iOS in-app web browser using WKWebView.reload
I tried two options, and the two options works for me the same but I want to know what is the technical correct option to use with #selector. Is it #selector(class.method) or #selector (object.method)  ?
Here is the first:
let webView = WKWebView()
view = webView
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(WKWebView.reload))

and here the second one:
let webView = WKWebView()
view = webView
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(webView))

Here is the full code
import UIKit
import WebKit

class ViewController: UIViewController {

    let webView = WKWebView()

    override func loadView() {
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(WKWebView.reload))
    }
}

Comment: Possible duplicate of [@selector() in Swift?](https://stackoverflow.com/questions/24007650/selector-in-swift)
Answer: Your let webView = WKWebView() is creating a new instance of yours.. it won't work independently of your #selector
try it out:
func reloadWebView() {
    webView.reload()
}

your call:
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(MyViewController.reloadWebView))

Comment: No it works, you can try the full code I added to my question, but first don't forget to embed your view controller in a navigation controller.
Answer: The function reload is not declared as @objc, therefore, it won't work as selector in swift. You may want to create a function in your ViewController and call the reload function from there.
@objc func reloadWebView() {
    webView.reload()
}

and your selector will look like this
#selector(reloadWebView)
Source: https://developer.apple.com/documentation/webkit/wkwebview/1414969-reload
Comment: No it works, you can try the full code I added to my question, but first don't forget to embed your view controller in a navigation controller.
Answer: Currently, my recommendation is using #selector(target.method).
When you pass self as target then, #selector(self.method), passing webView to target, then #selector(webView.method).
#selector is just an encoded ObjC method name (which does not include class name), so both #selector(ClassName.method) and #selector(object.method) should work. But you can expect a better compile-time diagnostic with #selector(target.method).


How do I make a backup of a PLSQL db?

Question: How do I make a backup of a PLSQL db?
Comment: WHAT I MENT IS HOW TO USE SQL COMMAND SUCH AS 'SQL>ALTER TABLESPACE BEGIN BACKUP ;'
AND  'SQL>HOST COPY SOURCE TARGET' AND 'SQL>ALTER TABLESPACE END BACKUP ;'
Comment: put a bunch of "execute immediate" statements in a pl/sql block is what I think you're asking about
Answer: The question is do you really want to do it from PL/SQL?
Assuming you are using an oracle DB they have commands that will dump your DB into a file. It is dumped in such a way that the DB (tables and all) can be re-created from scratch (so you can re-create a secondary backup [not that I would recommend this way]).
Here is the FAQ
http://www.orafaq.com/wiki/Import_Export_FAQ
Comment: WHAT I MENT IS HOW TO USE SQL COMMAND SUCH AS 'SQL>ALTER TABLESPACE BEGIN BACKUP ;' AND 'SQL>HOST COPY SOURCE TARGET' AND 'SQL>ALTER TABLESPACE END BACKUP ;'
Answer: Your question requires some clarification.
Do you want to:
a) create a copy of the database for use somewhere else
b) create a backup of the database for backup and recoverability purposes
If you are looking to simply create a copy of the database somewhere else, then the use of the import and export utilities (imp and exp, or impdp and expdp in 10g) should be sufficient.
If you are looking to backup the database for recoverability purposes, then you should really be looking into the use of RMAN, which is Oracle's enterprise backup solution.  Docs can be found here:    RMAN Quick Start Guide
Answer: When I do physical backups I use RMAN, not PL/SQL, since it's THE tool for this kind of job. However, here's a link that maybe can help you. http://psst0101.wordpress.com/2008/01/23/move-a-tablespace/
Answer: EXP command will help do this job
Syntax:
EXP schema_user_name/schema_pwd file=file_name.dmp
you can even export (take back up) of individual db objects

How do I make a backup of a PLSQL db?