text:
Q: How to give alternate color to rows in react? I have created a table in react js. I want to give alternate colors for alternate rows. I want to give all even rows with one color and all odd rows with another color. How it can be done?
I am not getting the appropriate approach for this and I have tried doing it at my end but unable to do so. So for the same I am adding my react js code along with its css.
This is my table code:-
import Box from '@mui/material/Box';
import { GridColumns, DataGrid } from '@mui/x-data-grid';
import "../../css/App.css";

const columns: GridColumns = [
    {
      field: 'Symbol',
      headerClassName: 'super-app-theme--header',
      headerAlign: 'center',
      width: 140,
      cellClassName: 'super-app-theme--cell',
    },
    {
      field: 'Side',
      headerClassName: 'super-app-theme--header',
      headerAlign: 'center',
      width: 140,
      cellClassName: 'super-app-theme--cell',
    },
    {
      field: 'Broker',
      headerClassName: 'super-app-theme--header',
      headerAlign: 'center',
      width: 140,
      cellClassName: 'super-app-theme--cell',
    },
    {
      field: 'OrderStatus',
      headerClassName: 'super-app-theme--header',
      headerAlign: 'center',
      width: 140,
      cellClassName: 'super-app-theme--cell',
    },
    {
      field: 'OrderQty',
      headerClassName: 'super-app-theme--header',
      headerAlign: 'center',
      width: 140,
      cellClassName: 'super-app-theme--cell',
    },
    {
      field: 'Cumulative',
      headerClassName: 'super-app-theme--header',
      headerAlign: 'center',
      width: 140,
      cellClassName: 'super-app-theme--cell',
    },
    {
      field: 'OrderType',
      headerClassName: 'super-app-theme--header',
      headerAlign: 'center',
      width: 140,
      cellClassName: 'super-app-theme--cell',
    },
    {
      field: 'Account',
      headerClassName: 'super-app-theme--header',
      headerAlign: 'center',
      width: 140,
      cellClassName: 'super-app-theme--cell',
    },
  ];

  const rows=[
              {id: 1, Symbol:'INR', Side:'Buy', Broker:'Steve', OrderStatus:'New', OrderQty:2, Cumulative:'-', OrderType:'Buy', Account:'Account 1'},
              {id: 2, Symbol:'INR', Side:'Sell', Broker:'John', OrderStatus:'New', OrderQty:3, Cumulative:'-', OrderType:'Sell', Account:'Account 2'},
              {id: 3, Symbol:'INR', Side:'Buy', Broker:'Alex', OrderStatus:'New', OrderQty:4, Cumulative:'-', OrderType:'Buy', Account:'Account 3'},
              {id: 4, Symbol:'INR', Side:'Sell', Broker:'Smith', OrderStatus:'New', OrderQty:5, Cumulative:'-', OrderType:'Sell', Account:'Account 1'},
              {id: 5, Symbol:'INR', Side:'Buy', Broker:'Harry', OrderStatus:'New', OrderQty:6, Cumulative:'-', OrderType:'Buy', Account:'Account 2'},
              {id: 6, Symbol:'INR', Side:'Sell', Broker:'Johnson', OrderStatus:'New', OrderQty:7, Cumulative:'-', OrderType:'Sell', Account:'Account 3'},
              {id: 7, Symbol:'INR', Side:'Buy', Broker:'Peter', OrderStatus:'New', OrderQty:8, Cumulative:'-', OrderType:'Buy', Account:'Account 1'},
              {id: 8, Symbol:'INR', Side:'Sell', Broker:'David', OrderStatus:'New', OrderQty:4, Cumulative:'-', OrderType:'Sell', Account:'Account 2'}
          ];

  export default function Table() {
    return (

      <Box className="box"
        sx={{
          height: 550,
          width: 1122,
        }}
      >
        <DataGrid rows={rows} columns={columns}/>
      </Box>

    );
  }

And this is the CSS which I have used:-
.box{
  margin-left: 100px;
  background-color: #36384f;
  color: white;
  margin-top: 10px;
}

This image is the sample output which I am expecting.

A: Updated answer:
Maybe <StripedDataGrid /> instead of <DataGrid /> does the magic.
Check out the MUI docs: Striped rows
Old answer:
Do the rows have a className? Then you should be able do that with CSS.
    .super-app-theme--row:nth-of-type(odd) {
      background-color: red;
    }

    .super-app-theme--row:nth-of-type(even) {
      background-color: green;
    }

:nth-of-type Selector


text:
Q: Have C# Regex.IsMatch return false if doesn't match entire input string I'm currently trying to implement a check for a regex matching an input string, which i would like to only validate letters a-z, (lower or caps) excluding all numbers, special characters...
However, if the regex matches partially, Regex.Match(input) will return true. I would like it to return false unless the entire input string is valid, how would i go about this?
Here is an example if how i would like it to work, the Regex pattern shown is what i'm currently using.
Regex expression = new Regex("^[a-zA-Z]*");

if(!expression.IsMatch("example123")) { /* do something */ }

As it is right now, the Regex will match up to "example", and still return true, even though it contains "123" at the end.

redpajama_set_name: RedPajamaStackExchange


text:
Q: outlook 2007 - auto suggest email recipients names sent to or read from in the past can anyone tell me the setting in outlook 2007 that would enable the hints of email addresses and contact names when generating an email to someone who you received or wrote to in the past.
i am tired of typing things out all the time and know it auto populates names for me on my other machines.

A: This should do it for you:

*

*On the Tools menu, click Options.

*On the Preferences tab, click E-mail Options, and then click Advanced E-mail Options.

*Select the "Suggest names while completing To, Cc, and Bcc fields" check box.


text:
Q: WampServer doesn't update the PHP version list as the title above, WampServer seems like doesn't update the PHP version list....
I already download and include php7.4.10 folder, but the list doesn't seems to be updated....
I also even restart my computer, and the list didn't updated..

For your info, this is on production server...
While in test server and my localhost, there's nothing problem at all to upgrade the php version...
This problem occurred only to my production server..
Is there any alternative way to update the php version?

A: Found it !
Add the following in line 2 of the wamp64/scripts/refresh.php file :

ini_set('memory_limit', '2048M');

It will just avoid a memory exceed issue aborting wamp manager update.
Then restart wampmanager :)

A: If you want to  manually install PHP 7.4.10,into your WampServer version.

*

*Download binaries on php.net

*Extract all files in a new folder :C:/wamp/bin/php/php7.4.10/

*Copy the wampserver.conf from another php folder (like php/php7.2.14/) to the new
folder

*Rename php.ini-development file to phpForApache.ini

*Done ! Restart WampServer.

This will help you.

A: Ok... now I know why... it is because there's something wrong in php.ini configuration.. need to check again the configuration..... for my case, I need to remove the code as image below:

Actually fresh php version 7.4.10 doesn't have this interbase configuration.... i copy this [interbase] code from previous php version which is version 7.2.14..
But after remove back this interbase configuration, my problem solved..
Conclusion is: If you face same problem like me (or if apache service cannot started), it means there's something wrong with your php.ini configuration... trust me...

A: I had this issue today when updating to PHP 8.0.3, where after installing the add-on for the new version from https://wampserver.aviatechno.ne, the new 8.0.3 version wasn't added to the list at WAMP>PHP>Versions.
The solution that worked for me:

*

*Check if there is a PHP error (that happens when you Refresh WAMP) by going to WAMP>PHP>PHP Error Log.

*I found an error where PHP didn't have enough memory to Refresh WAMP.

*I increased the memory_limit in C:\wamp64\bin\php\php5.6.40\php.ini to 2000M from 128M (Note: if WAMP uses a different PHP version for CLI, update their respective php.ini)

*Right-click WAMP > Refresh

Hopefully this helps

A: I had the same issue when updating WAMP Manager Update 3.2.5 and Upgrading to PHP 7.4 via the Addons Package both found here. When I updated WAMP Manager it showed an even older version than I already had (on the GUI) and when I ran the PHP 7.4 package addon it did not show up in my PHP list.
My solution was to choose an even older version of PHP from the list and then after WAMP restarted my new PHP 7.4 was showing and the WAMP Manager was showing the newest version. So it clearly had to do with WAMP restarting which makes me wonder if restarting all services or a full PC reboot would have helped as well.


text:
Q: Can't draw lines in GooCanvas In a Perl/Gtk3 script and using GooCanvas, I can easily draw a rectangle, or an ellipsis, or whatever, but it seems to be impossible to draw a simple line.
Lines are drawn with a call to Goo::CanvasPolyline->new(). The line's coordinates a specified by a call to Goo::CanvasPoints->new(), but that call creates the following error:
GLib-ERROR **: ../../../../glib/gmem.c:105: failed to allocate 18446744069314558208 bytes at /usr/lib/x86_64-linux-gnu/perl5/5.26/Glib/Object/Introspection.pm line 67.
Aborted (core dumped)

I've tried the Perl module Goo::Canvas and the more modern GooCanvas2; both produce the same error.
I wasn't able to find any working code examples; merely the non-working script below, which Google found on $RANDOM_WEBSITE.
#!/usr/bin/perl -w
use strict;
use warnings;
use Gtk3 -init;

Glib::Object::Introspection->setup(basename => 'GooCanvas', version => '2.0', package => 'Goo');

my $window = Gtk3::Window->new('toplevel');
$window->signal_connect('delete_event' => sub { Gtk2->main_quit; });
$window->set_size_request(640, 600);
$window->set_title("Gtk3 GooCanvas with Perl Gobject Introspection");
$window->signal_connect(destroy => sub { Gtk3->main_quit });

my $swin = Gtk3::ScrolledWindow->new;
$swin->set_shadow_type('in');
$window->add($swin);

my $canvas = Goo::Canvas->new; # Gobject Introspection of Gtk3 Goo version
$canvas->set_size_request(800, 650);
$canvas->set_bounds(0, 0, 1000, 1000);
$swin->add($canvas);
my $root = $canvas->get_root_item();

# first point set
my $pts_ref = [50,50,180,120,90,100,50,50];

my $points = Goo::CanvasPoints->new(
         $pts_ref,
         );

my $line = Goo::CanvasPolyline->new(
   'parent' => $root,
   'close-path' => 0,
   'points' => $points, #in Gtk2 could just use $pts_ref
   'stroke-color' => 'black',
   'line-width' => 3,
);

my $ellipse = Goo::CanvasEllipse->new(
   'parent' => $root,
   'center-x' => 20,
   'center-y' => 20,
   'width'  =>  +60,
   'height' =>  +60,
   'stroke-color' => 'goldenrod',
   'line-width' => 8,
   'fill-color-rgba' => 0x3cb37180,
);

$root->translate(200,200);

$window->show_all();
Gtk3->main;
__END__

A:
my $points = Goo::CanvasPoints->new( $pts_ref );

According to the documentation the constructor should take the number of points to reserve, not the reference to the points array. So you could try:
[...]
# first point set
my $pts_ref = [50,50,180,120,90,100,50,50];
my $num_points = (scalar @$pts_ref)/2;
my $points = Goo::CanvasPoints->new( $num_points );

# Set the points:
my $j = 0;
for my $i (0..($num_points -1)) {
    my $x = $pts_ref->[$j];
    my $y = $pts_ref->[$j+1];
    $points->set_point($i, $x, $y);
    $j += 2;
}
[...]


text:
Q: Squid - Selective reverse proxy and forward proxy I'd like to setup a squid instance to do selective reverse proxy for a configured list of URLs while acting as a normal forward proxy for everything else.
We are building new infrastructure, parallel live as it were, and I want to have a proxy that people can use that will force selective traffic into the new platform while acting as a forward proxy for anything else. This makes it very easy for people/systems to test the portions of the new platform we want without having to change too much, just use a proxy address.
Is such a setup possible ?

A: The following seems to work for me, anything for www.myurl.com gets sent to the new servers and everything else is proxied as normal.

# Setup a cache peer as an origin server
# Duplicate this line for each site you want to reverse for and give it a new name
cache_peer <new platform ip or fqdn> parent 80 0 no-query originserver proxy-only name=upstream1

# Set the domain the cache_peer should handle
cache_peer_domain upstream1 www.myurl.com

# Duplicate following three lines
# Add as many acl lines as necessary for all domains handled
acl our_sites  dstdomain www.myurl.com
cache_peer_access upstream1_sites allow our_sites
cache_peer_access upstream1_sites deny all


text:
Q: django login authentication I'm relatively new to django..
In the app that I'm building, there are multiple types of users (ie User1, User2, User3) that are all inheriting from django.contrib.auth.models.User and upon login, each user should be redirected to a success page depending on what type of user they are.
In views.py:
def login_attempt(request):

user = request.user
data = {}

username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
    if user.is_active:
        login(request, user)

        try:
            User1.objects.get(username = user.username)
            type = "undergrad"
        except ObjectDoesNotExist:
            pass

        try:
            User2.objects.get(username = user.username)
            type = "grad"
        except ObjectDoesNotExist:
            pass

        try:
            User3.objects.get(username = user.username)
            type = "sponsor"
        except ObjectDoesNotExist:
            pass

        return render_to_response (
                "templates/success_"+type+".html",
                data,
                context_instance=RequestContext(request)
        )

    else:
        return render_to_response (
                "templates/fail1.html",
                data,
                context_instance=RequestContext(request)
        )
else:
    return render_to_response (
            "templates/fail2.html",
            data,
            context_instance=RequestContext(request))

and type(user) is <class 'django.contrib.auth.models.User'>
I'm currently running tests via "manage.py test" -- authentication and redirects are working for User1 and User2 successfully, however it doesn't authenticate for User3 and returns the "fail2.html" template.  All other tests with User3 have returned valid results.
Any suggestions?  This is my first question post, so feel free to ask questions if I've left relevant information out!
Thanks in advance.

A: Not really an answer for your question, but why not use a user profile to determine your type and other data specific to the UserX classes?  They are easy to set up, allow you to store additional User information, and allows you to continue using the built in User objects.
The profile classes are pretty easy (I lifted this from The Django Book, Chapter 12):
class MySiteProfile(models.Model):
    # This is the only required field
    user = models.ForeignKey(User, unique=True)

    # The rest is completely up to you...
    type = models.CharField(maxlength=100, blank=True)

Beyond that, you change on item in settings.py, and set up a trigger to automagically create the profile on User creation, and you're good to go.
Your resulting view code would be drastically simplified, too:
def login_attempt(request):
    user = request.user
    data = {}
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            type = user.get_profile().type

            return render_to_response (
                "templates/success_"+type+".html",
                data,
                context_instance=RequestContext(request)
            )

        else:
            return render_to_response (
                    "templates/fail1.html",
                    data,
                    context_instance=RequestContext(request)
                )
    else:
        return render_to_response (
                "templates/fail2.html",
                data,
                context_instance=RequestContext(request)
            )

A: This is not exactly an answer to your problem but have you considered using groups/permissions to differentiate between different types of users rather than creating subclasses of auth.User? Django's auth feature comes with a reasonably useful groups/permissions mechanism which can be leveraged to make your life more easier.
Using groups you can various create groups ("undergrad", "grad" etc.) and grant each group appropriate permissions to achieve the necessary effect.


text:
Q: Can MVC (or MVP) co-exist with SOA? I think that business logic should exist in a model when using an MVC or MVP design pattern, but should be hidden behind a service in a service-oriented architecture.
Can a software system use the MVC or MVP design pattern within a service-oriented architecture? If so, where does the model sit?

A: Good Question.
I think MVC and SOA will and must co-exist. MVC is the most sucessful architecture for User to system communication. SOA is an architecture for effective system-system communication. In most organisation, there is a place for both. Therefore I believe they will co-exist.
In terms of how they interact with each other, my personal opinion is - MVC will remain (once the SOA hype is gone) as the core architectural pattern with both model and controller exposing service interfaces where appropriate.

A: Well they are totally different animals. MVC is all about presentation of data, controlling the navigation of the user dialog and some business logic in building the data model.
SOA is about retrieving data from a service provider.
On the client side, you can use SOA within the Model part of the MVC pattern to build up your model with data from a SOA service.
On the service side, as there is no presentation and no user dialog, most of the MVC pattern becomes redundant. Furthermore, good SOA design should concentrate on providing a useful service regardless of the underlying data store, so the "model" part becomes largely incidental.
It is true that many services are "stateful" (e.g. orders are validated, paid for, dispatched then received), but these states are an integral part of the business logic and don't lend themselves to the session management typical of the MVC pattern.


text:
Q: new thread blocks main thread from threading import Thread
class MyClass:
    #...
    def method2(self):
        while True:
            try:
                hashes = self.target.bssid.replace(':','') + '.pixie'
                text = open(hashes).read().splitlines()
            except IOError:
                time.sleep(5)
                continue
        # function goes on ...

    def method1(self):
        new_thread = Thread(target=self.method2())
        new_thread.setDaemon(True)
        new_thread.start()  # Main thread will stop there, wait until method 2

        print "Its continues!" # wont show =(
        # function goes on ...

Is it possible to do like that?
After new_thread.start() Main thread waits until its done, why is that happening? i didn't provide new_thread.join() anywhere.
Daemon doesn't solve my problem because my problem is that Main thread stops right after new thread start, not because main thread execution is end.

A: As written, the call to the Thread constructor is invoking self.method2 instead of referring to it. Replace target=self.method2() with target=self.method2 and the threads will run in parallel.
Note that, depending on what your threads do, CPU computations might still be serialized due to the GIL.

A: IIRC, this is because the program doesn't exit until all non-daemon threads have finished execution. If you use a daemon thread instead, it should fix the issue. This answer gives more details on daemon threads:
Daemon Threads Explanation


text:
Q: All possible ways to reach an ending position http://www.cstutoringcenter.com/problems/problems.php?id=103
For those who doesn't want to click it, it basically says there's a stepping stone, "-" and soldier "#", soldiers can only move right. If the soldier is behind another soldier, he must wait for the soldier to move first. The ending condition is when all soldiers reaches the end.
The number of ways 2 soldier can move across 5 stepping stones.
1) ##---  #-#--  -##--  -#-#-  --##-  --#-#  ---##
2) ##---  #-#--  -##--  -#-#-  -#--#  --#-#  ---##
3) ##---  #-#--  #--#-  -#-#-  --##-  --#-#  ---##
4) ##---  #-#--  #--#-  -#-#-  -#--#  --#-#  ---##
5) ##---  #-#--  #--#-  #---#  -#--#  --#-#  ---##

I'm using a breadth first search, with 5 stones, it's running within seconds, but with 10 stones, it's taking hours, the time is increasing exponentially with the depth. How can I deal with this?
My Codes:
States.java
import java.util.ArrayList;

public class State {
    public int stones;
    public Soldiers[] soldiers;
    public String currentState ="";
    public boolean visited = false;

    public State(int stones,int Numsoldiers){
        System.out.println(Numsoldiers);
        this.stones = stones;
        soldiers = new Soldiers[Numsoldiers];
        System.out.println("length" + soldiers.length);
        initState();
    }

    public State(int stones,Soldiers[] soldiers){
        this.stones = stones;
        this.soldiers = soldiers;
        paintState();
    }

    public void initState(){
        for(int i=0;i<soldiers.length;i++)
        {
            soldiers[i] = new Soldiers();
            soldiers[i].position =i;
            currentState+="#";
        }
        for(int j=soldiers.length;j<stones;j++)
        {
            currentState+="-";
        }
    }

    private void paintState(){
        for(int j=0;j<stones;j++)
        {
            currentState+="-";
        }
        char[] stateChar = currentState.toCharArray();
        currentState = "";
        for(int i=0;i<soldiers.length;i++){
            stateChar[soldiers[i].position] = '#';
        }
        for(int k=0; k<stateChar.length;k++){
            currentState += stateChar[k];
        }
    }

    public void printState(){
        System.out.println(currentState);
    }
    public ArrayList<State> getNextStates(){
        ArrayList<State> States = new ArrayList<State>();

        for(int i=0;i<soldiers.length;i++){
            Soldiers[] newSoldiers = new Soldiers[soldiers.length];
            for(int j=0;j<soldiers.length;j++){
                newSoldiers[j] = new Soldiers(soldiers[j].position);
            }
            if(!((newSoldiers[i].position+1)==stones))
            {
                if((currentState.charAt((newSoldiers[i].position+1))=='-'))
                {
                newSoldiers[i].move();
                States.add(new State(stones,newSoldiers));
                }
            }

        }
        if(States.size()==0)
        {
            TestSoldiers.count++;
        }
        return States;
    }

}

Soldiers.java
public class Soldiers {

    int position = 0;

    public Soldiers(){
        position =0;
    }

    public Soldiers(int pos){
        position = pos;
    }

    public void move(){
        position ++;
    }
}

TestSoldiers.java
import java.util.LinkedList;
import java.util.Queue;

public class TestSoldiers {

    public static int count=0;

    public static void main(String[] args){

        TestSoldiers t = new TestSoldiers();
    }
    public TestSoldiers()
    {
        State s = new State(10,3);
        breadthFirstTraversal(s);
        System.out.println(count);
    }

    public void breadthFirstTraversal(State rootNode){

        Queue<State> q = new LinkedList<State>();
        q.add(rootNode);
        while(!q.isEmpty()){
            State n = (State)q.poll();
            n.printState();
            for(State adj : n.getNextStates()){

                        q.add(adj);

                }

            }
        }

}

How can I make it so that I will only consider each State once while maintaining the integrity of the total number of ways to end (counts in TestSoldiers.java)?
For those of you who want to modify the parameters, it's the new State(n,k) where n is the number of stones and k is the number of soldiers.

A: Memoization might come in handy.
The idea would be to run depth-first search to count the number of ways to get from the current state to the end, and store this result, then look up the already-calculated value if ever that state is repeated.
For instance, there are 2 ways to reach the end from -#-#-, so, storing this result when we get there via -##--, we could simply look up 2 when we get there via #--#-.
The simplest (but far from most efficient) way to store these would simply be to have a:
Map<Pair<Integer (Position1), Integer (Position2)>, Integer (Count)>

More generically, you could perhaps make that Pair a List.
A more efficient approach would be to have a bitmap where each bit corresponds to whether or not there's a soldier at some given position. So -#-#- would correspond to 01010, which could simply be stored in an int as 10 in decimal - if there are more than 64 stones (i.e. what would fit into a long), you could use a BitSet.

A: You might be better using combinatorics to compute the number of paths.
For example, suppose there are 2 soldiers and 5 steps.
Represent the distance the first soldier has moved by y, and the distance the second soldier has moved by x.
You are trying to count the number of monotonic paths from 0,0 to 3,3 such that y is never greater than x.
This is a well known problem and the answer is given by the Catalan numbers.  In this case, the answer is given by the Catalan number for n=3, which is 5.
When you have more than 2 soldiers you will need to use multidimensional Catalan numbers.  A useful guide and formula can be found on OEIS:

T(m, n) = 0! * 1! * .. * (n-1)! * (m * n)! / ( m! * (m+1)! * .. * (m+n-1)! )

A: My solution runs 10 positions in less than 1 second. The solution is quick and dirty, but the algorithm is what you should be interested in right?
The idea of my algorithm is:

*

*manage a set of paths to compute. start with the path where both soldiers are at the left most positions.

*if the set of paths to compute is not empty pick any path and remove it from the set.

*if the path is terminated (both soldiers are at the most right positions) print the path. continue with 2.

*extend the path by moving the head soldier if possible and put it into the set.

*extend the path by moving the tail soldier if possible and put it into the set.

That's it.
public static void main(String[] args) {
    List<Node> nodes = Node.newRootNode(10);
    while (!nodes.isEmpty()) {
        Node node = nodes.remove(0);
        if (node.isLeaf()) node.printPath();
        else {
            if (node.headSoldierCanMove()) nodes.add(node.moveHeadSoldier());
            if (node.tailSoldierCanMove()) nodes.add(node.moveTailSoldier());
        }
    }
}

static final class Node {

    static List<Node> newRootNode(final int maxPos) {
        return new ArrayList<Node>() {{
            add(new Node(1, 2, maxPos, ""));
        }};
    }

    private final int maxPos;
    private final String path;
    private int tailPos = 1;
    private int headPos = tailPos + 1;

    private Node(int tailPos, int headPos, int maxPos, String path) {
        this.maxPos = maxPos;
        this.tailPos = tailPos;
        this.headPos = headPos;
        this.path = addPath(path);
    }

    boolean tailSoldierCanMove() {
        return tailPos < headPos - 1;
    }

    Node moveTailSoldier() {
        return new Node(tailPos + 1, headPos, maxPos, path);
    }

    boolean headSoldierCanMove() {
        return headPos < maxPos;
    }

    Node moveHeadSoldier() {
        return new Node(tailPos, headPos + 1, maxPos, path);
    }

    void printPath() {
        System.out.println(path);
    }

    boolean isLeaf() {
        return headPos == maxPos && tailPos == headPos - 1;
    }

    private String addPath(String prefix) {
        StringBuilder builder = new StringBuilder(prefix);
        for (int pos = 1; pos <= maxPos; pos++) {
            builder.append(tailPos == pos || headPos == pos ? "#" : "-");
        }
        return builder.append("  ").toString();
    }
}


text:
Q: Java: How to check if a byte[] array exists in a file? I come up an idea to read a byte[] array with the same size of the input, and check one by one. But it seems not very efficient. Is there a way to solve it by using rolling hash?

A: If you are using java 8 or above please check the
java.util.Optional<T>

The documentation is here
Optional
 If I got what you mean correctly


text:
Q: Replace a substring in an HTML formatted string in Perl I need to replace a substring in a HTML string and averything before that substring.
This is the code:
#!/usr/bin/perl -w

$str = "
00820: 1: Line1
00821: 2: Line2
00822: 3: Line3
00823: 4: Line4
00824: 5: Line5
00882: 6: No:6 check
00883: 1: Check1
00883: 1: Check2
00883: 1: Check3
";
$replace = "00882: 6: No:6 check";

$str =~ s/(.*)\Q$replace\E//;

print "str: $str\n";

I need to replace the following substring and everything before:
00882: 6: No:6 check

The result I need is:
str = "00883: 1: Check1
       00883: 1: Check2
       00883: 1: Check3";

The code I have tryed does't work, it replace only the key line, and not everything before that line. Output:
00820: 1: Line1
00821: 2: Line2
00822: 3: Line3
00823: 4: Line4
00824: 5: Line5

00883: 1: Check1
00883: 1: Check2
00883: 1: Check3

A: You're very close; you need the 'treat newlines as regular characters' single-line modifier, s:
$str =~ s/(.*)\Q$replace\E//s;

See: Perl regex modifiers — or perldoc perlre.
(The newline at the start of the output value is the newline after the text to be matched. I had to think about that for a few seconds.)
It is a good idea (though it is not material to your problem) to use use strict; and use warnings; in all your Perl scripts.

A: Your code deletes everything on the same line up to and including the contents of $replace because . matches everything except newlines.
If you mean to delete lines 1 to 5 as well then you need to use the /s modifier on your subtitution, which changes . to match any character at all.
You should also always use strict and use warnings (instead of the -w command-line option) at the top of every Perl program.
Using single quotes removes the need to escape double quotes.
This is what your code should look like
#!/usr/bin/perl

use strict;
use warnings;

my $str = <<'__END_HTML__';
00820: 1: Line1
00821: 2: Line2
00822: 3: Line3
00823: 4: Line4
00824: 5: Line5
00882: 6: No:6 check
00883: 1: Check1
00883: 1: Check2
00883: 1: Check3
__END_HTML__

my $replace = '00882: 6: No:6 check';

$str =~ s/(.*)\Q$replace\E//s;

print "str: $str\n";


text:
Q: How to update target table column value comparing than two source table in SQL server I have two SQL Server source tables. Each table that contains two columns, one is phoneno1 & ID and the other columns are phoneno2 & ID.
First source table has 30k rows and second source table has 1.8 million rows including 20k records out of 30k records from source table1.
I have 100 target tables and each table contains only one column - phoneno.
I need to compare these above two source tables with 100 target tables one by one and if any target tables phoneno values is matched with source tables phoneno1&2 values then I have to overwrite that source table ID column value in to target tables phoneno values.
If not matching then I need to insert that not matching values into one new table that contains two columns phoneno & ID.
How to do achieve in SQL Server?


text:
Q: Prove trigonometric identities in nasm Given to prove trigonometric identity:
cos(fi+theta) = cos(theta)cos(fi)-sin(theta).sin(fi)

The following program written in NASM should print 1 when the identity is verified else 0. I always get 0 as the output. According to me, I think my logic is right. There exists some problem in the loading of memory or stack overflow.
[bits 32]

extern printf
extern _exit

section .data

hello: db "Value =  %d ", 10, 0
theta: dd 1.0
fi: dd 2.0
threshold: dd 1e-1
SECTION .text

global  main                ; "C" main program

main:
start:

; compute cos(theta)cos(fi)-sin(theta).sin(fi)
fld dword [theta]
fcos
fld dword [fi]
fcos
fmul st0,st1
fstp dword [esp]
fld dword [theta]
fsin
fld dword [fi]
fsin
fmul st0,st1
fld dword [esp]
fmul st0,st1
fstp dword [esp]

;compute cos(fi+theta)
fld dword [theta]
fld dword [fi]
fadd st0,st1
fcos

; compare
fld dword [esp]
fsub st0, st1
fld dword [threshold]
fcomi st0, st1
ja .equal
mov eax, 0
jmp .exit

.equal:
    mov eax, 1
.exit:

    mov     dword[ esp ],       hello
    mov     dword [ esp + 4 ],   eax
    call   printf

    ; Call 'exit': exit( 0 );
    mov     dword[ esp ],       0
    call   _exit

A: Testing one value doesn't prove an identity!  If I evaluate x*x and x+x for x=2, does that mean I've proved that x^2 = x+x?
Testing with all possible floats (2^32 of them including NaNs) is a good way to check that a function you've written works properly for all possible corner cases, but floating point numbers still aren't the same thing as mathematical real numbers.  Esp. when the results have significant errors (see below about fsin).
Trying something like this and finding it works for all floats is confirmation that it's worth looking for mathematical proof, not that you've found it.

Also note that on Intel CPUs (and apparently all other x86 CPUs except AMD k5) the fsin insn is not accurate for inputs near Pi.  In the worst case, the error is 1.37 quintillion units in the last place, leaving fewer than four bits correct, according to Bruce Dawson's excellent blog post.  This is due to range-reduction with only a 66 bit Pi constant, and can't be fixed for backwards-compatibility reasons.  (i.e. the exact behaviour of fsin is essentially part of the ISA, warts and all).
The standard add/sub/mul/div/sqrt operations all produce results with at most 0.5 ulp of error (i.e. even the last bit of the mantissa is rounded correctly).
Bruce has a whole series of FP articles, with an index in this one about FP comparisons.  I've added links to some of those articles to the x86 tag wiki, because they have such good info.  They're not all about x87; most of them mention how things are different between x87 and SSE when it matters for current versions of MSVC and/or gcc.

Fun fact: A floating point trig identity:
sin(double(pi)) != 0.0.  You shouldn't expect it to be, because double can't exactly represent the value of the irrational number pi.  However,
 pi ~= double(pi) + sin(double(pi))

(If sin(double(pi)) is evaluated accurately, not with x87 fsin, and you do the addition with more precision than double)
Quoting Bruce Dawson again:

This works because the sine of a number very close to pi is almost equal to the error in the estimate of pi. This is just calculus 101, and a variant of Newton's method, but I still find it charming.

For more, see Bruce's FP comparison article, and search in it for sin(pi).  He has a whole section about this floating-point trig identity.

A: EDIT: Found!
In answer to your question, your code has one instruction wrong: I've added comments...
fld dword [theta]  ; Load theta
fcos               ; Get its cos()
fld dword [fi]     ; Load fi
fcos               ; Get its cos()
fmul st0,st1       ; Multiply them
fstp dword [esp]   ; Store away on stack [Why?]

fld dword [theta]  ; Load theta
fsin               ; Get its sin()
fld dword [fi]     ; Load fi
fsin               ; Get its sin()
fmul st0,st1       ; Multiply them

fld dword [esp]    ; Get what was stored away
fmul st0,st1       ; Multiply them??? [ You meant fsub!]
fstp dword [esp]   ; Store it away

The second-last line should be fsub, not fmul

General comments:
You've got a symbol pi in your code, and it is only set to 3.14 - luckily you don't use it in your code. Still, don't do this: the x87 knows all about pi: FLDPI
Another thing you're doing correctly is comparing against a threshold - still, 1e-1 is a pretty large delta...
You have a much more fundamental problem though, and you mention it when you talk about "stack overflow". Your code is storing values in the (program) stack without making room for them first:
fstp dword [esp]
...
fld dword [esp]
...
mov     dword[ esp ],       hello
mov     dword [ esp + 4 ],   eax
call   printf

This last one could crash your program: esp+4 could be past the top of the stack! If you want to use mov rather than push, you should start your program with sub esp,8 to make room for two dwords first.
And you do know that the x87 already has an internal stack of 8 floating point registers? You can 'save away' values inside that stack while working out other interim results, then get those values back again. Storing them to memory (such as the first line of code above) actually reduces the precision of your interim results.


text:
Q: Access Symbol(_latestValue) of an Observable Array I want to get the value from a observable array myViewModel[index]["Symbol(_latestValue)"]
With "...myViewModel[index]..." I've access of the object. (picture)

I need the value from "Symbol(_latestValue)".
Is there any way to access it ?
To receive the value with "...myViewModel[index]()..." has no effect. result->undefined

A: No. You can't access field with Symbol(key) key. That because Symbol will create unique key each time it called, so unless you obtained that key, you cannot generate it by yourself.
For ex. Symbol('key') !== Symbol('key')
More on that is here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol


text:
Q: Choosing a robust estimator to account for measurement error in dependent variable I have cross-sectional regression model $\hat{Y}_i = a + bX_i + e_i$ estimated over 200 cross-sectional observations. The $\hat{Y}_i$'s were generated in 200 time series regressions, and so has measurement error. Suppose that the measurement error can be modeled by $\hat{Y}_i = Y_i - u_i$, with $u_i \sim N(0,\sigma^2)$. Then we have $Y_i - u_i = a + b X_i + e_i$ ..$\Rightarrow$.. $Y_i = a + b X_i + (e_i + u_i) = Y_i = a + b X_i + \epsilon_i$, where $(e_i + u_i) = \epsilon_i$. This means the diagonal of the residual variance covariance matrix is larger. The variance covariance matrix is given by $\Sigma = E[\epsilon \epsilon^T]$; under this expression, every element of the diagonal in $E[\epsilon \epsilon^T]$ is larger than every diagonal element of $E[e e^T]$. Given the formula for the coefficient variance covariance matrix, the coefficient SEs will be larger from $E[\epsilon \epsilon^T](X^T X)^{-1}$ than from $[e e^T](X^T X)^{-1}$, leading to more abundant type 2 errors.
Another way to express this problem is as follows. Assume that $u_i$ and $e_i$ are uncorrelated, we have $var(e_i + u_i) = var(\epsilon_i) = \sigma_e^2 + \sigma_u^2 > var(e_i) = \sigma_e^2$ ... Our coefficient standard errors will be incorrectly large..
Slide 4 of THIS describes the issue (but gives no prescriptions).
So, what estimator do I use to reduce the instance of weak power/large type 2 errors in this econometric model?

A: It is not necessary to bootstrap in this case.  The issue seems to be error in the X variable although that is not how you described the problem.  If it is an error in variables problem then the remedy is to use the appropriate optimization criterion which is not least squares. Least squares is appropriate when all the error in the observed pairs is due to the Ys.  The answer is to minimize the squared distance in a direction based on the ratio of the error variance in X to the error variance in Y.  If the two error variances are equal this would be to minimize the squared error in the direction orthogonal to the line.  Error in variables regression is covered in a number of texts.
But the way you describe it all the measurement error is in Y and even though you claim to have two sets of errors e$_i$ and u$_i$ each with 0 mean, the residual variance from least squares will estimate the variance of u$_i$ + e$_i$ and you would do nothing different from what you would ordinarily do.
So I think you must not be stating your problem correctly.  In either of these modeling situations you could bootstrap the samples and get bootstrap estimates but if the error distribution is normal and you have either error in variables regression or ordinary least squares regression there is no need to do so.
Having looked at the slides I see that my explanation is correct.  But they claim that they want to estimate the variance of e$_i$ rather than e$_i$ + u$_i$. Unfortunately there is no way to decompose the error to get the estimate.  It is a problem without a solution.


text:
Q: Out of Memory Error Image Loader I have this application that loads images from a web service using the image loader 1.9.3 library and with having phones with low memory the image loader gives out of memory exception that is only visible in the log cat. I don't mind the exception but i want the exception to be visible to the user via a toast so that he knows why the images stopped loading.
Any ideas please

A: your images are too big compared to size of your ImageView.
I recommend you to use Picasso.
with this you can Resize your Image according to your need.
Picasso.with(this).load(image_link)
    .resize(100, 100)
    .placeholder(R.drawable.placeholder)
    .error(R.drawable.placeholder)
    .into(imageView);

Happy Coding.

A: Maybe your images are to big when you downloaded them. A single image with 800 x 600 pixels will be less than 100kb when it comes as JPG as it is compressed. However, when you decode it into an bitmap it will become approx. 2MB of data. When you load 80 books, you will get 160MB of data very soon. Mabye you should load less books (20) or reduce the size of your images from the server.
Usually, logcat prints an Exception which will show you what causes the OutOfMemoryException. When I got this exception it was always caused by too big or too many pictures at a time.

A: Try to add
 android:largeHeap="true"

in your mainfeist file app->Src->Main  folder
<application
    android:name="com.xxxxxxxxxxxxxx"
    android:icon="@drawable/app_icon"
    android:label="@string/app_name"

    android:largeHeap="true"

    android:theme="@style/myAppTheme">

    <activity
        android:name="com.xxxxxxxxxxxxxx"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

To decode file you can use this https://stackoverflow.com/a/823966/4741746
The solution work for me is https://stackoverflow.com/a/13226245/4741746
Let me know if not woking


text:
Q: Sorting a linked list of integers? I have a LinkedList that needs to be sorted (it contains ints), and i don't know how to do that. Can anyone give my the source code to sort an int Linked List?
i tried this code which i found online but it didn't work.
    public void sort(LinkedList sortlist)
{
    //Enter loop only if there are elements in list
    boolean swapped = (head != null);

    // Only continue loop if a swap is made
    while (swapped)
    {
        swapped = false;

        // Maintain pointers
        Node curr = head;
        Node next = curr.link;
        Node prev = null;

        // Cannot swap last element with its next
        while (next != null)
        {
            // swap if items in wrong order
            if (curr.data>next.data)
            {
                // notify loop to do one more pass
                swapped = true;

                // swap elements (swapping head in special case
                if (curr == head)
                {
                    head = next;
                    Node temp = next.link;
                    next.link = curr;
                    curr.link = temp;
                    curr = head;
                }
                else
                {
                    prev.link = curr.link;
                    curr.link = next.link;
                    next.link = curr;
                    curr = next;
                }
            }

            // move to next element
            prev = curr;
            curr = curr.link;
            next = curr.link;
        }
    }
}

A: There is a C++ implementation of merge sort on linked lists given in this handout for Stanford's CS106B course.  It runs in time O(n log n), which is quite good.
For a survey of other approaches, check out this older SO answer on how to sort linked lists.  There's no code there, but there are good descriptions of how to adapt existing ideas to work on linked lists.
Hope this helps!

A: Merge sort and quick sort can be used to sort llink-lists ( average O(n.long)) in place. In addition if your numbers are integers, there is a variation of radix sort which work O(n) and it is in place. So you do not meet to convert the link list to an array.
Here is info for the implementation in STL: http://www.cplusplus.com/reference/list/list/sort/


text:
Q: Why do we say function "parameterized by" vs just function of (x,y,z,...)? I'm studying statistics, and in a lot of textbooks, the regression formulas always refers to the functions themselves as f(x) parameterized by a,b,c or something. And they are often written $f(x; a,b,c)$, why can't we just write $f(x, a, b, c)$?
I would like to know perhaps the history of how this came about, and why there is this seemingly dual method of expressing the same idea. Is there some esoteric mathematical notation that a noob like me hasn't encountered yet, or did mathematicians of old just like doing things in different ways?
An example: A function that maps age of tree to height:
$$f(age; growth\_rate) = age * growth\_rate$$ vs $$f(age, growth\_rate) = age * growth\_rate$$

A: Think to something like this: $f(x;\sigma) = e^{-x^2/\sigma^2}$.
If you read for example "the derivative of $f$" probably you immediately undestand that we are speaking of $\partial f/\partial x$ because you recognize $f$ as a function of $x$, whose definition contains some $\sigma$ which is not a "variable".
Otherwise if you read:
$f(x, \sigma) = e^{-x^2/\sigma^2}$
a sentence like "the derivative of $f$" would be ambiguous: it's $\partial f/\partial x$? $\partial f/\partial \sigma$? $\nabla f = (\partial f/\partial x, \partial f/\partial \sigma)$?
So without this distinction every time one has to write explicitly "the derivative of $f$ with respect to the variable $x$".

A: In fact there is a formal distinction between parameter and argument, which captures our subjective view.
Let $P$ be the parameter space (set of growth rates), $X$ the domain (set of ages) and $Y$ the codomain (set of heights). A family of functions from $X$ to $Y$ parameterised by $P$ is formally a function $f: P \rightarrow Y^X$, where $Y^X$ is the set of functions from $X$ to $Y$.
In other words, it is a function taking growth rates and returning maps from ages to heights.
Of course, you are correct that this naturally and uniquely corresponds to a function $F: P \times X \rightarrow Y$, that is, a function taking a growth rate and an age and returning a height. This natural isomorphism is succintly denoted by
$$ \left( Y^X \right)^P \approx Y^{P \times X}$$

A: Strictly speaking you're right. It's sometimes difficult to explain clearly what is a parameter and what is a variable. When you write $f(x;a,b,c)$, there is no mathematical difference between $x$ and $a$ for example, they're both variables for the function $f$. I think the real difference is in how we interpret things. When we have an expression such as $f(x;\theta)$ or $f_\theta(x)$, $x$ and $\theta$ don't exactly play the same role, that's why we use different notations for them. In fact it's for the sake of clarity. When you have lots of different variables in an expression, using different notations is an easy way to know what role they play.
In the framework of statistics, the notion of parameter is even more important. As you may know, there's a whole branch of statistics called parametric statistics, where we introduce families of probability distributions, indexed by a set of parameters:
$$\mathcal{P}=\{P_\theta,\theta\in\Theta\}$$
where $\Theta$ is some subset of $\mathbb{R}^d$.
Note that you could actually see this as a function from $\Theta$ to the set of probability distributions on a certain space. In many cases, $P_\theta$ has a density w.r.t. the Lebesgue measure, and we denote it by $f(x;\theta)$ or $f_\theta(x)$. You see in this example that $x$ and $\theta$ have very different meanings. $\theta$ is the parameter that comes from our statistical model, whereas $x$ is a variable of integration.
In other cases, we use the "opposite" notation. For example when you consider the likelihood function $l(\theta;x_1,\dots,x_n)$, we consider it primarily as a function of $\theta$ (that we want to maximize most of the time), and $x_1,\dots,x_n$ as fixed parameters (they are the observation, we can't change them). Once again, it's a question of context and meaning of the variables.

A: The area where I am used to seeing parameterizations is when considering curves and similar geometric objects. Consider a curve drawn in $\mathbb{R}^3$, this is just a set of points and initially is not a function of any kind. But we can in fact make it into the image of a function by defining a mapping $f:[0,1] \rightarrow \mathbb{R}^3$ which 'traces' the curve as the input variable goes from 0 to 1. So in this context a parameterization means taking an object that is just a subset of a given space and defining a mapping whose image is the object we are interested in. The inportant thing here is that the choice of this mapping is arbirtrary, in that there are an infinite number of different functions we could define whose image would be our object of study. Hence calling it a parameterization really is indicating that we have chosen a suitable functional description, but indicates that it is not unique.
This seems the same as for the function example you give, as there are any number of ways of taking the heights of trees and defining functions which map to these correctly for each tree. So your semicolon notation appears to simply be saying that this function has been chosen to use growth rate along with the fixed age input in order to define height, but is indicating that there were other choices you could have made instead.

A: While the answers already given are correct, I suspect that they may be bringing in terminology and notations you are unfamiliar with. If so, let me try to recast the answer more simply.
You are correct that $f(x; a, b, c)$ is the exact same thing as $f(x, a, b, c)$. But the difference is in how we are using $x$ vs how we are using $a, b, c$. With $f(x, a, b, c)$, all four values are equally important, equally of interest. With the former, we are considering $f$ as a function of $x$ only. $a, b, c$ are simply values that we use in defining that function. By making these values variables too, the mathematics we do applies to all the different functions of $x$ that are defined by the various possible values of $a, b, c$, instead of having to work each particular example we need separately.
For example, when talking of linear functions, we will write things such as $$y = mx + b$$ You could consider this as defining $y$ as a function of three variables, $x, m, b$, but what is important is the dependence of $y$ on $x$. The slope $m$ and intercept $b$ are just values expressing which line is represented by the relationship between $y$ and $x$. So if want to find the root for $y = 0$, that is $x = \frac{-b}{m}$, not $b = -mx$ or $m = \frac{-b}x$.
That is what the notation $f(x; a, b, c)$ means. It is just telling you that $x$ is the one whose variance is important to us. The others we are going to consider fixed (although not currently known) values.


text:
Q: Postgres: Why is my delete query using up all available disk space? I have a postgres table set up like so:
                                                           Table "public.facts"
   Column    |           Type           | Collation | Nullable |              Default              | Storage  | Stats target | Description
-------------+--------------------------+-----------+----------+-----------------------------------+----------+--------------+-------------
 id          | integer                  |           | not null | nextval('facts_id_seq'::regclass) | plain    |              |
 value       | character varying(100)   |           |          |                                   | extended |              |
 measured_at | timestamp with time zone |           | not null |                                   | plain    |              |
 received_at | timestamp with time zone |           |          |                                   | plain    |              |
 written_at  | timestamp with time zone |           |          |                                   | plain    |              |
 is_numeric  | boolean                  |           |          |                                   | plain    |              |
 source_id   | character varying(100)   |           |          |                                   | extended |              |
 site_id     | integer                  |           |          |                                   | plain    |              |
Indexes:
    "facts_measured_at_idx" btree (measured_at DESC)
    "facts_source_id_measured_at_idx" btree (source_id, measured_at)
    "idx_source_id_measured_at" btree (source_id, measured_at)
Foreign-key constraints:
    "facts_site_id_fkey" FOREIGN KEY (site_id) REFERENCES site(id)
    "facts_source_id_fkey" FOREIGN KEY (source_id) REFERENCES source(id)
Triggers:
    ts_insert_blocker BEFORE INSERT ON facts FOR EACH ROW EXECUTE FUNCTION _timescaledb_internal.insert_blocker()
Child tables: _timescaledb_internal._hyper_1_100_chunk,
              _timescaledb_internal._hyper_1_101_chunk,
              _timescaledb_internal._hyper_1_102_chunk,
              _timescaledb_internal._hyper_1_103_chunk,
              _timescaledb_internal._hyper_1_104_chunk,
              _timescaledb_internal._hyper_1_105_chunk,
              _timescaledb_internal._hyper_1_106_chunk,
              _timescaledb_internal._hyper_1_107_chunk,
              _timescaledb_internal._hyper_1_108_chunk,
              _timescaledb_internal._hyper_1_109_chunk,
              _timescaledb_internal._hyper_1_110_chunk,
              _timescaledb_internal._hyper_1_111_chunk,
              _timescaledb_internal._hyper_1_112_chunk,
              _timescaledb_internal._hyper_1_113_chunk,
              _timescaledb_internal._hyper_1_114_chunk,
              _timescaledb_internal._hyper_1_115_chunk,
              _timescaledb_internal._hyper_1_116_chunk,
              _timescaledb_internal._hyper_1_117_chunk,
              _timescaledb_internal._hyper_1_118_chunk,
              _timescaledb_internal._hyper_1_119_chunk,

Recently a bug was introduced that caused an infinite loop and many thousands of duplicate rows were written. I want to delete those duplicate rows and I'm using the following query:
DELETE FROM facts a USING facts b WHERE a.id > b.id AND a.source_id = b.source_id AND a.measured_at = b.measured_at AND a.value = b.value;

Disk usage prior to running the query:
ubuntu@ip-xx-xx-xx-xx:~$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev             32G     0   32G   0% /dev
tmpfs           6.3G  844K  6.3G   1% /run
/dev/nvme0n1p1   49G  8.5G   40G  18% /
tmpfs            32G   44K   32G   1% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs            32G     0   32G   0% /sys/fs/cgroup
/dev/loop0       29M   29M     0 100% /snap/amazon-ssm-agent/2012
/dev/loop1       98M   98M     0 100% /snap/core/10126
/dev/loop2       98M   98M     0 100% /snap/core/10185
/dev/nvme1n1p1  3.9T  181G  3.5T   5% /mnt                <-- database on this volume
tmpfs           6.3G     0  6.3G   0% /run/user/1000

disk usage 3 days after executing the query (still running):
ubuntu@ip-xx-xx-xx-xx:~$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev             32G     0   32G   0% /dev
tmpfs           6.3G  836K  6.3G   1% /run
/dev/nvme0n1p1   49G  8.5G   40G  18% /
tmpfs            32G   44K   32G   1% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs            32G     0   32G   0% /sys/fs/cgroup
/dev/loop0       29M   29M     0 100% /snap/amazon-ssm-agent/2012
/dev/loop1       98M   98M     0 100% /snap/core/10126
/dev/loop2       98M   98M     0 100% /snap/core/10185
/dev/nvme1n1p1  3.9T  3.2T  527G  86% /mnt              <-- database on this volume
tmpfs           6.3G     0  6.3G   0% /run/user/1000

Nothing is being written to or read from the database while this query is executing. Most of the extra storage is in /mnt/postgres/12/main/base/pgsql_tmp. Why does it take >3TB to delete less than 200GB?
Please let me know if there's any other info I can provide.

A: It turns out all the extra child tables/chunks created by timescaledb were making this query run wild; running EXPLAIN as Schwern suggested was what keyed me into this. So here's what I ended up doing:
-- copy the table without any of the extra indices or child tables
CREATE TABLE facts_copy AS TABLE facts;

-- re-run the delete query, took about 23 hours, deleted 369225431 / 619858486 rows
DELETE FROM facts_copy a USING facts_copy b WHERE a.id > b.id AND a.source_id = b.source_id AND a.measured_at = b.measured_at AND a.value = b.value;

-- add fkeys and unique index so this can't happen again
ALTER TABLE facts_copy ADD CONSTRAINT facts_site_id_fkey FOREIGN KEY (site_id) REFERENCES site(id);
ALTER TABLE facts_copy ADD CONSTRAINT facts_source_id_fkey FOREIGN KEY (source_id) REFERENCES source(id);
CREATE UNIQUE INDEX unique_idx_source_id_measured_at ON facts_copy(source_id,measured_at);

-- drop the old table and rename the new one
DROP TABLE facts;
ALTER TABLE facts_copy RENAME TO facts;

-- re-create the hypertable
SELECT create_hypertable('facts','measured_at',migrate_data=>true);


text:
Q: UIRefreshControl crashes on Xamarin iOS This should not be a problem at all, looking at all the answers out there on Stackoverflow, but I just can't find out how to do this with a UITableView (not a TableViewController). I use the following code
 if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0))
 {
    _refreshControl = new UIRefreshControl();
    _refreshControl.ValueChanged += OnRefreshRequested;
    ResultsTableView.RefreshControl = _refreshControl;
 }

and noticed that there's a warning saying that the line
ResultsTableView.RefreshControl = _refreshControl;

Is only available in API 10 and above? I thought this might be one of Xamarin Studios many quirks, but saw that it actually does crash on any OS version less than 10. With exception
NSInvalidArgumentException', reason: '-[UITableView setRefreshControl:]:
unrecognized selector sent to instance 0x15f420c00'

I would just like some help on how I can add a refresh control too my UITableView in OS versions lower than 10.
Thank you.

A: Hopefully this will help out anyone who is still trying to figure this out.  I had to declare the following at the top of my ViewController
UIRefreshControl refreshControl;

Then I did the following where I was trying to set up the refresh control:
refreshControl = new UIRefreshControl();
refreshControl.AddTarget((sender, args) => GetData(), UIControlEvent.ValueChanged);

if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
    TableView.RefreshControl = refreshControl;
} else {
    TableView.AddSubview(refreshControl);
}

Then instead of referencing the RefreshControl on TableView I just have to reference refreshControl

A: Apple docs:

Because the refresh control is specifically designed for use in a table view that's managed by a table view controller, using it in a different context can result in undefined behavior.
SDK iOS 6.0+


text:
Q: installing lxml on the hosting server for python I had been using mikemaccana-python-docx module for reading from and writing to doc files in python. Now I had to move this feature to hosting server. Can any body suggest a way to install lxml on the hosting server to do the same

A: On Windows
And on Ubuntu
sudo apt-get install python-lxml

A: sudo apt-get install python-lxml

or sudo pip install lxml
be sure the libxml-dev installed


text:
Q: Have my web app product listing shown in Google search I have an e-commerce web app. I would like to have any user searching for a product in google search to have my web app within search results including the product.
If a user searches for Play Station for example he would get amazon etc and my web app as a result showing the searched for product.
What do I need to do from my end to have my web app listed in google searches for products.
Appreciate your help...
I did some my home work but failed to find a way to reach the above requirement.


text:
Q: Net Framework Xunit With Moq Unit Testing Keep Calling The Original Function I have a problem with mocking cause it keep calling the original function. This is my demo code
First file is interface that contains the function that I want to mock.
public interface IDemoReplace
{
    int FunctionToBeReplaced();
}

Second file is a class that actually has the implementation for the function
public class DemoReplace : IDemoReplace
{
    public int FunctionToBeReplaced()
    {
        //this function contains sql query in my real project
        return 1;
    }
}

Third file is a class that I want to test
public class ClassToBeTested
{
    public int TestThisFunction()
    {
        IDemoReplace replace = new DemoReplace();
        var temp = replace.FunctionToBeReplaced();
        return temp;
    }
}

Last file is the test class
public class TestClass
{

    [Fact]
    public void TryTest()
    {
        using (var mock = AutoMock.GetLoose()) {
            //Arrange
            mock.Mock<IDemoReplace>()
                .Setup(x => x.FunctionToBeReplaced())
                .Returns(returnTwo());

            var classToBeTested = mock.Create<ClassToBeTested>();
            var expected = 2;

            //Act
            var actual = classToBeTested.TestThisFunction();

            //Assert
            Assert.Equal(expected, actual);
        }
    }

    public int returnTwo() {
        return 2;
    }
}

This test will be failed with expected is 2 and actual is 1. When I tried to debug it doesn't call returnTwo but call the original function instead.
I am new to unit testing so what did I miss? Please be considered that the code above is only a demo of what is happened in my actual project. FunctionToBeReplaced is actually a function that execute and return record from database so I want to mock that function.
Thanks :)

A: This is a design issue. The subject under test is tight coupled to implementation concerns that make it difficult to isolation the subject so that it can be unit tested.
It (subject) is manually creating its dependency
IDemoReplace replace = new DemoReplace();

Ideally you want to explicitly inject dependencies. Those dependencies should also be abstractions and not concretions.
public class ClassToBeTested {
    private readonly IDemoReplace dependency;

    public ClassToBeTested(IDemoReplace dependency) {
        this.dependency = dependency;
    }

    public int TestThisFunction() {            ;
        var temp = dependency.FunctionToBeReplaced();
        return temp;
    }
}

At run time, the implementation (or mock) can be injected, either purely, or via a container.
The test in the original example shown should now behave as expected.
public class TestClass {
    [Fact]
    public void TryTest() {
        using (var mock = AutoMock.GetLoose()) {
            //Arrange
            var expected = returnTwo();
            mock.Mock<IDemoReplace>()
                .Setup(x => x.FunctionToBeReplaced())
                .Returns(expected);

            var classToBeTested = mock.Create<ClassToBeTested>();

            //Act
            var actual = classToBeTested.TestThisFunction();

            //Assert
            Assert.Equal(expected, actual);
        }
    }

    public int returnTwo() {
        return 2;
    }
}


text:
Q: Syntax and Sample Usage of _Generic in C11 I heard C11 added generics. I've googled a bit, looked at some articles, understood there's a new keyword ( _Generic ) and all. But I can't seem to grasp it all.
Is it something like the generics in C# or templates in C++? Can anyone give me a brief explanation of the C11 definition of generics, its syntax and a simple sample usage example?

A: This is a pretty good introduction. Here's the Overview:

Generic selection is implemented with a new keyword: _Generic. The syntax is similar to a
  simple switch statement for types:_Generic( 'a', char: 1, int: 2, long: 3, default: 0)
  evaluates to 2 (character constants are ints in C).

Basically it works like a kind of switch, where the labels are type names which are tested against the type of the first expression (the 'a' above). The result becomes the result of evaluating the _Generic().

A: I use CLion 1.2.4, and CLion doesn't support C11 now, so I use following code in GNU C99 instead of _Generic
#include <stdio.h>

int main(int argc, char **argv) {
    char *s;
    if (__builtin_types_compatible_p(__typeof__(s), long)) {
        puts("long");
    } else if (__builtin_types_compatible_p(__typeof__(s), char*)) {
        puts("str");
    }
    return (0);
};

A: The best example I have seen inspired the following (runnable) example, which unlocks all sorts of freaky possibilities for cracked-out introspection...
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>

#define typename(x) _Generic((x),        /* Get the name of a type */             \
                                                                                \
        _Bool: "_Bool",                  unsigned char: "unsigned char",          \
         char: "char",                     signed char: "signed char",            \
    short int: "short int",         unsigned short int: "unsigned short int",     \
          int: "int",                     unsigned int: "unsigned int",           \
     long int: "long int",           unsigned long int: "unsigned long int",      \
long long int: "long long int", unsigned long long int: "unsigned long long int", \
        float: "float",                         double: "double",                 \
  long double: "long double",                   char *: "pointer to char",        \
       void *: "pointer to void",                int *: "pointer to int",         \
      default: "other")

#define fmt "%20s is '%s'\n"
int main() {

  size_t s; ptrdiff_t p; intmax_t i; int ai[3] = {0}; return printf( fmt fmt fmt fmt fmt fmt fmt fmt,

     "size_t", typename(s),               "ptrdiff_t", typename(p),
   "intmax_t", typename(i),      "character constant", typename('0'),
 "0x7FFFFFFF", typename(0x7FFFFFFF),     "0xFFFFFFFF", typename(0xFFFFFFFF),
"0x7FFFFFFFU", typename(0x7FFFFFFFU),  "array of int", typename(ai));
}

                 ╔═══════════════╗
═════════════════╣ Amazeballs... ╠═════════════════════════════════════
                 ╚═══════════════╝
            size_t is 'unsigned long int'
         ptrdiff_t is 'long int'
          intmax_t is 'long int'
character constant is 'int'
        0x7FFFFFFF is 'int'
        0xFFFFFFFF is 'unsigned int'
       0x7FFFFFFFU is 'unsigned int'
      array of int is 'other'


text:
Q: Apply CSS to certain list items Problem: In the continuation of the solution provided by @potame in my previous question Table of contents XSL, I would like to know if there's someway of not applying the CSS style to certain list items. The CSS provided was the following:

Following the reasoning of the table of contents also provided by @potame in the previous question,I've made the XSL template for processing the chapters, sections, subsections and subsubsections:
<xsl:template match="t:chapter">

       <xsl:value-of select="t:title"/>

        <xsl:apply-templates select="*[not(self::t:title)]"/>

</xsl:template>

<xsl:template match="t:section">

        <xsl:value-of select="t:title"/>

        <xsl:apply-templates select="*[not(self::t:title)]"/>

</xsl:template>

<xsl:template match="t:subsection">

        <xsl:value-of select="t:title"/>

        <xsl:apply-templates select="*[not(self::t:title)]"/>

</xsl:template>

<xsl:template match="t:subsubsection">

        <xsl:value-of select="t:title"/>

    <xsl:apply-templates select="*[not(self::t:title)]"/>

</xsl:template>

And the following is the template for processing lists and paragraphs, that can appear in the content:
<xsl:template match="list:ol">

        <xsl:apply-templates/>

</xsl:template>

<xsl:template match="list:ul">

        <xsl:apply-templates/>

</xsl:template>

<xsl:template match="list:li/p:p">

        <xsl:apply-templates/>

</xsl:template>

<xsl:template match="p:p">

        <xsl:apply-templates/>

</xsl:template>

The problem is, when I have list items in the content, HTML result appears like this:
Chapter 1
   1.1. Motivation

        ...some text...

        Example list:

        1.1.0.1. text
        1.1.0.2. tex
        1.1.0.3. text
        1.1.0.4. text

And the desired result in HTML is this:
Chapter 1
   1.1. Motivation

        ...some text...

        Example list:

        1. text
        2. text
        3. text
        4. text

Which basically means I want "normal ordered lists" instead of appearing like it was a subsubsubsection or something...
Any suggestions?

A: I think the easiest way is to set classes to all
 related to your toc, and apply specific CSS styles to them (similarly to what I have done on the chapter). It will help you refine the styles to be applied.
Assuming you set in your XSLT class="tocentrynumbered" attribute on all
s related to a section, subsection, and so on, you can use the following modified CSS:
body {
     text-align: justify;
}
ol, ul {
     counter-reset: item;
}
li.chapter::before {
     content: "";
}
li.tocentrynumbered {
     display: list-item;
     list-style-type: none;
}
li.tocentrynumbered:before {
    content: counters(item, ".") ". ";
    counter-increment: item;
}

Therefore it won't affect the other list items you use in the document.


text:
Q: Cómo mostrar la frecuencia de la longitud de un string? Estoy confrontando un problema con este problema. El resultado está bien pero no se valida porque corre muy lentamente :-(
He aquí el problema:
Al estudiar diferentes tipos de textos (novelas, leyes, artículos periodísticos ...), nos damos cuenta de que no solo las palabras utilizadas no son las mismas, sino que sus longitudes son estadísticamente diferentes: por ejemplo, es mucho más común encontrar palabras largas y complejas en un artículo de ley que en un libro para niños.
Para intentar determinar automáticamente a qué categoría pertenece un libro, queremos determinar el número de palabras de 1 letra, 2 letras, 3 letras ... que contiene.
Restricciones
    • El texto contiene un conjunto de palabras, separadas por espacios, sin puntuación.
    • Cada palabra contiene como máximo 100 caracteres.
Entrada
    • La primera línea contiene dos enteros: num_lineas y num_palabras.
Salida
Para cada longitud de palabra posible, y solo si hubiera palabras de esta longitud en el texto, debe mostrar en una línea la longitud y el número de palabras de esa longitud, separado por dos puntos (debe colocarse un espacio a cada lado de los dos puntos).
Ejemplo:
Entrada
2 7
Salida
2 : 2
3 : 3
4 : 4
5 : 3
7 : 2
Mi programa:

num_lineas, num_palabras = map(int, input().split())
palabras = []
long_palabras = []
long = 0

for i in range(num_lineas):
   palabras.append(input().split())
   li_palabras = sum(palabras,[])

for i in range(len(li_palabras)):
   long_palabras.append(len(li_palabras[i]))
   long_palabras.sort()

for i in long_palabras:
   ol_long_palabras = long_palabras.count(i)
   if i > long:
      lng = i
      print(long,":",ol_long_palabras)

Gracias de antemano por tu respuesta :-)

A: Cuestiones dudosas en el código
¿Para qué la lista li_palabras? Le asignas valores dentro de un bucle mediante la línea:
   li_palabras = sum(palabras,[])

pero ya que palabras es la lista de palabras encontradas hasta ese momento y mediante sum() le añades una lista vacía, el resultado es equivalente a haber hecho li_palabras = palabras. Además en cada iteración del bucle le estás cambiando el valor. Por suerte, ya que palabras va almacenando todas las palabras encontradas hasta ese momento, no se pierde ninguna. Pero lo mismo podrias hacer con el código siguiente, acumulando los resultados en li_palabras en vez de en palabras:
li_palabras = []
for i in range(num_lineas):
   li_palabras.extend(input().split())

El siguiente bucle que haces:
for i in range(len(li_palabras)):
   long_palabras.append(len(li_palabras[i]))
   long_palabras.sort()

es para crear otra lista que contenga las longitudes de las palabras. El bucle es más pythónico (y fácil de leer) si iteras por las propias palabras en lugar de por sus índices. Además no tiene sentido que llames a sort() en cada iteración del bucle. Mejor te esperas a haber creado la lista completa y llamas a sort() después. Así:
for palabra in li_palabras:
   long_palabras.append(len(palabra))
long_palabras.sort()

Finalmente el tercer bucle es el más ineficiente:
for i in long_palabras:
   ol_long_palabras = long_palabras.count(i)
   if i > long:
      lng = i
      print(long,":",ol_long_palabras)

Ya que en long_palabras tendrás la longitud de cada una de las palabras introducidas, es decir, si se han introducido 1000 palabras esta lista tendrá 1000 números, el bucle se estaría repitiendo todas esas veces.
En cada repetición del bucle haces un long_palabras.count(i), que obliga a recorrer de nuevo todos los elementos de la lista (en un bucle implícito que Python hará por tí). ¿Por qué es eso? Imagina que el primer elemento del array es 3. Eso significa que la primera palabra leída tenía 3 letras. Pero long_palabras.count(3) le está pidiendo a Python "dame cuántos elementos de esta lista valen 3". Para responder a esa pregunta Python debe recorrer toda la lista.
Si el siguiente elemento de la lista vuelve a ser 3, de nuevo estarías re-contando cuántas veces aparece el 3. Y esto lo haces para cada número en long_palabras. Si long_palabras tenía 1000 elementos, ya que en cada iteración del bucle llamas a .count(), que se ve obligado a recorrer otra vez los 1000 elementos, al final tienes dos bucles anidados que acceden 1000000 de veces a la lista.
Después tienes un if i > long para imprimir ese resultado, pero esa condición es siempre cierta ya que nunca cambias de valor a long, sino a lng (una errata)
Una alternativa más sencilla
En el segundo bucle en que vas computando las longitudes de cada palabra, ya podemos aprovechar para ir contando cuantas veces aparece cada longitud, ahorrándonos así el tercer e ineficiente bucle.
Por ejemplo podemos tener un diccionario cuyas claves serán las longitudes de las palabras y los valores el número de veces que aparece esa longitud. Inicialmente el diccionario estará vacío. Cada vez que encontramos una palabra de longitud n, si esa clave ya existía en el diccionario, incrementamos su valor. Si no existía la añadimos con un valor de 1. Así:
cuenta = {}
for palabra in li_palabras:
   long_palabra = len(palabra)
   if long_palabra in cuenta:
       cuenta[long_palabra] += 1
   else:
       cuenta[long_palabra] = 1

A la salida de este bucle el diccionario podría tener por ejemplo este valor:
{ 1: 3, 2: 1, 3: 2, 5: 1, 7: 1 }

que significa "de longitud 1 hay 3 palabras, de longitud 2 hay una, etc..." Ya sólo te queda recorrer este diccionario con cuenta.items() para mostrar el resultado. De momento te lo dejo a tí, si tienes dudas pregunta de nuevo en un comentario.


text:
Q: How to animate endless loop using jquery? I have been trying using jquery animate to do a running text. But I can't seems to get it run in an endless loop. It always runs one time only..

/*  js:  */

$(document).ready(function(){
  function scroll() {
    $('.scroll').animate({
      right: $(document).width()
    }, 8000, scroll);
  }
  scroll();
});
/* css: */

.scroll {
  position: absolute;
  right: -200px;
  width: 200px;
}

This text be scrollin'!

This is the demo:
https://jsfiddle.net/y9hvr9fa/1/
Do you guys know how to fix it?

A: So this is what I did:

*

*Precalculate $(document).width() as if a horizontal scroll appears, the width will change in the next iteration

*Remove the width you have set for scroll so that the width is only as long as the content - and you would have to give white-space:nowrap to keep the text in a line.

*In the animate use the width of the scroll text using $('.scroll').outerWidth()
See demo below and update fiddle here

$(document).ready(function() {

  // initialize
  var $width = $(document).width();
  var $scrollWidth = $('.scroll').outerWidth();
  $('.scroll').css({'right': -$scrollWidth + 'px'});

  // animate
  function scroll() {
    $('.scroll').animate({
      right: $width
    }, 8000, 'linear', function() {
      $('.scroll').css({'right': -$scrollWidth + 'px'});
      scroll();
    });
  }
  scroll();
});
body {
  overflow: hidden;
}
.scroll {
  position: absolute;
  white-space: nowrap;
}

This text be scrollin'!

Let me know your feedback on this, thanks!

A: CSS Alternative:
Alternatively you could use a CSS transition like in this CodePen:
https://codepen.io/jamesbarnett/pen/kfmKa
More advanced:

$(document).ready(function(){
    var scroller = $('#scroller'); // scroller $(Element)
    var scrollerWidth = scroller.width(); // get its width
    var scrollerXPos = window.innerWidth; // init position from window width
    var speed = 1.5;
    scroller.css('left', scrollerXPos); // set initial position

    function moveLeft() {
     if(scrollerXPos <= 0 - scrollerWidth) scrollerXPos = window.innerWidth;
     scrollerXPos -= speed;
      scroller.css('left', scrollerXPos);
      window.requestAnimationFrame(moveLeft);
    }
  window.requestAnimationFrame(moveLeft);
});
.scroll {
  display: block;
  position: absolute;
  overflow: visible;
  white-space: nowrap;
}

This text be scrollin'!

Dirty solution (my original answer):
In this example this would be a quick fix:
The text is running to the left without ever stopping. Here you will tell the text to always start at that position. (After the time has run up - meaning not necessarily just when it has left the screen)
$(document).ready(function(){
    function scroll() {
      $('.scroll').css('right', '-200px').animate({
         right: $(document).width()
      }, 8000, scroll);
    }
    scroll();
});

A:
I have been trying using jquery animate to do a running text.

You know that the <marquee> HTML element works, right?
Which means you don't need CSS, Javascript or jQuery.

Pure HTML Solution:

<marquee>This text be scrollin'!</marquee>

The <marquee> element includes a large number of optional declarative attributes which control the behaviour of the scrolling text:

*

*behavior

*bgcolor

*direction

*height

*hspace

*loop

*scrollamount

*scrolldelay

*truespeed

*vspace

*width

Further Reading:

*

*https://developer.mozilla.org/en-US/docs/Web/HTML/Element/marquee
Note 1:
The resource above correctly notes that:

This feature is no longer recommended. Though some browsers might
still support it, it may have already been removed from the relevant
web standards, may be in the process of being dropped, or may only be
kept for compatibility purposes.

Note 2
The same resource also recommends:

see the compatibility table at the bottom of this page to guide your decision

And... a cursory look at that compatibility table shows that the <marquee> element is as browser-compatible as the most established, most browser-compatible elements which exist today.

A: I hope it is useful  :)

function start() {
    new mq('latest-news');
    mqRotate(mqr);
}
window.onload = start;

function objWidth(obj) {
    if (obj.offsetWidth) return obj.offsetWidth;
    if (obj.clip) return obj.clip.width;
    return 0;
}
var mqr = [];
function mq(id) {
    this.mqo = document.getElementById(id);
    var wid = objWidth(this.mqo.getElementsByTagName("span")[0]) + 5;
    var fulwid = objWidth(this.mqo);
    var txt = this.mqo.getElementsByTagName("span")[0].innerHTML;
    this.mqo.innerHTML = "";
    var heit = this.mqo.style.height;
    this.mqo.onmouseout = function () {
        mqRotate(mqr);
    };
    this.mqo.onmouseover = function () {
        clearTimeout(mqr[0].TO);
    };
    this.mqo.ary = [];
    var maxw = Math.ceil(fulwid / wid) + 1;
    for (var i = 0; i < maxw; i++) {
        this.mqo.ary[i] = document.createElement("div");
        this.mqo.ary[i].innerHTML = txt;
        this.mqo.ary[i].style.position = "absolute";
        this.mqo.ary[i].style.left = wid * i + "px";
        this.mqo.ary[i].style.width = wid + "px";
        this.mqo.ary[i].style.height = heit;
        this.mqo.appendChild(this.mqo.ary[i]);
    }
    mqr.push(this.mqo);
}
function mqRotate(mqr) {
    if (!mqr) return;
    for (var j = mqr.length - 1; j > -1; j--) {
        maxa = mqr[j].ary.length;
        for (var i = 0; i < maxa; i++) {
            var x = mqr[j].ary[i].style;
            x.left = parseInt(x.left, 10) - 1 + "px";
        }
        var y = mqr[j].ary[0].style;
        if (parseInt(y.left, 10) + parseInt(y.width, 10) < 0) {
            var z = mqr[j].ary.shift();
            z.style.left = parseInt(z.style.left) + parseInt(z.style.width) * maxa + "px";
            mqr[j].ary.push(z);
        }
    }
    mqr[0].TO = setTimeout("mqRotate(mqr)", 20);
}
.marquee {
      position: relative;
      overflow: hidden;
      text-align: center;
      margin: 0 auto;
      width: 100%;
      height: 30px;
      display: flex;
      align-items: center;
      white-space: nowrap;
    }

    #latest-news {
      line-height: 32px;
      a {
        color: #555555;
        font-size: 13px;
        font-weight: 300;
        &:hover {
          color: #000000;
        }
      }
      span {
        font-size: 18px;
        position: relative;
        top: 4px;
        color: #999999;
      }
    }

        •
      one Lorem ipsum dolor sit amet
        •
      two In publishing and graphic design
        •
      three Lorem ipsum is a placeholder text commonly

A: How is this?

.scroll {
 height: 50px;
 overflow: hidden;
 position: relative;
}
.scroll p{
 position: absolute;
 width: 100%;
 height: 100%;
 margin: 0;
 line-height: 50px;
 text-align: center;
 -moz-transform:translateX(100%);
 -webkit-transform:translateX(100%);
 transform:translateX(100%);
 -moz-animation: scroll 8s linear infinite;
 -webkit-animation: scroll 8s linear infinite;
 animation: scroll 8s linear infinite;
}
@-moz-keyframes scroll {
 0%   { -moz-transform: translateX(100%); }
 100% { -moz-transform: translateX(-100%); }
}
@-webkit-keyframes scroll {
 0%   { -webkit-transform: translateX(100%); }
 100% { -webkit-transform: translateX(-100%); }
}
@keyframes scroll {
 0%   {
 -moz-transform: translateX(100%);
 -webkit-transform: translateX(100%);
 transform: translateX(100%);
 }
 100% {
 -moz-transform: translateX(-100%);
 -webkit-transform: translateX(-100%);
 transform: translateX(-100%);
 }
}

This text be scrollin'!


text:
Q: Strange Issue with Facebook Android Example I am trying to implement the Single-Sign-On (SSO) example given on http://developers.facebook.com/docs/guides/mobile/#android. I have followed all the steps as mentioned in the example.
But when the application runs on the emulator a dialog box with facebook title only comes and then disappears.

I have tried to implement this  solution but nothing seems to work.
Please help me on this
Thanks,
Pankaj Khurana

A: Restarting the emulator fixed the problem for me.
And FYI, it would still work even if you do not change the default app id.

A: I have checked internet on my emulator it was not working. After configuring it the application worked perfectly.


text:
Q: How to Generate a Week Table and Split by Day and Hour First, to be clear; there is an example like this:

I can get courses with this query:
$qb
    ->select("c")
    ->from("ATLReservationBundle:Course", "c")
    ->where("WEEK(c.courseDate, 1) = WEEK(CURRENT_DATE(), 1)")
    ->orderBy("c.courseDate", "ASC");

QueryResult:
{   "courses": [
    {
      "id": 110,
      "name": "Pilates",
      "quota": 8,
      "course_date": "2015-08-31T12:15:00+0000",
      "studio": {
        "id": 2,
        "name": "Stüdyo 2"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 135,
      "name": "Spinning",
      "quota": 8,
      "course_date": "2015-08-31T19:30:00+0000",
      "studio": {
        "id": 2,
        "name": "Stüdyo 2"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 154,
      "name": "Kick Box",
      "quota": 6,
      "course_date": "2015-08-31T20:00:00+0000",
      "studio": {
        "id": 1,
        "name": "Stüdyo 1"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 133,
      "name": "Spinning",
      "quota": 8,
      "course_date": "2015-09-01T12:15:00+0000",
      "studio": {
        "id": 2,
        "name": "Stüdyo 2"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 113,
      "name": "Crunch 30 Min.",
      "quota": 8,
      "course_date": "2015-09-01T18:30:00+0000",
      "studio": {
        "id": 2,
        "name": "Stüdyo 2"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 112,
      "name": "Pilates",
      "quota": 8,
      "course_date": "2015-09-01T19:00:00+0000",
      "studio": {
        "id": 2,
        "name": "Stüdyo 2"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 150,
      "name": "Spinning",
      "quota": 8,
      "course_date": "2015-09-01T19:30:00+0000",
      "studio": {
        "id": 2,
        "name": "Stüdyo 2"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 136,
      "name": "TRX Group",
      "quota": 5,
      "course_date": "2015-09-01T20:00:00+0000",
      "studio": {
        "id": 2,
        "name": "Stüdyo 2"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 159,
      "name": "Pilates",
      "quota": 8,
      "course_date": "2015-09-02T10:00:00+0000",
      "studio": {
        "id": 2,
        "name": "Stüdyo 2"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 156,
      "name": "Stretching",
      "quota": 7,
      "course_date": "2015-09-02T18:30:00+0000",
      "studio": {
        "id": 2,
        "name": "Stüdyo 2"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 127,
      "name": "Zumba",
      "quota": 6,
      "course_date": "2015-09-02T19:00:00+0000",
      "studio": {
        "id": 1,
        "name": "Stüdyo 1"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 148,
      "name": "Kick Box",
      "quota": 6,
      "course_date": "2015-09-02T20:00:00+0000",
      "studio": {
        "id": 1,
        "name": "Stüdyo 1"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 138,
      "name": "Crunch 30 Min.",
      "quota": 8,
      "course_date": "2015-09-03T12:15:00+0000",
      "studio": {
        "id": 1,
        "name": "Stüdyo 1"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 121,
      "name": "Pilates",
      "quota": 8,
      "course_date": "2015-09-03T19:00:00+0000",
      "studio": {
        "id": 2,
        "name": "Stüdyo 2"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 117,
      "name": "TRX",
      "quota": 8,
      "course_date": "2015-09-03T20:00:00+0000",
      "studio": {
        "id": 2,
        "name": "Stüdyo 2"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 131,
      "name": "Spinning",
      "quota": 8,
      "course_date": "2015-09-03T20:00:00+0000",
      "studio": {
        "id": 2,
        "name": "Stüdyo 2"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 142,
      "name": "Pilates",
      "quota": 8,
      "course_date": "2015-09-04T12:15:00+0000",
      "studio": {
        "id": 2,
        "name": "Stüdyo 2"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 147,
      "name": "LBT 30 min.",
      "quota": 8,
      "course_date": "2015-09-04T19:00:00+0000",
      "studio": {
        "id": 1,
        "name": "Stüdyo 1"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 141,
      "name": "Crunch 30 Min.",
      "quota": 8,
      "course_date": "2015-09-04T19:30:00+0000",
      "studio": {
        "id": 2,
        "name": "Stüdyo 2"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    },
    {
      "id": 130,
      "name": "Crunch 30 Min.",
      "quota": 8,
      "course_date": "2015-09-05T14:00:00+0000",
      "studio": {
        "id": 2,
        "name": "Stüdyo 2"
      },
      "trainer": {
        "id": 1,
        "name": "-"
      }
    }   ] }

But i want to group this data like;
DAY - 31
    HOUR - 12:15 > Coursename
    HOUR - 19:30 > Coursename
DAY - 01
    HOUR - 10:00...

I don't know how to do this, anyone?
UPDATE
New Query:
   $qb
        ->select("c, HOUR(c.courseDate) as hour, DAY(c.courseDate) as day")
        ->from("ATLReservationBundle:Course", "c")
        ->where("WEEK(c.courseDate, 1) = WEEK(CURRENT_DATE(), 1)")
        ->orderBy("c.courseDate", "ASC")
        ->groupBy("hour, day");

But; there is a problem with this query i could not group by HOUR(c.courseDate), DAY(c.courseDate) because i got this error:

Error: Cannot group by undefined identification or result variable.

So, i defined hour and day as variable in select area.
I don't want to see day and hour as different variables.
QueryResult:
{
  "courses": [
    {
      "0": {
        "id": 110,
        "name": "Pilates",
        "quota": 8,
        "course_date": "2015-08-31T12:15:00+0000",
        "studio": {
          "id": 2,
          "name": "Stüdyo 2"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "12",
      "day": "31"
    },
    {
      "0": {
        "id": 135,
        "name": "Spinning",
        "quota": 8,
        "course_date": "2015-08-31T19:30:00+0000",
        "studio": {
          "id": 2,
          "name": "Stüdyo 2"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "19",
      "day": "31"
    },
    {
      "0": {
        "id": 154,
        "name": "Kick Box",
        "quota": 6,
        "course_date": "2015-08-31T20:00:00+0000",
        "studio": {
          "id": 1,
          "name": "Stüdyo 1"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "20",
      "day": "31"
    },
    {
      "0": {
        "id": 133,
        "name": "Spinning",
        "quota": 8,
        "course_date": "2015-09-01T12:15:00+0000",
        "studio": {
          "id": 2,
          "name": "Stüdyo 2"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "12",
      "day": "1"
    },
    {
      "0": {
        "id": 113,
        "name": "Crunch 30 Min.",
        "quota": 8,
        "course_date": "2015-09-01T18:30:00+0000",
        "studio": {
          "id": 2,
          "name": "Stüdyo 2"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "18",
      "day": "1"
    },
    {
      "0": {
        "id": 112,
        "name": "Pilates",
        "quota": 8,
        "course_date": "2015-09-01T19:00:00+0000",
        "studio": {
          "id": 2,
          "name": "Stüdyo 2"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "19",
      "day": "1"
    },
    {
      "0": {
        "id": 136,
        "name": "TRX Group",
        "quota": 5,
        "course_date": "2015-09-01T20:00:00+0000",
        "studio": {
          "id": 2,
          "name": "Stüdyo 2"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "20",
      "day": "1"
    },
    {
      "0": {
        "id": 159,
        "name": "Pilates",
        "quota": 8,
        "course_date": "2015-09-02T10:00:00+0000",
        "studio": {
          "id": 2,
          "name": "Stüdyo 2"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "10",
      "day": "2"
    },
    {
      "0": {
        "id": 156,
        "name": "Stretching",
        "quota": 7,
        "course_date": "2015-09-02T18:30:00+0000",
        "studio": {
          "id": 2,
          "name": "Stüdyo 2"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "18",
      "day": "2"
    },
    {
      "0": {
        "id": 127,
        "name": "Zumba",
        "quota": 6,
        "course_date": "2015-09-02T19:00:00+0000",
        "studio": {
          "id": 1,
          "name": "Stüdyo 1"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "19",
      "day": "2"
    },
    {
      "0": {
        "id": 148,
        "name": "Kick Box",
        "quota": 6,
        "course_date": "2015-09-02T20:00:00+0000",
        "studio": {
          "id": 1,
          "name": "Stüdyo 1"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "20",
      "day": "2"
    },
    {
      "0": {
        "id": 138,
        "name": "Crunch 30 Min.",
        "quota": 8,
        "course_date": "2015-09-03T12:15:00+0000",
        "studio": {
          "id": 1,
          "name": "Stüdyo 1"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "12",
      "day": "3"
    },
    {
      "0": {
        "id": 121,
        "name": "Pilates",
        "quota": 8,
        "course_date": "2015-09-03T19:00:00+0000",
        "studio": {
          "id": 2,
          "name": "Stüdyo 2"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "19",
      "day": "3"
    },
    {
      "0": {
        "id": 117,
        "name": "TRX",
        "quota": 8,
        "course_date": "2015-09-03T20:00:00+0000",
        "studio": {
          "id": 2,
          "name": "Stüdyo 2"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "20",
      "day": "3"
    },
    {
      "0": {
        "id": 142,
        "name": "Pilates",
        "quota": 8,
        "course_date": "2015-09-04T12:15:00+0000",
        "studio": {
          "id": 2,
          "name": "Stüdyo 2"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "12",
      "day": "4"
    },
    {
      "0": {
        "id": 141,
        "name": "Crunch 30 Min.",
        "quota": 8,
        "course_date": "2015-09-04T19:30:00+0000",
        "studio": {
          "id": 2,
          "name": "Stüdyo 2"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "19",
      "day": "4"
    },
    {
      "0": {
        "id": 130,
        "name": "Crunch 30 Min.",
        "quota": 8,
        "course_date": "2015-09-05T14:00:00+0000",
        "studio": {
          "id": 2,
          "name": "Stüdyo 2"
        },
        "trainer": {
          "id": 1,
          "name": "-"
        }
      },
      "hour": "14",
      "day": "5"
    }
  ]
}

I think i'm close now. But it must be like;
DAY
    HOUR
    HOUR
DAY
    HOUR
    HOUR

A: TO get your visual example table, use:

WEEKDAY(date)
Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 =
  Sunday

select hour(date), -- group by hour
case when weekday(date)=0 then course_name else null end as Monday, -- 1 col for each weekday
.....
case when weekday(date)=6 then course_name else null end as Sunday

from table
where -- select a monday to sunday calendar week unique by year
date(date) - interval weekday(date)=date(curdate()) - interval weekday(curdate())
group by hour(date)

To get the other variant you mentioned:
select right(date, 2), -- day of month,
hour(date) --hour,
course_name
from table
group by 1,2


text:
Q: Rewrite second URL Parameter htaccess I have searched in SO but never came across this specific answer. If anyone can help.
This use to be my URL structure /index.php?param1=is1 and I got it to look like this /is1 by using this Rewrite.
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(index\.php)?\?([^&\ ]+)
RewriteRule ^ /%1? [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?$1 [L]

Do not ask my how I got this as it's been a while that this was written. Now the issue is i have a second parameter. So my url that is like this /index.php?param1=is1&param2=is2 needs to be like this /is1/is2.
Obviously, now it's like this /is1&param2=is2. So i guess what I am searching for is a way to ask if &param2= is seen than hide it ?
I really don't get the logic behind all this URLREWRITE. I am trying to clean my URL structure for SEO purposes and COPY/PASTE logic as URL's should be shared between different users / clients. Obviously, having /this-is-something&this=that is not that bad but having /this-is-something/that is much better.
Just for info, first parameters is BRANDS /this-is-my-brand1 or /this-is-my-brand2 and second parameter is a product as /this-is-my-brand1/product1 before all that I use to have /index.php?brand=brand-one&product=product-one. Changing everything is not an issue, I can start from scratch if there is anything better than what I have.
I am on the learning curve, so I don't mind long explanations.
Any help is appreciated.

A: If your request parameters name are static (never change) you can use a more specifiq rule
RewriteRule  ^(.+)/(.+)$  index.php?brand=$1&product=$2 [L]