Display computer information in RDC

Question: What is the setting or configuration change in Remote Desktop Connection to display the server information (Server name, IP addresses) when connected to a windows server 2003 server?
Comment: Are you looking for a pop-up window, or some obvious way of displaying who you're logging on to?
Comment: It displays the server information the same way as BGInfo
Answer: You might be thinking of BGinfo?
EDIT to add:
If you put this line in a logon script for the system (or the user profile, GPO, whatever your preferred way), you'll get the BGinfo information "tattoo" on your desktop without actually installing BGinfo to the system:
<code>\\server\share\bginfo.exe /I\\server\share\bginfo-std.bgi /accepteula /timer:0
</code>
This assumes you've previously run BGinfo to create the bginfo.bgi config file, and placed it and the bginfo executable at \\server\share
Comment: bofe: When you first run BGinfo, it presents you with a screen that looks like this ( http://tinyurl.com/lxr69l ) - allowing you to choose what information about the computer will be presented on the desktop. This config info is then saved as a *.bgi file.
Comment: I do mot think that was it because I remember a fellow programmer able to do this without installing additional software.
Comment: +1 - I have been wondering about this for several years.  THANKS!
Comment: Can you elaborate on this a little more? What's the bgi file for?
Comment: The BGI file describes what information bginfo displays on the wallpaper.
Answer: \\live.sysinternals.com\Tools\Bginfo.exe is on the internet (via smb or CIFS)... your going to take a performance hit if you use it but at least you do not have install on the local network.

Display computer information in RDC


Mysql master to master group replication on ubuntu 16.04

Question: I configure mysql master to master group replication using following link https://www.digitalocean.com/community/tutorials/how-to-configure-mysql-group-replication-on-ubuntu-16-04
I have connected two different servers by using above link. First server is connected. But second server is not connected, it gives error
I use mysql> START GROUP_REPLICATION; this command to configure second server. But I get following error log
<code>2018-02-07T11:58:01.707051Z 0 [Note] Plugin group_replication reported: 'connecting to 188.8.131.52 33061'
2018-02-07T11:58:11.715442Z 0 [Note] Plugin group_replication reported: 'Timed out while waiting for connection to be established! Cancelling connection attempt. (socket= 78, error=0)'
2018-02-07T11:58:11.715470Z 0 [Warning] Plugin group_replication reported: 'select - Timeout! Cancelling connection...'
2018-02-07T11:58:11.715479Z 0 [Note] Plugin group_replication reported: 'Connecting socket to address 18.104.22.168 in port 33061 failed with error 115 - Operation now in progress.'
2018-02-07T11:58:11.715515Z 0 [ERROR] Plugin group_replication reported: '[GCS] Error on opening a connection to 220.127.116.11:33061 on local port: 33061.'
2018-02-07T11:58:11.715524Z 0 [Note] Plugin group_replication reported: 'connecting to 188.8.131.52 33061'
2018-02-07T11:58:21.725696Z 0 [Note] Plugin group_replication reported: 'Timed out while waiting for connection to be established! Cancelling connection attempt. (socket= 78, error=0)'
2018-02-07T11:58:21.726394Z 0 [Warning] Plugin group_replication reported: 'select - Timeout! Cancelling connection...'
2018-02-07T11:58:21.726406Z 0 [Note] Plugin group_replication reported: 'Connecting socket to address 188.8.131.52 in port 33061 failed with error 115 - Operation now in progress.'
2018-02-07T11:58:21.726442Z 0 [ERROR] Plugin group_replication reported: '[GCS] Error on opening a connection to 220.127.116.11:33061 on local port: 33061.'
2018-02-07T11:58:21.726451Z 0 [ERROR] Plugin group_replication reported: '[GCS] Error connecting to all peers. Member join failed. Local port: 33061'
2018-02-07T11:58:21.726558Z 0 [Note] Plugin group_replication reported: 'state 4338 action xa_terminate'
2018-02-07T11:58:21.726578Z 0 [Note] Plugin group_replication reported: 'new state x_start'
2018-02-07T11:58:21.726582Z 0 [Note] Plugin group_replication reported: 'state 4338 action xa_exit'
2018-02-07T11:58:21.728254Z 0 [Note] Plugin group_replication reported: 'Exiting xcom thread'
2018-02-07T11:58:21.728263Z 0 [Note] Plugin group_replication reported: 'new state x_start'
2018-02-07T11:58:21.728310Z 0 [Warning] Plugin group_replication reported: 'read failed'
2018-02-07T11:58:21.736534Z 0 [ERROR] Plugin group_replication reported: '[GCS] The member was unable to join the group. Local port: 33061'
2018-02-07T11:58:21.736559Z 0 [Note] Plugin group_replication reported: 'Destroying SSL'
2018-02-07T11:58:21.736565Z 0 [Note] Plugin group_replication reported: 'Success destroying SSL'
2018-02-07T11:58:21.736713Z 2 [Note] Plugin group_replication reported: 'auto_increment_increment is reset to 1'
2018-02-07T11:58:21.736720Z 2 [Note] Plugin group_replication reported: 'auto_increment_offset is reset to 1'
2018-02-07T11:58:21.736822Z 7 [Note] Error reading relay log event for channel 'group_replication_applier': slave SQL thread was killed
2018-02-07T11:58:21.738636Z 4 [Note] Plugin group_replication reported: 'The group replication applier thread was killed'
</code>
Please any one help me to solve this error
Comment: Can you run `telnet` from master to this `126.96.36.199:33061`? It might be the port on the salve is blocked by the firewall.
Comment: This question should be migrated to another website.
Comment: @Subarna did you found a solution for this problem?
Answer: Could it be SELinux?
You can try disabling SELinux by editting: /etc/selinux/config
and change following line: SELINUX=enforcing to: SELINUX=disabled
Reboot your system and try again.


Android ViewBinder values from cursor

Question: Hoping someone can help me here. I have a layout which contains listview, each item in the list view contains individual text fields to represent the days of the week --> SMTWTFS
What I am trying to do is change the colour of the text items if they are set within the database. This nearly works but I have noticed the first row in the list view changes the colour for all items when the are set in other list rows.
My text items are declared like this
        textSUN = (TextView) v.findViewById(R.id.textSUN);
        textMON = (TextView) v.findViewById(R.id.textMON);
        textTUE = (TextView) v.findViewById(R.id.textTUE);
        textWED = (TextView) v.findViewById(R.id.textWED);
        textTHU = (TextView) v.findViewById(R.id.textTHU);
        textFRI = (TextView) v.findViewById(R.id.textFRI);
        textSAT = (TextView) v.findViewById(R.id.textSAT);

I then query my db and set the adapter
db = new DatabaseHandler(getActivity());

            mCursor=db.getReadableDatabase().rawQuery("SELECT rowid _id,* "+
                              "FROM table", null);

            adapter = new SimpleCursorAdapter(getActivity(),
                    R.layout.list_row, mCursor,
                    new String[] {DatabaseHandler.KEY_SUNDAY, DatabaseHandler.KEY_MONDAY,DatabaseHandler.KEY_TUESDAY,DatabaseHandler.KEY_WEDNESDAY, DatabaseHandler.KEY_THURSDAY, DatabaseHandler.KEY_FRIDAY,
                            DatabaseHandler.KEY_SATURDAY,},
                    new int[] {R.id.textSUN,R.id.textMON, R.id.textTUE, R.id.textWED, R.id.textTHU, R.id.textFRI, R.id.textSAT});

Finally I try to set the color in the view binder if the value returned is 1 from the db
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
                @Override
            public boolean setViewValue(View view, Cursor cursor, int
                    columnIndex) {

                 final int sun_column = cursor.getColumnIndex("sun");
                 final int mon_column = cursor.getColumnIndex("mon");
                 final int tue_column = cursor.getColumnIndex("tue");
                 final int wed_column = cursor.getColumnIndex("wed");
                 final int thu_column = cursor.getColumnIndex("thu");
                 final int fri_column = cursor.getColumnIndex("fri");
                 final int sat_column = cursor.getColumnIndex("sat");

                 }

                 if (columnIndex == sun_column) {

                     int sun = cursor.getInt(cursor.getColumnIndexOrThrow("sun"));
                     if(sun == 1){
                         ((TextView) view).setTextColor(Color.parseColor("#FFFFFF"));
                     }
                 return true;

                 }

                 if (columnIndex == mon_column) {

                     int mon = cursor.getInt(cursor.getColumnIndexOrThrow("mon"));
                     if(mon == 1){
                         ((TextView) view).setTextColor(Color.parseColor("#FFFFFF"));
                     }
                 return true;

                 }

                 if (columnIndex == tue_column) {

                     int tue = cursor.getInt(cursor.getColumnIndexOrThrow("tue"));
                     if(tue == 1){
                         ((TextView) view).setTextColor(Color.parseColor("#FFFFFF"));
                     }
                 return true;

                 }

                 if (columnIndex == wed_column) {

                     int wed = cursor.getInt(cursor.getColumnIndexOrThrow("wed"));
                     if(wed == 1){
                         ((TextView) view).setTextColor(Color.parseColor("#FFFFFF"));
                     }
                 return true;

                 }

                 if (columnIndex == thu_column) {

                     int thu = cursor.getInt(cursor.getColumnIndexOrThrow("thu"));
                     if(thu == 1){
                         ((TextView) view).setTextColor(Color.parseColor("#FFFFFF"));
                     }
                 return true;

                 }

                 if (columnIndex == fri_column) {

                     int fri = cursor.getInt(cursor.getColumnIndexOrThrow("fri"));
                     if(fri == 1){
                         ((TextView) view).setTextColor(Color.parseColor("#FFFFFF"));
                     }
                 return true;

                 }

                 if (columnIndex == sat_column) {

                     int sat = cursor.getInt(cursor.getColumnIndexOrThrow("sat"));
                     if(sat == 1){
                         ((TextView) view).setTextColor(Color.parseColor("#FFFFFF"));
                     }
                 return true;

                 }
                 return false;
                 }
            });

        lv = (ListView) v.findViewById(R.id.listView);

        lv.setAdapter(adapter);

Perhaps I am going about this all wrong ?? It nearly works though.
Many thanks
Answer: You still need to handle the cases where mon, tue, etc. == 0. Adding the following to each if statement should fix it:
else {
((TextView) view).setTextColor(//color that you want if day == 0);
}

Also, you may want to consider changing your whole setViewValue to use a switch statement, it should make the cod more readable.

Android ViewBinder values from cursor


In $C([0,1],R)$ consider the subspace from the orthogonal set {$1,\cos(2\pi x),\cos(4\pi x),..,\cos(2N\pi x)$} what func is closest to $\sin(\pi x) $

Question: In $C([0,1],R)$ consider the subspace from the orthogonal set : $\{1,\cos(2\pi x),\cos(4\pi x),...,\cos(2N\pi x) \}$
Find the function in the subspace which is as close to $\sin(\pi x) $ as possible
how do i solve this?
Comment: im honestly not 100% sure what the question refers too, but i assume it is too the norm
Comment: okei. could you explain a bit of the reasoning behind that? the $f(x)=sin(\ pi x)$ is the correct one
Answer: I you meant close to $f(x) =\sin(\pi x)$ in the $L^2([0,1])$ sense, then extend $f$ to a $1$-periodic even function,
$f$ is equal to its Fourier series
$$f = a_0+\sum_{n=1}^\infty a_n \cos(2\pi n .)+b_n \sin(2\pi n .), \qquad \text{ in } L^2([0,1])$$
since $f$ is even, the $b_n = 0$, and hence
$$f = a_0+\sum_{n=1}^\infty a_n \cos(2\pi n .) $$
Comment: okei, think i got it now. thanks!


Using Granger Causality to determine effect of time series on another

Question: I understand the lag of one time series on another can be determined using Granger Causality. But is it possible to determine the effect of one time series on another? For example, a 1 point increase in time series $X$ affects $Y$ by $n$%.
Answer: You may test for Granger causality once you have built a model for the two time series. The estimated model will give you effect sizes, e.g. the effect of a 1 point increase in $x$ on $y$. (Regarding effect in percentage, a log-level model would give you a direct answer; it works for small changes where logarithmic change approximates percentage change well.)
Comment: could you please elaborate on "You may test for Granger causality once you have built a model for the two time series."? The model being? Thank you
Comment: The model should be appropriate for the data, so it will depend on the data. It may be a vector autoregression, for example, but it need not be.
Comment: why do I need to build the model first?
Comment: Because how else are you going the test for Granger causality? Normally you formulate the null hypothesis of the test as zero restrictions on certain model coefficients.
Answer: You may be interested in Impulse Response Analysis (http://www.statsmodels.org/dev/vector_ar.html).
Unfortunately, the statsmodels' package document does not clarify how to interpret the x-axis in the impulse response analysis graphs (check the mid-page in that webpage). However, in stata, I know that the vertical axis in the graphs reflect the estimated percentage point change in the response variable.
On the contrary, according to this link, "The vertical axis is expressed in units of the Y variable."
So, in sum, the x-axis values in an impulse response graph do indicate the extent to which the response variable changes as a result of changes in X. However, I personally don't know the unit in which the changes are expressed in Python's statsmodels. Based on my observation of a number of such graphs, the range of values the x-axis ticks have got in all of them, and how standard they look, I would guess that the x-axis ticks reflect percentage change in the response variable.
Comment: How does this answer the question?
Comment: The idea that the OP mentioned "a 1 point increase in time series X affects Y by n%" is the core of impulse response analysis.


The properties of integral

Question: Assume $f(x)$ is continuous on $[a, b]$.
(a) Prove that if $f(x) > 0$ for all $x \in [a, b]$, then the integral of
$f(x)$ from $a$ to $b > 0$. I tried to apply the Extreme Value Theorem and
into it, but I can not deal  with it  successfully.
(b) Prove that if $f(x) \ge 0$ for all $x \in [a, b]$, and that $f(c) > 0$ for some $c \in [a, b]$, then the integral of
$f(x)$ from $a$ to $b> 0$. I tried to use the
continuity assumption to get that $f(x) > 0$ for some sub-interval $[s, t]$ of $[a, b]$, but I have no idea about the rest of processes.
Could someone help me to finish it? I'd appreciate it!
Answer: Observe that part (a) follows from part (b), so you only need to prove (b). You have the right idea: continuity implies there exists $\delta$ with $f(x) > 0$ for all $x \in (c-\delta, c+\delta$).
Now, what can you say about the integral of $f$ on $(c-\delta, c+\delta$)? To finish, what can you say about $\int_{a}^{b}f$ compared to $\int_{c-\delta}^{c+\delta}f$?
Note: you will have to make sure to choose $\delta$ sufficiently small that $(c-\delta, c+\delta) \subset [a,b]$.
Comment: Could you show me some proof processes for me?I have tried but fails
Answer: Consider the given claim:
For, $m\leq f(x)\leq M$ $\forall$ $x\in [a,b]$, then:
$$m(b-a)\leq\int_a^b f\leq M(b-a)$$
The proof is as follows:
Suppose $f$ is integrable on $[a,b]$, and $m\leq f(x)\leq M$
Then given some partition $P=\left\{a,b\right\}$,
$$m(b-a)\leq L(P,f)\leq \underline {\int_a^b}f=\int_a^bf=\overline {\int_a^b}f\leq U(P,f)\leq M(b-a)$$
Now consider choosing $m=0$, then we have:
$$0\leq\int_a^b f\leq M(b-a)\Rightarrow \int_a^bf\geq0$$
So, given $f(x)>0$, and $\int_a^bf \ \exists$, then indeed:
$$0\leq\int_a^bf$$
$\mathbf{EDIT}$:
Here is another approach:
We note if $\int_{a}^{b}f \ \exists$, and $\exists \ c\in[a,b]$ such that $f$ is continuous, then $f$ has an antiderivative $F(x)=\int_a^cf$.
Note a separate proof is required for the above claim.
Furthermore, by taking the continuous extension of $f$ onto $\mathbb{R}$, we can thus note that if $f$ is continuous, then infact $f$ has an antiderivative $F(x)=\int_a^bf \ \forall \ x\in[a,b]$.
So let's prove your question, but in a different way:
If $f(x)\geq0 \ \forall \ x\in[a,b]$, and continuous on $[a,b]$, then its antiderivative $F(x) \ \exists$ on $[a,b]$.
Furthermore, by the definition of an antiderivative, $F'(x)=f(x)\geq0\Rightarrow F(x)$ is an increasing (monotone) function on $[a,b]$.
By the fundamental theorem of calculus, assuming $b>a\Rightarrow \int_a^bf=F(b)-F(a)\geq0$.
Can you prove the case where $f(x)=0$? In fact, by doing so, this restricts $\int_a^bf$ to be $>0$.
Comment: Thanks!And I have got your idea! How about question 2? Could you give me some processes? Thanks
Comment: Are we assuming f is continuous for the second question? Also if my question helped, don't forget to up vote and verify :D
Comment: okay!And f is also continuous for the second question and my idea is trying to use the continuity assumption to get that f(x)>0f(x)>0 for some sub-interval [s,t]of [a,b]
Comment: Well, if it's continuous, isn't it the same proof as in part a? Seems like my proof satisfies both questions.
Comment: Well, but my instructor require us use two different methods to prove this question.Do you have another method to prove b?
Comment: I added another proof. Keep in mind, this problem has a large variety of solutions, and can also be proven via the definition of continuity. Don't forget to up vote, and cheers!
Comment: Thanks.I have up vote your answer!

The properties of integral


How to capture onchange event for a

Question: I need to capture a change event on the TD below. Whenever its contents change (in this case "Rosemount Measurement"), I need to call a function. I don't think that  accepts the "onchange" attribute... so that's the problem. Can this be done?
Rosemount Measurement

I will post a print screen of a bigger portion of the code, in which the above line is included (in case it helps).
Comment: http://stackoverflow.com/questions/17470715/onchange-event-for-html-form-elements-in-td-tag-with-chrome. See this question may it will help you.
Comment: Read this too http://stackoverflow.com/questions/2844565/is-there-a-jquery-dom-change-listener
Answer: I would suggest using custom events, e.g. contentchange, and triggering it from the src that makes the content change.
Subscribe to event
$('table.yourClassName').on('contentchange', 'td', fn);

At the content changing code
$(refToTheTd).trigger('contentchange');

Answer: TD does not have a change event because it doesn't have a value, it only holds some text inside. The only way it to create a custom event for it (you need to trigger the event yourself after changing the text inside)

setTimeout(function() {
  $('td').text(function() {
    return this.innerHTML + '... success?';
  }).trigger('custom:td:name_whatever.event');
}, 1000);

$('td').on('custom:td:name_whatever.event', function(){
  alert(this.innerHTML);
});

    Test

Answer: I found a solution that could work for my requirement, but I haven't adapted it yet (still trying to figure it out):
//assume tbl has id foobar
document.getElementById('foobar').addEventListener('change',function(e)
{
    e = e || window.event;
    var target = e.target || e.srcElement;
    var name = target.id || target.getAttribute('name');
    alert('the ' + name + ' element changed!');
},false);

Unfortunately the two solutions provided above do not work for my requirement.
Comment: this works great, except for one thing: it doesn't capture changes done to the text in a ``. Please see this:
[link](http://stackoverflow.com/questions/26342367/event-listener-for-td-content)

How to capture onchange event for a


How to stop the fingers scrolling in pivot in winui3?

Question: <Pivot
    x:Name="pivot"
    Grid.Row="1"
    Margin="0,0,0,0"
    Background="{StaticResource Background}"
    SelectedIndex="{Binding SelectedIndexPivotItem, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
    SelectionChanged="pivot_SelectionChanged"
    TabNavigation="Once">
    <Pivot.HeaderTemplate>
        <DataTemplate>
            <Border
                Height="50"
                Margin="0,0,0,0"
                VerticalAlignment="Center">
                <TextBlock
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"
                    FontSize="16"
                    Text="{Binding}"
                    TextAlignment="Center" />
            </Border>
        </DataTemplate>
    </Pivot.HeaderTemplate>

    <PivotItem
        Margin="0,0,0,0"
        Header="Processing"
        ScrollViewer.IsHorizontalScrollChainingEnabled="False">
        <Grid Margin="0,0,12,0">
            <local:ProcessingTabPage />
        </Grid>
    </PivotItem>
    <PivotItem Background="{StaticResource PivotBackground}" Header="PMMS Processing">
        <Grid Margin="-12,0,0,0">
            <local:ImagineTabPage />
        </Grid>
    </PivotItem>
</pivot>

I don't need that behavior. How can I stop the fingers scrolling functionality?
Comment: What do you mean by "fingers scrolling"? Do you mean touch screen?
Comment: Moving the cursor swiping in the mouse pad
Comment: Still don't understand. You only have 2 `PivotItem`s (Processing and PMMS Processing) right? What scrolling are you trying to prevent?
Comment: @Siva A mouse pad is not a input device. Do you mean a touchpad of a laptop?
Comment: Here I have 2 pivot item. Currently first one is selected. then i had put my 2 finger in the mousepad and try to swipe from right to left. It navigates to the 2nd pivot item. that the thing i want tor restrict.
Answer: You need to disable manipulation on the headers and each PivotItems:
public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
        this.PivotControl.Loaded += PivotControl_Loaded;
        this.PivotControl.PivotItemLoading += PivotControl_PivotItemLoading;
    }

    private void PivotControl_Loaded(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
    {
        if (this.PivotControl
            .FindDescendant<ContentControl>(x => x.Name is "HeaderClipper") is ContentControl headerClipper)
        {
            headerClipper.ManipulationMode = ManipulationModes.None;
        }
    }

    private void PivotControl_PivotItemLoading(Pivot sender, PivotItemEventArgs args)
    {
        args.Item.ManipulationMode = ManipulationModes.None;
    }
}

NOTE:
FindDescendatnt comes from the CommunityToolkit.WinUI.UI NuGet package, but of course you can use the VisualTreeHelper instead.


I am looking for how to do the two (BFS, DFS) searches for my 8 puzzle. I'm so close to done

Question: I've linked the code here..I just don't feel like I understand the search algorithms. I haven't really tried to attempt them, but I know that I don't have to do a thing else. I feel as though this is too simple for me to understand.
When I read on Breadth-First Search, I do understand that I have to search the rows before I move down a level on the tree (and same for depth first moving down), but how would that be coded? I'm just stumped.
Basically, this is an 8-Puzzle using Glut/OPENGL, where the computer does the search for you, and is supposed to output the moves to said user. The blank will ALWAYS start in the middle. I save the order in an array, and then need to output the moves. The thing I am stumped on is the search itself.
<code>#include <stdio.h>                         // standard C libraries
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <string.h>
#include <GL/glut.h>                       // GLUT library
#include "cs_graphics_setup.h"             // Header for CS4250/5250/6250 courses

// Constants
#define WINDOW_XS 25                       // Window size
#define WINDOW_YS 256
#define WINDOW_NAME "Sliding Box Game"     // Window name
#define FONT_10 GLUT_BITMAP_TIMES_ROMAN_10 // font size to 10
#define FONT_24 GLUT_BITMAP_TIMES_ROMAN_24 // font size to 24
#define ANI_MSEC 10                        // gap between frames

// Structures
typedef struct pt
{
    GLfloat x, y;
} MyPoint;

// Global Variables
MyPoint bottomLeftPt;

int xside = 80;
int yside = 80;
int innerx = 70;
int innery = 70;
int i, j, temp, v;

int arrayNumRand[9] = {1, 2, 3, 4, 0, 5, 6, 7, 8};

//multidimensional array that holds the x-coordinate of the big square, the
//y-coordinate of the big square, and the number that is to be displayed.
int arrayCoord[9][2] =
{
    {8, 168},
    {88, 168},
    {168, 168},
    {8, 88},
    {88, 88},
    {168, 88},
    {8, 8},
    {88, 8},
    {168, 8}
};

//int goUp = 0;  // 0- go up, 1- come down

// Function prototypes
void display_func(void);
void keyboard_func(unsigned char c, int x, int y);
//void animation_func(int val);
void drawSquareFn(int, int, int, int, int);
void display_num(int, int, int);

int main(int argc, char **argv)
{
    glutInit(&argc, argv);
    init_setup(WINDOW_XS, WINDOW_YS, WINDOW_NAME);
    //initial testing of arrayNumRand randomization
    srand(time(NULL));
    for(i = 0; i <9; i++)
    {
        j = (rand() %8)+1;
        if(j != 4 && i != 4)
        {
            temp = arrayNumRand[i];
            arrayNumRand[i] = arrayNumRand[j];
            arrayNumRand[j] = temp;
        }
    }
    for(i = 0; i <9; i++)
    {
        printf(" %d", arrayNumRand[i]);
    }
    glutDisplayFunc(display_func);
    glutKeyboardFunc(keyboard_func);
    //glutTimerFunc(ANI_MSEC, animation_func, 0);
    glutMainLoop();
    return 1;
}   // end of main()

void display_func(void)
{
    glClearColor(0.50, 78.0, 139.0, 0.0); // background color (purple)
    glClear(GL_COLOR_BUFFER_BIT);         // clearing the buffer not to keep the color
    for(v = 0; v <9; v ++)
    {
        drawSquareFn(arrayCoord[v][0], arrayCoord[v][1], xside, yside, v);
    }
    glFlush();
    glutSwapBuffers();                    // double buffering
}   // end of display_func()

void keyboard_func(unsigned char c, int x, int y)
{
    switch(c)
    {
        /*case 'b' :
        case 'B' :
            //breadth_first_search function

            glutPostRedisplay();
            break;

        case 'd' :
        case 'D' :
            //depth_first_search function

            glutPostRedisplay();
            break;*/
    case 'i' :
    case 'I' :
        for(i = 0; i <9; i++)
        {
            j = (rand() %8)+1;
            if(j != 4 && i != 4)
            {
                temp = arrayNumRand[i];
                arrayNumRand[i] = arrayNumRand[j];
                arrayNumRand[j] = temp;
            }
            display_func();
        }
        for(i = 0; i <9; i++)
        {
            printf(" %d", arrayNumRand[i]);
        }
        break;
    case 'Q' :
    case 'q' :
        printf("Good Bye !\n");
        exit(0);                 // terminates the program
    }  // end of switch
}   // end of keyboard_func()

/*void animation_func(int val)
{
int moveGap = 5;

if( goUp == 0 )
{
    bottomLeftPt.x += moveGap;
    bottomLeftPt.y += moveGap;

    if( bottomLeftPt.x+recLength > WINDOW_XS)
    {
        bottomLeftPt.x -= moveGap;
        bottomLeftPt.y -= moveGap;

        goUp = 1;
    }
    else if( bottomLeftPt.y+recHeight > WINDOW_YS)
    {
        bottomLeftPt.x -= moveGap;
        bottomLeftPt.y -= moveGap;

        goUp = 1;
    }
}
else // goUp = 1
{
    bottomLeftPt.x -= moveGap;
    bottomLeftPt.y -= moveGap;

    if( bottomLeftPt.x < 50)
    {
        bottomLeftPt.x += moveGap;
        bottomLeftPt.y += moveGap;

        goUp = 0;
    }
    else if( bottomLeftPt.y < 50)
    {
        bottomLeftPt.x += moveGap;
        bottomLeftPt.y += moveGap;

        goUp = 0;
    }
}

glutPostRedisplay();
glutTimerFunc(ANI_MSEC, animation_func, 0);
}//end animation_func*/

//beginning of drawSquare Function to create the two nested squares and place the     number on the board.
void drawSquareFn(int x, int y, int xside, int yside, int num)
{
    // draw a rectangle
    glColor3f(0.0, 0.0, 0.0);           // setting pen color (black)
    glBegin(GL_POLYGON);
    glVertex2i(x, y);
    glVertex2i(x+xside, y);
    glVertex2i(x+xside, y+yside);
    glVertex2i(x, y+yside);
    glEnd();
    // draw the outline of rectangle
    glColor3f(0.0, 0.0, 0.0);           // setting pen color (black)
    glBegin(GL_LINES);
    glVertex2i(x, y);
    glVertex2i(x+xside, y);
    glVertex2i(x+xside, y);
    glVertex2i(x+xside, y+yside);
    glVertex2i(x+xside, y+yside);
    glVertex2i(x, y+yside);
    glVertex2i(x, y+yside);
    glVertex2i(x,y);
    glEnd();
    x += 5;
    y += 5;
    if(arrayNumRand[num] != 0)
    {
        // draw inner rectangle
        glColor3f(1.0, 1.0, 1.0);           // setting pen color (black)
        glBegin(GL_POLYGON);
        glVertex2i(x, y);
        glVertex2i(x+innerx, y);
        glVertex2i(x+innerx, y+innery);
        glVertex2i(x, y+innery);
        glEnd();
        //// draw the outline of rectangle
        //glColor3f(1.0, 1.0, 1.0);         // setting pen color (black)
        //glBegin(GL_LINES);
        //  glVertex2i(x, y);
        //  glVertex2i(x+innerx, y);
        //  glVertex2i(x+innerx, y);
        //  glVertex2i(x+innerx, y+innery);
        //  glVertex2i(x+innerx, y+innery);
        //  glVertex2i(x, y+innery);
        //  glVertex2i(x, y+innery);
        //  glVertex2i(x,y);
        //  glEnd();
        x += 23;
        y += 23;
        //new x value, new y-value, and the number listed above and decide upon color display_num
        display_num(x, y, num);
    }
}

void display_num(int newx, int newy, int newnum)
{
    int points[10];
    int i = 0, j;
    int pos;
    int is_negative = 0;
    for(j = 0; j < 10; j++)
    {
        points[j] = ' ';
    }
    if(newnum < 0)
    {
        is_negative = 1;
        newnum *= -1;
    }
    while(newnum > 9)
    {
        points[i] = newnum % 10;
        newnum = newnum / 10;
        i += 1;
    }
    points[i] = 1;
    glColor3f(0.0, 0.0, 0.0);
    pos = newx;
    if(is_negative == 1)
    {
        glRasterPos2i(pos, newy);
        glutBitmapCharacter(FONT_24, '-');
        pos += glutBitmapWidth(FONT_24, '-');
    }
    glRasterPos2i(pos, newy);
    glutBitmapCharacter(FONT_24, (char)(arrayNumRand[newnum]+48));
    pos += glutBitmapWidth(FONT_24, (char)(arrayNumRand[newnum]+48));
}

void breadthFirstSearch()

void depthFirstSearch()
{
}
</code>
Comment: Welcome to SO. Please read the FAQ. We are not here to scan your code for errors, but for answering questions concerning programming. Please ask a question so we can answer **something**.
Comment: @SauceMaster It doesn't belong there. The OP's wording `and is supposed to output the moves to said user` and `but how would that be coded` clears that this isn't working as intended. It belongs to SO although after some editing. Next time please flag the question to be migrated if you think it needs to be moved. It avoids cross-posting.
Comment: @Jamal If the question didn't belong here it would have been alosed already. SO has much higher traffic than codereview. It just needs editing and clarification to be answered. Maybe a language tag too. I'll add that.
Comment: @user2605141 Your [question on codereview](http://codereview.stackexchange.com/questions/28793/8-puzzle-search-algorithm-help) was put on hold as it wasn't working. Working code belongs there. Non-working belongs here. BUT be aware that people here would answer a specific question. At present **this question is too vague** to be answered. What you need to do is to ask a specific question. Perhaps you can point to a part of your code and ask what exactly isn't working.
Comment: This is a great candidate question for Code Review: http://codereview.stackexchange.com/
Comment: Thank you, guys! I have no really large errors, and am not looking for that kind of help. I just am stumped on this search algorithm.
Comment: @AseemBansal: Good call on the migration.  Whenever someone tells us they were referred to CR (but without a migration), I feel hesitant about believing that the post really didn't belong here.
Answer: The tree you want to traverse is the tree of board states.  This will be an implicit tree:  You will not construct a tree data structure and fill it up with boards.  Each node in the tree is one position of all of the tiles on the board.  Your root node is the board with 8 randomly arranged tiles around the perimeter and one blank in the center.  There's no need to have a tree data structure to traverse because you can easily compute the children of each state just by knowing the state.  From the root you have 4 children (each of the side tiles sliding into the hole).  Each of those has only 3 children (due to the edge of the board).  Some moves will create cycles (e.g. undoing your very first move in your second move) which you will want to avoid.
If you imagine this tree (without cycles) then the nodes of the tree are all of the other board states.  Some of those states are the solution to the puzzle.  From any one of those solution nodes the set of moves is just the path from the root through the tree to the goal node.
For a puzzle of that size you can probably just search directly to the goal.  For more complex problems (e.g. a 256x256 sliding tile puzzle, or more complex games like chess) you will not be able to "see" the endgame.  In those cases you will have to have a scoring function to evaluate whether you are getting better or worse.  Then you will navigate through the tree to promising areas that are close enough for you to see the goal state and find the answer.


Testing a Hamiltonian Path finder implementation

Question: I am implementing an algorithm which finds an optimal Hamiltonian path in a directed graph. I have implemented an algorithm which appears to work reasonably well, however I am not entirely sure if there are subtle bugs or other issues in certain cases. Therefore, I need a few diverse networks where the solution is known, to check if my implementation is also solving them as it should.
Since Wikipedia implies Hamiltonian paths is only an appropriate term for undirected graphs, assume that "Hamiltonian path" means a path which visits every node once and exactly once on a given network, directed or otherwise.
For simplicity, we can assume that every connection (or "edge") has a positive integer value (or "length"). We can also assume that no node is connected to itself, and there can be no more than one edge in each direction between any two nodes.
I happen to be interested in the path which has the highest total length, so "optimal" means longest, although it probably makes little difference if I wanted the shortest total length (as in the traditional TSP). I also happen to be using a greedy algorithm.
Where or how might I obtain directed networks for which TSP has been solved? It would be even better if the actual solution and the greedy (or other heuristic) solution was available. The networks should be large enough to make for an informative test, but small enough for me to manually check the solution (if the solution is initially unknown). They should be topologically diverse enough to cover both "easy" and "problematic" networks.
For anyone else looking for the same; the best I have is the following network:
<code>  A B C D E
A 0 1 2 0 1
B 1 0 0 0 1
C 0 3 0 1 2
D 4 0 0 0 0
E 1 0 0 2 0
</code>
This is an adjacency list, the rows are edge origins and columns are destinations. The numbers are lengths of each edge, and 0s indicate "no edge". For instance, the 4 shows that the length of the edge from D to A is 4, and there is no connection from A to D (length 0).
The maximum length path in this network is E->D->A->C->B. Its total length is 2+3+3+3=11. I believe a greedy algorithm is able to find the best solution in this case, and it happens to be possible to be obvious that it IS the best possible solution.
Comment: Shortly after I stumbled on an answer myself: The TSPLIB exists for this specific purpose.
Answer: As you have read the Wiki entry on Hamiltonian path, you should have noticed that finding a Hamiltonian path is NP-hard (To be precise, what you're solving is TSP - but that doesn't change much). That single fact suggests that a greedy algorithm won't give you optimal solution for the problem.
If your greedy algorithm works like

take edges ordered by descending value/length,
add the edge to the path-in-construction, unless it
(a) creates a cycle
(b) creates a node of deg=3 in the path-in-construction
otherwise skip it

here's the minimal counter-example I can think of where the greediness makes it fail:
<code>  A B C D E F
A 0 5 4 0 0 0
B 5 0 5 0 4 0
C 4 5 0 1 0 0
D 0 0 1 0 5 4
E 0 4 0 5 0 5
F 0 0 0 4 5 0
</code>
Greedy algorithm finds a path A-B-C-D-E-F with total length of 21, while the optimal path is A-C-B-E-D-F with total length of 22 (there's more of them with the same length).
If your algorithm works differently it may work well for this example, but there will still be a counter-example if it is greedy. Post your code if that's the case and you're interested.
Comment: Thank you for the info, but I was aware that the Greedy algorithm is not guaranteed to find all or any optimal solutions. To my knowledge, all non-exponential TSP solvers are heuristics in this sense; there always exists at least one TSP where they will not find the best solution (or all of them). (That's pretty much the meaning of NP-hard.)

Given this, I knew I couldn't solve the problem perfectly so I would have to settle for a solution that's "good enough". The issue was deciding whether the code I produced was good enough. Thus the question is independent of whether you use greedy.


How should we deal with questions from topics that overlap with other stack exchange sites?

Question: How should we deal with questions from topics that overlaps with other stack exchange sites? Although in many cases it's clear that a question doesn't belong on one site and definitely belongs on another site, there are cases where it seems like the question falls under the scope of both sites.
To provide some examples of these ambiguities, consider the following questions and meta posts:

There is some ambiguity about where econ.SE ends and quant.SE begins:

Is finance under our domain?
Might basic finance questions be on-topic?

There is similar ambiguity between mathematics and economics:

Are mathematical game-theoretic questions considered on-topic at EC.SE?

Here are a few questions that cross between stats.SE (cross validated) and our site:

How do I find the probability mass function of an individual observation for a multinomial logit model?
Testing for Endogeneity

These topics are generally on-topic on this site (sometimes with caveats), as described on the sites help page: https://economics.stackexchange.com/help/on-topic .
I believe that this site already has a working policy in place on how to deal with questions from topics that appear to overlap with other stack exchange site. However, my purpose in asking this question is to create a centralized place that is on the Economics.SE Meta site that we can reference whenever it comes up. Personally, I think that we have adopted and should continue to adopt the policy prescribed site-wide.
Comment: A good question with good references in the answer below. Thanks jm!
Answer: As I mentioned, my personal preference is to continue to abide by the policy
that has been prescribed site-wide. With respect to questions regarding econometrics vs. statistics, financial economics vs. quantitative finance, mathematical economics vs. mathematics, I believe there is significant overlap between the subjects that there should be many questions that could potentially live on two different sites. Allowing the overlap is by design and is not unique to economics.SE. As evidenced by the following site-wide meta posts, it is something that occurs throughout stack exchange, broadly.
I think the most relevant site-wide meta posts include these:

What to do with cross-site duplicates?
What to do about the same question on multiple sites?
What about questions already answered elsewhere?

To summarize the policy implications (i.e., lots of copy-paste :) ),

If it is clearly a question that does belong on another site, migrate it and then treat it as duplicate.
If the question seems plausibly on-topic on both sites, let it live in both cultures, as the answers will be different. Let the users of each community benefit from the information. (You can't assume that all users will be on all sites. Each site has to stand on its own merits and you have to treat each site as a separate community)
If a question is inappropriate on one site, users now have alternate places to go with it. It's a nice convenience if moderators choose to transfer it for them. If it turns out to be a duplicate, let the other community handle it with the means already in place
If the first moderator happens to spot it as a cross-site duplicate, it can simply be closed and the original poster can decide how to rework the question if they want to try it on another site.
Comment: I would add that our guidelines, https://economics.meta.stackexchange.com/q/164/61, provide good guidance on the matter.


One Number in the Set $\{0,1,...,m−1\}$

Question: Let $m$ be a natural number $>1$. Every natural number is congruent modulo $m$ to exactly one number in the set $\{0,1,...,m−1\}$.
Where can I find a concrete proof of this theorem?
Comment: Any number theory book
Comment: As $0,1\ldots ,m-1$ are the only possible remainders upon division by $m$, the result follows by definition does it not?
Comment: Euclidean division answers that, as pointed by the answers. Without even knowing about Euclidean division, it is still obvious that there is at most one such number. Assume $0\leq x<y\leq m-1$ and $x$ and $y$ are both congruent to your number. Then $x\equiv y$ mod $m$, which means $m$ divides $y-x$. But $0<y-x<m$. Is this possible? For the existence, start with your natural number $n\geq 0$. If $n\leq m-1$, you're done. If not, substract $m$ as many times as needed to obtain a number $\leq m-1$. That is $n-(k+1)m$ with $k=\min\{l\;;\;n-lm\geq m\}$.
Answer: This is basically just the so-called division algorithm, which isn't an algorithm at all: it's the theorem that if $n$ and $m$ are integers, and $m\ne 0$, then there are unique integers $q$ and $r$ such that $n=mq+r$ and $0\le r<|m|$. Clearly if $n=mq+r$, then $n\equiv r\pmod m$.
You can find a proof here or in just about any abstract algebra or number theory text.
Answer: This is a consequence of the division algorithm. A proof can be found in most elementary number theory texts. See Silverman's A Friendly Introduction to Number Theory for example.
Answer: Hint: to prove this result you can use the Euclidean division. And the fact that every number is congruent modulo $m$ to exactly one number in the set $\{0,1, \dots,m-1 \}$ follows from the uniqueness of the remainder and the fact that it must be less than $m$ to be a "valid" remainder.
Answer: Let $m \ge 1$.  Here is a proof that every natural number $n$ is congruent modulo $m$ to exactly one number in the interval $\{0,\ldots,m-1\}$.  First notice that no two of the numbers $0,\ldots,m-1$ are congruent modulo $m$, because adding a nonzero multiple of $m$ to any number in this interval results in a number outside the interval.
Therefore it suffices to prove that every natural number $n$ is congruent modulo $m$ to at least one number in this interval.  We can show this by induction on $n$.
The base case $n = 0$ holds because $0$ is congruent to itself.
For the induction step, assume that $n$ is congruent to $k \in \{0,\ldots,m-1\}$.  If $k < m-1$, then $n+1$ is congruent to $k+1$, which lies in this interval.  If $k = m-1$ then $n+1$ is congruent to $0$, which also lies in this interval.

One Number in the Set $\{0,1,...,m−1\}$


TypeError: this.c[i] is undefined

Question: I am actually trying to show photos using NgxGallery. but when i run the code i found an unexpected error in console. I am using Angular Version 12. here is my code:-
member.component.ts
  ngOnInit(): void {
      this.galleryPosts = this.getPosts();

     ...
  }

   n:any=0;
   c:any=[];

getPosts(): NgxGalleryImage[] {
    const postUrls = [];
    for (let i = this.n; i < this.member.posts.length ; i++) {
         this.c = this.member.posts[i];
        for(let j=0; j < this.c[i].postedpics.length;j++)
        {
          postUrls.push({
            small: this.c[j]?.postedpics.url,
            medium: this.c[j]?.postedpics.url,
            big: this.c[j]?.postedpics.url
          })

        }
        this.n++;
        return postUrls;
    }
}

member.component.html

{{m.description}}

{{s.url}}

                    <ngx-gallery class="mt-4" [options]="galleryOptions" [images]="galleryPosts"
                        style="display: inline-block; margin-bottom: 20px;"></ngx-gallery>

here is the error:-
ERROR TypeError: this.c[i] is undefined
    Ember 2
    RxJS 20
    Angular 17
    RxJS 8
    Angular 17
    RxJS 22

For alternative I tried  <ngx-gallery class="mt-4" [options]="galleryOptions" [images]="small:s.url;medium:s.url;big:s.url" style="display: inline-block; margin-bottom: 20px;"></ngx-gallery> but found a lot errors. it's ok.
My actual intention is how i resolve this c[i] is undifined issue, also Image not displayed as expected. I don't understand.
I am an absolute beginner. please help.
Comment: I voted to close this as a typo as you assign `this.c = this.member.posts[i];`, which makes `c` no longer be an array.
Comment: @fredrik please clarify specificly then what's the exact solution here?
Comment: @frederik If `this.member.posts = [['something']]` c will still be an array...
Answer: Try not to use properties as local variables, this gets confusing (this is living proof!)
getPosts(): NgxGalleryImage[] {
    const postUrls = [];
    for (let i = this.n; i < this.member.posts.length ; i++) {
         const post = this.member.posts[i];
        for(let j=0; j < post.postedpics.length;j++)
        {
          postUrls.push({
            small: post.postedpics[j]?.url,
            medium: post.postedpics[j]?.url,
            big: post.postedpics[j]?.url
          })

        }
        this.n++;
        return postUrls;
    }
}

See, I've changed that c to post and it made it clear that there was a confusion in your code... Does this look better?
Comment: It's look good. but when i return ```postUrls``` then i don't understand why next time n's value not change. like for n=0 for all ```postedpic``` n=1 for all ```postedpics```  above all time n =0! but why i don't understand.can you please help this.

TypeError: this.c[i] is undefined


How can I use get_template_part() for specific post using get_post() in wordpress?

Question: I am creating my first wordpress theme.
I'm currently using loops and get_template_part() for displaying my post list like this:
while ( have_posts() ) {
    the_post();
    get_template_part( 'content', get_post_format() );
}

this works great and is loading the content.php as template for post.
I want to display a specific post using get_template_part() at the end of the regular posts output.
I added this for displaying my post with Id 123 after my while loop:
get_post(123);
get_template_part( 'content', get_post_format() );

So the total code is:
while ( have_posts() ) {
    the_post();
    if($post->ID != 123) // exclude Post 123 from output
        get_template_part( 'content', get_post_format() );
}

get_post(123);
get_template_part( 'content', get_post_format() );

But this just repeats the last Entry from the regular loop.
Can anyone help?
Thanks and regards
Jan
Comment: Likely you can solve your problem with `setup_postdata`
Comment: Thanks naththedeveloper - that unfortunately didn't work. BUT I got it: the_post() generates an object wich is stored in $post automatically; get_post only returns that object. So my solution was $post = get_post(123) to store the oject in $post for further usage in my get_template_part.
Answer: Here is the working solution:
global $post;
$post = get_post(123);
setup_postdata($post);
get_template_part( 'content', get_post_format() );

https://codex.wordpress.org/Function_Reference/setup_postdata
Comment: Remember to reset with  `wp_reset_postdata();` when using `setup_postdata`. It  changes the global $post, and can give very weird errors.
For example: I just used 2 hours trying to figure out why me trying to edit my frontpage opened up a product edit page. This was a missing `wp_reset_postdata()` fault.


A dense, uncountable subset of reals whose complement is also dense and uncountable in every interval

Question: Does there exist a dense set of reals which is uncountable in every interval, whose complement is also dense and uncountable in every interval? So, for example, the union of positive rationals and negative irrationals would not work for my question.
Comment: Does this answer your question? [A question about uncountable, dense sets in R](https://math.stackexchange.com/questions/506423/a-question-about-uncountable-dense-sets-in-r)
Comment: https://math.stackexchange.com/questions/506423/a-question-about-uncountable-dense-sets-in-r
Comment: That's not exactly a duplicate - it doesn't get the "on every interval" requirement. The answer is still the same though (and if I recall correctly this has been asked before).
Comment: It follows for example from [here](https://math.stackexchange.com/questions/463601/a-partition-of-the-unit-interval-into-uncountably-many-dense-uncountable-subsets/463602).
Answer: I vividly remember this exact question being asked before, but I can't seem to find it at the moment. So here goes:

There are in fact natural examples of such pairs of sets - in particular, the axiom of choice isn't necessary. For example, the set $N$ of normal numbers has full measure (= complement has measure zero) but is meager (= union of countably many nowhere dense sets); in particular, for every nontrivial interval $I$ both $N\cap I$ and $I\setminus N$ have size continuum (which is a bit stronger than what you ask for). Besides providing an answer to the problem, $N$ and its variants are interesting objects in their own right.
What if we don't want to use measure/category ideas? Well, we can still get an explicit and choice-free construction, albeit a bit less natural: let $A$ be the set of all reals whose decimal expansion uses only finitely many $7$s (say). Then both $A$ and $\mathbb{R}\setminus A$ have size-continuum intersection with every nontrivial interval. This is definitely easier to construct and verify, but it's less interesting as an object in its own right; offhand I don't know of any natural examples which do not require at least a little bit of analysis to verify.
Answer: Using the axiom of choice, well order the reals in type $2^{\aleph_0}$ and go through and chose a real to belong in set $A$ and which has not already been chosen for $A^c$ and belongs in a given interval. Do this then for set $A^c$. Organize so that each interval with rational endpoints occurs uncountably many times.
Comment: Note that the axiom of choice is not actually needed for this problem, and in fact there are natural examples.
Answer: Just consider the unit interval, and take the decimal expansion of the reals. Let A be the set of reals which, from some point on, all even decimal positions are zero. Then given an interval there will be a finite expansion so that all completions of the finite decimal to an infinite decimal lie in the given interval. There are unaccountably many in $A$, as the odd places can be chosen at will. $A^c$ clearly has the same property.
Comment: This is basically equivalent to the second example in my answer.


HTML e JavaScript

Question: Gostaria de saber como faço para abrir essa telinha ao clicar em uma imagem, como o exemplo:
Comment: Isso pode ser feito de N formas. Comece tentando fazer e se surgir dúvidas em relação ao código você pode fazer perguntas específicas.
Comment: @dvd, na verdade N+1 formas. Você esqueceu do exemplo da minha resposta!  A propriedade `widht` no Trecho de código não funciona corretamente, você já percebeu isso?
Comment: Bem-vindo João Vitor Batistella, algumas coisas que você deve se inteirar  é: https://pt.stackoverflow.com/help/mcve mais esse https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-fazer-perguntas/5485#5485 e por fim  marcar uma resposta como aceita  https://i.stack.imgur.com/evLUR.png e o porque de marcar como aceita  https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
Answer: De uma forma bem simples, com CSS e algumas linhas de Javascript.

Ficar igual ao exemplo da sua imagem basta atuar no CSS. Divirta-se!!

CAIXA DE ENTRADA

Você pode configurar esta janela com CSS.No momento o CSS é conforme mostrado abaixo

#showDiv {

    width:250px;

    margin:auto;

    ...............

    }

    <form action="https://pt.stackoverflow.com/unanswered" method="post">

Registre-se ou faça log-in

<input type="submit" value="Registrar-se"  style="color: #000000; background-color: #FFFFFF">

    </form>

fechar

Comment: Muito obrigado, me ajudou muito, estou no segundo ano do ensino médio técnico em informática, estou recém aprendendo desenvolvimento WEB, por isso a falta de conhecimento. Muito obrigado

HTML e JavaScript


What's the correct way to set the time on ESXI hosts?

Question: I tried doing it through cli with the following command:
<code>esxcli system time set -d 3 -M 11 -y 2021 -H 14 -m 10 -s 0
</code>
But after restarting a guest OS (Windows), the time on it resets to the wrong one again (1 hour late in this case).
Comment: Windows guests usually aren't configured to synchronize time with the host.
Comment: Sometimes time-related tools miss the time zone info, or they use it badly.
Answer: The proper way is to continuously synchronize your host with an SNTP server.
You should always have an exact time on your host to ensure that any guest that is 'stunned' (pause, snapshot, ...) is resynchronized correctly.
If the host's time is off, it'll push that time to any stunned guests (regardless of the synchronize guest time with host setting!), potentially causing time to jump. You surely don't want that.
In vSphere Client, go to Host -> Manage -> System -> Time & Date -> Edit SNTP settings. Set NTP service startup policy to Start and stop with host and enter a trusted SNTP server. In Services start the ntpd service.
For the guest itself you can choose whether you generally want to synchronize with the host or (better) with your trusted SNTP server directly. Most often, Windows clients and servers are synced through AD - either a domain controller or a dedicated SNTP 'master'.
Comment: That's exactly what I needed, thanks. Although the path to NTP looks like this on my vSphere Client (version 7.0.2.00400): Host -> Configure -> System -> Time Configuration -> Network Time Protocol -> Edit.
Comment: Yes, that's likely the path with a vCenter connection - my lab VCSA's currently dead, so I connected to the host directly. ;-)


Strange behavior and output from percent function in calculator. Can some explain to me what is happening here?

Question: I'm building a calculator web app as a learning exercise, and when I got to the percent function I noticed something strange.
While entering this input on an iPhone calculator - I didn't have a handheld calculator available to verify this - I got this output.
4, *, %, -> (0.04), = (0.16)
but
4, +, %, -> (0.16), = (4.16)

What is confusing here is that the first operation seems to be applying the percent function to the number (4) resulting in the intermediate value of $(0.04)$ and then multiplying that by the number (4) and resulting in $(0.16)$ $4 * (0.04) = 0.16$
However, the addition does not seem to be doing the same number of operations.
It seems to be taking the percent of the number (0.04) and be multiplying it by the number (4) and then adding the number (4) and resulting in $(4.16)$ $4 + 4 * 0.04 = 4.16$
Can some one explain this?
Is this correct?
What math rule is this following?
Or have I perhaps stumbled upon a bug?
Also if this is not the correct forum for this question please let me know which is the correct forum.
Comment: It's not really a good idea to post a question on the peculiarities of a piece of hardware on a site oriented towards math problems.  Does your calculator have a manual?
Comment: It the calculator app on the iPhone. I don't think it has a manual.
Answer: This is not a bug, it is a carry-over from how many physical digital calculators behave, although they do not always display the intermediate calculations.
If you want to calculate $p$% of $X$ (e.g. to work out the tip on a bill), you would press
X * p % =
which relates to the fact that to do that calculation you can calculate $X \times \frac{p}{100}$ (and is why the iPhone calculator shows the conversion from $p$ to $p$%).
On the other hand, if you want to find the result of increasing $X$ by $p$% (e.g. to add sales tax), you press
X + p % =
and so there is an implicit equation here of $X(1 + \frac{p}{100})$, i.e. you're taking that $p$% of $X$ and adding it onto itself.
If you want to reduce $X$ by $p$% (e.g. to calculate a price after a discount), you press
X - p % =
for similar reasons.
Finally, if you press
X ÷ p % =
then this will calculate $X \div \frac{p}{100}$ (or equivalently $X \times \frac{100}{p}$), which lets you find the value that $X$ is $p$% of.
Notice that the addition and subtraction have a kind of symmetry between them, as do the multiplication and division, but those two groups do have different behaviour between them which is not immediately intuitive.
Comment: Excellent answer, this is exactly what I was trying to find out.  So the operation is correct, even though the input is deceivingly short and not at all suggestive of what is actually happening.   Thank you!


Existence of free operators, independent and with given distributions

Question: I am trying to learn free probability from scratch, mostly by myself. I am trying to prove the following result.

If $\mu$ and $\nu$ are compactly supported probability measures, then
  there exists a $C^*$ probability space $(\mathcal{A}, \phi)$ and self
  adjoint $a,~b\in \mathcal{A}$ which are free independent and have
  distributions $\mu$ and $\nu$ respectively.

I was told that this can be easily proved using free products of $*$-probability spaces. But I can not see how it follows. Can someone give me a line of proof, or point out some place where I can get the result? Advanced thanks for any helps/suggestions.
Answer: By the spectral theorem, for each bounded self-adjoint element $a$ of a non-commutative probability space $(\mathcal{A},\tau)$  ,there exists a unique Borel probability measure $\mu_{a}$ on $Spec(a)$ (known as the spectral measure of $a$) such that $\tau(P (a)) = \int_{\mathbb{C}} P (z) d\mu_{a}(z)$ holds for all polynomials $P : \mathbb{C} \rightarrow \mathbb{C}$.
One can consider the free product of the  unital $c^{\ast}$-algebra generated by $a$ and the unital $c^{\ast}$-algebra generated by $b$.


disable administrator role in add user form

Question: Some role in my site has permission to create users but not a administrator one.
How to disable create a new user of administrator role?
Is there a module for that?
thanks.
Comment: I haven't used it but [User protect](http://drupal.org/project/userprotect) sounds like it might do the trick
Comment: @abd did you find solution?
Answer: You can create a module that uses a hook, something like
<code>function remove_admin_role_choice_from_add_user_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['roles'][3]['#access'] = FALSE;
}
</code>


Como retornar respostas diferentes com valores diferentes em Classes iguais?

Question: Tenho dois valores diferentes que devem retornar respostas diferentes, porem as classes são iguais, como resolver ?
Veja que a respostas está errada.

.Container-Produto{display:block;border:solic 1px #ccc;}

99,00

98,00

Comment: De fato, eu só vi pq eu entrei aqui pra ler. Mas as 2 respostas contemplam o caminho correto pra solucionar, enão +1 em ambas ;)
Comment: @Bacco tem idéia que como resolver isso aqui ?
Comment: Só para informar, o Bacco não recebeu notificação do seu comentário acima, Gladson. Os usuários só são notificados com `@` se eles já tiverem comentado na pergunta ou resposta em questão.
Comment: Obrigado @bfavaretto, agora entendi como funciona
Comment: @Bacco, te perguntar uma coisa, no caso o .next() adiciona retorno no caso o $(this) na tag subsequente ao ".Preco", mas e se haver outra tags qualquer entre eles, como eu resolvo ?
Comment: Creio que é fundamental você entender os **seletores** do jQuery, pois são a base de qq coisa que você vá fazer. Em português, achei um video aqui numa pesquisa rápida, nao sei se presta pq assisti só o começo, mas tente ver se resolve: http://vimeo.com/15991889
Comment: E pra vc saber, o next da forma que foi posto na resposta aceita está retornando o "próximo .Frete-a" e nao a proxima tag qualquer.
Comment: Eu procurei ver todos os seletores hoje, testei vários, mais não achei um que selecionasse a tag que eu quero que aparece o texto "Frete Grátis", vou ver o vídeo, muito obrigado
Comment: @Bacco, por que .find() não funciona nesse caso, ela não deveria encontrar a TAG com a classe que eu quisesse ?
Comment: .find é pra achar uma tag dentro de outra. Se estiver fora, pode precisar de outros seletores. Melhor dar uma empenhada boa no estudo dos seletores e fazer mais testes (corte o código desejado e teste nele em separado num SQL Fiddle, por exemplo), pois você sempre vai estar esbarrando neste tipo de problema.
Comment: to no Dreamweaver aqui desde de cedo, não to conseguindo mesmo selecionar onde eu quero que executar a função,...
Answer: O teu código em jQuery está quase lá, mas quando trabalhas com múltiplos elementos tens que te referir a cada elemento um a um, para que possas agir sobre cada um dos diversos elementos encontrados sem influenciar os restantes.
Para o efeito podes fazer uso do this em JavaScript ou $(this) em jQuery.
Ver esta pergunta para saber mais.
Como te estás a referir a uma classe e não ao elemento X, a alteração ocorre em todos os que tenham a classe a que te referiste.
Para evitares isso, em jQuery tens a função .each que te permite iterar por cada elemento:
jQuery("document").ready(function($){

    // Por cada elemento com classe `Preco`
    $('.Preco').each(function() {

        var $this = $(this),                                    // eu
            preco = parseFloat($this.text().replace(",", ".")); // o meu valor

        // Definir o texto a usar
        var frete = ((preco > 98.99) ? '' : 'Sem ') + 'Frete Grátis';

        // Atualizar elemento a seguir a "eu"
        $this.next('.Frete-a').text(frete);
    });
});

    jQuery("document").ready(function($){

        // Por cada elemento com classe `Preco`
        $('.Preco').each(function() {

            var $this = $(this),                                    // eu
                preco = parseFloat($this.text().replace(",", ".")); // o meu valor

            // Atualizar elemento a seguir a "eu"
            var frete = ((preco > 98.99) ? '' : 'Sem ') + 'Frete Grátis';

            $this.next('.Frete-a').text(frete);
        });
    });

99,00

98,00

Exemplo também disponível no JSFiddle.
Comment: Obrigado @Zuul...
Answer: Se tem vários elementos com essas classes, é preciso fazer um loop no conjunto e alterar um por um. Você pode fazer isso com jQuery usando o .each():

jQuery(document).ready(function($){
    $('.Preco').each(function() {
         var preco = $(this).text();
         preco = parseFloat( preco.replace( '.', '' ).replace( ',', '.') );
         if( preco > 98.99 ) {
             $(this).next('.Frete-a').text( 'Frete Grátis' )
         } else {
             $(this).next('.Frete-a').text( 'Sem Frete Grátis' );
         }
     });
});

99,00

98,00

Note os outros ajustes que fiz no seu código:

Não existe $('.Preco').ready, usei .each no lugar.
Dentro do loop, this é o div de preço sendo acessado no momento
Usei .next relativo ao div de preço para pegar a âncora de frete seguinte
Comment: Obrigado @bfavaretto♦ entendi agora


Reverse DNS Resolve for MX record

Question: I've two servers running, one is a webserver and it's A record on my (external) DNS provider is in the form of:
example.com in A XXX.XX.XXX.171
The other is a mailserver and it's A record is in the form:
mail.example.com in A XXX.XX.XXX.170
and it's mx record is in the form:
example.com in MX 10 mail.example.com
How should my DNS reverse (i.e. my ISP provider) resolve:
example.com or mail.example.com?
BTW, this is how my /etc/hosts file looks like:
127.0.0.1   mail.example.com mail example.com
::1     mail.example.com mail example.com

Thanks in advance for all the help
Answer: Have both of them matched exactly. i.e.
171 IN PTR example.com.
170 IN PTR mail.example.com.

In fact you can just copy and paste that to your ISP; that's exactly how it will look in their bind (DNS server) configuration.
Comment: Thanks very much. In fact did it, seems like it gonna take a while to process everything.
Answer: You want the reverse DNS record to be for mail.example.com

Reverse DNS Resolve for MX record


Extract id value from css class to javascript variable

Question: I have a ul menu from which I want to retrieve certain information:

Maths<button onclick="deleteElement(event)" class="delbtn">&times</button>

I have a function in javascript:
function getSessionDatas()
{
    var sessions = [];
    $('.rightDiv').each(function(index)
    {
        var session = $.trim($(this).text().slice(0, -1)).split("×");
        var sessionData = [];
        for (var i = 0; i < session.length; i++)
        {
            var s = {
                subjectOrder: i,
                subjectID: subs[session[i]]
            };
            sessionData.push(s);
        }
        var ses = {
            sessionNo: index,
            sessionData: sessionData
        };
        sessions.push(ses);
    });
}

Here:
var s = {subjectOrder:i, subjectID:<get id here>};

I want to assign the subject id according to the class of the
 item, in this case in the class there is an id10. How can I assign the subjectID to 10 in this case?
Comment: Will there be multiple `li` in each `rightDiv`? Which id value will be assigned in that case?
Comment: @gurvinder372 yes, there will be multiple li, and the id value will be different. It is going to be the id of the subject in the database
Answer: I would suggest you to use data-* prefix custom attribute which can be retrieved using .data(key)  method.

$('.rightDiv li').each(function(index) {
  var id = $(this).data('id')
  console.log(id)
});

Maths<button onclick="deleteElement(event)" class="delbtn">&times</button>

English<button onclick="deleteElement(event)" class="delbtn">&times</button>

for those not using jQuery, same can be fetched using HTMLElement.dataset property
var id = this.dataset.id;

Comment: @DaniM Will each li have a different id value?  If so, add the `data-id` attribute to the li instead of the ul and this will work (in principle - just a minor change).
Answer: While this isn't a particularly good approach, it is possible to retrieve a specific class-name from an element's classes, so long as you can predict a particular pattern. In this case, for example, that the required class-name begins with the string of id:
// elem:   a single node reference, the element from which
//         you want to retrieve a specific class-name;
// prefix: String, the string with which the required
//         class-name(s) begins.
function retrieveClassByPrefix(elem, prefix) {

  // either elem, or prefix, are undefined or otherwise
  // falsey we quit here:
  if (!elem || !prefix) {
    return false;
  }

  // otherwise we convert the classList of the element into
  // an Array, using Array.from() on the result returned from
  // elem.classList, and then use Array.prototype.filter()
  // to filter the Array:
  return allClasses = Array.from(elem.classList).filter(

    // currentClass - using an Arrow function - is a reference
    // to the current class-name of the Array of class-names over
    // which we're iterating; if the currentClass String begins
    // with the supplied String ('prefix') then that class-name
    // is retained in the Array:
    currentClass => currentClass.startsWith(prefix)
  );

}

let idClassName = retrieveClassByPrefix(
  document.querySelector('#form_builder_sortable > li:first-child'), 'id'
);

Comment: I think it should be `document.querySelector('#form_builder_sortable > li:first-child'), 'id'` (minor syntax error)
Comment: @Satpal: you're absolutely right (of course); thanks, that's what comes of answering via phone... >.<
Comment: Thank you David for the time you put to this one. I accepted an answer above as it is easier for me to understand, thanks again!
Answer: You can get the classes of your li element, and find which one match with idXX
var regexId = /id([0-9]+)/gi
$('.rightDiv').each(function( index ) {
 //do some stuff
  $(this).find("li").each(function(){
      var classes = $(this).classes.split(/\s+/); // get the classes in an array
      for(var c in classes){
        c = classes[c]; //one classe
        var regexExec = regexId.exec(c);
        if(regexExec  && regexExec.length > 1){
                var id = regexExec[1];
               //do your stuff with the id
               break;
           }
      }
   }
}

Comment: Thank you for your effort, I had to accept another answer, but this is really good as well :)


Let $\{v_1,\cdots,v_k\}$ be linearly independent. Then we have $f$ st. $f(v_i)=1$ for all $i$

Question: Given a linearly independent set $\{v_1,\cdots,v_k\}$, do we always have an element $f$ st. $f(v_i)=1$ for all $i$? My textbook states this is the case, but I don't really see how we can construct such element.
Comment: What is $f$ supposed to be, a linear functional?
Comment: If yes, then you can just extend $v_1,\dots,v_k$ to a basis of the vector space (assuming that you are in the vector space case) and define $f$ by $f(v_i)=1$ for all $i$ and $f(v)=$ anything for the other basis vectors.
Comment: If $f$ is just intended to be a linear map, then this rule *defines* $f$.  Well, extend $f$ to be $0$ off the span of the $v_i$ for completeness.
Answer: This is one of the key ideas of linear algebra, so it's worth being confused about.
For convenience, let's assume that $\{v_1,\cdots,v_k\}$ is a basis for the space.  (If it isn't, we can just add vectors as needed to make any linearly independent set of vectors into a basis.  This gets messier if the space is not finite-dimensional, but I won't go there.)
Then, for any vector $u$ in our space, there is exactly one $k$-tuple of real numbers $(c_{u_1},...,c_{u_k})$ such that $$u=\sum_{i=1}^kc_{u_i}v_i$$  Let's assume that this appropriate choice of "coordinates" (relative to the basis) has been made for each vector $u$ in the space.  Notice that the coordinates of $v_1$ are $(1,0,...0)$, the coordinates of $v_2$ are $(0,1,0,...,0)$, and so on.  Also notice that the coordinates of $v_1+v_2$ are $(1,1,0,...,0)$ and the coordinates of $3v_1$ are $(3,0,...,0)$, so this correspondence between our vector space and $\mathbb R^k$ turns out to be a linear isomorphism.  (Some people use this identification to argue that $\mathbb R^k$ are the only finite dimensional vector spaces worth studying.)
With all this out of the way, the function you are looking for is just $$f(u)=\sum_{i=1}^kc_{u_i}$$  It's just a bunch of one-line proofs to show that $f$ is a linear form with $f(v_i)=1$ for each member of the basis.


How do I write a QuickCheck property that arbitrarily modifies its arbitrary input?

Question: Suppose I want to verify isSubsequenceOf. I then need to generate some xs, and then generate ys out of them by arbitrarily adding or removing some elements. Then I could verify the property for all the pairs thus obtained. Using sublistOf, I would go like this:
\xs -> sublistOf xs `isSubsequenceOf` xs

— Except that this does not type check.
Unfortunately I don't understand the design of the QuickCheck library overall, and even such seemingly trivial cases puzzle me a big deal. Do I have to spell out a full-blown monadic device of type Gen Result? It kind of defies the purpose of the abstraction.
Answer:
Do I have to spell out a full-blown monadic device of type Gen Result?

What is a "full-blown monadic device"?  Yes, you should probably use the Gen monad but it isn't hard and there is a Testable instance for you to use:
mytest :: [Int] -> Gen Bool
mytest xs = do ys <- sublistOf xs
               pure $ ys `isSubsequenceOf` xs
  where isSubsequenceOf _ _ = True

And the use:
*Main> quickCheck mytest
+++ OK, passed 100 tests.

Comment: @Kindaro But `xs` *is* arbitrary. In particular, `quickCheck mytest` proceeds by calling `arbitrary` and passing its result as `xs` to `mytest`.
Comment: You can pretty much always code golf things into a one liner.  `mytest xs = flip isSubsequenceOf xs <$> sublistOf xs`, for example.
Comment: This is not exactly what I meant. As the property should hold for any `xs`, I meant it to be arbitrary as well. This is not important to the spirit of the answer though, just a minor detail.
Comment: I'm confused as to what else you want to be arbitrary.  Do you understand how to write your property now or not?
Comment: Let me fix the previous comment: read as "I meant `xs` to be arbitrary as well". I do understand how to write my property, though I am a bit disappointed there is no clever combination of combinators to solve this in one line.
Comment: @DanielWagner Oh. This is revealing.
Comment: Thank you @DanielWagner, I was thinking I must be densely missing the question.


Finding the mistake in solving ODE of the form $y'(x) = ay^2 (x) +b$

Question: I was trying to solve the ODE $y'(x) = ay^2(x) +b$ given $a<0 ,b>0, y'(t) >0, y(0)=0$ yet the solution for which I found $y(x)$ doesn't fully fit the ODE.
Calculations I made:
$ay^2+b=a(y^2+\frac{b}{a})\Rightarrow \frac{y'}{y^2+\frac{b}{a}} = a$ when $y^2 +\frac{b}{a} \neq 0$ from the given condition $y'(x)\neq0$ and $a<0$.
Integrating both sides $dx$: $\int \frac{y'}{y^2+\frac{b}{a}}dx =ax+c$ assigning $y = z\Rightarrow y' =\frac{dz}{dx} \Rightarrow dx = \frac{dz}{dy'} $ we get: $\int \frac{y'}{y^2+\frac{b}{a}}dx = \int \frac{y'}{y^2+\frac{b}{a}} \frac{1}{y'}dz =_{y'>0} \int \frac{1}{z^2+\frac{b}{a}}dz = arctan(\frac{z}{\sqrt{\frac{-b}{a}}})$
We got:  $arctan(\frac{z}{\sqrt{\frac{-b}{a}}}) = ax+c$ from the condition $y(0)=0 \Rightarrow z(0)=0$ we get that $c=0$.
so, $arctan(\frac{z}{\sqrt{\frac{-b}{a}}}) = ax \Rightarrow (\frac{z}{\sqrt{\frac{-b}{a}}}) = tan(ax)\Rightarrow z=y(x) =tan(ax)\cdot \sqrt{\frac{-b}{a}} $
The problem is: $y'(x) = (1+tan^2(ax))\cdot a\cdot \sqrt{\frac{-b}{a}} = a(tan^2(ax)\cdot\sqrt{\frac{-b}{a}}+\sqrt{\frac{-b}{a}})\neq a\cdot(tan^2(ax)\cdot \frac{b}{a}+\frac{b}{a}) $
Answer: When you're integrating, $$\int \frac{1}{z^2+b/a} {\rm d}z$$
You need to take care that this isn't the format $$\int \frac{1}{x^2+A^2} = \frac 1A \arctan \left( \frac xA \right)$$
Since $\frac{b}{a}$ is negative. This in fact is of the format $$\int \frac{1}{x^2-A^2}= \frac{1}{2A} \ln \left( \left \vert \frac{x-A}{x+A} \right \vert\right)$$ with $A = \sqrt{ -\frac{b}{a}}$.
This is where you went wrong.
Comment: @dan Sorry, my bad, I forgot to put modulus in $\ln()$. Fixed it.
Comment: nothing to be sorry about! I really appreciate your help!
Comment: @jiadeep khare When trying to use this solution, the initial condition $x=0$ and $y(x) = 0$ leads to $ln(-1)$ Do you an idea how to deal with it?
Answer: Almost as Jaideep Khare answered, without considering the signs of $a$ and/or $b$, the solution of $$y=a\,y^2+b$$ is effectively given (as you did) by
$$y=\frac{\sqrt{b}}{\sqrt{a}} \tan \left(\sqrt{a} \sqrt{b} x+C\right)$$ and the initial condition makes $C=0$.
Now, if $a$  is negative, write it as $a=i^2 |a|$  to get
$$y=\frac{\sqrt{b}}{i\sqrt{|a|}} \tan \left(i\sqrt{|a|} \sqrt{b} x+C\right)$$ and remember than $\tan(iz)=i\tanh(z)$ making by the end
$$y=\frac{\sqrt{b}}{i\sqrt{|a|}} i\tanh \left(\sqrt{|a|} \sqrt{b} \,x\right)=\frac{\sqrt{b}}{\sqrt{|a|}} \tanh \left(\sqrt{|a|b} \, x\right)$$


json array returns, but can't use the response to access it

Question: I have been trying to fetch a json array from an external page. Even though it shows in the browser's element inspector, I can't use it in the console or in my code.
jquery code:
$.ajax({
  type:"POST",
  dataType:"json",
  url:"datacenter.php",
  success:function(data){
    console.log(data.codeName);
  },error:function(data){
    console.log(data);
  }
});

php code:
<?php header('Content-type: application/json'); ?>
insight = {
  "code":"v34ns",
  "codeName":["sureman","greatboy","namely"]
}

Answer: console print data as string use json.parse() function
success:function(data){
var res = JSON.parse(data);
console.log(res.codeName);

Comment: 'JSON.parse(data)' logged :Unexpected token o
Answer: You need to do everything inside the php tags. You also need to echo json
<?php
header('Content-type: application/json');
//$ makes it a variable
$insight = array(
    "code"=>"v34ns",
    "codeName"=>["sureman","greatboy","namely"]
);
echo json_encode($insight);
?>

Now in your JS you need to parse the encoded json
$.ajax({
    type:"POST",
    dataType:"json",
    url:"datacenter.php",
    success:function(data){
        console.log(data.codeName);
    },error:function(data){
        console.log(data);
    }
});

Comment: Uncaught SyntaxError: Unexpected token o in JSON at position 1:var obj = JSON.parse(data);
Comment: your php code worked alright and not the js, but i want to tick this for the correct answer, thank you.
Comment: I was trying to test it. Glad you solved the issue. Not sure why you don't need to parse.


Access denied occurs after translate menu link

Question: I want to translate my menu, I have installed internationalization, variable and locale modules but on my menu items when I click on translate :

An access Denied page is displayed :

What am I doing wrong?
[EDIT]
Log :
Comment: You need to check the permission
Comment: What's in Drupal's watchdog?
Comment: @Bala: All admin permissions are checked
Comment: @Molot: I have edited my post
Comment: @Bibix I hope this has been answered already
Answer: You need to make sure the menu is translatable.  Do this by clicking on the "Edit Menu" option and clicking on "Translate and Localize. Menu items with language will allow translations. Menu items without language will be localized."
The click "Save".
The path would be as follows: site/admin/structure/menu/manage/menu_id/edit
Comment: Thanks you. I can add my translation. But the menu is still not translated while the site content is translated... I'm out of this post scope but if you have an idea
Answer: you must first assign a language other than the default "language neutral" to the existing menu items (click edit for the menu item). Once a source language has been assigned, the translate link should work.
Answer: do you need to enable the option in admin/structure/menu/manage/main-menu/edit
you have three option choose the middle one...
i hope i help you!
Comment: Hello and welcome. Could you try to rewrite your answer? Now I'm not even sure if you are asking for additional details, or really answering, and if later, what exactly you meant.
Answer: When you have entered the menu item via the menu import, if you have selected language undefined during the import process for the new menu items, then trying to translate those menu items results in access denied.
If you re-edit those menu items, then you can translate them.
This works for the menu option "Translate and Localize. Menu items with language will allow translations. Menu items without language will be localized."
Comment: See this related post too:
https://www.drupal.org/node/2316659


The best way to debug a custom token module development

Question: I'm building a custom module to build some tokens. I have added hook_token_info() and it works great. I haved added hook_tokens(), but I'm not able to debug with var_dump() or with dpm().
function mymoduletoken_token_info() {
  $info['tokens']['node']['seccion'] = array(
    'name' => t('Seccion'),
    'description' => t('Custon token to add to the G.A. script more optoins in seccion'),
  );

  $info['tokens']['node']['subseccion'] = array(
    'name' => t('Subseccion'),
    'description' => t('Custon token to add to the G.A. script more options into subseccion'),
  );
  return $info;
}

function mymoduletoken_tokens($type, $tokens, array $data = array(), array $options = array()) {
  dpm($type);
  dpm($token);
  dpm($data);
  dpm($options);
}

I would like to debug the different options to build the token with the information I need.
Comment: If you add a hook implementation to an activated module, you have to clear the cache. Otherwise, Drupal will not know that your module implements a hook that it previously did not implement.
Comment: Thanks Oswald.
But the question, how to make the dpm() to know the information I have in some urls to use with token.
Comment: Ever considered xdebug?
Answer: I think I'm following you...you want a way to invoke the tokens you've created outside of their natural context, so you can debug easily? If so, you can use the token_replace() function. As you're defining tokens that need a node object, you'll have to load an appropriate one up for the job:
// Load the node.
$node = node_load($appropriate_nid);

// Prepare the text string.
$text = 'something involving [node:seccion]';

// Set up some options. Your mileage may vary here.
$options['sanitize'] = FALSE;

// Get the replacement text.
$replacement = token_replace($text, array('node' => $node), $options);

That will invoke your module's implementation of hook_tokens(), and the dpm() calls will fire.
If you're doing a lot of token development it might make sense to wrap that functionality in a simple form.


Why does my jquery ajax post succeed but the $_POST array is still empty?

Question: This is my first question on here, please bear with me:
My ajax request is:

In my something.php file I have:
$Building= $_POST['BuildingName']; //Error Occurs Here

I get an error on this line stating:
Notice: Undefined index: BuildingName.
When I do VAR_DUMP it returns the $_POST array as empty.
I have checked and rechecked. Looked at different answers here and cannot seem to find the problem. I hope it is not staring me in the face.
I appreciate any help, thank you.
SOLUTION: Instead of simply trying to pass data between pages solely which I do not think is possible(correct me if I'm wrong), there has to be an intermediary. I passed my data into MySQL and had my webpage "listen" to the DB and do something based on the most recent entry.

SOLUTION USING SESSIONS per the advice of Lukas1 (you're right this is more efficient.)
           <?php
                $_SESSION['Building']= 'something';
                $Building= $_SESSION['Building'];

                echo "";

            ?>

And my call on the next page is:
<?php echo $Building ?>

Works perfectly without using database as intermediary.
Comment: @SuperCoolHandsomeGelBoy - trailing comma in an object literal is not a syntax error in javascript
Comment: @MartinBarker - that would not make any difference. $.post is just a wrapper for $.ajax anyway
Comment: Nothing in code shown would be problematic. Show more code context. Inspect actual request also in browser dev tools network to see what is actually sent, status etc. Also explain how you are checking what is dumped
Comment: Why are you using `$.ajax` and not `$.post`
Comment: check the browser developer tools network tab to check the request is as expected
Comment: it's a wrapper that preconfigures stuff including making sure the processor for the data `processData` is turned on as the `$.ajaxSetup` could have it turned off by something else before hand
Comment: I used the network tools and found that it posting the data correctly:  array (size=1)
  'BuildingName' => string 'Jacaranda' (length=9) This is good, but I still need to figure out why the next page gives an empty set when getting this data.
Comment: My guess is somehow you are trying to return to that url after the ajax with no post data in the request ... or as shown in network tools the problem doesn't exist
Comment: @KeelanParaja If that's the response (that **is** PHPs `var_dump`) then what's the problem? You're posting and getting the expected result.
Comment: @MartinBarker The [jQuery.post() docs](http://api.jquery.com/jQuery.post/) don't seem to indicate anything about `processData`. In fact it states the shorthand to `jQuery.ajax()` with just `type, url, data, success and dataType` attributes. All of those are set in OPs question (or left as default). Where's the info about `processData` coming from? Edit: The [jQuery ajax source](https://github.com/jquery/jquery/blob/master/src/ajax.js) (Lines 833-852) define the wrapper, no additional configuration as far as I can see.
Comment: Interestingly using HTML post through  works fine. Although the network tools are saying that the correct data is getting sent with ajax request, when the next page is loaded which has the PHP script to grab the data, the var_dump then says empty set. Seems like a behind the scenes issues, something is conflicting.
Comment: @KeelanParaja I think you're confusing your expected result. using ajax does send the request and that's it. Using a form sends the request **and displays the result in the browser**. Your ajax works fine and the result returned works aswell, you're just not doing anything with it (see your "empty" success function).
Comment: @Toastrackenigma The ajax POST is working fine, if OP changed his `success` function to include something like `alert(data);` or `console.log(data);` he would in fact see the PHP output and the var_dump'ed `$_POST` array.
Comment: Yes it is working fine. I think the problem is that by the time I get to the page the data is gone (or something to that effect). Upon a button click my  takes me to datapage.php, which has an include('something.php') statement. However before I click that button my ajax request sends the data to something.php. So when I click on my button it takes me to a fresh page that no longer has the data because the something.php is refreshed. Is that correct logic? I hope I'm making sense.
Comment: When you load `something.php` again...it is a new instance and the data you sent previously won't be there
Comment: Yes thank you @charlietfl. I overlooked that... thanks for your patience.
Comment: Thank you @ccKep as well. Appreciate the help.
Comment: truth be told I have not studied your problem very well but in your suggested solution you're talking about using database as an intermediary to pass some data between pages. Now, I don't know what kind of data you're passing, but if those data are only relevant for current session, I'd suggest avoid using database for this particular purpose and use `$_SESSION` instead
Comment: @Lukas1 thanks, I added my code above using sessions rather than DB. Works very nicely, thank you.
Answer: Just change your data attribute to
"BuildingName=Jacaranda"

and it should work all fine.


Comparar todas as rows e columns de dois Df, atualizar e somar as diferenças ao final das rows e columns

Question: Possuo dois csv separados por tab. Ambos possuem o mesmo número de rows e columns. A primeira coluna POS possui os mesmos unique values nos dois df. As diferenças (ou não), ocorrem nos valores (strings) das colunas col1:col4.
Pensei em realizar uma query, algo como: query = subset_pl(subset_pl.isin(subset_ad))
e a partir disso continuar com o código, mas eu fiquei preso aí...
import pandas as pd

subset_ad = pd.read_csv('subset_ad.csv', sep='\t')
subset_ad.set_index('POS')
subset_ad

POS         col1    col2    col3    col4
28355991    A       A       A       A
28356037    A       A       A       A
28356130    A       A       A       A
28356246    A       A       A       A

subset_pl = pd.read_csv('subset_pl.csv', sep='\t')
subset_pl.set_index('POS')
subset_pl

POS         col1    col2    col3    col4
28355991    A       B       A       A
28356037    B       B       B       A
28356130    A       B       A       A
28356246    A       A       B       A

O que eu pretendo conseguir é: comparar subset_ad com subset_pl, atualizar subset_ad com o valor de subset_pl mantendo o valor de subset_ad separados por , (A,B por exemplo), caso haja values diferentes e contar essas diferenças tanto em rows como em columns adicionando uma row e uma column a mais (cont_col, cont_row) para exibir a contagem das células que sofreram alterações...
O output seria algo como:
subset_ad

POS         col1    col2    col3    col4    cont_row
28355991    A       A,B     A       A       1
28356037    A,B     A,B     A,B     A       3
28356130    A       A,B     A       A       1
28356246    A       A       A,B     A       1
cont_col    1       3       2       0

Qualquer direcionamento será bem vindo!
Comment: Colega, sua pergunta não tá nada clara. Pra começar, os seus valores são strings no formato "x/x" em que parece que x sempre é `0`, `1` ou `.`. Como isso é comparado? É comparação de string mesmo? Se sim, qual foi a sua dificuldade? Em segundo lugar, essa coluna `soma_rows`, por exemplo, de onde vem esse valor? Ele é uma soma? Se sim, soma de que?! Por que no resultado final tem uma vírgula? Enfim, sugiro que você forneça um exemplo **simples** do seu problema, talvez com duas linhas e colunas, e explique detalhadamente. Se não ninguém consegue te ajudar.
Comment: Olá amigo. Segui sua sugestão e alterei o exemplo...A princípio todos os dados são do tipo string mesmo! Eu estava lendo aqui, e pensei se a opção `df.merge` não seria possível neste caso...De modo que ao mergir ele adicionaria os valores de `subset_pl` ao `subset_ad` apenas onde estes fossem diferentes como mostrado acima no output desejado em `subset_ad[1,1]`
Comment: Agora sim! :) Vou responder.
Answer: Você pode fazer assim:

Leia ambos os arquivos em DataFrame's diferentes.
Concatene os DataFrames diretamente, usando o operador +. Você pode incluir uma string com a vírgula no meio. Esse operador vai executar para cada "célula" da tabela.
Itere sobre as linhas e colunas contabilizando as diferenças. Onde não houver diferenças (e se desejar), unifique as letras em uma só.

Exemplo de código:
import pandas as pd

# Lê o primeiro arquivo
subset_ad = pd.read_csv('subset_ad.csv', sep='\t', index_col=False)
subset_ad = subset_ad.set_index('POS')

print('subset_ad:')
print('-' * 20)
print(subset_ad)
print('-' * 20)

# Lê o segundo arquivo
subset_pl = pd.read_csv('subset_pl.csv', sep='\t', index_col=False)
subset_pl = subset_pl.set_index('POS')

print('\n')
print('subset_pl:')
print('-' * 20)
print(subset_pl)
print('-' * 20)

# Concatena os arquivos separando o conteúdo por uma vírgula
df = subset_ad + ',' + subset_pl

# Adiciona a coluna e a linha de somatório
df['cont_row'] = [0 for _ in range(len(df))]
df.loc['cont_col'] = [0 for _ in df.columns[:-1]] + ['']

print('\n')
print('subset_ad + subset_pl:')
print('-' * 20)
print(df)
print('-' * 20)

# Contabiliza as diferenças (unificando a letra onde não houver diferença)
for index, row in df.iterrows():
    if index != 'cont_col':
        for col in df.columns[:-1]:
            val = row[col]
            letters = val.split(',')
            if letters[0] == letters[1]:
                df.set_value(index, col, letters[0])
            else:
                cnt = df.loc[index]['cont_row']
                df.set_value(index, 'cont_row', cnt + 1)

                cnt = df.loc['cont_col'][col]
                df.set_value('cont_col', col, cnt + 1)

print('\n')
print('resultado final:')
print('-' * 20)
print(df)
print('-' * 20)

Resultado desse código:
subset_ad:
--------------------
         col1 col2 col3 col4
POS
28355991    A    A    A    A
28356037    A    A    A    A
28356130    A    A    A    A
28356246    A    A    A    A
--------------------

subset_pl:
--------------------
         col1 col2 col3 col4
POS
28355991    A    B    A    A
28356037    B    B    B    A
28356130    A    B    A    A
28356246    A    A    B    A
--------------------

subset_ad + subset_pl:
--------------------
         col1 col2 col3 col4 cont_row
POS
28355991  A,A  A,B  A,A  A,A        0
28356037  A,B  A,B  A,B  A,A        0
28356130  A,A  A,B  A,A  A,A        0
28356246  A,A  A,A  A,B  A,A        0
cont_col    0    0    0    0
--------------------

resultado final:
--------------------
         col1 col2 col3 col4 cont_row
POS
28355991    A  A,B    A    A        1
28356037  A,B  A,B  A,B    A        3
28356130    A  A,B    A    A        1
28356246    A    A  A,B    A        1
cont_col    1    3    2    0
--------------------

Comment: Muito obrigado Luiz! Apesar de querer a contabilização das rows e cols diferentes, a resposta sem esta etapa seria muito mais simples do que eu estava imaginando. Era só usar uma concatenação simples de `df = subset_ad + ',' + subset_pl`. Funcionou Perfeitamente!


Can I add scope information to tags generated with `--regex-` in exuberant ctags?

Question: Technically, I'm using Tagbar in vim to view a file's tags, but this question should apply generally to exuberant ctags, v5.8.
Suppose I've got the following python file, call it foo.py:
class foo:
    def bar(baz):
        print(baz)

Let's run ctags on it: ctags foo.py. The resulting tags file looks like this:
!_ some ctags version / formatting stuff not worth pasting
bar foo.py  /^    def bar(baz):$/;" m   class:foo
foo foo.py  /^class foo:$/;"    c

The bit I'm interested in is the last field of the second line, class:foo. That's the scope of the bar() function. If I use tagbar in vim, it nests the function in the class accordingly.
Now suppose I'm adding support for a new language in my ~/.ctags. In fact, I'm adding support for this puppet file:
class foo {
    include bar
}

Suppose I use the following ~/.ctags arguments. The 'import' regex is ugly (errr... ugly for regex) but it gets the job done enough for this example:
--langdef=puppet
--langmap=puppet:.pp
--regex-puppet=/^class[ \t]*([:a-zA-Z0-9_\-]+)[ \t]*/\1/c,class,classes/
--regex-puppet=/^\ \ \ \ include[ \t]*([:a-zA-Z0-9_\-]+)/\1/i,include,includes/

That generates the following tag in my tags file:
bar foo.pp  /^    include bar$/;"   i
foo foo.pp  /^class foo {$/;"   c

Notice neither line contains scoping information. My question is this: Is there anyway for me to construct the --regex-puppet argument, or --regex-<LANG> lines generally, to collect information about a tag's scope? To perhaps declare that tags meeting criterion A are always going to be scope-parents of tags meeting criterion B?
man ctags suggests no clear way to add arbitrary scope information, but I might be overlooking another solution (snipped slightly for emphasis):
--regex-<LANG>=/regexp/replacement/[kind-spec/][flags]

        Unless modified by flags, regexp is interpreted as a Posix extended regular expression. The replacement should expand for all matching lines  to  a  non-empty  string  of
        characters,  or  a  warning message will be reported. An optional kind specifier for tags matching regexp may follow replacement, which will determine what kind of tag is
        reported in the "kind" extension field (see TAG FILE FORMAT, below). The full form of kind-spec is in the form of a single letter, a comma, a  name  (without  spaces),  a
        comma, a description, followed by a separator, which specify the short and long forms of the kind value and its textual description (displayed using --list-kinds). Either
        the kind name and/or the description may be omitted. If kind-spec is omitted, it defaults to "r,regex". Finally, flags are one or more single-letter characters having the
        following effect upon the interpretation of regexp:

           b   The pattern is interpreted as a Posix basic regular expression.

           e   The pattern is interpreted as a Posix extended regular expression (default).

           i   The regular expression is to be applied in a case-insensitive manner.

Answer: No, unfortunately that is not possible with the regex pattern support in ctags. The only way to get ctags to generate correct scopes is to write a parser as an additional module in C. I would like to add support for a better handling of new languages to ctags if I find the time, but so far that hasn't worked out and I'm also still unsure about the best approach.
If you're mostly interested in Tagbar support there is another approach, though: Tagbar supports arbitrary tag-generating programs as long as their output is compatible to the ctags one, so you could write a simple parser in, say, Python and configure Tagbar to use that. Have a look at :h tagbar-extend (especially the last subsection "Writing your own tag-generating program") if that would be an option for you.
Answer: I'm working on such feature at universal ctags project:
https://github.com/universal-ctags/ctags/pull/562
.
(Don't expect too much; regex parser is not enough for complicated syntax.
The new feature is for a language with simple syntax.)
Example 1::
$ cat /tmp/input.foo
class foo:
def bar(baz):
    print(baz)
class goo:
def gar(gaz):
    print(gaz)

$ cat /tmp/foo.ctags
--langdef=foo
    --map-foo=+.foo
    --regex-foo=/^class[[:blank:]]+([[:alpha:]]+):/\1/c,class/{scope=set}
    --regex-foo=/^[[:blank:]]+def[[:blank:]]+([[:alpha:]]+).*:/\1/d,definition/{scope=ref}

$ ~/var/ctags/ctags --options=/tmp/foo.ctags -o - /tmp/input.foo
bar /tmp/input.foo  /^    def bar(baz):$/;" d   class:foo
foo /tmp/input.foo  /^class foo:$/;"    c
gar /tmp/input.foo  /^    def gar(gaz):$/;" d   class:goo
goo /tmp/input.foo  /^class goo:$/;"    c

Example 2::
$ cat /tmp/input.pp
class foo {
include bar
}

$ cat /tmp/pp.ctags
--langdef=pp
    --map-pp=+.pp
    --regex-pp=/^class[[:blank:]]*([[:alnum:]]+)[[[:blank:]]]*\{/\1/c,class,classes/{scope=push}
    --regex-pp=/^[[:blank:]]*include[[:blank:]]*([[:alnum:]]+).*/\1/i,include,includes/{scope=ref}
    --regex-pp=/^[[:blank:]]*\}.*//{scope=pop}{exclusive}

$ ~/var/ctags/ctags --options=/tmp/pp.ctags -o - /tmp/input.pp
bar /tmp/input.pp   /^    include bar$/;"   i   class:foo
foo /tmp/input.pp   /^class foo {$/;"   c