text:
Q: Why are those hash functions considered a bad choice? Given Hashtable $T[0,..,m-1]$ and $U =  \{0, . . . , n − 1 \}$ set of possible keys $k$ with $m  \ll n$
Let $$h: U \rightarrow \{0, . . . , m − 1 \}  $$
I am trying to understand why the hash functions $$h_{1}(k) =\Big\lfloor m\Big(\frac{k}{n}\Big)^2 \Big\rfloor$$
and
$$h_{2}(k) =\Big(l \Big\lfloor \frac{m}{n} k \Big\rfloor\Big) \text{mod } m  \qquad l \in \mathbb{N}$$
would be considered a bad choice. I understand that a good hash function should have higher probability to be injective (Correct?) but I still can't see how this applies in these specific cases based on the functions formula.
I've tried different values for $h_1$ and $h_2$ and it's obvious that when $k_1$ and $k_2$ are close then $h(k_1) = h(k_2)$ Is there a way to formally prove this?
Help?

A: At least in computer science, a good hash function has as little as possible collisions (it makes the algorithm faster) -a collision happens when we have  $k_{1} \neq k_{2}$ with the same hash value, $h(k_{1}) = h(k_{2})$. When a hash function is injective, it is called "perfect hash function"-it has no collisions. So, as you said, a good hash function should have higher probability to be injective. However, notice that with your condition $m<<n$, we cannot have $h:U\rightarrow \{0, 1, 2, ..., m-1\}$ injective, since the cardinality of $U$ $(|U|=n)$ is greater than the cardinality of $T$ $(|T|=m)$.
Looking to your hash function $h_{1}$, it seems that when $k$ and $m$ are too small compared to $n$, there will be many $k\in U$ such that $h_{1}(k) = 0$.  For exemple, if $n=2^{m}$, $h_{1}(k)= 0$ for every $k < \frac{2^{m}} {\sqrt{m}}$. I think it would be better if you use just
$$ h(k) = m
\left\lfloor\dfrac{k}{n}\right\rfloor $$
This way you know you are distribuiting your values with the same quantity of collisions, what is good - unless you know beforehand what values you are going to use more.
In fact, if you are going to use only a part $G\subset U$, you can look for a injective function (if $|G| \leq m$, of course). That is the best scenario for hash functions: when you have $\alpha \leq m$ numbers and you know who they are.
Your hash function $h_{2}$ looks fine, although you must choose a convenient $l$ - for example, if $l=pm, p\in \mathbb{N}$, $h_{2}(k) = 0\ \forall k\in U$.
About this "I've tried different values for h1 and h2 and it's obvious that when $k_{1}$ and $k_{2}$ are close then h(k1)=h(k2) Is there a way to formally prove this?": we can have $k_{1}$ and $k_{2}$ "really" close $(k_{2}=k_{1}+1)$ and $h_{2}(k_{1})$ completely different from $h_{2}(k_{2})$. However,
$$
\left\lfloor\dfrac{mk_{1}}{n}\right\rfloor  = \left\lfloor\dfrac{mk_{2}}{n}\right\rfloor \Rightarrow h_{2}(k_{1}) = h_{2}(k_{2}) $$
Perhaps a better choice for your hash function would be just
$h(k)=(lk)$ mod $m$, where $l$ is preferably a prime number -and big enough  so we don't have many $k$ such that $h(k)=0$. This way, even if $k_{1}$ and $k_{2}$ are close to each other, they are not likely to have the same hash value (and it is convenient for security reasons).
I said that if you know what values from $U$ you are going to use, you can search for a  perfect hash function, but it is frequently done by brute force algorithms.
If you don't mind, I would like to recommend you this book, Open Data Structures, from Pat Morin.

A: This is not a math question, but a computer science question.
There is no intrinsic problem if a hash functions gives collisions for similar keys — the problem is that when programs tend to work with many similar keys and put them in the hash table, they'll see poor performance.
This is a common use case, which is why such a hash function is considered to be bad. But for the occasional program that only uses dissimilar keys can use such a hash function just fine.


text:
Q: Can you embed "commands" in JSON? I have some JSON (let's call it json1), and I want to combine it with some other JSON (json2). I don't just want to merge or append data, I also want to be able to delete data from json1 by embedding "commands" in json2.
Example
json1 = {
  "a": 1,
  "b": "xyz",
  "c": ["foo", "bar"]
}

json2 = {
  "b": "hello world",
  "d": 4,
  "c": ["-foo", "+foobar"],
}

output = combine(json1, json2)

// Expected result from the fictional "combine()" method
output = {
  "a": 1,
  "b": "hello world",
  "c": ["bar", "foobar"],
  "d": 4
}

Of course I could just come up with my own syntax and logic, but I'm curious if there are any existing techniques for manipulating JSON using JSON?
Disclaimer: I'm not asking about recommendations for books, tools, software libraries (or more). I merely have a practical, answerable problem that is unique to software development pertaining to a specific programming problem and am asking about software tools commonly used by programmers, or possibly a software algorithm. Geez.

A: With jsonpatch your example would translate to a JSON Patch similar to this:
[
  { "op": "replace", "path": "/b", "value": "hello world" },
  { "op": "add", "path": "/d", "value": 4 },
  { "op": "replace", "path": "/c/0", "value": "foobar"}
]

redpajama_set_name: RedPajamaStackExchange


text:
Q: The Human Division - Who is the Stealing all the Ships? Okay just finished the Human Division from the Old Man War series and really just got to know. Will we every find out who is stealing the Conclaves and Unions ships? Then are these the same people who kidnapped the Unions soldiers and destroyed earth station and been attacking the Conclaves and Union ships?

A: Yes, in the final book The End of All Things we find out who is stealing all the ships and why.  Yes, it is the same group responsible for all the various things.

In End of All Things we learn a group called Equilibrium has been formed with goals which including destroying the Conclave and Colonial Union.  It does this by capturing ships and crews, and using CDF style technology to connect a brainwash pilot's brain directly to the ship's computer.  These captured ships are then generally sent on suicide missions.
Equilibrium includes members of many species, including some CDF and Conclave traitors.


text:
Q: Scrape Data from network request VB.net i am using VB.net to scrape data and update an ExcelFile.
I am facing a problem.
Da data are visible just in a network response. And I don't know how to get it.
They are never visible in source code.
This is the network header:

This is the network payload:

And this is the response i need to get, the value is 1976500

I don't know how to get it. I am pretty new in web scraping, i can get datas from html but not from here.


text:
Q: How to get the public DNS of EC2 instance from outside using AWS CLI? I have one instance and planning to have more in the near future but only if I can manage them from the outside world. Hence I need to be remotely request new servers, start them up or shut them down at will. Hence, since the IP address will change every time, I will need a method to query servers' public DNS name. And all of this needs to be done via AWS CLI.
For the ;ast few days I am trying to hunt this information down and I am finally here.
My server, outside the EC2 cluster has AWS CLI installed.
I have my "Access Key ID" copied from the IAM page and assigned to the proper variable on this server
$ echo $AWS_ACCESS_KEY
XXXXXXXXXXXX4PEXXXXX
$ ec2-describe-instances
sanity-check: Your system clock is 302 seconds behind.
<?xml version="1.0" encoding="UTF-8"?>
<DescribeInstancesResponse xmlns="http://ec2.amazonaws.com/doc/2013-10-15/">
        <requestId>53eb7530-2147-4ab6-8d6c-d9ddbdeef290</requestId>
        <reservationSet/>
</DescribeInstancesResponse>
$ ec2-describe-instances i-4XXXXXX0
sanity-check: Your system clock is 302 seconds behind.
+----------------------------+---------------------------------------------+
|            Code            |                   Message                   |
+----------------------------+---------------------------------------------+
| InvalidInstanceID.NotFound | The instance ID 'i-4XXXXXX0' does not exist |
+----------------------------+---------------------------------------------+

The secret key and the instance number both have been copied from the console and pasted into the terminal window. There is no way that there is a typo in either of them.

A: 1.can you install NTP in your server and Try you can see the error ""

A: Install NTP:
yum install ntp
service ntpd restart
wait for some time to sync time & then fire below command,
ec2-describe-instances i-4XXXXXX0
Hope it'll help :)

A: First you need to configure AWS CLI properly and baked in your AWS ACCESS KEY and SECRET which has policy to describe instance.
For more information on how to setup aws-cli follow the link http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
Once it is done properly, you can list ec2 instance in a particular region by passing region within query. Ex :- Describe all the ec2-instances in us-west-2 region.
aws ec2 describe-instances --region us-west-1
You can also use "jq" with pipe symbol, for parsing the json and just get the public ip of ec2-instance.


text:
Q: how to make a walker to this (in bootstrap, i try but not work)

            BrandName

Home

About

                Services

Web Design

Web Development

Graphic Design

Digital Marketing

Blog

Contact

            <form class="navbar-form form-inline">

                    <input type="text" id="search" class="form-control" placeholder="Search by Name">
                    

            </form>

1

10

                     Paula Wilson

 Profile

 Calendar

 Settings

 Logout

A: I use this navwalker
<?php
class wp_bootstrap_navwalker extends Walker_Nav_Menu {

    public function start_lvl( &$output, $depth = 0, $args = array() ) {
    $indent = str_repeat( "\t", $depth );
    $output .= "\n$indent
\n";
}

public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
    $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';

    if ( strcasecmp( $item->attr_title, 'divider' ) == 0 && $depth === 1 ) {
        $output .= $indent . '
';
    } else if ( strcasecmp( $item->title, 'divider') == 0 && $depth === 1 ) {
        $output .= $indent . '
';
    } else if ( strcasecmp( $item->attr_title, 'dropdown-header') == 0 && $depth === 1 ) {
        $output .= $indent . '
' . esc_attr( $item->title );
    } else if ( strcasecmp($item->attr_title, 'disabled' ) == 0 ) {
        $output .= $indent . '
' . esc_attr( $item->title ) . '';
    } else {

        $class_names = $value = '';

        $classes = empty( $item->classes ) ? array() : (array) $item->classes;
        $classes[] = 'menu-item-' . $item->ID;

        $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );

        if ( $args->has_children )
            $class_names .= ' dropdown';

        if ( in_array( 'current-menu-item', $classes ) )
            $class_names .= ' active';

        $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';

        $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
        $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';

        $output .= $indent . '
';

        $atts = array();
        $atts['title']  = ! empty( $item->title )   ? $item->title  : '';
        $atts['target'] = ! empty( $item->target )  ? $item->target : '';
        $atts['rel']    = ! empty( $item->xfn )     ? $item->xfn    : '';

        // If item has_children add atts to a.
        if ( $args->has_children && $depth === 0 ) {
            $atts['href']           = '#';
            $atts['data-toggle']    = 'dropdown';
            $atts['class']          = 'dropdown-toggle';
            $atts['aria-haspopup']  = 'true';
        } else {
            $atts['href'] = ! empty( $item->url ) ? $item->url : '';
        }

        $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args );

        $attributes = '';
        foreach ( $atts as $attr => $value ) {
            if ( ! empty( $value ) ) {
                $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
                $attributes .= ' ' . $attr . '="' . $value . '"';
            }
        }

        $item_output = $args->before;

        if ( ! empty( $item->attr_title ) )
            $item_output .= 'attr_title ) . '"> ';
        else
            $item_output .= '';

        $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
        $item_output .= ( $args->has_children && 0 === $depth ) ? ' ' : '';
        $item_output .= $args->after;

        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }
}

public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
    if ( ! $element )
        return;

    $id_field = $this->db_fields['id'];

    // Display this element.
    if ( is_object( $args[0] ) )
       $args[0]->has_children = ! empty( $children_elements[ $element->$id_field ] );

    parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
}

public static function fallback( $args ) {
    if ( current_user_can( 'manage_options' ) ) {

        extract( $args );

        $fb_output = null;

        if ( $container ) {
            $fb_output = '<' . $container;

            if ( $container_id )
                $fb_output .= ' id="' . $container_id . '"';

            if ( $container_class )
                $fb_output .= ' class="' . $container_class . '"';

            $fb_output .= '>';
        }

        $fb_output .= '
';
        $fb_output .= '
Add a menu
';
        $fb_output .= '
';

        if ( $container )
            $fb_output .= '</' . $container . '>';

        echo $fb_output;
        }
    }
}

Then call the navwalker in your menu array like so
<?php /* Primary navigation */
  wp_nav_menu( array(
    'menu' => 'top navigation',
    'depth' => 2,
    'container' => false,
    'menu_class' => 'nav navbar-nav',
    'theme_location' => 'main-nav',             // where it's located in the theme
    //Process nav menu using our custom nav walker
    'walker' => new wp_bootstrap_navwalker())
  );
  ?>

Code source https://github.com/twittem/wp-bootstrap-navwalker


text:
Q: Insert an animated gif image in a `beamer` presentation I have gif animated image that I want insert in a presentation that I'm building with the beamer package. I want that the image is animated also in the presentation and the only way that I know to do that is to isolate the gif images, save them as JPG, than insert the sequence of these images using the animate package. But this is a tedious work to do, so I ask if there is some other more quick way .

A: You could look to the package movie15 of LATEX.
Be careful, this package is advertised as deprecated on CTAN in favor of the newest media9. The problem is that media9 does NOT support GIFs as far as I know and therefore if you want to use a GIF directly in media9 you need to convert it in an available format for the package (i.e. FLV, MP4).
I hope this helped you.


text:
Q: React Native useEffect hook continues to be invoked even after component is unmounted I am new to React Native and I am trying to understand how the useEffect hook continues to work even after a component is unmounted.
I have the following screens defined in the stack navigator:
<NavigationContainer>
    <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} options={{ headerShown: false }}></Stack.Screen>
        <Stack.Screen name="Chat" component={ChatScreen} options={{ headerShown: false }}></Stack.Screen>
    </Stack.Navigator>
</NavigationContainer>

I have the following code in ChatScreen:
export default function ChatScreen({ navigation }: { navigation: any }) {
    const isError = useAppSelector((state) => state.chat.isError);
    useEffect(() => {
        console.log('useEffect')
        if (isError) {
            if (navigation.canGoBack())
            navigation.popToTop();
            return;
        }

        return () => { console.log('cleanup'); }
    }, [isError]);
}

isError comes from the redux store. When isError is true, it goes back to the Home screen because of the navigation.popToTop(). But, when isError is later modified in the store, I see that useEffect from ChatScreen is invoked again. Since ChatScreen is popped from the stack navigator, shouldn't the component be unmounted at this point? How does the useEffect still continue to be invoked?
I don't want the code inside useEffect to be executed when isError changes after navigation.popToTop() is done. How can I achieve that?


text:
Q: How to add a column after another column in sqlalchemy for mysql? I have a table where I need to add column say a_1 after column a and the table structure is like column a,b,c,d? How can i add this?
Below query adds column after d but I want to add column after a?
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('sample_table', sa.Column('a_1', mysql.JSON(), nullable=True, ))
# ### end Alembic commands ###

def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('sample_table', 'a_1')
# ### end Alembic commands ###

A: add_column(table_name, column, schema=None)

Issue an "add column" instruction using the current migration context.
e.g.:
from alembic import op
from sqlalchemy import Column, String

op.add_column('organization',
    Column('name', String())
)

The provided Column object can also specify a ForeignKey, referencing a remote table name. Alembic will automatically generate a stub "referenced" table and emit a second ALTER statement in order to add the constraint separately:
from alembic import op
from sqlalchemy import Column, INTEGER, ForeignKey

op.add_column('organization',
    Column('account_id', INTEGER, ForeignKey('accounts.id'))
)

Note that this statement uses the Column construct as is from the SQLAlchemy library. In particular, default values to be created on the database side are specified using the server_default parameter, and not default which only specifies Python-side defaults:
from alembic import op
from sqlalchemy import Column, TIMESTAMP, func

# specify "DEFAULT NOW" along with the column add
op.add_column('account',
    Column('timestamp', TIMESTAMP, server_default=func.now())
)

Parameters
table_name – String name of the parent table.
column – a sqlalchemy.schema.Column object representing the new column.
schema – Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct quoted_name.
Source https://alembic.sqlalchemy.org/en/latest/ops.html


text:
Q: XAML - StaticResources in Collection Initializers I want to add a single model object that has been instantiated once in XAML, and add it to two different collections (in xaml).
The following code renders fine in Blend's Design Time, but I get the following errors at run time:
For "Post1"
Object of type 'WpfBlog.Models.Tag' cannot be converted to type 'System.Collections.ObjectModel.ObservableCollection`1[WpfBlog.Models.Tag]'.  Error at object 'WpfBlog.Admin' in markup file 'WpfBlog;component/Admin.xaml' Line XX Position YY.
If I comment out "Post1", I'll get this error on "Post2"
Cannot add element to property 'Tags', because the property can have only one child element if it uses an explicit collection tag.  Error at object 'System.Windows.StaticResourceExtension' in markup file 'WpfBlog;component/Admin.xaml' Line AA Position BB.
<Window.Resources>
    <model:Tag x:Key="TDD" Name="TDD" ForeColor="Black" BackColor="White" />
    <model:Tag x:Key="Agile" Name="Agile" ForeColor="White" BackColor="Black" />
    <model:Tag x:Key="Waterfail" Name="Waterfail" ForeColor="Red" BackColor="White" />
</Window.Resources>
<Window.DataContext>
    <local:AdminViewModel>
        <local:AdminViewModel.AllTags>
            <StaticResource ResourceKey="TDD"/>
            <StaticResource ResourceKey="Agile"/>
            <StaticResource ResourceKey="Waterfail"/>
        </local:AdminViewModel.AllTags>
        <local:AdminViewModel.Posts>
            <local:PostViewModel Title="Post1">
                <local:PostViewModel.Tags>
                    <StaticResource ResourceKey="TDD" />
                </local:PostViewModel.Tags>
            </local:PostViewModel>
            <local:PostViewModel Title="Post2">
                <local:PostViewModel.Tags>
                    <StaticResource ResourceKey="TDD" />
                    <StaticResource ResourceKey="Agile" />
                    <StaticResource ResourceKey="Waterfail" />
                </local:PostViewModel.Tags>
            </local:PostViewModel>
        </local:AdminViewModel.Posts>
    </local:AdminViewModel>
<Window.DataContext>

The following code compiles and runs fine, but two tags named "TDD" get created, so if I try to rename the tag, I have to do it for all of the posts, instead of just the one Tag object.
<Window.Resources>
    <model:Tag x:Key="TDD" Name="TDD" ForeColor="Black" BackColor="White" />
    <model:Tag x:Key="Agile" Name="Agile" ForeColor="White" BackColor="Black" />
    <model:Tag x:Key="Waterfail" Name="Waterfail" ForeColor="Red" BackColor="White" />
</Window.Resources>
<Window.DataContext>
    <local:AdminViewModel>
        <local:AdminViewModel.AllTags>
            <StaticResource ResourceKey="TDD"/>
            <StaticResource ResourceKey="Agile"/>
            <StaticResource ResourceKey="Waterfail"/>
        </local:AdminViewModel.AllTags>
        <local:AdminViewModel.Posts>
            <local:PostViewModel Title="Post1">
                <local:PostViewModel.Tags>
                    <model:Tag Name="TDD" ForeColor="Black" BackColor="White" />
                </local:PostViewModel.Tags>
            </local:PostViewModel>
            <local:PostViewModel Title="Post2">
                <local:PostViewModel.Tags>
                    <model:Tag Name="TDD" ForeColor="Black" BackColor="White" />
                    <model:Tag Name="Agile" ForeColor="White" BackColor="Black" />
                    <model:Tag Name="Waterfail" ForeColor="Red" BackColor="White" />
                </local:PostViewModel.Tags>
            </local:PostViewModel>
        </local:AdminViewModel.Posts>
    </local:AdminViewModel>
<Window.DataContext>

Any ideas? I'd be able to ignore it and work around it if Blend didn't render it correctly, but it does!

A: I was able to avoid the problem by explicitly initializing a new collection within the Tags property. Something like this:
<local:PostViewModel Title="Post1">
  <local:PostViewModel.Tags>
     <model:TagCollection>
        <StaticResource ResourceKey="TDD" />
     </model:TagCollection>
  </local:PostViewModel.Tags>

Obviously, this is only possible if you allow your Tags property to be writable.

A: This is very similar to the problem described in this question, I think.
The solution should be to add an x:Shared="False" attribute to your <model:Tag> elements. That tells WPF not to share a single instance each time one is referenced, and instead to create new instances of them.


text:
Q: What is best way to create .NET6 class with many non-nullable properties? I trying to create class with some number of non-nulable properties (>7).
If I do like this:
public class Meeting
{

    public Name Name { get; set; }
    public Person ResponsiblePerson { get; set; }
    public Description Description {get; set; }
    public Category Category { get; set; }
    public Type Type { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public List<Person> Attendees { get; set; }

    public Meeting()
    {
        Attendees = new List<Person>();
    }
}

I get warnings like this:
"Non-nullable property '...' must contain a non-null value when exiting constructor. Consider declaring the property as nullable."
There is a list of variants I thinked of:

*

*Default values removes this warning, but I think, that it will just add useless values, that in the future will be needed to be changed anyway.

*If I init all properties in constructor this warning gets away, but then constructor will have >7 params which is nightmare.

*I have seen that some people use "Builder" pattern to init classes with many params. But the builder itself can't prevent 'null' values (The builder will get same warnings).

*There is easy way to remove warning, by making nullable property in .csproj file from true to false, but I don't want to just remove that warning. I want to make class itself safe from null values.
Whats clean way create that class?

A: The whole point of non-nullable is to initialize class instances in a "valid" state.
If Meeting is part of a domain, having some logic inside, you can't initialize Meeting without initial values. I.e., new Meeting() doesn't make any sense.
On the other hand, if Meeting is a so-called data transfer object and it may be initialized partially, if not even empty, then setters are fine, and you don't need a constructor.

A: Since C#11 you can add a Required modifier.
public class Meeting
{
    public required Name Name { get; set; }
    public required Person ResponsiblePerson { get; set; }
    public required Description Description {get; set; }
    public required Category Category { get; set; }
    public required Type Type { get; set; }
    public required DateTime StartDate { get; set; }
    public required DateTime EndDate { get; set; }
    public List<Person> Attendees { get; set; } = new List<Person>();
}

This feature aims to improve how we initialize objects that do not rely on constructor parameters.
More detailed info:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/required


text:
Q: creating tabs inside a fragment I have an application that contains one main activity that has a navigation panel to switch between fragments. Inside one fragment I would like to have tabs to switch between other fragments. I have created a separate fragment that I can visit from the navigation panel:
public class EventsTabsFragment extends Fragment
{
    private TabLayout events_tabs;
    private ViewPager events_pager;
    private static int int_items = 2;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        //the inflate() method takes the layout you wanna show as the first parameter
        View view = inflater.inflate(R.layout.event_tabs, container, false);

        //tabs for our fragment
        events_tabs = view.findViewById(R.id.events_tabs);
        events_pager = view.findViewById(R.id.events_pager);

        events_pager.setAdapter(new MyAdapter(getChildFragmentManager()));

        events_tabs.post(new Runnable() {
            @Override
            public void run() {
                events_tabs.setupWithViewPager(events_pager);
            }
        });

        return view;
    }

    class MyAdapter extends FragmentStatePagerAdapter
    {
        public MyAdapter(FragmentManager fm)
        {
            super(fm);
        }

        /**
         * I WANNA SWITCH BETWEEN FRAGMENTS HERE
         */
        @Override
        public Fragment getItem(int position)
        {
            switch (position) {
                case 0:
                    return new EventsActivity();
            }
            return null;
        }

        @Override
        public int getCount()
        {
            return int_items;
        }

        /**
         * This method returns the title of the tab according to the position.
         */
        @Override
        public CharSequence getPageTitle(int position)
        {
            switch (position)
            {
                case 0:
                    String main_events = "Events";
                    return main_events;
                case 1:
                    String pending = "Pending event invites";
                    return pending;
            }
            return null;
        }
    }
}

its xml(event_tabs.xml) uses a TabLayout and ViewPager and looks like this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/events_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        app:layout_constraintBottom_toTopOf="@+id/events"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/events_tab" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/pending_invites_tab" />

    </com.google.android.material.tabs.TabLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/events_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/events_tabs">
    </androidx.viewpager.widget.ViewPager>

</androidx.constraintlayout.widget.ConstraintLayout>

It appears that FragmentStatePagerAdapter has been deprecated. I'm not sure if this is causing the following error after running the program.
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
        at androidx.fragment.app.FragmentTransaction.doAddOp(FragmentTransaction.java:245)
        at androidx.fragment.app.BackStackRecord.doAddOp(BackStackRecord.java:180)
        at androidx.fragment.app.FragmentTransaction.add(FragmentTransaction.java:234)
        at androidx.fragment.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:173)
        at androidx.viewpager.widget.ViewPager.addNewItem(ViewPager.java:1010)
        at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1224)
        at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092)
        at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622)
        at android.view.View.measure(View.java:24510)
        at androidx.constraintlayout.widget.ConstraintLayout$Measurer.measure(ConstraintLayout.java:763)
        at androidx.constraintlayout.solver.widgets.analyzer.BasicMeasure.measure(BasicMeasure.java:426)
        at androidx.constraintlayout.solver.widgets.analyzer.BasicMeasure.measureChildren(BasicMeasure.java:105)
        at androidx.constraintlayout.solver.widgets.analyzer.BasicMeasure.solverMeasure(BasicMeasure.java:247)
        at androidx.constraintlayout.solver.widgets.ConstraintWidgetContainer.measure(ConstraintWidgetContainer.java:117)
        at androidx.constraintlayout.widget.ConstraintLayout.resolveSystem(ConstraintLayout.java:1532)
        at androidx.constraintlayout.widget.ConstraintLayout.onMeasure(ConstraintLayout.java:1607)
        at android.view.View.measure(View.java:24510)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at android.view.View.measure(View.java:24510)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
        at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1204)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:723)
        at android.view.View.measure(View.java:24510)
        at androidx.drawerlayout.widget.DrawerLayout.onMeasure(DrawerLayout.java:1156)
        at android.view.View.measure(View.java:24510)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:146)
        at android.view.View.measure(View.java:24510)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:842)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:721)
        at android.view.View.measure(View.java:24510)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at android.view.View.measure(View.java:24510)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:842)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:721)
        at android.view.View.measure(View.java:24510)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at com.android.internal.policy.DecorView.onMeasure(DecorView.java:736)
        at android.view.View.measure(View.java:24510)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:3004)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1833)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2122)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1721)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7595)
E/AndroidRuntime:     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:966)
        at android.view.Choreographer.doCallbacks(Choreographer.java:790)
        at android.view.Choreographer.doFrame(Choreographer.java:725)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:951)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7319)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)

Is there a better solution to creating tabs inside a fragment now that FragmentStatePagerAdapter is not supported?

A: You should use FragmentStateAdapter instead, along with a ViewPager2, as recommended in the FragmentStatePagerAdapter deprecation notice.


text:
Q: I need to update data from different google sheets to other sheet in real time. The data must be ordered in a table I have to import all the data come from many google sheets to one google sheet in an specific order. I have to use the function "IMPORTRANGE", that function allows me to import the data to one google sheet. The problem is that a have no idea how to order the data in a table in real time. All the data come of many google forms, is for that reason that i don´t have the same data all the time.
Example:
I have 3 google sheets like this:
Google sheet 1:
Date   Name   Music   Design
1/1/1  Juan   2       0
2/1/1  Lucy   0       3

Google sheet 2:
Date   Name   Music   Design
1/1/1  Tom    2       0
4/1/1  Pedro  0       3
6/1/1  Carmen 1       4

Google sheet 3:
Date   Name   Music   Design
1/1/1  Mary   0       2
3/1/1  Justin 0       3

Each google sheet contains the data from their own google form
So, i want to order the information in a google sheet in REAL TIME like this:
Date   Name   Music   Design
1/1/1  Juan   2       0
1/1/1  Tom    2       0
1/1/1  Mary   0       2
2/1/1  Lucy   0       3
3/1/1  Justin 0       3
4/1/1  Pedro  0       3
6/1/1  Carmen 1       4

The "date" means the date when data updated to the system.

A: =QUERY({IMPORTRANGE("1_fg2bHlXX6nPk_6FZSyy-CyzwCDSAmBP5XeQrOeKxmM", "sheet1!A2:D");
        IMPORTRANGE("1_fg2bHlXX6nPk_6FZSyy-CyzwCDSAmBP5XeQrOeKxmM", "sheet2!A2:D");
        IMPORTRANGE("1_fg2bHlXX6nPk_6FZSyy-CyzwCDSAmBP5XeQrOeKxmM", "sheet3!A2:D")},
 "select * where Col1 is not null order by Col1 asc", 0)

demo spreadsheet
note: every IMPORTRANGE needs to be authorised separately, so first you need to import each spreadsheet like =IMPORTRANGE("1_fg2bHlXX6nPk_6FZSyy-CyzwCDSAmBP5XeQrOeKxmM", "sheet1!A2:D") in any cell and press that allow button. then you can delete it and construct your formula like in the picture

A: Since you will need to authorise the link you might want to pull the data into one sheet before running a query on that, eg in case you need to sort out the separator convention. Assuming in each sheet Date is in A1, as a single formula:
=query({importrange(" k e y ","Sheet1!A1:D99");importrange(" k e y ","Sheet2!A1:D99");importrange(" k e y ","Sheet3!A1:D99")},"select * where Col1 is not NULL order by Col1")


text:
Q: Mark Android Sms Conversation as read. Sql query getting executed again and again.(Error) I am trying to mark all messages in a android chat thread as read. I am using following code which I copied from AOSP project but I my app goes into ANR and I keep getting following message in logs.
ContentValues sReadContentValues = new ContentValues(2);
sReadContentValues.put("read", 1);
sReadContentValues.put("seen", 1);
private static final String UNREAD_SELECTION = "(read=0 OR seen=0)";
context.getContentResolver().update(threadUri, sReadContentValues, UNREAD_SELECTION, null);

Log message repeating in loop
SQLiteConnectionPool:   executeForChangedRowCount started 152577ms ago - running, sql="UPDATE sms SET read=?,seen=? WHERE (read=0 OR seen=0) AND thread_id=1464"

I have been trying to fixed this issue since ours but still no luck.

A: This is an old thread, but I found it looking for how to properly utilize the ContentValue type and it answered my question, so I will answer it...
Looping Log Message:
You have only posted a small portion of your code, so my best guess is that you are executing this update every time you select a message - inside your code loop. If that is the case, since you are attempting to update the entire thread in one execution, it would be logical to move this section of code into its own method (assuming it isn't already) and call it only once, AFTER you have received all of the desired messages and you have exited the loop.
App Entering ANR:
Though the Log message you have posted reads "(read=0 OR seen=0) AND thread_id=1464", your code only reflects "(read=0 OR seen=0)" in your Where Clause - this would obviously cause some frustration due to the fact that you would be attempting to update every message in every message thread.
While a method attempting to update all existing threads would be time-consuming for the processor, if you also execute this within the loop (as your Log message implies), then it makes a lot of sense that you would receive an ANR, even if you are including the requirement that it only run for a single thread_id...
Solution:
Feel free to correct me, but making some logical assumptions, I believe this is your solution:
public void mainMethod()
{
    String threadId = "1464";
    Cursor cursor = getSomeMessages(threadId);
    if (cursor != null && cursor.moveToFirst()) {
        do {
            // ... Do something with the message
        } while (cursor.moveToNext());
        cursor.close();
    }

    updateMessagesToReadAndSeen(threadId);
}

private void updateMessagesToReadAndSeen(String threadId) {
    if (threadId != null && !threadId.isEmpty()) {
        ContentValues sReadContentValues = new ContentValues(2);
        sReadContentValues.put("read", 1);
        sReadContentValues.put("seen", 1);
        String UNREAD_SELECTION = "(read=0 OR seen=0) AND thread_id=" + threadId;
        context.getContentResolver().update(threadUri, sReadContentValues, UNREAD_SELECTION, null);
    }
}

I guess if I had to make some suggestions for "scope-friendly changes" it would be to break this apart into more flexible methods. eg...
private void UpdateContent(Uri uri, ContentValues values, String _where, String[] args) {
    _context.getContentResolver().update(uri, values, _where, args);
}

...
private static String UNREAD_UNSEEN_THREADID = "(read=0 OR seen=0) AND thread_id=";

private void updateMessagesReadAndSeen(String threadId, int setRead, int setSeen) {
    if (threadId != null && !threadId.isEmpty()) {
        ContentValues sReadContentValues = new ContentValues(2);
        sReadContentValues.put("read", setRead);
        sReadContentValues.put("seen", setSeen);

        UNREAD_UNSEEN_THREADID +=  threadId;
        UpdateContent(threadUri, sReadContentValues, UNREAD_UNSEEN_THREADID, null);
    }
}

I could go on forever, but this would allow a lot more flexibility moving forward as you develop new features for your product. Good luck!


text:
Q: Get Local Ip address in c++ I have a code to get local ip address. This is the code I use.
typedef std::map<string,string> settings_t;

void loadLocalIp (settings_t &ipConfig)
{
    struct ifaddrs * ifAddrStruct=NULL;
    struct ifaddrs * ifa=NULL;
    void * tmpAddrPtr=NULL;

    getifaddrs(&ifAddrStruct);

    for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
        if (ifa ->ifa_addr->sa_family==AF_INET) { // check it is IP4
            // is a valid IP4 Address
            tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
            char addressBuffer[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);

            string key(ifa->ifa_name);
            string value(addressBuffer);
            cout<<key<<" =1 " <<value<<endl;
            ipConfig.insert(std::pair<string,string>(key, value));

           // printf("'%s': %s\n", ifa->ifa_name, addressBuffer);
         }
     }
    if (ifAddrStruct!=NULL)
        freeifaddrs(ifAddrStruct);//remember to free ifAddrStruct
}

int main()
{
    settings_t ipConfig;
    loadLocalIp(ipConfig);
    cout<<ipConfig.at("enp2s0")<<endl;
    return 0;
}

So My result, is
lo =1 127.0.0.1
enp2s0 =1 172.20.55.6
172.20.55.6

But In another computer, the interface name is different. They get result like bellow,
lo =1 127.0.0.1
ens32 =1 172.20.55.9
terminate called after throwing an instance of 'std::out_of_range'
  what():  map::at
Aborted (core dumped)

I want to get my Ip address whatever the interface name is. How can I get my local ip address if the interface name varies from different computer. It should give the ip address whatever the interface name is. How can I do this?
My question is, Now I am getting my local IP from this method. But I should get IP whatever the Interface name is. One thing, I need to find that interface name and apply it in my above code (or) Is there any other option to find that IP without that interface?

A:
I want to get my IP address whatever the interface name is.

It is difficult to reliably get the local ip address by looking at the network interface.  As you have already discovered, the network interface name can be unique for each host you run on. To further complicate things, a computer may have multiple network interfaces and each of those may or may not be connected to the Internet.
You don't need to use the default interface.  A more simplistic approach is to just let the OS routing table figure it out for you.  You can do this by setting up a socket connection to some external server and then calling getsockname to get the local address. This example uses Google's DNS server at 8.8.8.8 to establish a socket connection but you can use whatever external server you'd like.
#include <iostream>     ///< cout
#include <cstring>      ///< memset
#include <errno.h>      ///< errno
#include <sys/socket.h> ///< socket
#include <netinet/in.h> ///< sockaddr_in
#include <arpa/inet.h>  ///< getsockname
#include <unistd.h>     ///< close

int main()
{
    const char* google_dns_server = "8.8.8.8";
    int dns_port = 53;

    struct sockaddr_in serv;
    int sock = socket(AF_INET, SOCK_DGRAM, 0);

    //Socket could not be created
    if(sock < 0)
    {
        std::cout << "Socket error" << std::endl;
    }

    memset(&serv, 0, sizeof(serv));
    serv.sin_family = AF_INET;
    serv.sin_addr.s_addr = inet_addr(google_dns_server);
    serv.sin_port = htons(dns_port);

    int err = connect(sock, (const struct sockaddr*)&serv, sizeof(serv));
    if (err < 0)
    {
        std::cout << "Error number: " << errno
            << ". Error message: " << strerror(errno) << std::endl;
    }

    struct sockaddr_in name;
    socklen_t namelen = sizeof(name);
    err = getsockname(sock, (struct sockaddr*)&name, &namelen);

    char buffer[80];
    const char* p = inet_ntop(AF_INET, &name.sin_addr, buffer, 80);
    if(p != NULL)
    {
        std::cout << "Local IP address is: " << buffer << std::endl;
    }
    else
    {
        std::cout << "Error number: " << errno
            << ". Error message: " << strerror(errno) << std::endl;
    }

    close(sock);
    return 0;
}

A: None of these answers seemed good enough: either too much trouble walking through the interfaces or required connection to internet.
Here is a method based upon Justin Randall's answer. It's basically the same but it connects a UDP socket rather than a TCP. As per udp(7), using connect(3) on a unbound UDP socket:

will automatically assign a free local port [...] and bind the socket to INADDR_ANY

Moreover, conversely to a TCP socket, connect(3) on a UDP socket does not present any network overhead or communication, as it only changes the rules regarding which packet to drop and which to keep on the socket buffers.
Therefore, connecting to any IP address that is not INADDR_LOOPBACK is sufficient to retrieve a local address which has been chosen to bind the socket.
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

#include <cstring>
#include <iostream>

int main(void) {
    int sock = socket(PF_INET, SOCK_DGRAM, 0);
    sockaddr_in loopback;

    if (sock == -1) {
        std::cerr << "Could not socket\n";
        return 1;
    }

    std::memset(&loopback, 0, sizeof(loopback));
    loopback.sin_family = AF_INET;
    loopback.sin_addr.s_addr = 1337;   // can be any IP address
    loopback.sin_port = htons(9);      // using debug port

    if (connect(sock, reinterpret_cast<sockaddr*>(&loopback), sizeof(loopback)) == -1) {
        close(sock);
        std::cerr << "Could not connect\n";
        return 1;
    }

    socklen_t addrlen = sizeof(loopback);
    if (getsockname(sock, reinterpret_cast<sockaddr*>(&loopback), &addrlen) == -1) {
        close(sock);
        std::cerr << "Could not getsockname\n";
        return 1;
    }

    close(sock);

    char buf[INET_ADDRSTRLEN];
    if (inet_ntop(AF_INET, &loopback.sin_addr, buf, INET_ADDRSTRLEN) == 0x0) {
        std::cerr << "Could not inet_ntop\n";
        return 1;
    } else {
        std::cout << "Local ip address: " << buf << "\n";
    }
}

A: Thank you for your solution. It works fine. But When I search for solution, I came up with the following answer also. Please have a look at it. What is pros and cons of this answer.
 FILE *f;
    char line[100] , *p , *c;

    f = fopen("/proc/net/route" , "r");

    while(fgets(line , 100 , f))
    {
        p = strtok(line , " \t");
        c = strtok(NULL , " \t");

        if(p!=NULL && c!=NULL)
        {
            if(strcmp(c , "00000000") == 0)
            {
                printf("Default interface is : %s \n" , p);
                break;
            }
        }
    }

    //which family do we require , AF_INET or AF_INET6
    int fm = AF_INET;
    struct ifaddrs *ifaddr, *ifa;
    int family , s;
    char host[NI_MAXHOST];

    if (getifaddrs(&ifaddr) == -1)
    {
        perror("getifaddrs");
        exit(EXIT_FAILURE);
    }

    //Walk through linked list, maintaining head pointer so we can free list later
    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
    {
        if (ifa->ifa_addr == NULL)
        {
            continue;
        }

        family = ifa->ifa_addr->sa_family;

        if(strcmp( ifa->ifa_name , p) == 0)
        {
            if (family == fm)
            {
                s = getnameinfo( ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6) , host , NI_MAXHOST , NULL , 0 , NI_NUMERICHOST);

                if (s != 0)
                {
                    printf("getnameinfo() failed: %s\n", gai_strerror(s));
                    exit(EXIT_FAILURE);
                }

                printf("address: %s", host);
            }
            printf("\n");
        }
    }

    freeifaddrs(ifaddr);

    return 0;

A: Cool method of getting local ip is to execute the ipconfig command, save the output to a file read it, and parse the data so the output only shows your ipv4 address for example.
Can be done with something like this:
std::string GetParsedIPConfigData(std::string Columb)
{
    //Set up command file path and command line command
    std::string APPDATA = getenv("APPDATA");
    std::string path = APPDATA + "\\localipdata.txt";
    std::string cmd =  "ipconfig > " + path;

    //execute ipconfig command and save file to path
    system(cmd.c_str());

    //current line
    std::string line;

    //Line array : Here is all lines saved
    std::string lineArray[500];
    int arrayCount = 0;

    std::ifstream file(path);
    if (file.is_open())
    {
        //Get all lines
        while (std::getline(file, line))
        {
            //Save each line into a element in an array
            lineArray[arrayCount] = line;
            arrayCount++;
        }

        for (int arrayindex = 0; arrayindex <= arrayCount; arrayindex++)
        {
            std::string s = Columb;
            std::string s2 = ":";

            //Search all lines and get pos
            std::size_t i = lineArray[arrayindex].find(s);
            std::size_t i2 = lineArray[arrayindex].find(s2);

            //Found a match for Columb
            if (lineArray[arrayindex].find(s) != std::string::npos)
            {
                //Validate
                if (i != std::string::npos)
                {
                    //Earse Columb name
                    lineArray[arrayindex].erase(i, s.length());

                    //Erase all blanks
                    lineArray[arrayindex].erase(remove_if(lineArray[arrayindex].begin(), lineArray[arrayindex].end(), isspace), lineArray[arrayindex].end());

                    //Found match for ':'
                    if (lineArray[arrayindex].find(s2) != std::string::npos)
                    {
                        //Validate
                        if (i2 != std::string::npos)
                        {
                            //Delete all characters prior to ':'
                            lineArray[arrayindex].erase(0, lineArray[arrayindex].find(":"));
                            lineArray[arrayindex].erase(std::remove(lineArray[arrayindex].begin(), lineArray[arrayindex].end(), ':'), lineArray[arrayindex].end());
                        }
                    }
                    //Return our data
                    return lineArray[arrayindex];
                }
            }

            //Only go through all lines once
            if (arrayindex == arrayCount)
                break;
        }

        //Close file
        file.close();
    }
    //Something went wrong
    return "Invalid";
}

And the just call it like so:
cout << parser.GetParsedIPConfigData("IPv4 Address") << "\n\n";


text:
Q: How to use .htaccess to reformat a directory listing while including the directory name? For directory listings, I've created a common .htaccess file as well as a common header ("HeaderName /header.html).
Everything works fine, except one thing: while I don't want the derpy h1 version of "Index of /blah", I'd like to display a customized (and normal-sized) version of that, e.g., "CurDir = /blah". By default, specifying the HeaderName replaces all of that with some static text.
I tried embedding a bit of PHP (getcwd()) but that just returned the root directory where the header.html lives, no matter what subtree was being displayed. Surely there's some way to access the CWD without having to sprinkle control files like this in each subfolder?

A: I stumbled upon what may be a suitable environment variable while looking at the phpinfo() output... but is there a better (more common) way people handle this, perhaps without even using PHP?
<?php
$dir = getenv("REQUEST_URI");
?>


text:
Q: R - new line in paste() function How can we insert a new line when using the function paste() or any function that concatenates strings in R?
There are many web pages on this topic but none answers clearly or gives a solution that works. I precise I don't want to use the function cat, I need to work with string of characters.
Here are all my attempts (derived from all the suggestions on from different forum), they all fail...
1st Try: paste()
msg <- "==================================================\n"
msg <- paste(msg, "Var:")
print(msg)

Output:

[1] "==================================================\n Var:"

2nd Try: paste0()
msg <- "==================================================\n"
msg <- paste0(msg, "Var:")
print(msg)

Output:

[1] "==================================================\nVar:"

3rd Try: sep
msg <- "=================================================="
msg <- paste(msg, "Var:", sep = "\n")
print(msg)

Output:

[1] "==================================================\nVar:"

4th Try: sprintf
msg <- sprintf("==================================================\n")
msg <- paste(msg, "Var:")
print(msg)

Output:

[1] "==================================================\nVar:"

I believe I've tried everything I could... If you have an idea?!

A: You could try strsplit
msg <- "==================================================\n"
msg2 <- paste(msg, "Var:")
strsplit(msg2, "\n")[[1]]
# [1] "=================================================="
# [2] " Var:"

This can also be used with noquote if you don't want quotes.
noquote(strsplit(msg2, "\n")[[1]])
# [1] ==================================================
# [2]  Var:

This produces virtually the same result as if you were to use print with quote = FALSE
You can also define your own print method
print.myClass <- function(x, ...)  strsplit(x, "\n")[[1]]
class(msg2) <- "myClass"
print(msg2)
# [1] "=================================================="
# [2] " Var:"


text:
Q: Call Rest endpoint and display data into Spring MVC table I have this Endpoint:
@RestController
public class FileImportsController {

    private EntityImportRequestsService entityImportRequestsService;

    @Autowired
    public FileImportsController(EntityImportRequestsService entityImportRequestsService) {
        this.entityImportRequestsService = entityImportRequestsService;
    }

    @GetMapping("/imported_files")
    public String viewHomePage(Model model) {
        List<EntityImportRequestsTable> listProducts = entityImportRequestsService.findAll();
        System.out.println("Size is " + listProducts.size());

        model.addAttribute("listProducts", listProducts);
        return "index";
    }
}

Entity:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
@Entity
@Table(name = "EntityImportRequests")
public class EntityImportRequestsTable implements Serializable {

    @Id
    @Column(name = "requestId")
    private String requestId;
}

Web page index.html
<!DOCTYPE html>

  <meta charset="utf-8"/>
  <title>Product Manager</title>

Product List

      requestId

When I open the page data is not displayed. What is the proper way to call endpoint imported_files and display all the data?


text:
Q: How to simplify this php switch statement? I would like to change this:
// use appropiate lang.xx.php file according to the value of the $lang
switch ($_SESSION['lang']) {
case 'en':
 $lang_file = 'lang.en.php';
 break;

case 'es':
 $lang_file = 'lang.es.php';
 break;

case 'zh-tw':
 $lang_file = 'lang.zh-tw.php';
 break;

case 'zh-cn':
 $lang_file = 'lang.zh-cn.php';
 break;

default:
 $lang_file = 'lang.en.php';
}

into something like this:
//include file for final output
 include_once 'languages/lang.'.$_SESSION['lang'].'php;

(I think the $lang_file variable becomes redundant if I do the include-final-output-thing above)
So that I can skip the whole switch part. I tried other combinations but they don't seem to work. Any suggestions?

A: $lang_file = 'lang.' . ($_SESSION['lang']) . 'php';
if(!file_exists($lang_file))
{
    $lang_file = 'lang.en.php';
}

although it isn't secure against injections.  It does, however, allow you to add new language codes without modifying the code.

A: Or:

$allowed   = array('en', 'es', 'zh-tw', 'zh-cn');
$lang_file = (in_array($_SESSION['lang'], $allowed))
           ? 'lang.'.$_SESSION['lang'].'.php' : 'lang.en.php';

A: You can do this:
switch ($_SESSION['lang']) {
case 'en':
case 'es':
case 'zh-tw':
case 'zh-cn':
    $lang_file = 'lang.'.$_SESSION['lang'].'.php';
    break;

default:
    $lang_file = 'lang.en.php';
}

Or you use an array and use in_array to see if the value is in the array:
$languages = array('en', 'es', 'zh-tw', 'zh-cn');
if (in_array($_SESSION['lang'], $languages)) {
    $lang_file = 'lang.'.$_SESSION['lang'].'.php';
} else {
    $lang_file = 'lang.en.php';
}

You even could omit en in both cases since it's the default.

A: This will work perfectly fine
$lang_file_tmp = 'lang.' . $_SESSION['lang'] . '.php';
if ( preg_match( '/^[a-zA-Z\-]{2,5}$/', $_SERSSION['lang'] ) && file_exists( $lang_file_tmp ) ) {
    $lang_file = $lang_file_tmp;
} else {
    $lang_file = 'lang.en.php';
}

With this, you won't have to edit the code every time your're adding a new language and you will not have to worry about security.


text:
Q: Probability of finding particle in ground state of old potential immediately after potential is changed? Suppose a particle's wavefunction satisfies the 1d time-independent Schrodinger equation with potential $U(x)$ and that its ground state is known to be $\psi_0(x)$.
The particle is in the state $\psi_0$ when at time $t = t_0$ the potential is suddenly changed from $U(x)$ to $V(x)$ (e.g., this could correspond to a potential well doubling in size). Suppose I know the stationary states of this new potential and their corresponding energy eigenvalues; call them $\phi_n$ and $E_n$ respectively (say).
What is the expression for the probability of finding a particle in the old ground state $\psi_0$ immediately after time $t=t_0$?
I know the new wavefunction is
$\phi(x,t) = \sum_{n=0}^\infty c_n\phi_n(x)e^{-iE_nt/\hbar}$ where the $c_n$'s are determined from the normalisation condition using Fourier.
Not sure how to take it from here. Any help appreciated.

A: The probability of the particle being in the ground state of $U$ at $t=t_0$ is $1$, and the evolution of the wave function is continuous. So in the limit $\lim_{\Delta t\rightarrow 0}t = t_0 + \Delta t$, the probability of finding it in the ground state of $U$ tends to $1$.
What is happening is that at $t=t_0$, the wave function is the ground state eigenfunction of the Schrödinger equation for potential $U$, but when the potential is changed to $V$, that will in general not be an eigenfunction of the new Schrödinger equation. So to get the time evolution for $t > t_0$, you have to write the old eigenfunction $\Psi(t_0, x) = \psi_0(x)$ as a linear combination of the new eigenfunctions such that $\Psi(t_0, x) = \sum_n c_n \phi_n(x)$, with $c_n = \langle\phi_n | \psi_0\rangle$, and then each of the $\phi_n$ time evolves with a phase factor of $e^{-iE_n (t - t_0)/\hbar}$, so for $t>t_0$ we get $\Psi(t, x) = \sum_n c_n\phi_n(x)\,e^{-iE_n (t - t_0)/\hbar}$. In the limit of $t\rightarrow t_0$ this obviously recovers $\psi_0(x)$ by construction.


text:
Q: flutter v2.2.1 with firebase realtime database configuration error [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: MissingPluginException(No implementation found for method DatabaseReference#set on channel plugins.flutter.io/firebase_database)
Flutter with firebase error when i post my realtime data,


text:
Q: Problem with compiling xepersian in LaTeX I have a question about xepersian package. I'm familiar with LaTeX, but a beginner with xepersian. I tried to compile this simple code with TeX Live 2017:
\documentclass{article}
\usepackage{xepersian}
\settextfont{B Nazanin}
\begin{document}
سلام
\end{document}

But I got this error
! Fatal Package fontspec Error: The fontspec package requires either XeTeX or
(fontspec)                      LuaTeX.
(fontspec)
(fontspec)                      You must change your typesetting engine to,
(fontspec)                      e.g., "xelatex" or "lualatex"instead of
(fontspec)                      "latex" or "pdflatex".

Type <return> to continue.
 ...

l.45 \msg_fatal:nn {fontspec} {cannot-use-pdftex}

I tried all other compilers and even updated xepersian, but anytime I received similar errors. Also, I googled my problem a lot, but didn't find my answer. Finally, I removed TeX Live 2017 and installed TeX Live 2020. It didn't change anything at all! I'll be appreciated if someone help me.


text:
Q: My reCAPTCHA Enterprise site key says "Key Status: Incomplete" then offers no information on how to complete it I created a new site key with Google reCAPTCHA Enterprise for my company's website and it said "all you need to do is finish setting up your key.  Follow the instructions above to do so."  There were no instructions though and the status indicator for my site key says "incomplete."  How am I supposed to complete my site key?  I copied the key into the site key field in my google captcha extension on my website admin page, but there was no secret key given this time to replace it with, so the old secret key is still there.  What do I need to do to finish the site key?
I tried to set up the Google reCAPTCHA Enterprise for my website and ended up with nothing but problems and an incomplete site key.  I was expecting seamless instructions but was left wanting.

A: Incomplete in this case means specifically that your reCAPTCHA key has been used to create tokens using the grecaptcha.enterprise.execute function, but these tokens have not yet been used to create an assessment and therefore determine if the traffic was desirable or not.
Note that in reCAPTCHA Enterprise you no longer need a secret key. See more details here.
However it is common when integrating with third-party applications (such as CMS) that the generated reCAPTCHA keys are non-Enterprise, and therefore they would include a secret key as well. Here is how you can identify the secret key when you are in the Google Cloud console https://cloud.google.com/recaptcha-enterprise/docs/create-key#find-key


text:
Q: Progress bar for Leaflet map Is there any way to show progress bar while waiting that all layers are rendered on Leaflet map? In this specific case, while GeoJSON layers are rendered.

A: Thanks, but I already found this solution:
https://github.com/makinacorpus/Leaflet.Spin

A: There is the leaflet loading plugin https://github.com/ebrelsford/Leaflet.loading, it is straightforward to use. you could also look at the Spin plugin https://github.com/makinacorpus/Leaflet.Spin which is more customizable.


text:
Q: PHP Creating a function for Shortening Large Numbers to English Equivalent Name Based Decimals In my database I have a store of property values in Int form. They range from $1000 to $100,000,000. How would I create a function that could break this information down to symbolized text/decimal form.
For example
1,300,000 would become 1.3 Million
250,000 would become 250 Thousand
10,300,000 would become 10.3 Million
What I'm trying to get is the English equivalent of the long number
Any Idea on where to start?

A: Start here:
$x = 1300000;
$text = ($x / 1000000) . ' Million';

Then, detect the number of digits in your source number to check whether it makes more sense to divide by thousand or a million.
Then, apart from dividing, also round the number, so 1,387,238 is translated to 1.4 Million instead of 1.387238 Million.

A: I used something similar to this once:

function abbNumber($var)
{
    if(($var/1000000000)>1)
    {
        $retVal=round($var/1000000000,1).' hundred million';
    }
    else if(($var/1000000)>1)
    {
        $retVal=round($var/1000000,1).' million';
    }
    else if(($var/1000)>1)
    {
        $retVal=round($var/1000,1).' thousand';
    }
    else
    {
        $retVal=$var;
    }
    return $retVal;
}

echo abbNumber(5234000);

?>
// 5.2 million

echo abbNumber(5234000000);
5.2 hundred million
echo abbNumber(523400000);
523.4 million
echo abbNumber(523400);
523.4 thousand
echo abbNumber(5.234);
5.234


text:
Q: How do I abort or stop an http request in NodeJs While NodeJs architecture does very well to process server requests in a non-blocking way, it is sometimes required to stop/abort a request being processed at the server side.
How can I get my NodeJs server to abort a request even when it's not blocking the server?


text:
Q: What is 'kernel times' in Windows Task Manager This is my task manager when running some Python multiprocessing tasks.

The shaded parts are "kernel times". Are those the utilisation associated with my Python programme, or the basic Windows OS tasks?
In other words, am I really utilising most of the computing capacity, or just a fraction?
I Googled around and every explanation I've seen is along the line of "kernel times are the time spent on kernel tasks", which is not helpful.


text:
Q: Ensure a class in notnull in Scala? Since the NotNull trait is being deprecated, what is the new best way to declare my classes not nullable?
There is still the compiler option (does not prevent someone from misusing my libraries in other projects).  Along with the handful of conflicting Java annotations that I doubt the Scala compiler will respect.

A: You should not be using null in Scala at all, and if you don't, it's not necessary to use the NotNull trait.
If you have values or variables which can have "no value", use the Option type instead of the null value. Option has two subclasses: Some and None.
// text is "None", which means it has no value
var text: Option[String] = None

// Use "Some" when it should have a value
text = Some("Hello World")

Option has lots of useful methods; it can (more or less) be treated as a collection that has zero or one elements, so you can call common collection methods on it and you can use it with pattern matching.
text match {
  case Some(s) => println("Text: " + s)
  case None    => println("Empty")
}


text:
Q: Advantages of a lookup table with INTs over decimals in MySQL records? Trying to summarize in as few of words as possible:
I am trying to create a system that tracks the various products an individual can sell and the commission percentage they earn on that particular item. I am thinking about creating reference integers for each product called "levels" which will relate to their commission percentage in a new lookup table instead of a single reference point.. Is this overkill though or are there any benefits over just placing inline for each record?
My gut tells me there are advantages of design 1 below but not sure what they are the more I think about it. If I need to update all individuals selling product X with level Y, indexes and replaces make that easy and fast ultimately in both methods. By using design 2, I can dynamically change any "earn" to whatever percentage I can come up with (0.58988439) for a product whereas I would have to create this "level" in design 1.
Note: the product does not relate to the earn diretly (one sales rep can earn 50% for the same product another sales rep only earns 40% on).
Reference Examples:
Design 1 - two tables
table 1
ID  |  seller_id   |   product_id   |   level
-----------------------------------------------
1   |   11111      |     123A       |    2
2   |   11111      |     15J1       |    6
3   |   22222      |     123A       |    3

table 2
ID  | level |   earn
--------------------------
1   |   1   |   .60
2   |   2   |   .55
3   |   3   |   .50
4   |   4   |   .45
5   |   5   |   .40
6   |   6   |   .35

Design 2 - one table
ID  |  seller_id   |   product_id   |   earn
-----------------------------------------------
1   |   11111      |     123A       |    .55
2   |   11111      |     15J1       |    .35
3   |   22222      |     123A       |    .45

(where earn is decimal based, commission percentage)
Update 1 - 7/9/13
It should also be noted that a rep's commission level can change at any given time. For this, we have planned on simply using status, start, and end dates with ranges for eligible commission levels / earn. For example, a rep may earn a Level 2 (or 55%) from Jan 1 to Feb 1. This would be noted in both designs above. Then when finding what level or percentage a rep was earning at any given time: select * from table where (... agent information) AND start <= :date AND (end > :date or END IS NULL)

A: Does level mean anything to the business?
For instance, I could imagine a situation where the levels are the unit of management.  Perhaps there is a rush for sales one quarter, and the rates for each level change.  Or, is there reporting by level?  In these situations is would make sense to have a separate "level" table.
Another situation would be different levels for different prices of the product -- perhaps the most you sell it for, the higher the commission.  Or, the commissions could be based on thresholds, so someone who has sold enough this year suddenly gets a higher commission.
In other words, there could be lots of rules around commission that go beyond the raw percentage.  In that case, a "rule" table would be a necessary part of the data model (and "levels" are a particular type of rule).
On the other hand, if you don't have any such rules and the commission is always based on the person and product, then storing the percentage in the table makes a lot of sense.  It is simple and understandable.  It also has good performance when accessing the percentage -- which presumably happens much more often than changing it.

A: First of all, using id values to reference a lookup table has nothing to do with normalization per se.  Your design #2 shown above is just as normalized.  Lots of people have this misunderstanding about normalization.
One advantage to using a lookup table (design #1) is that you can change what is earned by level 6 (for example), and by updating one row in the lookup table, you implicitly affect all rows that reference that level.
Whereas in design #2, you would have to update every row to apply the same change.  Not only does this mean updating many rows (which has performance implictations), but it opens the possibility that you might not execute the correct UPDATE matching all the rows that need updating.  So some rows may have the wrong value for what should be the same earning level.
Again, using a lookup table can be a good idea in many cases, it's just not correct to call it normalization.


text:
Q: JavaCV v0.9 - getAffineTransform() how to use I want to use getAffineTransform(...) method in my Android (Java) app, but unfortunately I have seen that there are only the following options:
getAffineTransform(Mat src, Mat dsc) and getAffineTransform(Point2f src, Point2f dsc)
In OpenCV: http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html?highlight=getaffinetransform#getaffinetransform
Use: Mat getAffineTransform(const Point2f src[], const Point2f dst[])
Why can't use this method with Point2f arrays?
Maybe I know the wrong use, but how to use it correctly?
Thank you!
Regards
Csaba


text:
Q: Can $ℂ$ be viewed as a (nontrivial) field of fractions? Is there an interesting ring $S ⊂ ℂ$ such that $ℂ = Q(S)$? I'm thinking no, but how can I prove it?

A: There is an isomorphism $\mathbf{C} \cong \mathbf{C}_p$ -- i.e. you can extend the p-adic absolute value to the complexes.
$\mathbf{C}_p$ is the field of fractions of its ring of integers: the subring of numbers whose $p$-adic absolute value is less than or equal to $1$.

A: Depends what you mean by "interesting". The smallest examples of rings with $\mathbb{C}$ as their field of fractions would be
$$R[\{t_\alpha\}_{\alpha\in A}]$$
where $R$ denotes the ring of algebraic integers, and $\{t_\alpha\}_{\alpha\in A}$ is a (edit: pure) transcendence basis for the extension $\mathbb{C}/F$, where $F$ is the field of algberaic numbers i.e. the field of fractions of $R$.
(Pure  transcendence basis means that the $t_\alpha$ are transcendental numbers, algebraically independent, and $\mathbb{C}=F(\{t_\alpha\}_{\alpha\in A})$.)
Of course they are just isomorphic to $R$ with continuum-many variables adjoined. I don't think these rings are terribly useful, but they could arguably be "interesting".


text:
Q: margin and padding are causing issues calculating layout I am having this issue where I am not getting the true offset in IE6. I am using the offset to position a pop-in.
The CSS is something like this:
.container50-50-right-border              { }
.container50-50-right-border .title       {padding: 0px; margin: 0px;
                                           clear: both;}
.container50-50-right-border .leftcolumn  {width: 47%; float: left;
                                           display:inline;}
.container50-50-right-border .rightcolumn {width: 48%; float: left;
                                           display:inline;
                                           border-left: 1px solid #D6D7DE;
                                           padding: 0px 0px 0px 10px;
                                           margin: 0px 0px 0px 10px;}
.container50-50-right-border .description {clear: both;}

when I remove the padding and margin from the
.container50-50-right-border .rightcolumn

it behaves a little better but not perfectly. The positioning code is well tested so I don't think it's that.
Sorry for the sparse amount of code. Any help would be appreciated.

A: Keep in mind, IE will switch box-models based on what rendering mode it is in (Quirks mode vs Standards mode). Verify that the Doctype you are using is putting IE into Strict mode, else the box model it uses for positioning will not be the standard W3C model.
http://www.quirksmode.org/css/quirksmode.html

A: I did a simple test with your CSS, the javascript from your comment, and some made up HTML to test this. I added the showDiv function to test

1

test

move me

I tested in IE6, it positioned fine. Can you give some more code, perhaps the HTML and JavaScript?


text:
Q: How can i solve "Mix of label input types (string and number)"? error description here
model_evaluate.py procedure description here
test dataset description here
weibo sentiment analysis procedure as follows:
How can i solve "Mix of label input types (string and number)"??
How can i solve "Mix of label input types (string and number)"??
#test dataset procedure
import json
import numpy as np
import pandas as pd
from sklearn.metrics import classification_report

from util import dataset, test_file_path
from model_train import convert_example_to_feature
from transformers import TFBertForSequenceClassification

with open("{}_label.json".format(dataset), "r", encoding="utf-8") as f:
    labels = json.loads(f.read())

cls_model = model = TFBertForSequenceClassification.from_pretrained('bert-base-chinese', num_labels=len(labels))
cls_model.load_weights("{}_cls.h5".format(dataset))

test_df = pd.read_csv(test_file_path).fillna(value="")

test_data = []
for i in range(test_df.shape[0]):
    label, content = test_df.iloc[i, :]
    test_data.append((content, label))

input_ids_list = []
token_type_ids_list = []
attention_mask_list = []
true_cls_labels = []

for review, label in test_data:
    bert_input = convert_example_to_feature(review)
    input_ids_list.append(bert_input['input_ids'])
    token_type_ids_list.append(bert_input['token_type_ids'])
    attention_mask_list.append(bert_input['attention_mask'])
    true_cls_labels.append(label)

print("first 10 true cls labels: ", true_cls_labels[:10])
test_ds = [np.array(input_ids_list), np.array(attention_mask_list), np.array(token_type_ids_list)]
predictions = cls_model.predict(test_ds).logits
label_ids = np.argmax(cls_model.predict(test_ds).logits, axis=1)
predict_cls_labels = [labels[_] for _ in label_ids]
print("first 10 predict cls labels: ", predict_cls_labels[:10])
print("result for model evaluate: \n")
***print(classification_report(true_cls_labels, predict_cls_labels, digits=2))***

A: I think your problem is this. The true_cls_labels are saved by index not the value you want to represent, as you see in the output you commented.
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, ]
and
['喜悦', '低落', '低落', '厌恶', '愤怒', '厌恶', '厌恶', '愤怒', '厌恶', '厌恶', '厌恶', '厌恶', '喜悦', '厌恶', '愤怒', '喜悦', '厌恶', '喜悦', '低落', '厌恶', '愤怒', '厌恶', '愤怒', '喜悦', '愤怒', '愤怒', '厌恶', '厌恶', '厌恶', '愤怒', '厌恶', '喜悦', '厌恶', '愤怒', '愤怒', '低落', '厌恶', '低落', '厌恶', ]
You input the label here:
for i in range(test_df.shape[0]):
    label, content = test_df.iloc[i, :]
    test_data.append((content, label))

Maybe this test_df.iloc[i, :] does not what you want, but I don't now how the test_data[] looks like. Maybe you wanted to do:
for i in test_df.shape[0]:
    label, content = test_df.loc[i, :]
    test_data.append((content, label))

A: I know this post is not new, but I am writing this answer to help others who have the same question:
This error means you have a mixed data type in your labels. You have to make sure the data type of the columns are the same (e.g., you can use pd.to_numeric to force the dtype to be numeric.
Please see this similar question:
ValueError: Mix of label input types (string and number)


text:
Q: How to get Player duration, current Time, and video frames or Seek Position (JQuery) I am able to put this code together to get player duration, current time, and to derive a value which i use to update the progress bar width.
Such As
var slideOff=Math.floor((100 / tDuration) *( tCurrent));

progBar.css({width:slideOff+'%'});

My issue is that i want also to be able to the get the seek position.
For example with the code below is working fine but the seek figure is not tally or the same with current time .
if you run this code on JSFiddle you will get somthing like this:
Duration  29:05
Current Time  2:25
SeekPosition   1:44 This is the issue i want the seek position to be the same as current time when computed.
Html

Duration00:00

Current Time00:00

SeekPosition 00:00

Css
#seekbar{
    border:none;
    width:480px;
    height:6px;
    background-color:#00ffcc;
    position:relative;
    margin:auto;

    }

    #seekLay{
    margin:0;
    height:4px;
    background-color:#001001;
    position:relative;
    top:1px;}

    #seeker{
    width:6px;
    height:100%;
    position:absolute;
    left:0;
    background-color:red;
    cursor:pointer;}
span{margin-left:30px;}

Javascript
String.prototype.pad = function(l, s){
return (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length) + 1).join(s)).substr(0, s.length) + this + s.substr(0, l - s.  length) : this;}

function playerTime(dcurT) {
       var tCurrent = dcurT  ,//player.getCurrentTime(),
           tDuration= 1745,  //player.getDuration(),
           dbar=$("#seekbar"),
           progressBar=$("#seeker"),
           progBar=$("#seekLay"),
           currenT = tCurrent,
           slideOff=Math.floor((100 / tDuration) *( tCurrent));
    //Get current time
$('span#currenT').html(Math.floor(tDuration/ 60) + ":" + (tDuration % 60).toFixed().pad(2, "0"));
    //get duration
$('span#durationT').html(Math.floor(tCurrent / 60) + ":" + (tCurrent % 60).toFixed().pad(2, "0"));
    //Update bars
progressBar.css({marginLeft:slideOff+'%'});
progBar.css({width:slideOff+'%'});

      //Get seek position

    var ratio=Math.floor((progBar.width())/progressBar.width()),
        xpos=Math.floor( tDuration* (ratio / 100));

$('span#resulk').html(Math.floor(xpos / 60) + ":" + (xpos % 60).toFixed().pad(2, "0"));

      }
playerTime(145);//change

//Out Put
//Duration  29:05
//Current Time   2:25
//SeekPosition 1:44

I know this won't take you 5 minutes to figure out.

A: Simply change this line
var ratio=Math.floor((progBar.width())/progressBar.width()),
        xpos=Math.floor( tDuration* (ratio / 100));

============
Replace It with  this line
var xpos=Math.floor(tDuration*progBar.width()/dbar.width());

==============


text:
Q: Shortcode to delete post from front end I'm trying to create a short code to delete post that user publish from the front end of my site.
I've tried the short-code below but I keep getting the error "The link you followed has expired." Kindly see image screenshot below.
  //Shortcode to delete post
    function delete_my_posts() {
        ob_start();

            $url = get_bloginfo('url');
     if (current_user_can('edit_post', $post->ID)){
       echo 'ID);
       echo '">Delete post';
     }

       return ob_get_clean();
    }
    add_shortcode( 'delete_me', 'delete_my_posts' );

Screenshot: https://imgur.com/a/PMB1uU4
Can someone kindly advise on this error?
Thanks

A: Following is the reformatted version of your code. get_delete_post_link() is used for fetching delete post URL so that we dont have to worry about nonce stuff. global $post is kept to avoid PHP notice which is currently there in your code. Please check it.
function wpso_delete_my_posts() {
    global $post;
    ob_start();
    if ( current_user_can('delete_posts', $post->ID ) ) {
        echo 'ID ) ) . '">Delete Post';
    }
    return ob_get_clean();
}
add_shortcode( 'delete_me', 'wpso_delete_my_posts' );


text:
Q: basic question about angles of lines
Show that the tangent lines to the regular parametrized curve $$
\alpha \left( t \right) = \left( {3t,3t^2 ,2t^3 } \right)
$$
   make a constant angle with the line $y=0$ , $z=x$

First of all, the derivate of that curve is $$
\left( {3,6t,6t^2 } \right)
$$
So in an arbitrary point of the curve at $ t=$$
\varphi
$$
_0 $ the tangent line is
$$
\eqalign{
  & \left( {3\varphi _0 ,3\varphi _0 ^2 ,2\varphi _0 ^3 } \right) + t\left( {3,6\varphi _0 ,6\varphi _0 ^2 } \right)  \cr
  &  = \left( {3\varphi _0  + 3\,t\,\,,\,\,\,3\varphi _0 ^2  + 6\,t\,\varphi _0 ,\,\,\,2\varphi _0 ^3  + 2\,t\,\varphi _0 ^2 } \right) \cr}
$$
The other line is $ (u,0,u) $   but the dot product betweem this two lines is not constant, what is bad?

A: The vectors we want to take the dot product of are
$$\mathbf{a}=(u,0,u),$$
$$\mathbf{b}=(3,6t,6t^2).$$
(As Jim points out below, we want to take the dot product of the direction vectors of the lines; what I wrote before was the dot product of $(u,0,u)$ and the position vector of a point on the tangent line). Recall that
$$\mathbf{a}\cdot\mathbf{b}=||\mathbf{a}||\,\,||\mathbf{b}||\cos(\theta).$$
The fact that the dot product you're getting isn't constant is due to factor of $||\mathbf{a}||\,\,||\mathbf{b}||$ that you are forgetting to compensate for (or at least, I assume this is the problem that's occuring). Once you divide your answer by $||(u,0,u)||=u\sqrt{2}$ and $\left|\left|\left( {3\,\,,\,6\,t\,,6\,t ^2 } \right)\right|\right|=\sqrt{9+36t^2+36t^4}$, it should be constant, i.e. not have any $t$'s or $u$'s.


text:
Q: I have connnected to fb and my coc has been deleted. How to get back that account which I had linked it to fb? My account was th 8. I had connected it to fb. Now my coc has been deleted. When I installed it. My old account is not coming. How do I get it back?

A: not related to minecraft, but go into settings ,help, then "i lost my village" or something like that, and follow the instructions. i recommend connecting your COC account to google play(android) or the game center(IOS).


text:
Q: How to add image with Inline Editor on Dialogflow I am using Inline Editor in Fulfillment on Dialogflow. I can add response with these codes:
    const NEED_QUOTE_INTENT = 'Need Quote'
app.intent(NEED_QUOTE_INTENT, (conv) => {
    const quote_type = conv.parameters[QUOTE_TYPE_ENTITY].toLowerCase();
    if (quote_type == "inspiration") {
            conv.ask("Nice")
    }else if (quote_type == "happiness") {
        conv.ask("Happy")
    }else if (quote_type == "friendship") {
        conv.ask("Friend")
    }else {
        conv.ask("Hello There")
}
})

But i can't add image response. I did some research and found people adding with firebase. I want to add image response on this codes. How can i do?

A: If you are using actions-on-google library You can use a Basic Card to display an image.
Make sure you require Basic Card and Image from the actions-on-google library as below:
const {
  dialogflow,
  BasicCard, // important
  Button,
  Image, // important
} = require('actions-on-google');

and then use it providing URL of the image you want to display, as below:
const NEED_QUOTE_INTENT = 'Need Quote'
app.intent(NEED_QUOTE_INTENT, (conv) => {
    const quote_type = conv.parameters[QUOTE_TYPE_ENTITY].toLowerCase();
    if (quote_type == "inspiration") {
               conv.ask("Nice"); // this Simple Response is necessary
               conv.ask(new BasicCard({
                    image: new Image({
                     url: 'https://example.com/image.png', //url of your image.
                     alt: 'Image alternate text',
                 }),
         }));
    }else if (quote_type == "happiness") {
        conv.ask("Happy")
        //similarly add an image here
    }else if (quote_type == "friendship") {
        conv.ask("Friend")
    }else {
        conv.ask("Hello There")
}
})

Hope that helps!

A: The actions-on-google library only works on devices that are running the Google Assistant. The responses are for Actions only.
If you also wanted this to work on other platforms that Dialogflow supports, you may want to look into the dialogflow-fulfillment library and tailor your response depending on which platform the request comes from.


text:
Q: How to remove mirror duplicate pair rows in pandas? This is my dataframe consisting of columns a,b,c,d.
Here

1 2 3 4

has mirror duplicate pair row of

3 4 1 2

Removing the duplicate pair should give me

A: df.loc[pd.DataFrame(np.sort(df[['a','b','c','d']],1),index=df.index).drop_duplicates(keep='first').index]

U can use np.sort to sort columns in ascending order and then use .drop duplicates to get rid of the duplicate rows.


text:
Q: HTML5 input type number reformats long number I have an application whereby a user has to input a minimum of 15 digits in a number type textbox.
If a user enters a longer number, sometimes >= 19 digits, and then either uses the arrows on the right or the arrow keys on their keyboard, it autoformats the number to a float with e+ at the end which, obviously, isn't ideal.

<input min="0" type="number" value="7897894561234567898">

What's the best way to either remove or counteract this behaviour? Is there anything to be done, or will I have to use a text type input? (I'd rather not).

A: The HTML5 <input type=number> specifically uses the same Number type as JavaScript. The maximum integer value before precision is lost is 9007199254740991, which has 16 digits.
You can't handle larger integers than that as a Number in JavaScript, you have to treat it as a string.
You should use <input type=text>, along with a pattern attribute for validation, and an inputmode attribute for touchscreens. The default validation message is not useful, so the 'invalid' event should also be handled.
(Just kidding, inputmode isn't supported anywhere. You should use <input type=tel> to show a numeric keyboard on touchscreen devices.)

<form>
  <input name=num type=tel
         required pattern="\d+"
         oninvalid="setCustomValidity('A number is required')"
         oninput="setCustomValidity('')">
  <input type=submit>
</form>

There's a note in the spec about credit card numbers:

The type=number state is not appropriate for input that happens to only consist of numbers but isn't strictly speaking a number. For example, it would be inappropriate for credit card numbers or US postal codes. A simple way of determining whether to use type=number is to consider whether it would make sense for the input control to have a spinbox interface (e.g. with "up" and "down" arrows).

See: https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number)


text:
Q: $(document).ready function in thymeleaf fragment - $ is not defined I am trying to add a js file with a $(document).ready function into a thymeleaf fragment, so that the js file is always added when including the fragment. When I do this, I get the error message "Uncaught ReferenceError: $ is not defined" in the browser.
pageIncludingFragment.html
...
<div th:include="fragment :: fragment"></div>
...

fragment.html
<div th:fragment="fragment">
   ...
   <script th:src="resources/js/fragment.js"></script>
</div>

fragment.js
$(document).ready(function() {
   ...
});

Is there a way to do this or do I have to include the script directly in pageIncludingFragment.html every time?

A: freedomn-m is right, my jquery inclusion was beneath the inclusion of the fragment.


text:
Q: Автомонтирование в Symfony Только начинаю изучать Symfony, не могу справиться с проблемой. Хочу попробовать автомонтирование, но Symfony выдаёт ошибку о том, что класс не существует.
HelloController (\src\Controller\HelloController.php):
<?php
namespace App\Controller;

use App\GreetingGenerator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

class HelloController extends AbstractController
{
    /**
     * @Route ("/hello/{name}")
     */

     public function index($name, GreetingGenerator $greeting)
     {
        $info = $greeting->getRandomGreeting($name);
        return $this->render('index.html.twig',
        [
            'info' => $info
        ]);
     }
}

GreetingGenerator (\src\GreetingGenerator.php):
<?
namespace App;

class GreetingGenerator
{
    public function getRandomGreeting($name)
    {
        $greetings = ['Hi', 'Hello', 'Hey'];
        return $greetings[random_int(0,count($greetings) - 1)].', '.$name;
    }
}

Полностью сообщение об ошибке выглядит так:
Cannot resolve argument $greeting of "App\Controller\HelloController::index()": Cannot determine controller argument for "App\Controller\HelloController::index()": the $greeting argument is type-hinted with the non-existent class or interface: "App\GreetingGenerator".
Использовал команду php bin/console debug:autowiring --all, которая сообщила мне следующее:
The following classes & interfaces can be used as type-hints when autowiring:
App\Controller\DefaultController
App\Controller\HelloController
App\GreetingGenerator
App\Kernel (kernel)
Как я понимаю, это означает, что я могу использовать для автомонтирования свой класс.
Подскажите, пожалуйста, в чём может быть проблема.

A: Есть три варианта:

*

*Перенесите это в параметры контроллера и далее присвойте свойству класса (самый простой, всё будет сделано автоматически).

*Если хотите оставить в текущей реализации, то вам нужно определить ваш сервис в services.yaml и явно указать его как аргумент метода контроллера (контроллер необходимо будет тоже зарегистрировать как сервис).

*Напишите и зарегистрируйте новый ArgumentResolver.

A: Всё дело было в shot tag php. Нужно было использовать обычный тэг. Я использую для тестирования встроенный сервер symfony, который запускаю с помощью symfony:start. Видимо, в настройках сервера отключен флаг short_open_tag.


text:
Q: Qt4: Window appears in the upper left corner on metacity I have a problem with window appearance in qt4 on Metacity. Initial problem was with the window appearing under another window, from which it was called by clicking the button. I solved that on Compiz by sending _NET_ACTIVE_WINDOW, but on metacity it still wasn't working. After hours of googling, I tried this:
if (window -> isMinimized())
{
  window -> showNormal();
}
else if (window -> isHidden())
{
  window -> show();
}

//the code that I added, which makes the window appear above.

window ->setWindowFlags(Qt::WindowStaysOnTopHint);
Qt::WindowFlags flags = window->windowFlags();
flags &= ~Qt::WindowStaysOnTopHint;
window->setWindowFlags(flags);

window->setGeometry(window->geometry());

window -> activateWindow();
window->show();
window -> raise();

It is just workaround, but it actually makes the window appear above. And this is where another problem occurs: If the window is shown and I change the focus to the window from where it is called and press the button, my window appears above on the same place as it should. But if I close the window and call it again, it appears in the upper left corner.
Does anyone have an idea why it is happening?
Thanks in advance.


text:
Q: How can I bind an event handler to an instance in jQuery? I am trying to bind an event to a "method" of a particular instance of a Javascript "class" using jQuery. The requirement is that I in the event handler should be able to use the "this" keyword to refer to the instance I originally bound the event to.
In more detail, say I have a "class" as follows:
function Car(owner) {
  this.owner = owner;
}
Car.prototype = {
  drive: function() {
    alert("Driving "+this.owner+"s car!");
  }
}

And an instance:
var myCar = new Car("Bob");

I now want to bind an event to the drive "method" of my car so that when ever I click a button for example the drive "method" is called on the myCar instance of the Car "class".
Up until now I've been using the following function to create a closure that allows me to comfortably access instance members using the "this" keyword in my "methods".
function createHandler( obj, method ) {
  return function( event ) {
    return obj[method](event||window.event);
  }
}

I've used it as follows:
document.getElementById("myButton")
  .addEventListener("click", createHandler(myCar,"drive"));

How do I accomplish something like this with JQuery?
I'm specifically asking about associating "this" with a designated instance, the other cruft all around I can handle on my own.

A: Just use an anonymous function:
$("#myButton").click(function() { myCar.drive(); });

A: Try this :
$("#myButton").each(function() {

var $btn = $(this);

    $btn.on('click',function(){

     // Do whatever you want.

    });
});

Here you first create a loop to target all #myButton elements (Which is wrong in your example, You should be using Class instead) like:
$(".myButton").each(...

Then we attach the click event handler to all of them.


text:
Q: How to post pictures with the mobile app? How to post pictures with the mobile app?  I wanted to answer a question with a diagram on my mobile.  How should I do that?
I am currently on iPhone, using the Stack Exchange application.
If this feature is not present, I would like to request for it.

A: There's a Camera button when writing a post, which will let you choose between the iPhone's camera itself or the Photo Library.

(trivia: the screenshot was originally uploaded via the iPhone app)
You need to allow the Stack Exchange app to access your camera or photos, the app will ask you for this the first time you use this function.


text:
Q: Maven can't download its plugin (as clean), can this situation depend by a proxy configuration issue? I am not so into Maven and I have the following problem:
I have download a project (that use Spring) from the SVN repository of my company and there are some building errors that seems depends by the fact that some dependencies are missing (for example all the Spring dependencies).
So I tried to select the project and do a Run as ---> Maven Clean as first step before building the project (also if it should perform the clean before the build if I do Maven build but this is not important at this stage) and I obtain this error message:
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building GestioneUtenzeCloud 1.0.0-BUILD-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] Downloading: http://srvabc02.soft.it:8888/artifactory/plugins-release/org/apache/maven/plugins/maven-clean-plugin/2.5/maven-clean-plugin-2.5.pom
[INFO] Downloading: http://srvabc02.soft.it:8888/artifactory/plugins-snapshot/org/apache/maven/plugins/maven-clean-plugin/2.5/maven-clean-plugin-2.5.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.561 s
[INFO] Finished at: 2015-08-19T12:35:43+02:00
[INFO] Final Memory: 7M/123M
[INFO] ------------------------------------------------------------------------
[ERROR] Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-clean-plugin:jar:2.5: Could not transfer artifact org.apache.maven.plugins:maven-clean-plugin:pom:2.5 from/to central (http://srvabc02.soft.it:8888/artifactory/plugins-release): srvabc02.soft.it: Unknown host srvabc02.soft.it -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginResolutionException

So it seems that it can't download the Maven plugin (in this case the clean plugin).
My computer is connected to Internet passing through the company proxy so I think that is can not download the Maven plugin because the proxy is not configured on my Eclipse...is it possible? What can I do to solve this issue?

A: Solved by myself. I have added the Maven proxy settings into the settings.xml file that is into the .m2 directory.
As explained here on the official documentation: https://maven.apache.org/guides/mini/guide-proxies.html