text:
Q: Difference in number of table rows in information_schema how can information_scheme table show different information rows when i'm counting the table with query :
select count(id) from mytable

and the other query :
SELECT

   engine AS Engine,
   table_name AS Table,
   table_rows AS Rows,
   round(((data_length + index_length) / 1024 / 1024), 2) as Size

FROM

   information_schema.TABLES

WHERE

   table_schema = DATABASE()

ORDER BY

   Size desc;

My Database Version : 10.1.33-MariaDB
Thanks for advice!

A: The first query returns the correct value.
The second query gets the value from information_schema.TABLES, which purpose if to store statistics about each table. The point of this table if to help MySQL query optimizer to choose the best execution plan.
As a consequence, the order of magnitude should be correct, but this table must not be used to get an accurate rowcount.


text:
Q: Listener implementation: 3 EditTexts in a single Fragment Goal of this code:
I have a fragment layout with 3 EditTexts :

*

*Multi-line description

*a decimal amount

*a date.

I wish a user to enter this information using the software keyboard and then the Fragment return a newItem (record) to the parent Activity so it can be stored in a db.

*

*Am I taking the right approach using a Listener?
onEditorActionListener seems more flexible than an onKeyListener.

*Eclipse really isn't happy with the line:
descriptionEditText.setOnEditorActionListener(this);
complaining that the setOnEditorActionListener is not applicable with the arguments.
I'm assuming this means I have a problem here:
public interface OnEditorActionListener {
    public void onNewItemAdded(String[] newItem);
    // need to change this newItem?
}

Any other comments welcome as this is my first attempt at trying this and I'm sure it's awful.
Full code below.
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

public class AddNewItemTextFragment extends Fragment {

    // A Fragment event callback interface, pg 126 Meier; used to share info with host Activity
    // Host activity listens for a new item to be created

    public interface OnEditorActionListener {
        public void onNewItemAdded(String[] newItem);
        // need to change this newItem?
    }

    // Create a variable to store a reference to the parent Activity that will implement the interface.

    private OnEditorActionListener onEditorActionListener;

    // This reference can be retrieved as soon as the parent has been bound to the Fragment with the Fragment's onAttach handler.

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            onEditorActionListener = (OnEditorActionListener)activity;
        } catch (ClassCastException e) {
          throw new ClassCastException(activity.toString() + "must implement OnEditorActionListener");
        }
    }

    // The Listener implementation

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstaceState) {
        View view = inflater.inflate(R.layout.add_new_item_text_fragment , container, false);

        final EditText descriptionEditText = (EditText)view.findViewById(R.id.description);
        descriptionEditText.setOnEditorActionListener(this);
        final EditText amountEditText = (EditText)view.findViewById(R.id.amount);
        amountEditText.setOnEditorActionListener(this);
        final EditText dateEditText = (EditText)view.findViewById(R.id.date1);
        dateEditText.setOnEditorActionListener(this);
        // add category, sub category Spinner

        // need to add newItem as a parameter?
        descriptionEditText.setOnEditorActionListener (new OnEditorActionListener() {

            public boolean onEditorAction (TextView v, int actionId, KeyEvent event) {
                boolean handled = false;

                    if (actionId == EditorInfo.IME_ACTION_SEND) {
                        String newDescription = descriptionEditText.getText().toString();
                        String newAmount = amountEditText.getText().toString();
                        String newDate = dateEditText.getText().toString();
                        // add other fields here; create array newItem containing all fields
                        String [] newItem ={newDescription, newAmount, newDate};

                        onEditorActionListener.onNewItemAdded(newItem);
                        handled = true;
                    }
                return handled;

            }

        });
        return view;
    }

}

A: The problem is, that you define the interface OnEditorActionListener with the same name as the TextView.OnEditorActionListener. If you would like to use the second one, than you should explicitly write the TextView prefix before it.
For example:
public class AddNewItemTextFragment extends Fragment implements TextView.OnEditorActionListener

...with this the next code will work:
descriptionEditText.setOnEditorActionListener(this);

...or this:
 descriptionEditText.setOnEditorActionListener (new TextView.OnEditorActionListener() {

            public boolean onEditorAction (TextView v, int actionId, KeyEvent event) {
...

A: Let me suggest another approach.
Add a button to your Fragment layout.
Name it addNewItem ("@+id/addNewItem").
This button allow user to add a new item.
Declare the Interface that activity must implement:
public interface OnAddNewItemListener {
    public void onNewItemAdded(String[] newItem);
}

Your Fragment class:
public class AddNewItemTextFragment extends Fragment {

    // A Fragment event callback interface, pg 126 Meier; used to share info with host Activity
    // Host activity listens for a new item to be created

    public interface OnAddNewItemListener {
        public void onNewItemAdded(String[] newItem);
    }

    // Create a variable to store a reference to the parent Activity that will implement the interface.

    private OnAddNewItemListener onAddNewItemListener;

    // This reference can be retrieved as soon as the parent has been bound to the Fragment with the Fragment's onAttach handler.

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            onAddNewItemListener = (OnAddNewItemListener)activity;
        } catch (ClassCastException e) {
          throw new ClassCastException(activity.toString() + "must implement OnEditorActionListener");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.add_new_item_text_fragment , container, false);

        final EditText descriptionEditText = (EditText)view.findViewById(R.id.description);
        final EditText amountEditText = (EditText)view.findViewById(R.id.amount);
        final EditText dateEditText = (EditText)view.findViewById(R.id.date1);
        final Button addNewItemButton = (Button)view.findViewById(R.id.addNewItem);

        // onClickListener for button
        addNewItemButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

            // need to add newItem as a parameter?
            String newDescription = descriptionEditText.getText().toString();
            String newAmount = amountEditText.getText().toString();
            String newDate = dateEditText.getText().toString();

           // add other fields here; create array newItem containing all fields
            String [] newItem ={newDescription, newAmount, newDate};

            // call method on Interface(activity)
            onAddNewItemListener.onNewItemAdded(newItem);
           }
        });

        return view;
    }

}

Implement the Interface in activity.
When addNewItem button is clicked the method onNewItemAdded is called in activity.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP.NET MVC 4 bundle with wildcard in folder path My team uses a custom NuGet package for installing jQuery UI, which puts the theme files into a directory structure like this:

*

*Content

*

*jquery-ui-1.10.3

*

*images

*jquery-ui.css

*jquery-ui.min.css

I'm trying to use ASP.NET MVC 4 bundles to include this content in the BundleConfig class inside my application's App_Start folder like so:
bundles.Add( new StyleBundle( "~/bundles/css" )
                 .Include( "~/Content/normalize-{version}.css",
                           "~/Content/jquery-ui-{version}/jquery-ui.css",
                           "~/Content/Site.css" ) );

This throws an error when I run the site:
Directory does not exist.
Parameter name: directoryVirtualPath

I also tried:
bundles.Add( new StyleBundle( "~/bundles/css" )
                 .Include( "~/Content/normalize-{version}.css" )
                 .IncludeDirectory( "~/Content/jquery-ui-*", "*.css" )
                 .Include( "~/Content/Site.css" ) );

That doesn't work either (obviously). I can explicitly specify the version on the folder, but that defeats part of the benefit of using the bundle.
So how can I use a wildcard in the folder path?

A: You could use the overloaded version of IncludeDirectory which searches subdirectories.
Suppose you have the following file:
\Root\Content\jquery-ui-1.10.3\jquery-ui.css
Use this code to find and add it:
.IncludeDirectory("~/Content", "jquery-ui.css", true)

This is useful because it will always find jquery-ui.css, regardless of where you put it.
The downside to this method is that it will search for and include all jquery-ui.css files that it finds, which could cause some bugs if you don't ensure that only one jquery-ui.css exists.
(Remember that searching for subdirectories will also still search the root directory i.e. ~/Content)


text:
Q: Netflix Zuul server - /routes endpoint not available In this coding exercise for learning microservices, I've created a Netflix Zuul project for service routing my microservices.
Sadly, the /routes endpoint does not seem to be mounted. Everything else seems to be working fine: Defining prefixes and setting up specific routes for my services.
There are no errors on the zuul server log files.
When I try to hit the /routes url on postman, I get an 404 error:

My Zuul application class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@SpringBootApplication
@EnableZuulProxy
public class ZuulServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ZuulServerApplication.class, args);
    }
}

pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion> <!--should be set to 4.0.0 -->
    <groupId>com.booking.system.hotel</groupId>
    <version>0.0.1-SNAPSHOT</version>
    <artifactId>hotel-gateway-service-server</artifactId>

    <name>Hotel Gateway service - zuul</name>
    <description>Hotel Gateway service - it uses Netflix Zuul Proxy Server</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <start-class>com.booking.system.hotel.zuulsvr.ZuulServerApplication</start-class>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-client</artifactId>
        </dependency>
    </dependencies>

    <build>
    <finalName>hotel-gateway-service-server</finalName> <!--name of the jar -->
        <plugins>
            <!-- packages the project as an executable jar, as an Spring Boot application -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- used for running tests at various stages -->
        </plugins>
    </build>
</project>

bootstrap.yml file:
spring:
  application:
    name: hotel-gateway-service-server
  profiles:
    active:
      default
  cloud:
    config:
      enabled: true

Zuul configuration file from configuration server:
zuul.ignored-services: "*"
zuul.prefix:  /api
zuul.routes.hotel-reservations-service: /reservations/**
zuul.routes.hotel-rooms-service: /rooms/**

docker-compose.yml entry for initializing the zuul gateway server:
   hotel-gateway-service-server: #zuul server
      image: imageprefix/hotel-gateway-service-server
      ports:
         - 5555:5555
      environment:
         PROFILE: "dev"
         SERVER_PORT: "5555"
         CONFIGSERVER_URI: "http://hotel-configuration-server:8888"
         CONFIGSERVER_PORT: "8888"
         EUREKASERVER_URI: "http://hotel-service-discovery-server:8761/eureka/"
         EUREKASERVER_PORT: "8761"

I don't seem to spot what I am missing.

A: The actuator base path has changed to /actuator. So you need to use /actuator/routes. It is also not enabled by default.
management.endpoints.web.exposure.include=*


text:
Q: How to restrict my particular page and it can only access after submit action occurred Please help me.. I have a contact form page and thank you page. I just want to restrict my thank you page and it can only access after submit action on contact form click. So how can I do that? Thank you! :)
EX:
If directly access the thankyou.php ex: (localhost/test/thankyou.php). it automatic redirect on index.php.
And thankyou.php can only access after clicking the submit button or action on contact form.

A: Rather simple, replace $_POST with the type you are using ($_POST / $_GET)
<?php

if(!isset($_POST)){
    header('Location:URLHERE');
    die();
}

 <<START/REST OF YOUR THANK YOU CODE/PAGE>>
?>

If you want to you can also check for a specific variable / name is set. Again replace the $_POST with the type you are using. ($_POST / $_GET) - Along with the variable to check for of course :)
<?php

if(!isset($_POST['name'])){
    header('Location:URLHERE');
    die();
}

 <<START/REST OF YOUR THANK YOU CODE/PAGE>>

?>

A: the easiest way is to have a hidden field on your form maybe called "form-sent" for example with value "yes". thrn on your thankyou page use an if statement to check this field is in $_POST along with the value:
if(isset($_POST["form-sent"]) && $_POST["form-sent"] == "yes"){
}
just a badsic example. you could in fact check it does not exist or the value is not "yes" and redirect back off the page.
sorry for poor formatting i posted on my phone.


text:
Q: ExactTarget API - get report of all emails sent SOAP::Lite example Trying to use PERL SOAP::Lite module to get email sent report from the ET API. Anyone have success using the examples here in PERL:
https://help.exacttarget.com/en-US/technical_library/web_service_guide/technical_articles/retrieve_sentevent_details_for_job/


text:
Q: Multiple nested queries in Laravel Eloquent I have a chat app, and I need to filter those user conversations that have attachment[s] in the groups last message, by using eloquent ORM. I have following DB tables/models:

*

*Groups & Users. Relation is N-N between them, so there's a pivot table between groups and users, named group_user. Although this table has been expanded with some extra fields, as a result group_user have it's own model now.

*Messages. Relations are 1-N from both groups and users.

*Attachments. Relation is 1-N from messages.

The algorithm of this filtering isn't the problem - take user (because I need specific users groups) and his groups, find all group messages, sort them by date of creation in descending order and take the top one. And then check whether this message have any records in 'attachments' table. Obivously I do have all the relations defined in the respective Models. Right now I have this code, but it returns all groups that have attachments in any of the messages.
Also, I need to sort the query by the last message 'created_at' date.
return $user->user_groups()->whereHas('group', function($query) {
        $query->whereHas('messages', function ($query) {
            $query->whereHas('attachments');
        });
})->with('group')->latest()->paginate($this->group->getPerPage());

Edit.
class User
{
  public function messages()
  {
    return $this->hasMany('App\Models\Message');
  }

  public function user_groups()
  {
    return $this->hasMany('App\Models\GroupUser');
  }
}

class Message
{
  public function attachments()
  {
    return $this->hasMany('App\Models\Attachment');
  }

  public function author()
  {
    return $this->belongsTo('App\Models\User');
  }

  public function group()
  {
    return $this->belongsTo('App\Models\Group');
  }
}

class Attachment
{
  public function message()
  {
    return $this->belongsTo('App\Models\Message');
  }
}

class GroupUser
{
  public function user()
  {
    return $this->belongsTo('App\Models\User');
  }

  public function group()
  {
    return $this->belongsTo('App\Models\Group');
  }
}

class Group()
{
  public function messages()
  {
    return $this->hasMany('App\Models\Message');
  }

  public function group_users()
  {
    return $this->hasMany('App\Models\GroupUser');
  }
}

A: Add a groups relationship to your User model:
public function groups() {
    return $this->belongsToMany('App\Models\Group');
}

Then try this:
$user->groups()
    ->select('groups.*')
    ->join('messages', function($join) {
        $join->on('groups.id', 'messages.group_id')
            ->where('created_at', function($query) {
                $query->selectRaw('max(created_at)')
                    ->from('messages')
                    ->where('group_id', DB::raw('groups.id'));
            });
    })
    ->whereExists(function($query) {
        $query->from('attachments')
            ->where('attachments.message_id', DB::raw('messages.id'));
    })
    ->orderByDesc('messages.created_at')
    ->paginate($this->group->getPerPage());


text:
Q: google map extract LatLng of pinned location Trying to extract Lat and Lng of a location using google map autocomplete method to get the location/place and output it in a hidden input.
I read somewhere that place.geometry.location is equal to LatLng but when I do a console.log these lines I get location.lat(); not a function. Also can someone point me how to output the LatLng in the input and update when dragged the marker.
var locPosition = place.geometry.location;
            var LocLat = location.lat();
            var LocLng = location.lng();
            console.log(LocLat);

Okay: found the way to console lat and lng separately by doing so.
var locPositionLat = place.geometry.location.lat();
var locPositionLng = place.geometry.location.lng();

found my way to output in the field by doing so, but unless its wrong then please correct it.
$('#lat').val(locPositionLat);
$('#lng').val(locPositionLng);

JsFiddle: https://jsfiddle.net/kfofu92g/
Edit: follow up question, how do I get the getPosition of the pin when dragged this  time.

A: UPDATED:
You can output them to the field by:
document.getElementByName("lat").value = "somevalue";
//same for Lng.

As for the updated marker position after drag you need to have a "dragend" listener, something like:
        google.maps.event.addListener(markers, 'dragend', function(event) {

             document.getElementById('lat').value = event.latLng.lat();
            document.getElementById('lng').value = event.latLng.lng();

});


text:
Q: How to simulate typing in input field using jQuery? What I want is to simulate typing in <input> field using javascript.
I have the following code:
var press = jQuery.Event("keydown");
press.ctrlKey = false;
press.which = 65;
$("#test").trigger(press);

But when I load the page, the #test input field has no typed characters,  the keycode of '65' represents 'A', but there is no 'A' input.
Basically what I want is to automatically typing in the website using Greasemonkey.
Please give me some ideas or some library with which I can use to do this.
Thanks a lot!

A: You can send key events, and anything listening for them will get them, but they will not change the input, so you will not see the letter A appear, for example.  This is mostly a security thing; see "Manually firing events" for a discussion about that.
So, if you want the letter to appear, you must alter the input's value as you send the key event.  There is a jQuery plugin for that, see "The $.fn.sendkeys Plugin".
You can see how an <input> reacts with user-applied keys, key events, and that plugin at this jsFiddle.
For reference, this is the key piece of code from that jsFiddle:
$("button").click ( function (zEvent) {
    if (zEvent.target.id == "simA_plain") {
        console.log ("Send Plain key event");
        var keyVal = 65;
        $("#eventTarg").trigger ( {
            type: 'keypress', keyCode: keyVal, which: keyVal, charCode: keyVal
        } );
    }
    else {
        console.log ("Use the Plugin to simulate a keystroke");
        $("#eventTarg").sendkeys ("B") ;
    }
} );

That plugin should be sufficient if you are just trying to "simulate typing on an <input>".  However, depending on what you are really trying to do, you may need to do one or more of the following:

*

*Just set the text to what you want it to be.

*Send a keydown event, if the page's javascript triggers off of that.

*Likewise, send a change event, etc., if the page's javascript triggers off of that.

*Just find and call the page's javascript directly.  Use script injection, the location hack, unsafeWindow, and/or @grant none mode to do that.

*Something else?  State your true objective and link to the target page.


text:
Q: Bootstrap Toggle Switch Displays Wrong Content On Page Load UPDATED: SEE BELOW
I created a bootstrap toggle switch that is supposed to toggle between two different content, and it should show the current content by the direction of the switch and the color black.
PROBLEM: When the page loads or reloads the wrong content is displayed, and the switch is in the wrong side, and the color of the selected text is not black (to signify selected)

Murad improved on it, but there's still some issues:

UPDATED Fiddle: https://jsfiddle.net/godsnake/bdqychLw/
How can I make sure that the page loads the content and toggle switch in the correct order and functionality?
Please use this Fiddle:
https://jsfiddle.net/godsnake/jmc798qx/4/
JS:
   var month = document.getElementById("filt-monthly"),
    annual = document.getElementById("filt-annual"),
    swicther = document.getElementById("switcher"),
    montWrapper = document.getElementById("monthly"),
    annualWrapper = document.getElementById("annually");

month.addEventListener("click", function(){
  month.classList.add("toggler--is-active");
  annual.classList.remove("toggler--is-active");
  montWrapper.classList.remove("hide");
  annualWrapper.classList.add("hide");
  document.querySelector("[type='checkbox']").checked = false
});

 annual.addEventListener("click", function(){
  month.classList.remove("toggler--is-active");
  annual.classList.add("toggler--is-active");
  montWrapper.classList.add("hide");
  annualWrapper.classList.remove("hide");
  document.querySelector("[type='checkbox']").checked = true
});

swicther.addEventListener("click", function(event){
  month.classList.toggle("toggler--is-active");
  annual.classList.toggle("toggler--is-active");
  montWrapper.classList.toggle("hide");
  annualWrapper.classList.toggle("hide");
})

HTML:

Monthly

    <input type="checkbox" id="switcher" class="check"/>

  Annual

Hello This is priced annually

Hello This is priced monthly

CSS[Bootstrap]
.toggle, .toggler {
  display: inline-block;
  vertical-align: middle;
  margin: 0px;
}

.toggler {
  color: #ddd;
  transition: .2s;
  font-weight: bold;
}

.toggler--is-active {
  color: #000000;
}
x-shadow: inset 0 1px rgba(0, 0, 0, 0.02);
}

.b {
  display: block;
}

.toggle {
  position: relative;
  width: 80px;
  height: 35px;
  border-radius: 100px;
  background-color: #ff9900;
  overflow: hidden;
  box-shadow: inset 0 0 2px 1px rgba(0, 0, 0, 0.05);
}

.check {
  position: absolute;
  display: block;
  cursor: pointer;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  z-index: 6;
}

.check:checked ~ .switch {
  right: 2px;
  left: 57.5%;
  transition: 0.25s cubic-bezier(0.785, 0.135, 0.15, 0.86);
  transition-property: left, right;
  transition-delay: .08s, 0s;
}

.switch {
  position: absolute;
  left: 2px;
  top: 2px;
  bottom: 2px;
  right: 57.5%;
  background-color: #fff;
  border-radius: 36px;
  z-index: 1;
  transition: 0.25s cubic-bezier(0.785, 0.135, 0.15, 0.86);
  transition-property: left, right;
  transition-delay: 0s, .08s;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.hide{
  display: none;
}

A: var month = document.getElementById("filt-monthly"),
    annual = document.getElementById("filt-annual"),
    swicther = document.getElementById("switcher"),
    montWrapper = document.getElementById("monthly"),
    annualWrapper = document.getElementById("annually");

month.addEventListener("click", function(){
  month.classList.add("toggler--is-active");
  annual.classList.remove("toggler--is-active");
  montWrapper.classList.remove("hide");
  annualWrapper.classList.add("hide");
  document.querySelector("[type='checkbox']").checked = false
});

 annual.addEventListener("click", function(){
  month.classList.remove("toggler--is-active");
  annual.classList.add("toggler--is-active");
  montWrapper.classList.add("hide");
  annualWrapper.classList.remove("hide");
  document.querySelector("[type='checkbox']").checked = true
});

swicther.addEventListener("click", function(event){
  month.classList.toggle("toggler--is-active");
  annual.classList.toggle("toggler--is-active");
  montWrapper.classList.toggle("hide");
  annualWrapper.classList.toggle("hide");
})

I change some code and change variable name for readability. This is work but my opinion this is not valid code.

A: Changed in the html and css the toggle, check, and switch. Feel free to use this.
HTML

Monthly

       <input type="checkbox" id="switcher" class="check"/>

 Annual

CSS
.toggler {
  display: inline-block;
  vertical-align: middle;
  margin: 12px 0 0 0;
  color: #ddd;
  transition: .2s;
  font-weight: bold;
}
.toggler--is-active {
  color: #000000;
}
.b {
  display: block;
}
.hide{
  display: none;
}
/* slide/switch */
.toggle {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}
.toggle input {
  opacity: 0;
  width: 0;
  height: 0;
}
.switch {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  cursor: pointer;
  background-color: #999;
  -webkit-transition: .4s;
  transition: .4s;
  border-radius: 34px;
}
.switch:before {
  position: absolute;
  bottom: 4px; left: 4px;
  content: "";
  width: 26px;
  height: 26px;
  background-color: #fff;
  -webkit-transition: .4s;
  transition: .4s;
  border-radius: 50%;
}
input:checked + .switch {
  background-color: #f66;
}
input:focus + .switch {
  box-shadow: 0 0 1px #f66;
}
input:checked + .switch:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}


text:
Q: Eclipse package explorer error in a web application project I am following a tutorial by Google on "google app engine using java" and trying to make a simple web application. But I am having problem to make a JSP file in the war directory. This is the tutorial page: https://developers.google.com/appengine/docs/java/gettingstarted/usingjsps
I am using eclipse. When I create a new JSP file in the war directory, it causes an error in the package explorar. The error is:"Your project must be configured to use a JDK in order to use JSPs"
How can I get rid from this error?

A: In Window - Preferences - Java - Installed JREs, make sure you have a JDK installed, and select it as the default.

A: First thing, go into Window>Preferences>Installed JREs and sellect a JDK's JRE.
Them add this line to eclipse.ini:
-vm C:\Program Files\Java\jdk1.7.0_45\bin\javaw.exe

That line must be in the beginning of the file, before any -vmargs argument, or else Eclipse will crash on start.
Last go into your System's environment variables and add "C:\Program Files\Java\jdk1.7.0_45\bin" to the PATH variable, before the "%SystemRoot%\system32" entry.
Those three entries must all point to the same JDK and, of course, must be changed to whatever your JDK's path actually is.
Restart your Eclipse and you should be good to go.


text:
Q: SyntaxException in Arity.jar I am using the Arity Arithmetic Engine for my calculations. So I wanted to know what are all the exceptions that can arise when I use

double res =  Symbols.eval("string");

Im enclosing this in a try block as
try{
double res = Symbols.eval("Expression");
return res;
}
catch(SyntaxException s)
{
System.out.println("Exception..!");
}

So i want to know what all exceptions are generated So that I can know where I may be going wrong.

A: Not sure I fully understand the question, but if you catch any exception and then print the stack trace you can more accurately figure out what type of exception was thrown and what caused it. This will allow you to accurately distinguish SyntaxErrors which you mentioned from any other exception which could arise for other reasons.
try
{
    double res = Symbols.eval("Expression");
    return res;
}
catch(Exception e)
{
    e.printStackTrace();
}

Printing the stack trace is very important as it will allow you to figure out exactly where in your code the issue is coming from. If you just do a simple System.out.println("Error happned") you aren't going to get as much information.
When you print the stack trace you can see the precise chain of method calls that led to the ultimate failure down to the line, which makes it easy to find out why the error is arising.

A: I am unfamiliar with Arity, especially since all the link I find leads to 404 error pages. But aside that, you can catch known exceptions, and a final catch for any other exception that you can refactor later on to handle it.
try {
    double res = Symbols.eval("Expression");
    return res;
} catch (SyntaxException s) {
    System.err.println("Syntax exception");
} catch (Exception e) {
    System.err.println("Unknown exception caught!");
}

A: I'm sure System.out.println(e.getMessage()); will give you more usable information.


text:
Q: Spring boot Constructor Autowired Exception I have this classes in my spring boot App(spring hibernate/data/jpa/web):
pkg entity:
public interface Base {
// getter/setter methods
}

@MappedSuperclass
public abstract class AbsBase implements Base {
// common fields & getter/setter methods
}

@Entity(name = "Config")
@Table(name = "config")
public class Config extends AbsBase implements Base, Serializable {
  //additional fields & getter/setter methods
}

pkg repository:
@NoRepositoryBean
public interface BaseRepository<T extends Base> extends JpaRepository<T, Integer> {}

@Repository
public interface ConfigRepository extends BaseRepository<Config> {
//Queries
}

pkg service:
@Transactional
public interface BaseService<T extends Base> {

    @Transactional  void add(T obj);
    @Transactional  void edit(T obj);
    //Etc..
}

public abstract class AbsBaseService<T extends Base> implements BaseService<T> {

    private BaseRepository<T> repository;

    public AbsBaseService(BaseRepository<T> repository) {
        super();
        this.repository = repository;
    }

    @Override   public void add(T obj) { repository.save(obj); }
    @Override   public void edit(T obj) { repository.save(obj); }
    // Etc
}

@Service
public class ConfigService extends AbsBaseService<Config> implements BaseService<Config> {

    private ConfigRepository repository;

    @Autowired
    public ConfigService(ConfigRepository repository) {
        super(repository);
        this.repository = repository;
    }
    // Etc.
}

If I don't create any Controller all work, but if I create a controller:
pkg controller:
public interface BaseController<T extends Base> { // methods }

public abstract class AbsBaseController<T extends Base> implements BaseController<T> {

    private BaseService<T> service;

    public AbsBaseController(BaseService<T> service) {
        this.service = service;
    }

@Override
@RequestMapping(value = "/Add", method = RequestMethod.POST)
public String addAction(@ModelAttribute("entity") T entity, BindingResult result, Model model,
        final RedirectAttributes redirectAttributes) {

    service.add(entity, result);
    if (result.hasErrors()) {
        return addUrl;
    }
}

@Controller
public class ConfigController extends AbsBaseController<Config> implements BaseController<Config> {

    private ConfigService configService;

    @Autowired
    public ConfigController(ConfigService configService) {
        super(configService);
        this.configService = configService;
    }
}

I get this error (error autowired ConfigService in ConfigController):
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'configControllerImpl' defined in file [C:\workspace-sts\prueba_boot_thymeleaf\target\classes\prueba\controller\config\ConfigControllerImpl.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [prueba.service.config.ConfigServiceImpl]: No qualifying bean of type [prueba.service.config.ConfigServiceImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [prueba.service.config.ConfigServiceImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
    at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
    at prueba.BootThymeleafApplication.main(BootThymeleafApplication.java:12) [classes/:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [prueba.service.config.ConfigServiceImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    ... 19 common frames omitted

The first question is:
I have annotated @Transaction the BaseService interface and its methods. It's correct? Better in AbsBaseService class?
I see that configService constructor executes before Exception.
Why not Autowired?

UPDATE
I need constructor @Autowired because I implement common methods in abstract/superclass generic service/controller.
The inheritance tree:
AbsBaseXXXX  -->   AbsBaseCodeNameXXXX  -->   AbsBaseCodeNamePeriodXXXX
Config extends from AbsBase and implements Base.
    ConfigService extends from AbsBaseService<> and implements BaseService<> (use ConfigRepository)
    ConfigController extends from AbsBaseController<> and implements BaseController<> (use ConfigService)
I have a generic abstract classes for common method implementation:
Interfaces for entity:
    Base, BaseCodeName, BaseCodeNamePeriod....

*

*Abstract generic entity class:
AbsBase, AbsBaseCodeName, AbsBaseCodeNamePeriod....

*Generic Interfaces:
BaseRepository, BaseCodeNameRepository, BaseCodeNamePeriodRepository,...

*Abstract generic service (That they need corresponding generic repository):
AbsBaseService, AbsBaseCodeNameService,AbsBaseCodeNamePeriodService,...

*Abstract generic controller (that they need corresponding generic service):
AbsBaseController, etc...

A: First of all, most of you code could be simplified, at least to test that it works well:
@Transactional
public interface BaseService<T extends Base> {

    void add(T obj); // No need to repeat @Transactional here, unless you want to override default behaviour (says, read_only, for instance)
    void edit(T obj);
    //Etc..
}

// Not much use of an Abstract class here, all methods are exposed in the interface already

@Service
public class ConfigService implements BaseService<Config> {

    // Autowire the field directly. Constructor not needed anymore in this case
    @Autowired
    private ConfigRepository repository;
    // Etc.
}

The controller will follow the same guideline as the service.
This should work alright now. If not, you need to update your question with the full stack trace (or at least the last caused by block, which is the one really meaningful).

A: The solution:
Create Service interface:
IConfigService extends BaseService
Change Service class:
ConfigService extends AbsBaseService implements IConfigService
In ControllerConfig replace ConfigService for IConfigService
If I use interface work but if i use class don't work. I don't understand why but it works.

A: According to the code posted at https://drive.google.com/open?id=0B4DUWMYsjWtdVVRibDFZOVhac2s, it is now clear for me what you're trying to achieve.
You want to create a hierarchy of classes (services, for instance), that define some functionalities at each level. For instance:

*

*RepoA defines a methodA method.

*RepoB extends RepoA and
defines a methodB method.

*ServiceA uses the RepoA class to
expose this method

*ServiceB extends ServiceA and expose its
methods and ServiceA methods

*And so forth...

Debugging your application, I found out that Spring tries to create a new AccountService bean rather than using the existing one when this code is called:
@Controller
@RequestMapping("/Account")
public class AccountController extends AbsBaseDataController<Account> {

    private AccountService service;

    @Autowired
    public AccountController(AccountService service) {
        super(service);
        this.service = service;
        System.out.println("AccountController-CONSTRUCTOR");
    }
}

This is because you're using the AccountService class directly, rather than an interface. This is what matters here, because Spring creates a proxy around your classes to be able to use AOP on them. So when it comes to autowire it, classes mismatch (you think an instance of your class is injected, but this is actually a com.sun.proxy.Proxy).
Since those Java proxies implement your classes' interfaces, you should create an interface for your AccountService (say IAccountService), and use it instead of the raw AccountService class in your AccountController class' constructor:
The interface
public interface IAccountService extends BaseDataService<Account> {
}

The controller
@Controller
@RequestMapping("/Account")
public class AccountController extends AbsBaseDataController<Account> {

    private IAccountService service;

    @Autowired
    public AccountController(IAccountService service) {
        super(service);
        this.service = service;
        System.out.println("AccountController-CONSTRUCTOR");
    }
}

The service class
@Service
public class AccountService extends AbsBaseDataService<Account> implements IAccountService {
[...]
}


text:
Q: phpMyAdmin 4.6 persistent login Is there a way to stay logged-in forever in phpMyAdmin 4.6?
Previous versions were straightforward to edit but this one has multiple configuration files spread across multiple folders in Ubuntu.
I would like to have it like that in my VirtualBox, so security is not a concern here.

A: If you're logging in as the same user and don't need to have multiple user accounts, it could be that changing to the 'config' authentication type would be best for you.
auth_type config
It sounds like you're using the Ubuntu packaged version (or the phpMyAdmin PPA), in which case the main configuration file is /etc/phpmyadmin/config.inc.php. Other files are included from there for things like the blowfish secret key that are set automatically on install and don't usually need to be managed manually. You can edit that file and look for a line like
$cfg['Servers'][$i]['auth_type'] = 'cookie';
and change it to
$cfg['Servers'][$i]['auth_type'] = 'config';
If the line doesn't exist, just add the config line (the default is cookie), so it might not be set by Ubuntu.
You'll also need to add the username and password as hardcoded values in the configuration:
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'yourPassword';

Of course, if you have a user other than root, you would use that username there, and substitute out your password in the appropriate spot as well.
Extending cookie expiration
If that's not appealing to you, you'll have to increase the time before the cookie session expires. Because PHP does some garbage collection and removes old sessions, you'll have to tell both phpMyAdmin and PHP to allow extra time. The phpMyAdmin setting is called LoginCookieValidty and the PHP setting is session.gc_maxlifetime
In /etc/phpmyadmin/config.inc.php, you'll have to add another line. I don't know if there's an upper limit on this, (comments here conflictingly suggest either 65535 or something higher, where as this question shows a value of 200000). You could try setting it to, for instance, 5 years, and see what happens (or some lower, more sane, value):
$cfg['LoginCookieValidity'] = 157680000;
You'll also have to edit your PHP configuration file (if your Ubuntu installation is similar to my Debian one, it's probably /etc/php/7.4/apache2/php.ini, adjusted of course if you're not using Apache or have a different PHP version). Mine already has the default of
session.gc_maxlifetime = 1440
so you could change this to
session.gc_maxlifetime = 157680000
Note that the upper limit of both these values probably depends on your system architecture and some PHP limit that I can't find documented anywhere, so it might take some experimentation to find a high value that works correctly.


text:
Q: XSLT-1.0 How to edit tag elements data I am using xsl to transform xml to xml. Could you please help me to write xsl code to convert input to output? I need the data as rich text data in CDATA for first two tags. Thanks in advance.
Note: I have the solution from Martin @ XSLT-1.0 How to pick multiple tags between two similar tags as it is? but now I need to edit  value. How to do that? Please help.
Input:
<ATTRIBUTE-VALUE>
    <THE-VALUE>

Main Description

Line1 The main description text goes here.

Line2 The main description text goes here.

****

Key Consideration

Line1 The key consideration text goes here.

Line2 The key consideration text goes here.

Skills

Line1 The Skills text goes here.

Line2 The Skills text goes here.

Line3 The Skills text goes here.

Synonyms

The Synonyms text goes here.

    </THE-VALUE>
</ATTRIBUTE-VALUE>

Output:
<MainDescription>
    <![CDATA[

Line1 The main description text goes here.

Line2 The main description text goes here.

****

    ]]>
</MainDescription>
<KeyConsiderations>
    <![CDATA[

Line1 The key consideration text goes here.

Line2 The key consideration text goes here.

    ]]>
</KeyConsiderations>
<Skills>

Line1 The Skills text goes here.

Line2 The Skills text goes here.

Line3 The Skills text goes here.

</Skills>
<Synonyms>

The Synonyms text goes here.

</Synonyms>

A: If you only want the first two tags as CData, just add this template to your XSLT
<xsl:template match="xhtml:h1[position() > 2]">
  <xsl:element name="{translate(., ' ', '')}">
    <xsl:apply-templates select="key('h1-group', generate-id())"/>
  </xsl:element>
</xsl:template>

Or, if by "first two tags" you mean just "MainDescription" and "KeyConsideration", try this template instead....
<xsl:template match="xhtml:h1[. != 'Main Description' and . != 'Key Consideration']">
  <xsl:element name="{translate(., ' ', '')}">
    <xsl:apply-templates select="key('h1-group', generate-id())"/>
  </xsl:element>
</xsl:template>

EDIT: If you want to "edit" one of the child nodes too, then simply add a template for the element, or attribute, you wish to modify. For each, to modify the src attribute of img do this
<xsl:template match="xhtml:p/xhtml:img/@src">
  <xsl:attribute name="src">
    <xsl:value-of select="concat(substring-before(., '?'), '.jpg')" />
  </xsl:attribute>
</xsl:template>

Note, this is just an example, as you did not make clear exactly what logic you required for modifying the value, so I have assumed you just want to replace the query string portion with a file extension of ".jpg".


text:
Q: Right() function in older firebird versions What is an equivalent to RIGHT() (as in FB2.5)
for older versions of firebird (Firebird 2.0) without using UDFs?

A: Use SUBSTRING and CHARACTER_LENGTH functions. Both internally available as of version FB 2.0:
SELECT
  IIF(CHARACTER_LENGTH(str_field) <= <right_characters_count>,
    str_field,
    SUBSTRING(str_field FROM
      (CHARACTER_LENGTH(str_field) - <right_characters_count> + 1)))
FROM
  some_table


text:
Q: The meaning of "It isn't honest"
Jenny got really angry. "It isn't honest", she said.
I didn't listen. I bet all my money on myself to win and then I lost the fight. (I was told to lose the fight)

What does it mean by sentence "it isn't honest"?
I think it implies that she can't believe what she's been told or it's somehow unpleasant, Am I right?

A: The snippet that you've provided is slightly confusing. In the context of a fighting contest, such as a boxing match, with this sort of concern for honesty I'd be expecting that the fighter was intending to throw the bout, to lose on purpose.
A dishonest approach would be to bet all your money on your opponent, and then lose on purpose claiming a much bigger return than the winning prize money. However that doesn't make much sense when he then bets all his money on himself to win.


text:
Q: sudo ./sakis3g not found Python subprocess I need subprocess in my script to connect with 3G. But unfurtunately it's throwing me alot of errors. So I was hoping maybe someone here could help me.
My code:
import subprocess
import time

subprocess.run('sudo ./sakis3g connect OTHER="USBMODEM" USBMODEM="12d1:1001" APN="internet"', shell=True)

When I run this simple script in my home directory I get the following error:
sudo: ./sakis3g: command not found
Is it maybe because the sakis3g script itself it located in /usr/local/bin. Any help would be appreciated, thanks in advance

A:
I run this simple script in my home directory

./ means the current directory i.e. the home directory in this case.

Is it maybe because the sakis3g script itself it located in /usr/local/bin

/usr/local/bin is (likely) not your home directory. sudo can't find sakis3g in the current directory because there is no such file.
Use /usr/local/bin/sakis3g instead of ./sakis3g.

A: copy that saskis3g object file in your directory where you have your code then you can use the command directly without including any file path for the object file(i.e sakis3g) in your connect command.
if suppose you have a folder named sample. and your program resides in this folder then copy+paste the sakis3g object file to this folder[you can do this by using the CP command in linux ] and use the normal command ie " system("sudo ./sakis3g connect"); "  no need of any path.


text:
Q: Counting existing records in php and mysql I have a simple php/mysql script that stores in mysql database id, link, and date fields. It stores various links and some of them appear several times. I would like to count the number of times each link was accessed. I was thinking of adding new field counter and updating it every time new record is inserted, but this needs to check if the link already exists and update counter when necessary.
This means I would have to:
1. Search the entire table to look if the link already inserted.
2. If no - insert it and set counter to value of 1.
3. If yes - find the correct record and update its counter by 1.
I would like to have something like:
1. www.link1.com 11:20
2. www.link2.com 11:30
3. www.link1.com 11:40
www.link1.com counter: 2 times
www.link2.com counter: 1 time
I am wondering what is the best way to do that? Should I rather create a new table that stores the counter for each link?

A: It depends on what you need to track. Do you only need to track total number of visits? If so, add a column to your table. You don't need to check wheter the link exists if you want to update the counter this way.
If you need to track who visisted when etc, create a new table with a foreign key and neccesary columns to your table. With this, you need to have the id of your link, but when you update the number of visits, you should already have it.

A: creating a new field and incrementing it is probably the simplest approach and should be easy to do.
If your site has users logging in, then you might want to create a table like users_links and store a record each time a user clicks a link, this way you can get the number of clicks, as well as more useful things like distinct users clicking, a history of what each user clicks on, correlations between link popularity and more!!!

A: Sorry if I didn't understand, but if you have this table structure:
CREATE TABLE IF NOT EXISTS `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `link` varchar(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;

And these data:
INSERT INTO `test` (`link`, `id`) VALUES
(1, 'link1'),
(2, 'link2'),
(3, 'link1'),
(4, 'link2'),
(5, 'link1'),
(6, 'link1'),
(7, 'link3');

If I want to see how many occurrences of each link, I can use the COUNT() and GROUP BY from MySQL:
SELECT COUNT(link), link FROM `test` WHERE 1 GROUP BY link

And I get:

4 link1
2 link2
1 link3

Is it this you are looking for?


text:
Q: Creating unique groups in sequential data that repeats through time This kind of thing has been asked before, but not quite in this way that I can find.
Thread about creating sequential IDs, with several additional links
It's not hard to create identifiers in a sequence, but my data includes a temporal element that has thrown me for a loop. The following data is an imaginary dataset just to illustrate the problem in something tractable:
    dput(walking_dat)
structure(list(neighborhood = structure(c(3L, 3L, 3L, 3L, 3L,
2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L), .Label = c("Dinkytown", "Downtown",
"Uptown"), class = "factor"), street = structure(c(4L, 3L, 3L,
5L, 3L, 4L, 6L, 7L, 4L, 4L, 1L, 2L, 1L), .Label = c("12thAve",
"14thAve", "Dupont", "Hennepin", "Lyndale", "Marquette", "Nicolette"
), class = "factor"), sequence = c(1, 2, 3, 4, 5, 1, 2, 3, 4,
5, 1, 2, 3), visit = c(1, 1, 1, 1, 2, 1, 1, 1, 2, 2, 1, 1, 2)), .Names = c("neighborhood",
"street", "sequence", "visit"), row.names = c(NA, -13L), class = "data.frame")

   neighborhood    street sequence visit
1        Uptown  Hennepin        1     1
2        Uptown    Dupont        2     1
3        Uptown    Dupont        3     1
4        Uptown   Lyndale        4     1
5        Uptown    Dupont        5     2
6      Downtown  Hennepin        1     1
7      Downtown Marquette        2     1
8      Downtown Nicolette        3     1
9      Downtown  Hennepin        4     2
10     Downtown  Hennepin        5     2
11    Dinkytown   12thAve        1     1
12    Dinkytown   14thAve        2     1
13    Dinkytown   12thAve        3     2

All data are, for the sake of imagination, from three individuals walking east in three neighborhoods of Minneapolis. Each row represents a time when their location was recorded. The first column is the neighborhood they are walking through. The second column is the intersection where they were located at each time-point. The third column is the sequence that these data occurred.
I want to create the visit column that records sequential time-points at the same street, in the same neighborhood, as a single visit, and later return visits as the next visit. How do I create this sort of sequential identifier?

I was thinking this ave() with FUN=seq_along trick might work, but I can't find a way of combining the factors that gets me where I want to be.
Create a sequential number (counter) for rows within each group of a dataframe [duplicate]

Update: Uwe's solution works, but is broken if someone decides to stay at one intersection for all the measurements, which is what happened when I tried to put this to real data. If this happens, then the original number of rows are not returned to the final data.table. See what happens here:
dput(walking_dat_2)
structure(list(neighborhood = structure(c(3L, 3L, 3L, 3L, 3L,
2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L), .Label = c("Dinkytown", "Downtown",
"Uptown"), class = "factor"), street2 = structure(c(2L, 2L, 2L,
2L, 2L, 2L, 3L, 4L, 2L, 2L, 1L, 1L, 1L), .Label = c("12thAve",
"Hennepin", "Marquette", "Nicolette"), class = "factor"), sequence = c(1,
2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3), visit_2 = c(1, 1, 1, 1,
1, 1, 1, 1, 2, 2, 1, 1, 1)), .Names = c("neighborhood", "street2",
"sequence", "visit_2"), row.names = c(NA, -13L), class = "data.frame")

   neighborhood   street2 sequence visit_2
1        Uptown  Hennepin        1       1
2        Uptown  Hennepin        2       1
3        Uptown  Hennepin        3       1
4        Uptown  Hennepin        4       1
5        Uptown  Hennepin        5       1
6      Downtown  Hennepin        1       1
7      Downtown Marquette        2       1
8      Downtown Nicolette        3       1
9      Downtown  Hennepin        4       2
10     Downtown  Hennepin        5       2
11    Dinkytown   12thAve        1       1
12    Dinkytown   12thAve        2       1
13    Dinkytown   12thAve        3       1

in this case, running Uwe's solution returns only 6 rows.
library(data.table)
setDT(walking_dat)[, visit_2 := rleid(neighborhood, street2)][
     , unique(.SD, by = "visit_2")][
         , visit_2 := rowid(neighborhood, street2)][
             walking_dat, on = .(neighborhood, street2, sequence), roll = TRUE, visit_2 := x.visit_2][]

   neighborhood   street2 sequence visit visit_2
1:       Uptown  Hennepin        1     1       1
2:     Downtown  Hennepin        1     2       1
3:     Downtown Marquette        2     3       1
4:     Downtown Nicolette        3     4       1
5:     Downtown  Hennepin        4     5       2
6:    Dinkytown   12thAve        1     6       1

A: # Not required, but convenient:
walking_dat$combo <- paste(walking_dat$neighborhood, walking_dat$street)

# Place holder:
walking_dat$visit <- NA

# Create it:
for(i in 1:nrow(walking_dat)){
  if(i %in% row.names(walking_dat[with(walking_dat, c(TRUE, diff(as.numeric(interaction(neighborhood, street))) != 0)), ])){
    walking_dat$visit[i] <- sum(walking_dat$combo[with(walking_dat, c(TRUE, diff(as.numeric(interaction(neighborhood, street))) != 0))][1:i]==walking_dat$combo[i], na.rm=T)
  } else{
    walking_dat$visit[i] <- 1
  }
}

walking_dat

   neighborhood    street sequence visit              combo
1        Uptown  Hennepin        1     1    Uptown Hennepin
2        Uptown    Dupont        2     1      Uptown Dupont
3        Uptown    Dupont        3     1      Uptown Dupont
4        Uptown   Lyndale        4     1     Uptown Lyndale
5        Uptown    Dupont        5     2      Uptown Dupont
6      Downtown  Hennepin        1     1  Downtown Hennepin
7      Downtown Marquette        2     1 Downtown Marquette
8      Downtown Nicolette        3     1 Downtown Nicolette
9      Downtown  Hennepin        4     2  Downtown Hennepin
10     Downtown  Hennepin        5     1  Downtown Hennepin
11    Dinkytown   12thAve        1     2  Dinkytown 12thAve
12    Dinkytown   14thAve        2     1  Dinkytown 14thAve
13    Dinkytown   12thAve        3     2  Dinkytown 12thAve

A: The difficulty here is that subsequent recordings to the same street in the same neighborhood should be counted as one visit. This requires to collapse these rows into one, count the visits to different neighborhoods & streets and finally expand this to the original number of rows.
Note that column visit containing the expected result is not overwritten but kept for comparison with the computed visit_new column.
library(data.table)
setDT(walking_dat)[, visit_new := rleid(neighborhood, street)][
  , unique(.SD, by = "visit_new")][
    , visit_new := rowid(neighborhood, street)][
      walking_dat, on = .(neighborhood, street, sequence), roll = TRUE, .SD]

    neighborhood    street sequence visit visit_new
 1:       Uptown  Hennepin        1     1         1
 2:       Uptown    Dupont        2     1         1
 3:       Uptown    Dupont        3     1         1
 4:       Uptown   Lyndale        4     1         1
 5:       Uptown    Dupont        5     2         2
 6:     Downtown  Hennepin        1     1         1
 7:     Downtown Marquette        2     1         1
 8:     Downtown Nicolette        3     1         1
 9:     Downtown  Hennepin        4     2         2
10:     Downtown  Hennepin        5     2         2
11:    Dinkytown   12thAve        1     1         1
12:    Dinkytown   14thAve        2     1         1
13:    Dinkytown   12thAve        3     2         2

Explanation step by step
DF is coerced to data.table. The rleid() function creates unique numbers for changes in neighborhood & street.
 setDT(walking_dat)[, visit_new := rleid(neighborhood, street)][]

    neighborhood    street sequence visit visit_new
 1:       Uptown  Hennepin        1     1         1
 2:       Uptown    Dupont        2     1         2
 3:       Uptown    Dupont        3     1         2
 4:       Uptown   Lyndale        4     1         3
 5:       Uptown    Dupont        5     2         4
 6:     Downtown  Hennepin        1     1         5
 7:     Downtown Marquette        2     1         6
 8:     Downtown Nicolette        3     1         7
 9:     Downtown  Hennepin        4     2         8
10:     Downtown  Hennepin        5     2         8
11:    Dinkytown   12thAve        1     1         9
12:    Dinkytown   14thAve        2     1        10
13:    Dinkytown   12thAve        3     2        11

Note that rows 2 & 3 are repeated as well as rows 9 & 10. The duplicates are removed in the next step which creates a new, temporary data.table object:
setDT(walking_dat)[, visit_new := rleid(neighborhood, street)][
  , unique(.SD, by = "visit_new")][]

    neighborhood    street sequence visit visit_new
 1:       Uptown  Hennepin        1     1         1
 2:       Uptown    Dupont        2     1         2
 3:       Uptown   Lyndale        4     1         3
 4:       Uptown    Dupont        5     2         4
 5:     Downtown  Hennepin        1     1         5
 6:     Downtown Marquette        2     1         6
 7:     Downtown Nicolette        3     1         7
 8:     Downtown  Hennepin        4     2         8
 9:    Dinkytown   12thAve        1     1         9
10:    Dinkytown   14thAve        2     1        10
11:    Dinkytown   12thAve        3     2        11

Now, we can number the visits to distinct neighborhoods and streets using the rowid() function:
setDT(walking_dat)[, visit_new := rleid(neighborhood, street)][
  , unique(.SD, by = "visit_new")][
    , visit_new := rowid(neighborhood, street)][]

    neighborhood    street sequence visit visit_new
 1:       Uptown  Hennepin        1     1         1
 2:       Uptown    Dupont        2     1         1
 3:       Uptown   Lyndale        4     1         1
 4:       Uptown    Dupont        5     2         2
 5:     Downtown  Hennepin        1     1         1
 6:     Downtown Marquette        2     1         1
 7:     Downtown Nicolette        3     1         1
 8:     Downtown  Hennepin        4     2         2
 9:    Dinkytown   12thAve        1     1         1
10:    Dinkytown   14thAve        2     1         1
11:    Dinkytown   12thAve        3     2         2

Finally, we need to expand the result to the original number of rows again. This is accomplished by a rolling join of the temporary data.table with the original DF (all rows included):
setDT(walking_dat)[, visit_new := rleid(neighborhood, street)][
  , unique(.SD, by = "visit_new")][
    , visit_new := rowid(neighborhood, street)][
      walking_dat, on = .(neighborhood, street, sequence), roll = TRUE, .SD]

Perhaps, it might be worth to note that visit_new is used and re-used to hold temporary data through various stages until the final update.
New data set
The fixed code works also with the second data set provided by the OP:
walking_dat_2 <-
structure(list(neighborhood = structure(c(3L, 3L, 3L, 3L, 3L,
2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L), .Label = c("Dinkytown", "Downtown",
"Uptown"), class = "factor"), street = structure(c(2L, 2L, 2L,
2L, 2L, 2L, 3L, 4L, 2L, 2L, 1L, 1L, 1L), .Label = c("12thAve",
"Hennepin", "Marquette", "Nicolette"), class = "factor"), sequence = c(1,
2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3), visit = c(1, 1, 1, 1, 1,
1, 1, 1, 2, 2, 1, 1, 1), visit_new = c(1L, 1L, 1L, 1L, 1L, 2L,
3L, 4L, 5L, 5L, 6L, 6L, 6L)), .Names = c("neighborhood", "street",
"sequence", "visit", "visit_new"), row.names = c(NA, -13L), class = "data.frame")

setDT(walking_dat_2)[, visit_new := rleid(neighborhood, street)][
  , unique(.SD, by = "visit_new")][
    , visit_new := rowid(neighborhood, street)][
      walking_dat_2, on = .(neighborhood, street, sequence),
      roll = TRUE, .SD]

    neighborhood    street sequence visit visit_new
 1:       Uptown  Hennepin        1     1         1
 2:       Uptown  Hennepin        2     1         1
 3:       Uptown  Hennepin        3     1         1
 4:       Uptown  Hennepin        4     1         1
 5:       Uptown  Hennepin        5     1         1
 6:     Downtown  Hennepin        1     1         1
 7:     Downtown Marquette        2     1         1
 8:     Downtown Nicolette        3     1         1
 9:     Downtown  Hennepin        4     2         2
10:     Downtown  Hennepin        5     2         2
11:    Dinkytown   12thAve        1     1         1
12:    Dinkytown   12thAve        2     1         1
13:    Dinkytown   12thAve        3     1         1


text:
Q: Fragment returns null while reading from sharedpreferences file I am reading string value from sharedpreferences in fragment but it return null sometime? Here is my logcat output:
java.lang.IllegalStateException: Fragment Home{fc6bf3a} (14420322-2dbf-46e9-9f52-12586f9fa36b) not attached to a context.
    at androidx.fragment.app.Fragment.requireContext(Fragment.java:900)
    at com.example.socialmediacloneapp.Fragments.Home.getUserName(Home.java:114)
    at com.example.socialmediacloneapp.Fragments.Home.access$000(Home.java:34)
    at com.example.socialmediacloneapp.Fragments.Home$1.onDataChange(Home.java:77)
    at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)

Here is my sharedPreference code:
 private void setUserName(String name){
    SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyFile",MODE_PRIVATE);
    SharedPreferences.Editor editor;
    editor = sharedPreferences.edit();
    editor.putString("name",name);

    editor.apply();

    b.textView.setText("Hi," + name);
}

How to avoid this exception while reading a value from sharedpreferences?

A: call fun "setUserName" in to onViewCreated!


text:
Q: Inheriting dialogs in Adobe CQ5 I'm trying to implement a component dialog by inheriting a dialog of a base component. I'm having troubles with dialogs when used twice.
BASE COMPONENT

*

*dialog

*

*text (name: "./text/content")

OTHER COMPONENT

*

*dialog

*

*text (inherited from base)

*text  (inherited from base)

*settings

*other

The problem with this is that it inherits the name as well and it doesn't look like you can override it. How can I make my jsp print out the two rich-text if they get inherited with the same name? Does CQ5 provide an index so that they can be referenced in the JSPs?

A: If your plan is to have two rich text areas in the dialog of components that inherit from the base, then you must include two rich text areas with unique names in the base component dialog.
Each input field of a dialog must have a unique name otherwise they will point to the same property path relative to the jcr:content node of the component when used on a page.

A: As mentioned above, Each input field of a dialog must have a unique name otherwise they will point to the same property path relative to the jcr:content node of the component when used on a page. Here, this will confuse the CRX while recognizing the textArea to be referred and the second one will not be referred.


text:
Q: Undo fixups on a `git rebase -i` I've seen a few posts here on undoing a git rebase but haven't come across anything that fits my particular case.
I've run the command git rebase -i HEAD~10
After running that, I did fixup to all commits but 3
The first 2 commits is code written by someone else here but only on one file, everything else for this branch was written by me across 5 files and I am the author of the latest commit. All commits between the first 2 and the last 1, I've applied fixup.
When I look at VS Code git blame, I see all the code I wrote but it shows the other guy as the author of the code.
Is there a way for me to undo the fixup so that I can redo the fixup so that I appear as the author for the code I wrote?
An example would be:
git rebase -i HEAD~5

terminal outputs
pick 12345 Commit 1
pick 12344 Commit 2
pick 12343 Commit 3
pick 12342 Commit 4
pick 12341 Commit 5

I apply the fixup so that it now looks like
pick 12345 Commit 1
pick 12344 Commit 2
fixup 12343 Commit 3
fixup 12342 Commit 4
pick 12341 Commit 5

I've now saved these changes.
When I look at my commit history it shows
Commit 1
Commit 2
Commit 5

My goal is to revert my changes so that when I run

git rebase -i HEAD~5

It should look like this again:
pick 12345 Commit 1
pick 12344 Commit 2
pick 12343 Commit 3
pick 12342 Commit 4
pick 12341 Commit 5

A: for your case, you should follow these steps.

*

*suppose your actual working branch is Master (or dev or any other name).

*find your old commits which you have made a fixup by error, to do that you can run this command
git reflog

*suppose now you have found your commits by SHA-1, lets say COMMIT_2, COMMIT_3 and COMMIT_4

*checkout the commit before the fixup commits, in your case, it is COMMIT_1
git checkout COMMIT_1

*make a cheery-pick for old commits
git cherry-pick COMMIT_2
git cherry-pick COMMIT_3
git cherry-pick COMMIT_4

*now after making cherry-pick for your COMMIT_4, you should see an other SHA-1 (commit number) for this commit, lets say COMMIT_4'

*go to your working branch
git checkout Master

*rebase your master on the last cherry-picked commit COMMIT_4'
git rebase COMMIT_4'


text:
Q: Why u-boot calls grub in rpi3? I have rpi3.
This situation is under the embedded system.
The RPI reference shows how to boot Ubuntu.
It shows the way that u-boot calls grub and grub calls Linux...
and I have tried this chain loading.
In that situation, I wonder why u-boot calls grub? not directly calls Linux? Is it possible that grub calls Linux without u-boot?

A: GRUB requires a firmware to load it. U-Boot is one embodiment of such a firmware. For the Raspberry 3 you could use EDK2 [1] or barebox [3] instead.
Linux can be loaded directly from U-Boot. Either using the Linux EFI stub via the bootefi command or via the booti (64 bit) or bootm (32 bit) command.
Some distributions (Suse, Fedora [2]) have decided that it will make maintenance easier if all supported systems are booted in the same way, i.e. via GRUB. Debian Buster is also moving to GRUB on ARMv8 with the Buster release.
[1] https://github.com/tianocore/edk2-platforms/tree/master/Platform/RaspberryPi/RPi3
[2] https://fedoraproject.org/wiki/Changes/uEFIforARMv7
[3] https://www.barebox.org/


text:
Q: LARAVEL get result of withErrors in view in controller i'm using:
if ($validator->fails())
{
   return Redirect::to('/admin/profile')
    ->withErrors($validator)
    ->withInput();
}

how to get result of withErrors in view ?
{{ $errors->all() }}

A: If you want to show all errors in one place you can use
@foreach ($errors->all() as $error)

  <div>{{ $error }}</div>

@endforeach

If you want to show each field's errors e.g. bellow the field you can use (e.g. for email)
{{ $errors->first('email') }}

we use first() in order to show only one error each time for each field.


text:
Q: How to user Viewer js in Laravel Hello I'm trying to display PDF documents with ViewerJS plugin but it doesn't work properly. As documentation says I have <iframe id="viewer" src = "{{URL::to('/')}}/ViewerJS/#../uploads/files/{{$video->source}}" width='100%' height='600' allowfullscreen webkitallowfullscreen></iframe>
I have ViewerJS folder in public folder and my pdf files in public/uploads/files folder. When I use this url it shows my page in frame instead of document. Where is a mistake?

A: Although this is old question, I would like to share how I got that working:
Step 1: Download ViewerJs - http://viewerjs.org/releases/ViewerJS-latest.zip
Step 2: Extract this in public directory of Laravel (I used it with Laravel 4.0)
Step 3: Now, extract another copy in Views folder. That means, you will have ViewerJs library at two locations. One inside public (public/ViewerJs) folder and another will be at (views/ViewerJs)
Step 4: Add below code in your app/routes.php
//DocumentViewer Library
Route::any('ViewerJS/{all?}', function(){

    return View::make('ViewerJS.index');
});

Step 5: Now, add any sample PDF file in your public folder (for testing purpose)
Step 6: Open below URL in your browser
http://example.com/ViewerJS/index.html#../demodoc.pdf
Please replace example.com (in my case this was localhost/webapp) by your project path and replace demodoc.pdf by name of sample PDF file that you added in public folder.
That's it. This will work fine.

A: You should do as follows:

*

*copy the content of ViewerJS folder e.g in your public/viewerjs

*edit PluginLoader.js, ODFViewerPlugin.js, PDFViewerPlugin.js and search for the string ./ and change it to the relative path of the directory, in my example viewer/
Ex.: in PluginLoader.js, you will find:
loadPlugin('./ODFViewerPlugin', function () {
                Plugin = ODFViewerPlugin;
            });
replace this to:
loadPlugin('viewerjs/ODFViewerPlugin', function () {
                Plugin = ODFViewerPlugin;
            });

*create a GET route like: Route::get('/ViewerJS/{all?}', array('as' => 'pdfViewer', 'uses' => 'YOURCONTROLLER@pdfViewer'));

*create the method in you controller like:
public function pdfViewer()
{
  return View::make('pdfview.view');
}

*Create your the view and paste the entire content of the index.html, it's inside the ViewerJS folder. Don't forget to replace all css and javascript file references with:
{{ asset('viewerjs/viewer.css') }}
{{ asset('viewerjs/viewer.js') }}
{{ asset('viewerjs/PluginLoader.js') }}

*Call the route like: http://www.xxxxx.com/ViewerJS#YOUR_PATH_TO_THE_PDF_FILE_UNDER_THE_PUBLIC_FOLDER
example: uploads/pdfs/test.pdf
Note that you don't have to specify public/uploads/pdfs/test.pdf !!

A: You have to add the PDF's name to the path, as well. For example:
http://www.xxxxx.com/ViewerJS#YOUR_PATH_TO_THE_PDF_FILE_UNDER_THE_PUBLIC_FOLDER/NAME_FILEP


text:
Q: Spring don't displaying webpage and can't found resource I wrote simple Java application using Spring framework and Thymeleaf. On my IDE it's working complettly fine but when I'm making JAR artifact and exporting it to my linux server it's booting but I'm getting this errors:
02:56:06.447 [main] INFO com.ibcs.rfid.RfidApplication - Started RfidApplication in 142.158 seconds (JVM running for 151.664)
Jul 15, 2021 2:56:10 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring DispatcherServlet 'dispatcherServlet'
02:56:10.948 [http-nio-8080-exec-1] INFO org.springframework.web.servlet.DispatcherServlet - Initializing Servlet 'dispatcherServlet'
02:56:10.954 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Detected StandardServletMultipartResolver
02:56:10.959 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Detected AcceptHeaderLocaleResolver
02:56:10.964 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Detected FixedThemeResolver
02:56:11.171 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Detected org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator@1db0c88
02:56:11.251 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Detected org.springframework.web.servlet.support.SessionFlashMapManager@1384aac
02:56:11.257 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
02:56:11.261 [http-nio-8080-exec-1] INFO org.springframework.web.servlet.DispatcherServlet - Completed initialization in 308 ms
02:56:11.638 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/", parameters={}
02:56:11.745 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.ibcs.rfid.controllers.ServiceControllers#loginForm(Model)
02:56:12.994 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.view.ContentNegotiatingViewResolver - Selected 'text/html' given [text/html, application/xhtml+xml, image/webp, application/xml;q=0.9, */*;q=0.8]
02:56:13.003 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.view.InternalResourceView - View name 'login', model {authentication=com.ibcs.rfid.models.Authentication@14147d2, org.springframework.validation.BindingResult.authentication=org.springframework.validation.BeanPropertyBindingResult: 0 errors}
02:56:13.065 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.view.InternalResourceView - Forwarding to [login]
02:56:13.265 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - "FORWARD" dispatch for GET "/login", parameters={}
02:56:13.383 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped to ResourceHttpRequestHandler [Classpath [META-INF/resources/], Classpath [resources/], Classpath [static/], Classpath [public/], ServletContext [/]]
02:56:13.434 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.resource.ResourceHttpRequestHandler - Resource not found
02:56:13.441 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Exiting from "FORWARD" dispatch, status 404
02:56:13.461 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
02:56:13.480 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - "ERROR" dispatch for GET "/error", parameters={}
02:56:13.549 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)

My files tree:
├───.idea
│   ├───artifacts
│   └───libraries
├───.mvn
│   └───wrapper
├───out
│   └───artifacts
│       └───rfid_jar
├───src
│   ├───main
│   │   ├───java
│   │   │   ├───com
│   │   │   │   └───ibcs
│   │   │   │       └───rfid
│   │   │   │           ├───controllers
│   │   │   │           ├───models
│   │   │   │           └───storers
│   │   │   └───META-INF
│   │   └───resources
│   │       ├───jsons
│   │       ├───static
│   │       │   ├───css
│   │       │   ├───img
│   │       │   └───js
│   │       └───templates
│   └───test
│       └───java
│           └───com
│               └───ibcs
│                   └───rfid
└───target
    ├───classes
    │   ├───com
    │   │   └───ibcs
    │   │       └───rfid
    │   │           ├───controllers
    │   │           ├───models
    │   │           └───storers
    │   ├───jsons
    │   ├───static
    │   │   ├───css
    │   │   ├───img
    │   │   └───js
    │   └───templates
    ├───generated-sources
    │   └───annotations
    ├───generated-test-sources
    │   └───test-annotations
    └───test-classes
        └───com
            └───ibcs
                └───rfid

And my application.properties content:
spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false

Also here is part of my Controller:
    @GetMapping("/")
    public String loginForm(Model model)
    {
        model.addAttribute("authentication", new Authentication());
        return "login";
    }

Any ideas how can I fix it?
Also I'm limited to only .jar file cause It have to run on Zebra FX9600

A: Solution (from comments):

*

*Build it with maven

Thanks M. Deinum


text:
Q: Right or wrong? Limit of sequence Let $\{a_n\}$ a sequence such that $a_n\ge0$ for all $n\in\mathbb{N}$. We suppose that
\begin{equation}
\lim_{n\to\infty}a_n=0.
\end{equation}
I would like to show that $a_n=0$ for all $n\in\mathbb{N}$. Then from the definition of limit for all $\epsilon>0$ $\exists n_0>0$ such that
\begin{equation}
0\le a_n<\epsilon\quad\text{for all}\;n>n_0>0
\end{equation}
can I conclude by saying that $a_n=0$ for all $n\in\mathbb{N}$ ?
Thanks!

A: $a_n = \frac{1}{n}$ is a sequence such that $a_n > 0$ for all $n$ and $\lim_{n \to \infty} a_n = 0$, but $a_n$ itself is never zero.
So the statement (as I understand it) is false.

A: What you write is neither right nor wrong, since you don't tell us what $n_0$ is. But, whatever you may add about about $n_0$ will turn your statment into a false one (assuming that it turns it into a meaningful statement). For instance, $\lim_{n\in\mathbb N}\frac1n=0$, but it is not true that $(\forall n\in\mathbb{N}):\frac1n=0$.

A: If $\lim_{n\to\infty}a_n=0$ then for every $\epsilon>0$ an integer $n_{\epsilon}$ exists such that $n> n_{\epsilon}$ implies that $a_n<\epsilon$.
Note that $n_{\epsilon}$ depends on $\epsilon$.


text:
Q: MongoDB - Updating subdocument I'm working with mongo 3.4.13 and I want to add an element in this document:
{
    "_id" : ObjectId("5981d38cf43047f3235febbc"),
    "code" : "A0001",
    "subItems": [
        {
            "_id" : ObjectId("5981d38cf43047f3235febbc"),
            "code" : "A1001",
            "subItems": []
        },
        {
            "_id" : ObjectId("5981d38cf43047f3235febbc"),
            "code" : "A2001",
            "subItems": [
                {
                    "_id" : ObjectId("5981d38cf43047f3235febbc"),
                    "code" : "A2101",
                    "subItems": [
                        //I wanna add an element here
                    ]
                }
            ]
        }
    ]

}

But I have no idea how to do it, any idea?

A: According to description as mentioned into above question I assume that you need to add an  element into subItems array field belonging to BSON Document as mentioned above.
$addToSet operator is used to append a value into an array field as a part of update operation only if value does not exist into an array thereby ensuring uniqueness of values into an array field.


text:
Q: Http Error: 400 Missing Required Parameter while using jobs.query() BQ API I couldn't find the exact same question in stack-overflow. Apologies, if this is a repeated question.
I am using this code snippet to pass query to a table.
_body = {'_query':'SELECT * FROM `<projectId>.<datasetId>.<tableId>`',
                   'useLegacySql': False,
                   'maxResults': 100
                   }

table = _bq.jobs().query(projectId= <projectId>,alt = "json", body = _body).execute()

I am passing all the required arguments, since using jobs.query API, I am getting status code 200, with the results, but while integrating the snippet in python program, I get following error:

File "D:\Applications\Python27\lib\site-packages\oauth2client\_helpers.py", line 133, in positional_wrapper\n    return wrapped(*args, **kwargs)\n', '  File "D:\Applications\Python27\lib\site-packages\googleapiclient\http.py", line 842, in execute\n    raise HttpError(resp, content, uri=self.uri)\n', 'HttpError: https://www.googleapis.com/bigquery/v2/projects/projectId/queries?alt=json returned "Required parameter is missing">\n']

A: I am not sure about which library you are using in your example, but I would advise to use the Python BigQuery Client Libraries. You will find the complete reference (as well as plenty of examples) in its GitHub reference page.
More specifically, here you will find some examples on how to query data using the Python Client Library.
After installing the client library and setting up authentication (both steps are explained in the first link I shared), you will be able to execute a script such as the one I present below. In it, a public dataset is being queried, but feel free to modify the query to the one of your need.
from google.cloud import bigquery

client = bigquery.Client()

# Define the query
query = "SELECT * FROM `bigquery-public-data.stackoverflow.posts_questions` LIMIT 10"

# Define the query job, by default uses Standard SQL
query_job = client.query(query)

results = query_job.result()  # Waits for job to complete.

for row in results:
    print("{}".format(row.title))

Also note that this Client Library uses Standard SQL by default (which is the preferred language to work with BigQuery), but you can always modify the job settings by adjusting the QueryJobConfig.

A: I believe issue not with bq parameters but with execute() parameters.
It should have http parameter where you supply http context with user credentials
In appengine you can do something like this
SCOPE='https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/cloud-patform '
_http = AppAssertionCredentials(scope=SCOPE).authorize(httplib2.Http(timeout=600))
table = _bq.jobs().query(projectId= <projectId>,alt = "json", body = _body).execute(http=_http)

A: You are not sending the required parameters indeed. Check this example for how to properly do so:
def sync_query(service, project_id, query, timeout=10000, num_retries=5):
    query_data = {
                    'query': query,
                    'timeoutMs': timeout,
                 }
    return service.jobs().query(
            projectId=project_id,
            body=query_data).execute(num_retries=num_retries)


text:
Q: Designing a PCB that allows to measure current What is the best way to "debug" the current in a PCB?
My (first!) PCB has a 220v->5v PS on it. I would like to measure how much current is using after the PS to monitor how far from the limits my circuit is.
To achieve that, I was thinking on adding jumper pins, to be able to attach a multimeter.
Is there a better way of doing that?

A: Add a low value current sense resistor in series with the output from the 5V supply, and then measure the voltage across it to determine current. In other words, do it the same way your multimeter does (it measures current internally by looking at the voltage drop across a low value resistor.)
Later on, in 'production', you can replace the shunt resistor with a shunt.  (If this is important, and current margins allow, pick a standard case size so you can put a 0ohm resistor in there later.)
If you want to bring the ends of the resistor out to a connection, use a separate pair of tracks to make a kelvin connection as directly to the pads of the resistor.
Generally test points aren't brought out to headers like that, but to little pins like this which you can clip a lead to.  I'm no expert, however, in PCB design. If you have a ready made lead to connect a header to your multimeter (in voltage mode) go ahead and use a header.  But if people will be clipping leads to it, clipping two test probes to a 0.1" pitch header is quite hard.
Note that what you're proposing will work, but has quite a few disadvantages:

*

*When measuring it adds long wires in series with the output of the psu.  This will change the regulator's inductive load and may effect performance, or even cause oscillation.

*All the current has to go through that tiny little header.

*All the current has to go through a tiny little header shunt when you're not measuring.

A: In addition to the first answer, if it is important in production you may consider the permanent addition of a TS1100 Uni/Bidirectional Current-Sense Amplifier and a good shunt resistor to give you a direct measurement of voltage across the shunt resistor and consequently the actual current, all with great accuracy. There's even a demo board that you can very quickly wire-in, and with a standard voltmeter or oscilloscope, you can measure the PS current as required.


text:
Q: How do I change the below code such that it prints "present" without changing the main function import java.util.HashMap;
import java.util.Map;

public class StudentTest {
    public static final class Student {
        public Student( String name ) {
            this.name = name;
        }
        private String name;
    }

    public static void main(final String[] args ) {
        Map<Student, String> map = new HashMap<>();
        map.put( new Student( "john"), "present" );
        System.out.println( map.get( new Student( "john" ) ) );
    }

I know how to make this work by changing the main function and initializing the object but is it possible to achieve the result without touching the main? I was asked this in an interview.
I have spent a lot of time googling but haven't been able to get close to the answer. I'm not even sure what should be my search parameters anymore. Please help.

A: You have 2 different student object used while putting to and  getting from HashMap. So you were not able to print "present".
So you can override 2 methods in Student class, equals and hashcode such that when name is equal it equals should return true and hashcode should return same value.
That's it, your are done. You will get "present"
Overriding just equals is not fully correct answer. There is contract "Equal objects should always return same hashcode"
So overriding equal and hashcode is the clean way

A: You need to override the equals(Object o) method in class Student.
As default in java, the equals method just check if the objects are exactly the same, create with one new expression.
To change it, override the equals method to compare the name of the students.
For example:
public boolean equals(Object o){
    if(o instanceof Studet){
        return this.name.equals(((Student)o).name);
    }
    return false;
}

And, because of java contract, you should override hashCode like this:
public int hashCode(){
    return this.name.hashCode();
}


text:
Q: What network protocols does luarocks install use? I am running on a redhat box, behind a corporate firewall.  I'm guessing that some of the protocols are getting blocked, but I'm a relative neophyte to git, and this is my first time ever using luarocks.  It looks to me like luarocks is trying to use https:// so there should be no firewall issues....  But the error messages imply a firewall problem.
Here's what I know:
I do know that this git command works fine on my machine.  git is able to clone the repository locally, and I can build luarocks from source.
git clone https://github.com/torch/luajit-rocks.git

But, this command fails:
luarocks install cwrap

Here is the output from the command
Installing https://raw.githubusercontent.com/torch/rocks/master/cwrap-scm-1.rockspec...
Using https://raw.githubusercontent.com/torch/rocks/master/cwrap-scm-1.rockspec... switching to 'build' mode
Initialized empty Git repository in /tmp/luarocks_cwrap-scm-1-8589/cwrap/.git/
github.com[0: 192.30.252.129]: errno=Connection timed out

A: LuaRocks uses LuaSocket and LuaSec when available to do HTTP and HTTPS, but apart from that it just defers to external commands, such as git.
You can run luarocks with the --verbose flag and it will output every external command it calls. You can then check what is the git command line it is calling, and try it directly from the command line. This should help to diagnose if any flag is causing problems.

A: As a workaround, you can force git to use https with the following command:
git config --global url.https://github.com/.insteadOf git://github.com/

Source: https://github.com/torch/rocks/issues/38


text:
Q: Query different models from the same set of tables with spring-data I would like to know how to best use Spring Data to query the same set of database tables differently depending on the use cases.

Scenario: Products can be bought by Users via Orders. Each Product can either be a standalone product or consist of multiple Subproducts (self referencing table).
The database schema is managed separately.
What's the most elegant way to retrieve different models from the same set of tables using Spring Data? Considering the following queries:

*

*Get all products including their subproducts

*Get all the users that purchased a product

*Get all products with the number of purchases for each.

From a framework agnostic view I would create separate models for each and then fill them with the result of an sql query. This would lead to

*

*A CombiProduct entity that maintains references to other CombiProducts.

*A UserProduct that maintains references to all users that bought it.

*A PurchasedProduct that maintains a purchase count.
Each model would be different, because the use case that needs the UserProduct doesn't need information about sub products for example. The use case would then define what's needed from the database.

But with Spring Data i can't find any easy-to-use solutions for scenarios like this. Because the whole Repository support in spring-data-jdbc requires me to define AggregateRoots. And with Aggregate Roots it seems like I can only ever have a table/entity in a single Aggregate (and not have three separate ones like described above) - Am I right?
And the other possibility is querying the database using JdbcTemplate which looks like it could end up beeing a lot of boilerplate code.
What is the spring-data way of creating solutions like that?

A: Spring Data JDBC manages aggregates as described in Domain Driven Design.
The primary aggregates in your model seem to be those that you already described: Product, Order, and User.
Each of those would get their respective repository.
For example
interface ProductRepository extends CrudRepository<Product, Long>{}

References between those are modelled via ids, not Java references.
See https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates for more details.
With this number 2 in your list of examples is pretty straight forward

*Get all the users that purchased a product

You would simply create a method in your UserRepository with a custom query.
interface UserRepository extends CrudRepository<User, Long> {

    @Query("""
        select * from User
        where id in (
            select o.user_id
            from Order o
            join Order_Item oi
            on o.id = oi.order_id
            where oi.product_id = :product_id
       )
    """
    List<User> findAllByOrderedProduct(Long productId)
}

Number three is a little more tricky.

*Get all products with the number of purchases for each.

I see 3 main ways to do this.

*

*You could either make the number of purchases a read only property of your Product and map the complete entity to a view containing that column.
Of course you would need to make that view updatable.

*You could make a separate ProductWithStatistics entity, for which the repository is a readonly one. You would map that to the view as in the previous variant, but would define your repository as:
interface ProductWithStatistics extends Repository<ProductWithStatistics, Long> { // <-- note: not a CrudRepository
    Optional<T> findById(ID id);

    boolean existsById(ID id);

    Iterable<T> findAllById(Iterable<ID> ids);

    long count();
}

These are the reading repository methods from the CrudRepository except findAll which probably doesn't make sense for Product.

*The JdbcTemplate is always a good fallback, when Spring Data JDBC doesn't give you what you need.
And with DataClassRowMapper the amount of boiler plate should be limited in most cases.

For the first use case

*

*Get all products including their subproducts

I'm afraid you are limited to JdbcTemplate if you want to load them in one go, because I don't see a way how a self refence like this can be turned into a single aggregate.
Finally:

with Aggregate Roots it seems like I can only ever have a table/entity in a single Aggregate (and not have three separate ones like described above) - Am I right?

No, that is not correct. For example the Order aggregate almost certainly contains a LineItem entity of some sort, which will be stored in its own table.