text:
Q: My ethernet interface name has changed from eth0 to eth1 I was doing some work in GNS3 in which I had to run a Virtual machine(tiny version of OS) and needed to connect that machine to a virtual router that was running also on GNS3. For this I needed to set an ip address in one of my interfaces(eth0).
After I close GNS3, and failed to get internet from port. I also found that my Ethernet interface name has changed from eth0 to eth1.
I think that is the reason I am not getting internet form my LAN port.
I deleted that project in GNS3 but problem persists.
Is there any way to change it again to eth0 ?

A: You need to modify the udev rule for the network interface to change the name. As seen in the /etc/udev/rules.d/70-persistent-net.rules file:
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*",
ATTR{address}=="xx:xx:xx:xx:xx:xx", ATTR{dev_id}=="0x0", ATTR{type}=="1",
KERNEL=="eth*", NAME="eth1"

the name has been changed to eth1.
To change the name of the interface back to eth0:

*

*Open the file /etc/udev/rules.d/70-persistent-net.rules with your favorite editor

*Find the rule matching your MAC address

*Change the NAME value from eth1 to eth0 i.e. NAME="eth0"

*To apply changes without restarting run sudo udevadm trigger

A: first, SU -l into root then perform the following:
cd /etc/sysconfig
ls
cd network-scripts/
ls
vi ifcfg-eth0
VI is an editor that is very dangerous lol, but be careful to not change anything unless that is the objective.

A: For ubuntu 16.04 and above you should not use KERNEL=="eth*". So you should just use
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*",
ATTR{address}=="xx:xx:xx:xx:xx:xx", ATTR{dev_id}=="0x0", ATTR{type}=="1", NAME="eth1"


text:
Q: Mapping several columns from sql to a java object I am trying to retrieve and process code from JIRA, unfortunately the pieces of information (which are in the Metadata-Plugin) are saved in a column, not a row.
Picture of JIRA-MySQL-Database
The goal is to save this in an object with following attributes:
public class DesiredObject {
    private String Object_Key;
    private String Aze.kunde.name;
    private Long Aze.kunde.schluessel;
    private String Aze.projekt.name;
    private Long Aze.projekt.schluessel
    //getters and setters here
}

My workbench is STS and it's a Spring-Boot-Application.
I can fetch a List of Object-Keys with the JRJC using:
JiraController jiraconnect = new JiraController();
List<JiraProject> jiraprojects = new ArrayList<JiraProject>();
jiraprojects = jiraconnect.findJiraProjects();

This is perfectly working, also the USER_KEY and USER_VALUE are easily retrievable, but I hope there is a better way than to perform
three SQL-Searches for each project and then somehow build an object from all those lists.
I was starting with
for (JiraProject jp : jiraprojects) {
            String SQL = "select * from jira_metadata where ENRICHED_OBJECT_KEY = ?";
            List<DesiredObject> do = jdbcTemplateObject.query(SQL, new Object[] { "com.atlassian.jira.project.Project:" + jp.getProjectkey() }, XXX);
        }

to get a list with every object, but I'm stuck as i can't figure out a ObjectMapper (XXX) who is able to write this into an object.
Usually I go with
object.setter(rs.getString("SQL-Column"));

But that isn't working, as all my columns are called the same. (USER_KEY & USER_VALUE)
The Database is automatically created by JIRA, so I can't "fix" it.
The Object_Keys are unique which is why I tried to use those to collect all the data from my SQL-Table.
I hope all you need to enlighten me is in this post, if not feel free to ask for more!
Edit: Don't worry if there are some 'project' and 'projekt', that's because I gave most of my classes german names and descriptions..

A: I created a Hashmap with the Objectkey and an unique token in brackets, e.g.: "(1)JIRA".
String SQL = "select * from ao_cc6aeb_jira_metadata";
List<JiraImportObjekt> jioList = jdbcTemplateObject.query(SQL, new JiraImportObjektMapper());
    HashMap<String, String> hmap = new HashMap<String, String>();
    Integer unique = 1;
    for (JiraImportObjekt jio : jioList) {

        hmap.put("(" + unique.toString() + ")" + jio.getEnriched_Object_Key(),
                jio.getUser_Key() + "(" + jio.getUser_Value() + ")");
        unique++;
    }

I changed this into a TreeMap
Map<String, String> tmap = new TreeMap<String, String>(hmap);

And then i iterated through that treemap via
String aktuProj = new String();
for (String s : tmap.keySet()) {
        if (aktuProj.equals(s.replaceAll("\\([^\\(]*\\)", ""))) {

        } else { //Add Element to list and start new Element }
//a lot of other stuff
}

What I did was to put all the data in the right order, iterate through and process everything like I wanted it.
Object hinfo = hmap.get(s);
        if (hinfo.toString().replaceAll("\\([^\\(]*\\)", "").equals("aze.kunde.schluessel")) {
            Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(hinfo.toString());
            while (m.find()) {
                jmo[obj].setAzeKundeSchluessel(Long.parseLong(m.group(1), 10));
                // logger.info("AzeKundeSchluessel: " +
                // jmo[obj].getAzeKundeSchluessel());
            }
        } else ...

After the loop I needed to add the last Element.
Now I have a List with the Elements which is easy to use and ready for further steps.
I cut out a lot of code because most of it is customized for my problem.. the roadmap should be enough to solve it though.
Good luck!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как выровнять содержимое button по вертикали если использовался float? Заметил что у кнопок со свойством float содержимое немного вниз сдвинуто vertical-align и line height не работают. Как выровнять?

A: А попробовали использовать padding-top и padding-bottom? Должно работать.


text:
Q: jquery . Fast image slide on IE I am try to do something like video manyal on how to use some pages on my website.
with vector editor i have made step by step pictures and want to show tham realy fast each after other to something like gif file.
Using jquery hide and show methods.
$(firstimage).hide();
$(secondimage).show();

it works fine on chrome nad firefox but ie make it slower and blicks.
i have try to preload images to chache but no luck.
mybe someone done it before?

A: You have two options.
Option one is to create absolute positioned divs for each image and cycle through them with the click event.
Option two is to cycle through each image using the click event.
Option one:
HTML

CSS
#container {
    position:relative;
}

.images {
    position:absolute;
    top:0px;
    left:0px;
    display:none;
}

JavaScript
var total_images = 4; // Set this variable to total number of images
$(document).ready(function() {
   $('.images').hide();
   $('#image-1').show();
   $('.images').click(function() {
       var current_img = parseInt($(this).attr('id').split('-')[1]); // get current file number
       var new_img = current_img+1; // Increment current image number by one
       $('#image-' + current_img).hide();
       if(new_img > total_images){  // check if total has been reached
          new_img = 1;
       }
       $('#image-' + new_img).show(); // set new image source
  });
});

this option will be faster as you don't have to wait to load the image.
Here is the JSFiddle for this option: http://jsfiddle.net/xsCVY/1/
Option two:
HTML

JavaScript

Please keep in mind that for this to work, the file and file path should only have one "-" in it or you'll have to split on a different unique character, and then name all the images with a number 0 - whatever after the "-" or the other character that you've chosen.
Here is a jsfiddle: http://jsfiddle.net/PDzT8/

A: The problem  in my case is pre-load images to cache.
I can not user absolute position , becose  my parent element mixed positions and it bring images outside of parent element. I need to keep it simple.
Bu thanks for respond, i have found solution which working today.
I just before slide , duplicate  all used images on the page second time with 1px width so that will cache them to memory. Unfortunately all JavaScript pre-loads methods did not work


text:
Q: Why can't round correctly using Math.round? Why can't I round correctly this:
val solution = Math. round(iDouble * 10.00) / 10.00

Debugger says:
iDouble = 118.64300000000001
solution = 118.6

A: I dont see what is wrong with that. Here is the explanantion.
118.64300000000001d * 10L = 1186.43d
Math.round will return the number rounded to the integer part as an long.
Math.round(1186.43d) = 1186L.
1186L / 10.00d = 118.6d
So it looks fine to me. Keep in mind that dividing by a double/float will result in a double/float.


text:
Q: (Express, Node, TypeScript, REST API) How can I import a function from the service to the controllers? Property ... does not exist on type typeof How should I import loginMember in Controller? I am developing a REST API and now I need to use code in a different file location. I am having an error in the controller. When I am calling loginMember. (Cannot find name 'loginMember'.ts(2304))
SERVICE
import MembersModel from '../models/MembersModel';
import BaseService from './BaseService';
import { createPasswordToHash } from '../scripts/utils/auth';
class MembersService extends BaseService {
  constructor() {
    super(MembersModel);
  }

  // loginMember
  loginMember = async (email: any, password: any) => {
    return new Promise(async (resolve, reject) => {
      try {
        let data = await this.BaseModel.findOne({
          email: email,
          password: createPasswordToHash(password),
        });
        return resolve(data);
      } catch (error) {
        return reject(error);
      }
    });
  };

}

export default MembersService;

CONTROLLER
import BaseController from './BaseController';
import MembersService from '../services/MembersService';
import ApiError from '../errors/ApiError';
import { NextFunction, Request, Response } from 'express';
import { createPasswordToHash, generateAccessToken } from '../scripts/utils/auth';
import httpStatus from 'http-status';

class MembersController extends BaseController {
  constructor(membersService: MembersService) {
    super(membersService);
  }

login = (req: Request, res: Response, next: NextFunction) => {
  MembersService.loginMember(req.body)
    .then((response: any) => {
      if (response) {
        const member = {
          ...response.toObject(),
          accessToken: generateAccessToken(response.toObject()),
        };
        delete member.password;
        delete member.createdAt;
        delete member.updatedAt;
        return res.status(httpStatus.OK).send(member);
      }
      return res.status(httpStatus.UNAUTHORIZED).send({ error: 'Invalid email or password' });
    })
    .catch((err: { message: string }) => {
      return next(
        new ApiError(err.message, httpStatus.UNAUTHORIZED, 'login', req.headers['user-agent']?.toString() || 'Unknown')
      );
    });
};

}
export default new MembersController(new MembersService());

Now I am gettig a new error: "Property 'loginMember' does not exist on type 'typeof MembersService'.ts(2339)"

A: You're trying to call loginMember as a static method, but it's not defined as one. You'll have to use an instance of MembersService to use the method. Since your MembersController is already being initialized with a MembersService instance, you may just want to have a membersService property on the MembersController. Also, the loginMember method takes an email and a password, so you'll have to pass those arguments explicitly instead of just passing the request body. (I'm not sure where the email and password are in the request body though, so I can't help you there.) So with those changes, it would look like:
class MembersController extends BaseController {
  private membersService: MembersService;

  constructor(membersService: MembersService) {
    super(membersService);
    this.membersService = membersService;
  }

login = (req: Request, res: Response, next: NextFunction) => {
  this.membersService.loginMember(email, password) // <- Get these from the request
    .then((response: any) => {
      if (response) {
        const member = {
          ...response.toObject(),
          accessToken: generateAccessToken(response.toObject()),
        };
        delete member.password;
        delete member.createdAt;
        delete member.updatedAt;
        return res.status(httpStatus.OK).send(member);
      }
      return res.status(httpStatus.UNAUTHORIZED).send({ error: 'Invalid email or password' });
    })
    .catch((err: { message: string }) => {
      return next(
        new ApiError(err.message, httpStatus.UNAUTHORIZED, 'login', req.headers['user-agent']?.toString() || 'Unknown')
      );
    });
};

One other code style suggestion would be to use async await instead of .then in the login method. Also, the Promise wrapping in the loginMember method looks unnecessary, and using an async function as the argument is an antipattern. The following should get the job done while avoiding those pitfalls:
  loginMember = (email: any, password: any): Promise<Response> => {
    return this.BaseModel.findOne({
      email: email,
      password: createPasswordToHash(password),
    });
  };


text:
Q: Error retrieving data from firebase using recycler view: E/RecyclerView: No adapter attached; skipping layout I am on a project now and am trying to obtain data from my firebase using recycler view and viewholder, but using my helper class, immediately when the app launches and I try retrieving data through my helper class it crashes, and when i look through my logcat, I get this error

E/RecyclerView: No adapter attached; skipping layout....

I have searched for a lot o answers and i see some but they are not related to my code...
Here is my mainactivity code
package com.example.android.journalapp;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.example.android.journalapp.users.LogInActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private static final String DATE_FORMAT = "dd/MM/yyy";
    private SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT,
    Locale.getDefault());

    private FirebaseAuth mFirebaseAuth;
    private FirebaseUser mFirebaseUser;
    private DatabaseReference mDatabase;
    String mUserId;

    private RecyclerView mRecyclerView;

    private FirebaseHelper helper;

    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mFirebaseAuth = FirebaseAuth.getInstance();
        mFirebaseUser = mFirebaseAuth.getCurrentUser();

        mRecyclerView = (RecyclerView) findViewById(R.id.journal_recycler);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setHasFixedSize(true);

        if (mFirebaseUser == null) {
            // Not logged in, launch the Log In activity
            loadLogInView();
        } else {
            mDatabase = FirebaseDatabase.getInstance().getReference();
            mUserId = mFirebaseUser.getUid();
            helper = new FirebaseHelper(context, mDatabase, mRecyclerView,
            mUserId);
            helper.refreshData();

        }

        FloatingActionButton fab = (FloatingActionButton)
        findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent addJournalIntent = new Intent(MainActivity.this,
                AddJournalActivity.class);
                addJournalIntent.putExtra("USER_ID", mUserId);
                startActivity(addJournalIntent);
            }
        });

    }

    private void loadLogInView() {
        Intent intent = new Intent(this, LogInActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is         present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_logout) {
            mFirebaseAuth.signOut();
            loadLogInView();
        }

        return super.onOptionsItemSelected(item);
    }

}

here is my firebase helper class
    package com.example.android.journalapp;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.example.android.journalapp.model.Journal;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

public class FirebaseHelper {

    private String mUserId;
    private Context context;
    private DatabaseReference mDb;
    RecyclerView mRecyclerView;
    ArrayList<Journal> journals = new ArrayList<>();
    public JournalAdapter mJournalAdapter;
    private static final String DATE_FORMAT = "dd/MM/yyy";
private SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT,     Locale.getDefault());

    public FirebaseHelper(Context context, DatabaseReference mDb,     RecyclerView mRecyclerView, String mUserId) {
        this.context = context;
        this.mDb = mDb;
        this.mRecyclerView = mRecyclerView;
        this.mUserId = mUserId;

    }

    public void saveData(String journal, String date) {
        Journal journalEntry = new Journal(journal, date);
        mDb.child("users").child(mUserId).child("journals").push().setValue(journalEntry)    ;
//        .child("journal")
    }

    public void recieveData(DataSnapshot ds) {

        journals.clear();
        for (DataSnapshot dataSnapshot : ds.getChildren()) {
        Journal journal = dataSnapshot.getValue(Journal.class);

        journals.add(journal);
    }

        mJournalAdapter = new JournalAdapter(context, journals);
    mRecyclerView.setAdapter(mJournalAdapter);
//        if (journals.size() > 0) {
//
//            mJournalAdapter = new JournalAdapter(context, journals);
//            mRecyclerView.setAdapter(mJournalAdapter);
//        } else {
//            Toast.makeText(context, "No data", Toast.LENGTH_SHORT).show();
//        }
    }

    public void refreshData() {
        mDb.child("users").child(mUserId).child("journals").addChildEventListener(new     ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot,     @Nullable String s) {
                recieveData(dataSnapshot);
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot,     @Nullable String s) {
                recieveData(dataSnapshot);
            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot,     @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

here is my model class
    package com.example.android.journalapp.model;

import java.util.Date;

public class Journal {

    private String journalContent;
    private String date;

    public Journal(String journalContent, String date) {
        this.journalContent = journalContent;
        this.date = date;
    }

    public String getJournalContent() {
        return journalContent;
    }

    public void setJournalContent(String journalContent) {
        this.journalContent = journalContent;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }
}

///
here is my adapter class
    package com.example.android.journalapp;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.android.journalapp.model.Journal;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

public class JournalAdapter extends RecyclerView.Adapter<JournalHolder> {

    Context context;
    private ArrayList<Journal> journals;

    private static final String DATE_FORMAT = "dd/MM/yyy";
    private SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT,     Locale.getDefault());

    public JournalAdapter(Context context, ArrayList<Journal> journals) {
        this.context = context;
        this.journals = journals;
    }
    @NonNull
    @Override
    public JournalHolder onCreateViewHolder(@NonNull ViewGroup parent, int     viewType) {
        View view =     LayoutInflater.from(parent.getContext()).inflate(R.layout.journal_layout, parent,     false);
        JournalHolder holder = new JournalHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull JournalHolder holder, int position)     {
        holder.mJournalTextView.setText(journals.get(position).getJournalContent());

        String date = journals.get(position).getDate();
        holder.mDateTextView.setText(date);
    }

    @Override
    public int getItemCount() {
        if (journals == null) {
            return 0;
        }

        return journals.size();
    }
}

//
here is my viewholder class
    package com.example.android.journalapp;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

public class JournalHolder extends RecyclerView.ViewHolder {

    TextView mJournalTextView;
    TextView mDateTextView;

    public JournalHolder(View itemView) {
        super(itemView);

        mJournalTextView = itemView.findViewById(R.id.journal_text_view);
        mDateTextView = itemView.findViewById(R.id.journal_date_text_view);
    }
}

i am able to push into the data base, but to retrieve data gives me the error E/RecyclerView: No adapter attached; skipping layout

A: Try this code..
display_data.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.RecyclerView
    android:id="@+id/rvData"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</android.support.v7.widget.RecyclerView>

<TextView
    android:id="@+id/dlTvEmpty"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="No Found"
    android:textSize="16dp"
    android:visibility="gone"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

DisplayActivity.java..
public class DisplayActivity extends AppCompatActivity {
private RecyclerView mRvData;
private DisplayAllData allDataAdapter;
private DatabaseReference mDatabase;
private TextView mTvEmpty;
private FirebaseDatabase mFirebaseInstance;
private List<User> mUserList = new ArrayList<>();

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.display_data);
    initView();
}

private void initView() {
    mFirebaseInstance = FirebaseDatabase.getInstance();
    mDatabase = mFirebaseInstance.getReference("usersDb/UserTable");

    mRvData = findViewById(R.id.rvData);
    mTvEmpty = findViewById(R.id.dlTvEmpty);
    mRvData.setLayoutManager(new LinearLayoutManager(this));
    mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            mUserList.clear();
            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                User user = dataSnapshot1.getValue(User.class);
                mUserList.add(user);
            }
            allDataAdapter = new DisplayAllData(DisplayActivity.this, mUserList);
            mRvData.setAdapter(allDataAdapter);
            allDataAdapter.notifyDataSetChanged();
            if (mUserList.isEmpty())
                mTvEmpty.setVisibility(View.VISIBLE);
            else
                mTvEmpty.setVisibility(View.GONE);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}
}

DisplayAdapter.java..
public class DisplayAllData extends RecyclerView.Adapter<DisplayAllData.ItemViewHolder> {
private List<User> mUserLsit = new ArrayList<>();
private Context mContext;

@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout, parent, false);
    return new ItemViewHolder(view);
}

public DisplayAllData(Context mContext, List<User> mUserLsit) {
    this.mContext = mContext;
    this.mUserLsit = mUserLsit;
}

@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
    User user = mUserLsit.get(position);
    holder.mTvName.setText(user.name);
    holder.mTvEmail.setText(user.email);
    holder.mTvPwd.setText(user.pwd);
}

@Override
public int getItemCount() {
    return mUserLsit.size();
}

public class ItemViewHolder extends RecyclerView.ViewHolder {
    TextView mTvName, mTvEmail, mTvPwd;

    public ItemViewHolder(View itemView) {
        super(itemView);
        mTvEmail = itemView.findViewById(R.id.rlTvEmail);
        mTvName = itemView.findViewById(R.id.rlTvName);
        mTvPwd = itemView.findViewById(R.id.rlTvPwd);

    }
}
}

row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">

<TextView
    android:id="@+id/rlTvName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Name"
    android:textSize="20dp" />

<TextView
    android:id="@+id/rlTvEmail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Email"
    android:textSize="20dp"
    app:layout_constraintTop_toBottomOf="@+id/rlTvName" />

<TextView
    android:id="@+id/rlTvPwd"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Password"
    android:textSize="20dp"
    app:layout_constraintTop_toBottomOf="@+id/rlTvEmail" />

</android.support.constraint.ConstraintLayout>

and i hope you add internet permission into android manifest file..
<uses-permission android:name="android.permission.INTERNET"/>

more information refer this link
https://www.simplifiedcoding.net/firebase-realtime-database-crud/


text:
Q: Rack::Request - how do I get all headers? The title is pretty self-explanatory. Is there any way to get the headers (except for Rack::Request.env[])?

A: Based on @matt's answer, but this really gives you the request headers in a hash as requested in the question:
headers = Hash[*env.select {|k,v| k.start_with? 'HTTP_'}
  .collect {|k,v| [k.sub(/^HTTP_/, ''), v]}
  .collect {|k,v| [k.split('_').collect(&:capitalize).join('-'), v]}
  .sort
  .flatten]

Depending on what key convention you prefer you might want to use something else instead of :capitalize.

A: Like @Gavriel's answer, but using transform_keys (simpler):
class Request
  def headers
    env.select { |k,v| k.start_with? 'HTTP_'}.
      transform_keys { |k| k.sub(/^HTTP_/, '').split('_').map(&:capitalize).join('-') }
  end
end

You can even make it so lookups still work even if the case is different:
  def headers
    env.
      select { |k,v| k.start_with? 'HTTP_'}.
      transform_keys { |k| k.sub(/^HTTP_/, '').split('_').map(&:capitalize).join('-') }.
      sort.to_h.
      tap do |headers|
        headers.define_singleton_method :[] do |k|
          super(k.split(/[-_]/).map(&:capitalize).join('-'))
        end
      end
  end

So for example, even if headers normalizes the keys so it returns this:
{
  Dnt: '1',
  Etag: 'W/"ec4454af5ae1bacff1afc5a06a2133f4"',
  'X-Xss-Protection': '1; mode=block',
}

you can still look up headers using the more natural/common names for these headers:
headers['DNT']
headers['ETag']
headers['X-XSS-Protection']

A: The HTTP headers are available in the Rack environment passed to your app:

HTTP_ Variables:    Variables corresponding to the client-supplied HTTP request headers (i.e., variables whose names begin with HTTP_). The presence or absence of these variables should correspond with the presence or absence of the appropriate HTTP header in the request.

So the HTTP headers are prefixed with "HTTP_" and added to the hash.
Here's a little program that extracts and displays them:
require 'rack'

app = Proc.new do |env|
  headers = env.select {|k,v| k.start_with? 'HTTP_'}
    .collect {|key, val| [key.sub(/^HTTP_/, ''), val]}
    .collect {|key, val| "#{key}: #{val}<br>"}
    .sort
  [200, {'Content-Type' => 'text/html'}, headers]
end

Rack::Server.start :app => app, :Port => 8080

When I run this, in addition to the HTTP headers as shown by Chrome or Firefox, there is a "VERSION: HTPP/1.1" (i.e. an entry with key "HTTP_VERSION" and value "HTTP/1.1" is being added to the env hash).


text:
Q: random Java буквы как выводит на экран 7 случайных букв через консоль.
допустим пишем через консоль:  Privet kak dela, segodnya pogoda xoroshaya.
И из этой строки выбрал 7 случайных букв.

A: *

*Берете массив длиной равной цельной строке

*Заполняете массив числами от 0 до длины строки-1

*Применяете функцию перемешивания данных в этом массиве (любая, какая есть на свете)

*Пробегаетесь циклом от 0 до 7 по массиву и берете из строки один элемент, начиная со значения, указанному под индексом цикла. (например str.substring(arr[i], 1))

1 и 2 пункт можно заменить банально разбив указанную строку на массив символов. Тогда останется просто перемешать данные и взять первые 7 элементов массива

A: А еще проще:
List<Character> list = Arrays.asList(scanner.nextLine().split("").replaceAll(' ', '' );
list.shuffle;
System.out.println (list.subList(0, 7));
Либо если пробелы неконтролируюмые то вместо пробела "\\s+"

A: try (Scanner sc = new Scanner(System.in)) { // считывать ввод будем сканнепром
    String input = sc.nextLine().replaceAll(" ", ""); // считываем ввод
    String preparedInput = input.replaceAll(" ", ""); // убираем пробелы
    List<String> list = Arrays.asList(preparedInput.split("")); // создаем список
    Collections.shuffle(list); // перемешиваем список
    System.out.println(list.subList(0, 7)); // печатаем первые 7 элементов
}


text:
Q: Importing Attribute Price on Vague Feeds This is less a programming question and more a process/policy question.
When dealing with product feeds from manufactures/resellers, it's very common to run into a product variant that looks something like this
Size        Color       price
--------------------------------------------------
625 ml      Red         47.70
1.25 litre  Red         69.33
4 litre     Blue        165.98
4 litre     Green       170.78
5 litre     Red         173.56
10 litre    Blue        454.72
10 litre    Green       454.72
16 litre    Yellow      456.96
200 litre   Yellow      4648.00

We have a product with two attributes (Size, Color), and it's unclear how each attribute effects the price.  In the above example you might assume its size that would effect the price (as more product would cost more).  However, comparing two products with the same size
4 litre     Blue        165.98
4 litre     Green       170.78

there's still a slight price different due to color.
When setting these products up as configurable products, how do you split the option price between the two attributes for the Super Product Attributes Configuration?  It doesn't seem like it's possible algorithmically without more information, but I also see feeds like this all over the place so I assume people are finding a way to deal with it.

A: My first thought is to just assign those prices directly to the component "Simple" products and install "Simple Configurable Products" extension.  Of course this means you would have to treat all configurable products this way, you can no longer use the old scheme for pricing.
With a bit of thought you can show that it is not possible to correctly price these products with the old scheme.  Look at these 4 in particular:
4 litre     Blue        165.98
4 litre     Green       170.78
...
10 litre    Blue        454.72
10 litre    Green       454.72

The difference between blue and green is both 4.80 and 0.00 which is not an option in an unaltered Magento.

A: To my experience - and in the long run - it would be good to make that manufacturer to fix their stuff one way or another. By "dealing with this" on Magento's side is just moving the problem around from one place to another. It's not finding and fixing the root cause. Finding the root cause of problems was something that I learnt to be important while I was in telco business. Just ask your customer to put a little more pressure on the manufacturer, write some good specs, invent, discuss and promote standards.
About specific problem - explain it to your customer and ask them to advise you if you should go for highest price or the lowest. At Eepohs we built an addition to our EepohsImporter that was called "Margin Matrix". The logic was that often stores import manufacturer prices, not retail prices and there could be some logic to add margins to cost level prices. I guess it can be reused here, too. Build a matrix where there are blanks for price ranges and blanks for prices or margins or whatever "fixes".
Then let your customer to fill it in so you'd get logic like that:
IF price >=x and =q and

I guess most important is to check with the customer and not to make pricing decisions for them:)

A: Yes, supplier onboarding is a pain. The data feeds are usually low quality so you need some pretty complex solutions to automate it hence why companies like Heiler charge $10s-$100s thousands for their solution. We use a supplier onboarding solution that does this using non-code mapping with direct loading to Magento from supplier files, but it was developed by high-end consultants who knew what they were doing.
Manufacturers are unlikely to change their feeds, and you would be suprised how they generate them anyway. There is a lot of Excel used, we know of multi-nationals who ran on Excel taking data from high-end ERPs.
For the above you set the combination price and add your markup, that is the simple way rather than trying to reverse engineer their pricing structure.


text:
Q: Robot Framework: access Robot's global variables from Python library code? I have some settings-type global vars that I'd like to be able to access from Python code. For example:
pybot --variable RESULTS_PATH:/wherever/this/points test.txt

Now, my module logger.py file needs to know the results_path to set up properly.
I know that I can initialize the logger with a variable, like
***Settings***
Library  logger  ${RESULTS_PATH}

And then in logger I'll be passed results_path:
 def __init__(self, results_path):
   # Whatever

However the problem with doing it this way for me is that I want to access and use the logger from both Python code and within test cases. So if I set it up this way, if I want to use the logger from Python code I run into the same problem of needing results_path to initialize the logger properly.
Are there any functions in the robot framework library that would allow me to grab the value of ${RESULTS_PATH} from Python code? What is the proper way to do something like this?
Right now, my workaround for the issue is to set RESULTS_PATH as an environment variable. So I have something like:
Run like:
RESULTS_PATH=/wherever/this/points pybot test.txt

File test.txt:
***Settings***
Library  logger
...

File logger.py:
results_path = os.environ["RESULTS_PATH"]
# Other set up stuff

A: You will want to use rf's BuiltIn library, for reference read the documentation as found here. This provides the keywords that are built into Robot Framework and so should reliably stay usable:
from robot.libraries.BuiltIn import BuiltIn
results_path = BuiltIn().get_variable_value("${RESULTS_PATH}")


text:
Q: roots of multi-variable polynomials and extension fields I am teaching a course in (standard single-variable) Galois theory and the following, presumably naive, question occurred to me:
Given a finite collection of polynomial equations in a finite number of variables with coefficients in some field $K$ such that they have a finite number of solutions, are the coordinates of the solutions necessarily algebraic over $K$?

Since googling multi-variable Galois theory brought up very little except this MO question, I assume the answer is no, but I would love to know something about it,

A: Let me state your question more precisely (since you don't say where these solutions are, if they aren't in an algebraic extension of $K$):

Suppose $f_1, \dots f_m$ are polynomials in $K[x_1, \dots x_n]$ such that the system $f_1 = \dots = f_m = 0$ has finitely many solutions in any field $L$ containing $K$. Are these solutions always algebraic over $K$?

The answer is yes, which you can see as follows. By Noether normalization, the ring $R = K[x_1, \dots x_n]/(f_1, \dots f_m)$ is a finite integral extension of some free subring $S = K[y_1, \dots y_d]$. If $L$ is any infinite and algebraically closed field containing $K$, it follows that there are infinitely many $L$-points (homomorphisms $R \to L$ of $K$-algebras, or solutions over $L$ of our system of equations) unless $d = 0$.
If $d = 0$, then $R$ is finite-dimensional over $K$, from which it follows that there are at most finitely many $L$-points for any $L$, whose coordinates must be algebraic. This is because, since $R$ is finite-dimensional, for any $x_i$ there is some linear dependence among the monomials $\{ 1, x_i, x_i^2, \dots \}$, so each $x_i$ satisfies a polynomial over $K$.
In general, there is a subject one might call "multivariable Galois theory," but people usually call it "algebraic geometry" (over non-algebraically closed fields), or more specifically "Galois descent."

Edit: Here's a lower-tech but longer argument using only transcendence degree. We'll prove the contrapositive: if the system has a solution over some field $L$ whose coordinates are not algebraic over $K$, then it has infinitely many solutions over some other field.
Suppose $(\ell_1, \dots \ell_n) \in L^n$ is a transcendental solution over $L$, and let $D$ be the $K$-subalgebra of $L$ generated by the coordinates. ($D$ is a quotient of $R$ above, but unlike $R$ it is an integral domain.) We'll attempt to construct infinitely many new solutions over some other field $L''$ by writing down infinitely many $K$-algebra homomorphisms $D \to L''$.
Let $L'$ be the fraction field of $D$. By hypothesis, $L'$ has positive transcendence degree over $K$. Hence $L'$ is an algebraic extension of a transcendental extension of $K$. Since $D$ is finitely generated as a $K$-algebra, $L'$ is a finite algebraic extension of a finite transcendental extension $K(t_1, \dots t_d)$ of $K$. Let $\alpha_1, \dots \alpha_k$ be the finitely many elements generating $L'$ as an algebraic extension of $K(t_1, \dots t_d)$.
By construction, we can write each $\ell_i$ as a polynomial in the $\alpha_i$ with coefficients in $K(t_1, \dots t_d)$. We will now attempt to write down infinitely many $K$-algebra homomorphisms $g : D \to L''$ for some third field $L''$ containing $K$. We will do this by picking values for $g(\alpha_i), g(t_i)$ such that each $\ell_i$ continues to be well-defined; equivalently, we just need to arrange for the denominators of each term of each $\ell_i$ to be nonzero. An easy way to do this is to take $L''$ to be the algebraic closure of $K(s_1, s_2, \dots)$. Then we can send $g(t_i)$ to any $s_j$, and send $g(\alpha_i)$ to various roots of various polynomials, which exist since $L''$ is algebraically closed. If there are infinitely many $s_j$ then there are infinitely many such homomorphisms, as desired.
(Other arguments are possible at this last step if $K = \mathbb{Q}, L = \mathbb{C}$. Then we can take $L'' = \mathbb{C}$. We need to avoid the zero sets of a finite set of polynomials in the $t_i$, but there are many ways to see that there are infinitely many ways to do this: for example, the zero sets of polynomials have measure zero.)
(Note how much work we have to do to cobble together a substitute for Noether normalization!)


text:
Q: Python Tkinter, how to get the dictionary automatically updated by a list filled in by entries? Application: we are working in a sector where our product can have hundreds of different properties. And when we have to do an offer for tens products, this app could help us to reduce the number of offers by gathering products with the same configuration
How it works: user gives the properties in the entries and the application will compare them to see if some configurations are the same (Here configuration = "Config 0", or "Config 1" and so on ...).
The configurations and the given properties should be put in a dictionary-like {Config 1:[1800,1,1500,x...], Config 2:[2000,2,1600,x...], Config n:[x,y,o,x...]} The program will compare the values list of the keys and try to if some values list are the same.
Problem: when I put some data in the entries, the dictionary will not be updated.
How can I solve this problem?
The button 'Launch' enables to launch of the comparison
import os
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from openpyxl import Workbook
from openpyxl import load_workbook
from tkinter.filedialog import askopenfilename
from tkscrolledframe import ScrolledFrame

data_list=['Name','Q','Speed','TH','Open through','Level','Accesses','CW','CD','CH','SW','SD','Headroom','SP','Door type','DW','DH']
main_list=[]
list_excel=[]
user_entries=[]
user_entries_2=[]
dict_user_entries={}
dict_redundance={}
fenetre =Tk()
fenetre.geometry('800x750')
a = 5

for i in range(a):
    user_entries.append(0)

def test():
    for i in range(len(dict_user_entries)):
        for u in range(3):
            print(dict_user_entries['Config '+str(i)][u].get())

def comparison():
    dict_redundance={}
    print(user_entries[2].get())

    for e in range(a):
        for y in range(a):
            dict_user_entries['Config '+str(e)][y]=(user_entries[y].get())
    print(dict_user_entries)
    for r in range(len(dict_user_entries)):
        for o in range(len(dict_user_entries)):
            if dict_user_entries['Config '+str(r)] == dict_user_entries['Config '+str(o)]:
                print('yes -- Config ',str(r),' = Config ',str(o))
                if  'Config '+str(o) in dict_redundance:
                    dict_redundance['Config '+str(o)].append('Config '+str(r))
                else:
                    dict_redundance['Config '+str(o)]=['Config '+str(r)]

            else:
                print('no -- Config ',str(r),' =x= Config ',str(o))

    #----- print
    for i in dict_redundance.keys():
        print(i)

cadrebouton=Frame(fenetre)
cadrebouton.pack(side=TOP,anchor=NW)
boutontest=Button(cadrebouton,text="Test",width=15,height=1,bg="white",bd=5, command=test)
boutontest.pack(side=LEFT, anchor =NW)
boutonlaunch=Button(cadrebouton,text="Launch",width=15,height=1,bg="white",bd=5, command=comparison)
boutonlaunch.pack(side=LEFT, anchor =NW)

cadre_global=Frame(fenetre)
cadre_global.pack(side=TOP,anchor=NW)

cadre_global2=Frame(cadre_global)
cadre_global2.pack(side=LEFT)

for x in range(a):
    frame=Frame(cadre_global2)
    frame.pack(side=TOP,anchor=NW)

    label_data=Label(frame,width=15,text=data_list[x])
    label_data.pack(side=LEFT)

cadre_global3=Frame(cadre_global)
cadre_global3.pack(side=LEFT)
bx=0#------Test, to delete

for i in range(5):

    frame2=Frame(cadre_global3)
    frame2.pack(side=LEFT)
    user_entries=[]
    for x in range(a):
        bx+=x
        var_entry=StringVar()
        my_entry=Entry(frame2,textvariable=var_entry, width=15,bd=2)
        my_entry.pack()
        user_entries.append(my_entry)
    dict_user_entries['Config '+str(i)]=[]
    for r in range(a):
        dict_user_entries['Config '+str(i)].append(user_entries[r].get())

fenetre.mainloop()

os.system('pause')

Thank you!
EDIT : 10.05.2021 -
I found the solution by myself. I put directly the Entries in the dictionnary without any list between entries and dictionnaries
for i in range(nbofconfig):

    frame2=Frame(cadre_global3)
    frame2.pack(side=LEFT)
    dict_user_entries['Config '+str(i)]=[]
    for x in range(a):
        bx+=x
        var_entry=StringVar()
        my_entry=Entry(frame2,textvariable=var_entry, width=15,bd=2)
        my_entry.insert(0,bx)
        my_entry.pack()
        dict_user_entries['Config '+str(i)].append(my_entry)


text:
Q: How can I load a VBA image object from WIA directly into Access Image Control? I used code from "How to rotate, crop, scale, flip an image?" to rotate an image in an Access image control, but I can't find a way to directly load the image object returned from the API into the Access control.  I first have to save the object to a file, then load the file into the control, and I then need to delete the file used to save the rotated file.  Is there a way to load the image object directly to the control?  I have no need to save the altered image.
The following code is from the source referenced above.  I modified variable and object names to be consistent with my programming and added some clean up code.
Sub apiRotateImage(strSourcePath As String, strDestPath As String, lngAngle As Long)
' Rotates image in path strSourcePath, returns image rotated to lngAngle (must be 90, 180 or 270) degrees and saves image at strDestPath
Dim objSource As Object
Dim objProcess As Object

If lngAngle <> 90 And lngAngle <> 180 And lngAngle <> 270 Then
    MsgBox "Reqiested angle of " + lngAngle & "° is not valid.  Only 90 180 and 270 are allowed", , "apiRotateImage Invalid Entry Value"
    Exit Sub
End If
Set objSource = CreateObject("WIA.ImageFile") 'create WIA objects
Set objProcess = CreateObject("WIA.ImageProcess")
objProcess.Filters.Add objProcess.FilterInfos("RotateFlip").filterid 'setup filter
objProcess.Filters(1).Properties("RotationAngle") = lngAngle
objSource.LoadFile strSourcePath 'load image
Set objSource = objProcess.Apply(objSource) 'apply change
objSource.SaveFile strDestPath 'save new image
Set objSource = Nothing
Set objProcess = Nothing

End Sub
The calling code provides the source and destination paths and the desired rotation angle, then calls the following procedure to load the the rotated image.
Public Function DisplayImage(ctlImageControl As Control, strFilePath As Variant) As Boolean
On Error GoTo Err_DisplayImage
Dim bolResult As Boolean
bolResult = False
With ctlImageControl
If IsNull(strFilePath) Then 'No path, hide image box
.Picture = ""
Else    ' Display image in box and make it visible
.Picture = strFilePath
bolResult = True
End If
.Visible = bolResult
End With
Exit_DisplayImage:
Exit Function
Err_DisplayImage:
Select Case Err.Number
Case 2220       ' Can't find the picture.
ctlImageControl.Visible = False
Resume Exit_DisplayImage:
Case Else       ' Some other error.
MsgBox Err.Number & " " & Err.Description
Resume Exit_DisplayImage:
End Select
End Function
This code works.  It seemed logical to me that an image object returned from the Windows API could be loaded into an Access image control, but I could not find a way to do this directly.  Creating a file on disk seemed to me to be a work-around, so I thought I would ask.


text:
Q: Strategy to migrate from StarTeam 5 to Subversion? I need to migrate a large project from StarTeam 5 to Subversion, and I'd like to keep snapshots of (at least) 5-10 of the major releases.  I've considered the following:

*

*Manual or scripted export/import of each snapshot.  Advantages: straightforward, easy to select labeled/dated versions.  Disadvantages: time-consuming, does not preserve comments.

*Polarion offers what seems to be the perfect tool in svnimporter, but it requires a .jar file from StarTeam 8.0 that is not present in StarTeam 5.  Advantages: automated, complete.  Disadvantages: requires upgrade to StarTeam 8.0 for one-time use.

*Migrate via some intermediate repository (e.g. StarTeam -> CVS -> Subversion).  I haven't yet found any intermediary that will cooperate with StarTeam.

*Migrate only the latest source.  Advantages: simple, fast, encourages developers to invent new solutions rather than repeating history.  Disadvantage: encourages developers to invent new solutions rather than repeating history.  :-)

I'd appreciate any experiences or suggestions you might offer.  Thank you.

A: You can run a Star Team server for an evaluation period (30 days?) without requiring additional licensing from Borland - this would give you plenty of time to run a few practice runs, and give you a complete, reliable solution. Well worth the effort.
Also, don't underestimate the value of retaining your source history.
Updated Nov 6: One project that I'm involved with has used the Polarion tool to migrate a single StarTeam project into SVN. Took a little bit of work, but the end result is flawless. Well worth the time investment.

A: Regarding the comments about StarTeam versions: yes, the Polarion SVNImporter tool does need starteam80.jar, and yes, the StarTeam SDK 2005 only has a file called starteam70.jar.  However I've discovered that you can cheat by copying starteam70.jar into the SVNImporter lib directory and renaming it starteam80.jar.

A: Having not used StarTeam I cannot speak to that -- but I think you've laid out some nice options.

*

*Scripted import seems like it could be time consuming, not really get you everything, but at the same time, be a reliable way to get into svn and still preserve your release history.

*What is the real downside of upgrading and throwing away the install after? Do you have to re-purchase the software? Is it a tedious upgrade? Barring that, it sounds like this may just be the best option.

*I would really stay away from this option. cvs -> svn import is pretty shaky (really, it's a one-off thing, probably not that many individual people work on it enough to really care about making it perfect). Going from another SCM system to cvs, and THEN to svn sounds like a recipe for useless history data and frustration. :)  I've only done it a couple of times, and really, the best part is once you're done, you're in svn and never touch cvs again.

*This option does really suck. You lose all your history.. can no longer blame other dev's for screwing things up.. On the upside though, it will absolutely work, if all else fails.

A: I'm struggling to migrate StarTeam 8 to SVN using the Polarion kit.  I'm getting:
[main] DEBUG STProvider:80 - checkout ...relative/path/to/build.xml version:1.0
09:25:10,378
[main]  INFO historyLogger:84 - EXCEPTION CAUGHT: java.lang.UnsatisfiedLinkError: com.starbase.util.NativeFileAccess.setLastModifiedAsLong(Ljava/lang/String;J)V
and the target file exists, but I suspect that it's unable to resolve the relative path.  Do you know if there are properties (other than the ones in the config.properties file) that can be set to control this?


text:
Q: datatables - Custom sorting a column with datetime and string I am working with jquery datatables and i have a column that contains a combination of these values. A date, a string 'A' and another string 'B'. When i click on that column i want the column to be sorted with 'A' appearing first then sorted by date and then 'B' appearing next. Is there a way to achieve this functionality?

A: Client Side :
$.extend($.fn.DataTable.ext.oSort, {
   /*
   *
   *custom_date sorting
   */
    "custom_date": function (a) {
        return a;
    },
    "custom_date-asc": function (x, y) {
        var x = getCustomEuroDateValue(x);
        var y = getCustomEuroDateValue(y);
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    },
    "custom_date-desc": function (x, y) {
        var x = getCustomEuroDateValue(x);
        var y = getCustomEuroDateValue(y);
        return ((x < y) ? 1 : ((x > y) ? -1 : 0));
    },
});
function getCustomEuroDateValue(strDate) {
   // return a string by spiting and merging the date as you need
   // B A 02/11/2013 to A20131102B
   //
   // Example :
   // var frDatea = $.trim(strDate);
   // var frDatea1 = frDatea.split(' ');
   // var frDatea2 = frDatea1[2].split('/');
   // var x = (frDatea1[1] + frDatea2[2] + frDatea2[1]+ frDatea2[0] + frDatea1[0]);
   // return x;

}

Then add this to your otable properties
"aoColumns": [ {  }, { },{ "sType": "custom_date" },{ } ],

A: If using client side, detect the DataTables sort listener and then attach your own that calls http://www.datatables.net/ref#fnSort
This is much easier to achieve using server-side with database, as you can always include a static order by clause in your select statement as the secondary sort option
post some more code if additional help is needed


text:
Q: How do I modify the Previous and Next Page posts on blog pages to include "previous" and "next" before the links? I want to add "previous" and"next" to the individual blogs since they only have the blog titles for the next and previous links. I want to keep the links and I am having a hard time using any of the solutions provided to me and they seem to make the page worse. Am I coding the information incorrectly or am I deleting important PHP that needs to stay?
This is the problem I am dealing with:
wp_link_pages( array( 'before' => '
' . esc_html__( 'Pages:', 'thermal-tech' ),
            'after'  => '
', ) );

A: You can do this very easily using the_post_navigation. The WordPress reference page for it has more information.
the_post_navigation( array(
                'prev_text'=>__('Previous: %title'),
                'next_text'=>__('Next: %title'),
            ));

That said, if you do want to continue using `wp_link_pages' then, again, its WordPress resource is your friend, explaining the parameters and how to change them.
Hope that helps!


text:
Q: Combined real + p-adic numbers? So most p-adic notes inevitably beat us with a club with Ostrowski's theorem on absolute values.
However what if we forsake absolute values, and instead use a digit system where the value $v(x)$ of a number $x$ equals a tuple $(a,b)$. Here $a$ is the smallest negative exponent of some prime $p$ in the representation of $x$, while $b$ is the smallest positive exponent. For instance for $p=2$, $v(9/4)$ = $v(1/4 + 2)$ = $(2,1)$.
However we allow infinite expansions too:
We define a sequence as 'left-convergent' if for $\lim v_2(x_n - x_{n-1})$ the first tuple value approaches infinity, and likewise for 'right-convergent'.
In other words, high positive or negative powers of a prime both converge to different zeros. And therefore we can write unconditionally convergent expressions of the form $\sum_{-\infty}^{\infty} p^n a_n$ where $a_n$ is between $0$ and $p-1$.
So we basically obtain real (base $p$) plus p-adic 'combined' numbers.
The number zero can e.g. be represented as either:
$\cdots 0.0 \cdots$
or
$\cdots (p-1)(p-1)(p-1).(p-1)(p-1)(p-1) \cdots$
Since the latter is divisible by all factors of $p-1$, for $p>2$ we aren't dealing with a field (at least by the usual definition) as there are zero divisors. Though I don't know what happens with $p=2$?
Something like $\frac{1}{x}$ for $(x,p)=1$ will have multiple solutions. With the 'new' solutions corresponding to linear combinations of the real and p-adic solution.
E.g.
$\frac{1}{3}$ for $p=2$ has representations:
$0.010101 \cdots$ (real)
$\cdots 0101011;$ (2-adic)
$\cdots 010101.1010101 \cdots$ (sum of both divided by two)
This sort of feels like 'field extension' since we are adding new solutions to an equation.
In these numbers, series like $\displaystyle \sum_{n=0} p^{(-1)^n n}$ converge to finite values. Also power series converge absurdly: $\sum_{n=-\infty}^{\infty} x^n = 0$ for all $x$ with a power of $p$ in the numerator or denominator.
How about products? (responding to Julian Rosen). In general we can use Cauchy products if at least one of the numbers has a finite representation. However multiplying an infinite p-adic and infinite real number together causes convergence issues.
If we denote $\frac{1}{x}_p$ and $\frac{1}{x}$ for the p-adic and real representatives of a fraction. Then $\frac{1}{x}_p \cdot \frac{1}{x} = \frac{1}{x}_p \cdot \frac{x}{x^2} = \frac{1}{x^2} = \frac{x}{x^2}_p \cdot \frac{1}{x} =  \frac{1}{x^2}_p$. Hence by implication there can't be a 'single' representative for this product.
My questions are:

*

*Does this approach make sense/does it have a name?

*Does it have any benefits or unique advantages?

E.g. tying p-adic results to real ones? For instance 'hypothetically' if we can demonstrate that the 'combined' expression (real + p-adic) is irrational and the real solution is rational, then the remaining term must be irrational.


text:
Q: rotating cubes differently I have 25 cubes that i want to rotate each one differently this is my code on both x and y axis
i tried using rand() but it kept rotating them weirdly and all of them rotate in the same directions
this is in the game loop
for (unsigned int i = 0; i < 25; i++)
{
    glm::mat4 model = glm::mat4(1.0f);
    model = glm::translate(model, cubePositions[i]);
    view = glm::translate(model, glm::vec3(0.0f, 0.0f, -10.0f));
    float angle = 20.0f * i;

    angle = glfwGetTime() * 20.0f;

    model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.0f, 0.5f));
    GLint modelLoc = glGetUniformLocation(ourShader.Program, "model");
    glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
    GLint viewLoc = glGetUniformLocation(ourShader.Program, "view");
    glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
    GLint projLoc = glGetUniformLocation(ourShader.Program, "projection");
    glUniformMatrix4fv(projLoc, 1, GL_FALSE,
    glm::value_ptr(projection));

    glDrawArrays(GL_TRIANGLES, 0, 36);
}

A: Since there is no actual question, I try to give some comments on the posted code
that could explain the unexpected behavior of the resulting program.

*

*The angle variable is initialised, then assigned immediately with a new
value ; only this new value is relevant, then the cubes should all rotate
at the rate of  20 degrees per second. (this is not a problem)

*The view matrix is reassigned with a new value for each object! It is
extremely unlikely that this is what you want.
It's like if, while drawing a single frame, you move the camera in front of
each object being drawn ; if you move the camera and the object the same way,
then everything is displayed at the same place in the rendered frame.
(I think this is the main problem)
You should choose once for all the view matrix (as well as the projection
matrix) for the whole frame.

Some other comments, not directly related:

*

*You should retrieve the uniform locations once for all before the loop
(and even at the beginning of the program) since they won't change as long
as you use the same shader program.

*The glUniformMatrix4fv() calls for projection and view should
occur once for all before the loop; only the model matrix changes from
one object to another.

That could look like this
  GLint modelLoc = glGetUniformLocation(ourShader.Program, "model");
  GLint viewLoc = glGetUniformLocation(ourShader.Program, "view");
  GLint projLoc = glGetUniformLocation(ourShader.Program, "projection");

  glm::mat4 projection = ... already known ...
  glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));

  glm::mat4 view = glm::mat4(1.0f);
  // adjust to the layout of your scene
  view = glm::translate(view, glm::vec3(0.0f, 0.0f, -10.0f));
  glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));

  for(unsigned int i = 0; i < 25; i++)
  {
    glm::mat4 model = glm::mat4(1.0f);
    model = glm::translate(model, cubePositions[i]);

    // the same rotation rate but a different offset for each object
    float angle = 20.0f * i;
    angle += std::fmod(glfwGetTime() * 20.0f, 360.0f);
    // choose x or y rotation axis
    auto axis=(i%2) ? glm::vec3(1.0f, 0.0f, 0.0f) : glm::vec3(0.0f, 1.0f, 0.0f);
    model = glm::rotate(model, glm::radians(angle), axis);

    glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));

    glDrawArrays(GL_TRIANGLES, 0, 36);
  }


text:
Q: sharepoint list - column formatting doesn't render correctly in NewForm.aspx or EditForm.aspx (looks fine in DispForm.aspx) I have used JSON column formatting in a SharePoint list. The fields appear correctly formatted in DispForm.aspx, but not EditForm.aspx or NewForm.aspx.
The formatting on the 'span' elements seems to work on all forms, but formatting on the 'div' parent only seems to work on DispForm. Is this by design?
EditForm.aspx
DispForm.aspx
My column formatting JSON for 'Applicant_Approval_Status' is -
{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
  "elmType": "div",
  "style": {
    "color":"black",
    "background-color": "=if(@currentField == 'Approve', '#D5E8D4', if(@currentField == 'Pending', '#F5F5F5', if(@currentField == 'Reject', '#F8CECC', '#FFE6CC')))",
    "border": "='1px solid ' + if(@currentField == 'Approve', '#82B366', if(@currentField == 'Pending', '#666666', if(@currentField == 'Reject', '#B85450', '#D79B00')))"
  },
  "children":
  [
    {
      "elmType": "span",
      "style": {"display": "inline-block", "padding": "0 4px", "background-color": "#D5E8D4"},
      "attributes": {"iconName": "=if(@currentField == 'Approve', 'CheckMark', if(@currentField == 'Pending', 'Forward', if(@currentField == 'Reject', 'ErrorBadge', 'Warning')))"}
    },
    {
      "elmType": "span",
      "txtContent": "@currentField",
        "style":{"background-color": "#D5E8D4"}
    }
  ]
}

I have tried different parent 'elmType' (p, span, button) (As per Formatting syntax reference), but this had no effect.


text:
Q: OpenGL background clear color bleeds into transparent texture I'm writing a simple 2D framework with OpenGL and C++ and have now run into a problem related to transparent textures and blending. I've reduced my problem to the following.
I have two textures: A floor tile and a fish bone. The latter contains transparent pixels. I set my OpenGL clear color to "transparent green" and enable depth test and blending like this:
glClearColor(0, 1, 0, 0)
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

With two calls to glDrawElements() I draw the fish and then the floor. The fish has a higher Z value and should thus be placed in front of the floor tile. This is the result.
Obviously, I don't want the green box around the fish like that. I think what happens is that the fish pixels blends with whatever is in the framebuffer's color renderbuffer at the moment of drawing and that happens to be a solid green (due to glClearColor and glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)). For each transparent pixel in the fish texture, I would have expected this blending to resolve to transparent (as I've set a transparent clear color) but as you can see that isn't what's happening.
If I draw the floor first, and then the fish, it works as expected.
My fragment shader is dead simple:
varying lowp vec2 TexCoordOut;
uniform sampler2D Texture;

void main(void) {
    gl_FragColor = texture2D(Texture, TexCoordOut);
}

Do I really have to manage the drawing order manually (ordered by Z coordinate) or is there a way to fix this issue? Isn't the OpenGL depth buffer system designed to address this issue?
I'm testing my program on the iOS simulator through Xcode.

A: I do believe depth sorting is necessary - as even though the resulting pixel from the blend is transparent, the depth buffer IS written. So anything to be drawn behind (higher depth) these transparent pixels is simply discarded. The depth buffer doesn't take transparency into account, unfortunately.
If you don't have any semi-transparent pixels in your textures you could use alpha testing, which discards a pixel if it is transparent and so it doesn't write the depth buffer. This obviously doesn't work (well) with semi-transparent pixels as they either become fully opaque or are discarded depending on your implementation/settings. You could easily implement it by changing your shader to:
varying lowp vec2 TexCoordOut;
uniform sampler2D Texture;

void main(void) {
   vec4 tc = texture2D(Texture, TexCoordOut);
   if (tc.a < 0.5) //for example, change to any value suitable
     discard;
   gl_FragColor = tc;
}

Other than this there is no way I know of to fix transparency with depth buffering besides sorting.
You can read more details on both transparency sorting and alpha testing here: http://www.opengl.org/wiki/Transparency_Sorting

A: Had this exact issue and tried all sorts to rectify it with no solid results trying to work with the majority of suggestions that centred around changing the calculations being made. In the end it was fairly simple!
The culprit in my code looked like this:
glClearColor(1, 0, 1, 0);
glClear(GL_COLOR_BUFFER_BIT);

Despite the fact it was transparent when it was blending between background and the colour of the subject it would bleed. What fixed it for me was wrapping this code to mask the glClear step. It looked like this:
glColorMask(false, false, false, true);
glClearColor(1, 0, 1, 0);
glClear(GL_COLOR_BUFFER_BIT);
glColorMask(true, true, true, true);

This seems to negate the bleed issues by eliminating all but the alpha channel from the clear process.

A: Z Values are used for culling. A fragment is not drawn if there is already another fragment with a smaller z value or it is outside the view frustum. But all Vertex buffer objects are drawn in order. For 2D you can use any sort "by z" algorithm. Discarding fragments will be problematic if you want add some filters like blur or edge anti-aliasing later on.


text:
Q: r tm determine polarity of documents parallel using foreach I am new to the r tm coding world and I am trying to process a large textual data frame parallel while using a foreach %dopar% loop (as I found out that this is way quicker). However, I do not really understand how that works respectively how I can convert my initial for loop into a parallel foreach loop.
Particularly, I want to determine the polarities of my data set, whereas I need the score for many different polarity.frames(WORDKEY). The results shall be passed to a summarizing data frame (frequency_w). My for loop code so far looks as follows (works fine for smaller samples):
for (i in 1:length(POLKEY$x)){
WORDKEY=sentiment_frame(as.character(POLKEY$x[i]),NULL,as.integer(POLKEY$y[i]))
Poldat2=with(data, polarity(text, list(docs), polarity.frame = WORDKEY, negators=Negator,amplifiers=Ampl,deamplifiers=DeAmpl, amplifier.weight = 1))
frequency_w$docs=as.factor(Poldat2[["group"]][,"docs"])
frequency_w[(i+1)]=as.numeric(Poldat2[["group"]][,"ave.polarity"]
}

The main problem is that the code so far takes forever to run through my entire data base (80.000 docs), hence if you have any other recommendations in terms of the coding, to reduce memory usage or increase the speed I'd be happy.
Moreover, as I need to run sentSplit to use the polarity-function I'd also be glad if anybody has an idea how to increase the speed of that process as well for my entire data set or even include it into the loop.
Thanks you so much for your help in advance!


text:
Q: shell scripting to send mail Created script and its writing in sample.txt, Unable to grep the below text "EX_R02"and need to send mail.
cat sample.txt|mailx -a sample.txt -s "GG status Report" $MAIL_LIST

Sample.txt:
Program     Status      Group       Lag at Chkpt  Time Since Chkpt

MANAGER     RUNNING
EXTRACT     STOPPED     EX_R02      00:00:03      01:10:37

A: If you by "grep the below text EX_R02" mean "grep the text below for EX_R02", then you may simply replace your cat with grep "EX_R02":
grep "EX_R02" sample.txt | mailx -a sample.txt -s 'GG status Report' "$MAIL_LIST"


text:
Q: Convert an SCCM SQL query OS Installdate comparison to an hourly comparison Old SCCM Query was used to compare against the date the OS was installed.  The new requirement is to now use an hourly comparison and I don't know how to convert the change to hours.  Instead of "If the OS install date is <= 3 days" I need to instead use "If the OS install date is greater than 4 hours old and less than 72 hours old".
All I've managed to make work is "If the OS install date is greater than 1 days old and less than 3 days old".
Code:
select
SMS_R_SYSTEM.ResourceID,
SMS_R_SYSTEM.ResourceType,
SMS_R_SYSTEM.Name,
SMS_R_SYSTEM.SMSUniqueIdentifier,
SMS_R_SYSTEM.ResourceDomainORWorkgroup,
SMS_R_SYSTEM.Client
from SMS_R_System
inner join SMS_G_System_OPERATING_SYSTEM on SMS_G_System_OPERATING_SYSTEM.ResourceID = SMS_R_System.ResourceId
where
DATEDIFF(DD, SMS_G_System_OPERATING_SYSTEM.InstallDate, GetDate()) <= 3 and
DATEDIFF(DD, SMS_G_System_OPERATING_SYSTEM.InstallDate, GetDate()) >= 1 and
not (SMS_G_System_Ford_General_Info.Type = "PauseSCCMPatching" and SMS_G_System_Ford_General_Info.GenInfo = "Self-Managed")


text:
Q: Angular- como es mejor validar un form a nivel de formBuilder o a nivel de modelo bindeado estoy remotando angular pues quiero volver con esta herramienta de front, estaba viendo las validaciones.
Y principalmente que tienes 2 opciones por las que puedes guiar tu validacion:
1- FormBuilder
Te creas un validator con require o lo que necesites, parecido a esto:
this.zapatillaForm = this.formBuilder.group({
  nombre:[this.zapatilla.nombre,[Validators.required,Validators.minLength(3),Validators.maxLength(20)]],
  marca:[this.zapatilla.marca,[Validators.required]],
  precio:[this.zapatilla.precio,[Validators.required,Validators.min(0)]],
  color:[this.zapatilla.color,[Validators.required]],
  stock:[this.zapatilla.stock,[Validators.required]],
});

*NgModel
Le asignas una clase js que tengas, y actue como modelo, por ejemplo: user.js.
Y siemplemente en el obsubmit, te olvidas del form y validas las propiedades del objeto js. Algo asi:
if (user.name.length <0) //no envio el form

Debo decir que tener todo en componentes dentro de angular me parece una pasada. Es decir un componente que sea  app-login, otro , app-crear-usuario, y que no tengan que vercon un modelo que a lo mejor mañana tenga un campo nuevo, es decir, prefiero algo compacto en cuanto a componente, pero si que es verdad que bindeando te soluciona muchas cosas. Pero dependes  de tener un modelo al corriente de cambios del backend.
Por otra parte la validacion ¿No hay una manera de displayear los errores en bucle en vez de ponerlos debajo de ada correspondiente input?. A esto me refiero:

El campo es obligatorio

Caracteres minimos: {{zapatillaForm.get('minLength')}}

Caracteres maximos: {{zapatillaForm.get('maxLength')}}

Eso debajo de un input y asi con todos. No se podria hacer un foreach de validaciones al final???

A: He sacado esta conclusion de las validaciones

           First

         <input class="form-control"
                [class.border-danger]="!first.valid && (first.dirty || first.touched)"
                [class.border-success]="first.valid && (first.dirty || first.touched)"
                name="first" ngModel  #first="ngModel" required minlength="3" maxlength="10">

           Campo obligatorio
           Longitud minima: 3 caracteres
           Longitud maxima: 10 caracteres

Toda esa pesca seria para un campo, que si es validado en verde que si no en rojo (en cuanto a que sea llamativo) depues diferentes smalls que saldrian debajo del input para indicar el error (algo muy importante que a difernrecia de angular no te lo automatiza.. no me gusta eso)
Pero con este ejemplo me quedaria si puediera dinamizar variables del input, me explico, tengo un maxlength y un minlength. Con valores de 3 y 10 respectivamente.
A la hora de decir que no puede haber mas de x o menos de y. Tengo que ir a donde esta el valor del min/maxlength , fijarme en el y ponerlo yo hardcodeado. He intentado buscar algo tipo : first.maxlength.value para que acceda automaticamente al valor que le he puesto pero no he encontrado nada al respecto, y veo que lo hace poco dinamico. Es el unico pero que le veo asi a grosso modo.
¿Alguna sugerencia?


text:
Q: Multiple exclusive OR filter in a bool Query In the Previous version of the Nest ie in 1.x multiple exclusive or filters were allowed like the below raw query
AS orFilters are no more recommended in 2.x what could be the replacement for this. How to have multiple exclusive should(s) (orfilters) along with a Must in a Bool Query?
Raw query from 1.x
  {
       "bool": {
         "must": [
           {
             "bool": {
               "must": [
                 {
                   "term": {
                     "EntityType": "ITSTrucks"
                   }
                 },
                 {
                   "or": {
                     "filters": [
                       {
                         "term": {
                           "AvailableDate": 36523
                         }
                       },
                       {
                         "range": {
                           "AvailableDate": {
                             "gte": "42036"
                           }
                         }
                       }
                     ],
                     "_name": "date"
                   }
                 },
                 {
                   "or": {
                     "filters": [
                       {
                         "geo_distance": {
                           "OriginCoordinate": "42.815656,-73.942324",
                           "distance": "100miles",
                           "distance_type": "plane"
                         }
                       }
                     ],
                     "_name": "OriginOrFilter"
                   }
                 },
                 {
                   "or": {
                     "filters": [
                       {
                         "term": {
                           "IsOpen": true
                         }
                       },
                       {
                         "term": {
                           "IsDestinationBoundaryNull": true
                         }
                       }
                     ],
                     "_name": "DestinationOrFilter"
                   }
                 }
               ]
             }
           }
         ]
       }
     }

Will something like this ?
    BoolQueryDescriptor<AvailableTrucks>  queryParameterMust= new BoolQueryDescriptor<AvailableTrucks>();
    BoolQueryDescriptor<AvailableTrucks> queryParameterShouldFirst= new BoolQueryDescriptor<AvailableTrucks>();
    BoolQueryDescriptor<AvailableTrucks> queryParameterShouldSecond= new BoolQueryDescriptor<AvailableTrucks>();
    BoolQueryDescriptor<AvailableTrucks> queryParameterShouldThird= new BoolQueryDescriptor<AvailableTrucks>();
    if (mustfc.Count > 0)
    {
        queryParameterMust.Must(mustfc.ToArray());
    }
    if (shouldQueryListFirst.Count > 0)
    {
        queryParameterShouldFirst.Should(shouldQueryListFirst.ToArray());
    }
    if (ShouldQueryListSecond.Count > 0)
    {
        queryParameterShouldSecond.Should(ShouldQueryListSecond.ToArray());
    }
    if (ShouldQueryListThird.Count > 0)
    {
        queryParameterShouldThird.Should(ShouldQueryListThird.ToArray());
    }
elasticClient.Search<Truck>(s => s.Query(f => f.Bool(c => c.Must(u => u.MatchAll()).Filter(q => q.Bool(b => queryParameterMust && queryParameterShouldFirst && queryParameterShouldSecond && queryParameterShouldThird)))))>Index("Trucks")

A: In 2.x.x version you can use Should term for logic OR queries.
Some example:
{
    "bool" : {
        "must" : {
            "term" : { "user" : "kimchy" }
        }
        "should" : [
            {
                "term" : { "tag" : "wow" }
            },
            {
                "term" : { "tag" : "elasticsearch" }
            }
        ],
        "minimum_should_match" : 1
    }
}

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html
Please note you can also nest those terms.
To build query using NEST you could try:
var mustMatchQueries = new List<QueryContainer>()
var shouldMatchQueries = new List<QueryContainer>();

// ... add queries to both lists

// aggregate queries
var mustMatchAggregatedTerms = mustMatchQueries.Aggregate(new QueryContainer(), (s, ff) => s &= ff);
var shouldMatchAggregatedTerms = shouldMatchQueries.Aggregate(new QueryContainer(), (s, ff) => s |= ff);

// build descriptor
var descriptor = new SearchDescriptor<DocumentClassName>()
descriptor.Query(q => q.Bool(b => b.Must(m => mustMatchAggregatedTerms && m.Bool(c => c.Should(shouldMatchAggregatedTerms)))));


text:
Q: Order query after JOIN and AND I'm having issues ordering this query, I've tried:
$query .= " ORDER BY t.id DESC";

and it does not show anything. Any light?

$query = "SELECT t.name, t.id FROM #__k2_tags as t";
$query .= " LEFT JOIN #__k2_tags_xref tags_xref ON tags_xref.tagID = t.id";
$query .= " LEFT JOIN #__k2_items i ON tags_xref.itemID = i.id";
$query .= " LEFT JOIN #__k2_categories c ON c.id = i.catid";
$query .= " WHERE t.published=1";
$query .= " AND i.published=1 ";
$query .= " AND ( i.publish_up = ".$db->Quote($nullDate)." OR i.publish_up <= ".$db->Quote($now)." ) ";
$query .= " AND ( i.publish_down = ".$db->Quote($nullDate)." OR i.publish_down >= ".$db->Quote($now)." )";
$query .= " AND i.trash=0 ";
$query .= " AND i.access <= {$aid}";
$query .= " AND c.published=1 ";
$query .= " AND c.trash=0 ";
$query .= " AND c.access <= {$aid}";

A: The hash symbol denotes a comment in php and also MySQL. If #__k2_tags is really your table name which for your sake I hope it is not then you need to put backticks ` around it like
$query = "SELECT t.name, t.id FROM `#__k2_tags` as t";

Reference: http://dev.mysql.com/doc/refman/5.1/en/comments.html
Making your query end up looking like the following to MySQL which is an invalid bad syntax query.
$query = "
SELECT t.name, t.id FROM
 LEFT JOIN
 LEFT JOIN
 LEFT JOIN
 WHERE t.published=1
 AND i.published=1
 AND ( i.publish_up = ".$db->Quote($nullDate)." OR i.publish_up <= ".$db->Quote($now)." )
 AND ( i.publish_down = ".$db->Quote($nullDate)." OR i.publish_down >= ".$db->Quote($now)." )
 AND i.trash=0
 AND i.access <= {$aid}
 AND c.published=1
 AND c.trash=0
 AND c.access <= {$aid}"


text:
Q: Function with attr() function not executing all statements when there are multiple elements on screen created dynamically by a function The function below creates a red dot on the right end of the screen, animate() to move it left and when clicked, its src file should be changed, along with a few other things as you can see below:
function spawnEnemy()
{
    $("body").prepend("<img src='red_dot.png' class='enemies' id='enemy' style='left:calc(" + thewidth/2 + "px)'/>");
    $("#enemy").attr("id", "enemy"+i);
    $("#enemy"+i).css({"left" : thewidth+'px', "top" : (randomInt(10,500))+'px'});
    $("#enemy"+i).animate({left :'-400px'}, 20000);
    $("#enemy"+i).click(function()
    {
      var snd = new Audio("laser.mp3");
      snd.play(); //function stops here
      $("#enemy"+i).stop();
      $("#enemy"+i).attr("src","explosion.gif");
      $("#enemy"+i).css({"transform" : "scale(0.11,0.11)"});
      setTimeout(function()
      {
        $('#enemy'+i).hide();
      }, 350);
    });
    i+=1;
  }

This function is executed every six seconds. If, however, the element is not clicked before a new element is created, then all of the elements when clicked stop executing at the line where I have placed a comment. I checked the console, and I couldn't find anything of value, although I know that the problem isn't with the ids as they all have different ids in the console, and since I can hear the sound from snd.play() and none of the effects of the statements after snd.play() are seen, I'm sure the problem lies there. This problem is only when multiple elements are created, as they all execute fine if I click the element before six seconds, i.e, before the function is executed again. Also, thewidth is just a pre-defined global var, so it's not related.
I'm very new to jquery, so I apologize if there's something obvious I'm missing.
Edit: Okay, now all the statements aren't executing even if there is only one element on the screen. I'm quite lost.

A: Ok, I think I see what's happening.  You need to reference enemy with $(this) inside the callback, because i is in the encapsulating scope, which means it can change and break the internal scope of that callback:
While at it, I cleaned up your jQuery code a little to simplify it.
function spawnEnemy() {
    $('<img />', {
        id: 'enemy' + i,
        src: 'red_dot.png',
        className: 'enemies',
        style: 'left: ' + thewidth / 2 + 'px; top: ' + randomInt(10,500) + 'px'
    })
    .prependTo($('body'));
    .animate({left :'-400px'}, 20000);
    .click(function() {
        var snd = new Audio("laser.mp3");
        snd.play(); //function stops here
        $(this).stop();
        $(this).attr("src","explosion.gif");
        $(this).css({"transform" : "scale(0.11,0.11)"});
        setTimeout(function() {
            $(this).hide();
        }.bind(this), 350);
    });
    i+=1;
}


text:
Q: Possible to rollback changes to MySQL databases without any form of backup I understand I might be asking the impossible but, well never hurts to try.
Is it possible to rollback changes to a handful of MySQL databases without having any form of backup. The only thing left are the databases with the changes I wish to undone.
Why this happened you might ask, well simply putting it, Windows XP scheduler decided not to run the backup task as scheduled, therefore no backups were made previous to a few dozen queries queried to those databases.
I doubt it is possible to undo those changes, and if it is possible I don't know how.
Maybe MySQL keeps some sort of record on the changes performed to a database, but I don't know.
Does anybody knows a way to undo changes to a MySql database without any form of backup
(neither dump file or files from the data folder)?
Thank you.

System Details:
Windows XP SP3
Server: localhost via TCP/IP
Software: MySQL
Software version: 5.5.25a - MySQL Community Server (GPL)
Protocol version: 10
Server charset: UTF-8 Unicode (utf8)

Update
Possible that Windows XP system restore kept a previous version of
MySQL DBs on file?

A: Without having any database backup, you are probably pretty much out of luck.  If you had mysql query logging or binary logging on, you could glean some information about what queries had been run since a certain point in time, but if you had destructive queries (UPDATE, DELETE, etc.) you will have no way of knowing what the previous data was.


text:
Q: Custom Evaluator in PySpark I want to optimize the hyper parameters of a PySpark Pipeline using a ranking metric (MAP@k). I have seen in the documentation how to use the metrics defined in the Evaluation (Scala), but I need to define a custom evaluator class because MAP@k is not implemented yet. So I need to do something like:
model = Pipeline(stages=[indexer, assembler, scaler, lg])
paramGrid_lg = ParamGridBuilder() \
    .addGrid(lg.regParam, [0.001, 0.1]) \
    .addGrid(lg.elasticNetParam, [0, 1]) \
    .build()

crossval_lg = CrossValidator(estimator=model,
                      estimatorParamMaps=paramGrid_lg,
                      evaluator=MAPkEvaluator(),
                      numFolds=2)

where MAPkEvaluator() is my custom evaluator. I've seen a similar question but not the answer.
Is there any example or documentation available for this? Does anyone know if it Is possible to implement it in PySpark? What methods should I implement?

A: @jarandaf answered the question in the first comment, but for clarity reasons I write how to implement a basic example with a random metric:
import random
from pyspark.ml.evaluation import Evaluator

class RandomEvaluator(Evaluator):

    def __init__(self, predictionCol="prediction", labelCol="label"):
        self.predictionCol = predictionCol
        self.labelCol = labelCol

    def _evaluate(self, dataset):
        """
        Returns a random number.
        Implement here the true metric
        """
        return random.randint(0,1)

    def isLargerBetter(self):
        return True

Now the following code should work:
from pyspark.ml.tuning import CrossValidator, ParamGridBuilder

paramGrid_lg = ParamGridBuilder() \
    .addGrid(lg.regParam, [0.01, 0.1]) \
    .addGrid(lg.elasticNetParam, [0, 1]) \
    .build()

crossval_lg = CrossValidator(estimator=model,
                      estimatorParamMaps=paramGrid_lg,
                      evaluator= RandomEvaluator(),
                      numFolds=2)

cvModel = crossval_lg.fit(train_val_data_)

A: @Amanda answered very well the question, but let me show you something to avoid too. If you check the help of Evaluator() class doing:
help(Evaluator())

you'll see a method defined there:
isLargerBetter(self)
 |      Indicates whether the metric returned by :py:meth:`evaluate` should be maximized
 |      (True, default) or minimized (False).
 |      A given evaluator may support multiple metrics which may be maximized or minimized.
 |
 |      .. versionadded:: 1.5.0

Now if you your metric needs to be minimized, you need to set this method as:
def isLargerBetter(self):
        return False

The default value for the current method is True.

A: Adding an actual example to @Amanda's clear answer, the following code can be used to create a custom Evaulator which computes the F1-score in a binary classification task. It may be not optimized (I actually don't know if there is a more efficient way to implement the metric), but it gets the job done.
import pyspark.sql.functions as F
from pyspark.ml.evaluation import Evaluator

class MyEvaluator(Evaluator):

    def __init__(self, predictionCol='prediction', labelCol='label'):
        self.predictionCol = predictionCol
        self.labelCol = labelCol

    def _evaluate(self, dataset):
        tp = dataset.filter((F.col(self.labelCol) == 1) & (F.col(self.predictionCol) == 1)).count()
        fp = dataset.filter((F.col(self.labelCol) == 0) & (F.col(self.predictionCol) == 1)).count()
        fn = dataset.filter((F.col(self.labelCol) == 1) & (F.col(self.predictionCol) == 0)).count()
        f1 = (2 * tp) / (2 * tp + fp + fn)
        return f1

    def isLargerBetter(self):
        return True


text: Q: Make object move out from origin in three.js I am rather new to three.js, and I am creating a cube that should pop. However, I cannot find a way to make an edge piece on the cube move away from the origin. How can I do this? The cube code can be found at https://github.com/molarmanful/DayanZhanchi in the gh-pages branch.


text:
Q: First Day Of Month For Calculated Number Of Months I'm running into an issue where I need some more guidance. I've got a form that allows users to enter a start date and end date to represent the length of a contract. I'm using the following query to calculate the monthly amount :
SELECT t_Actuals.InvoiceAmount,
 (DateDiff("m",[StartDate],[EndDate])+1) AS [Contract Term],
 CCur(Round(([InvoiceAmount]/[Contract Term]),0)) AS MonthlyAmount
 FROM t_Actuals;

Our VP wants the MonthlyAmount projected throughout the length of the Contract Term (ie. 11 months from Start Date). Ideally, I would like to allocate the MonthlyAmount in a MM-YYYY (01/2012, 02,2012) format throughout the length of the contract term, but, admittedly, I am not that experienced with working with dates in Access outside of the Query Grid.
Regardless, I've been reading about the DateSerial function to find the first day of the month, but how would you implement that into a loop to find the value of the first date of the month for the next 36 months and write that date to a table with the projected date as fldDate and MonthlyAmount.
Sorry, this is kind of a convuluted question. Any advice would be greatly appreciated. Thank you in advance for any direction.

A: "a loop to find the value of the first date of the month for the next 36 months and write that date to a table with the projected date as fldDate and MonthlyAmount"
Given the starting date of the first month and the number of months, you can use the DateAdd() function to determine the rest of the dates you need to insert.  Open your table as a DAO recordset, use its .AddNew method to add a row, assign the values you want in the fields, and call .Update to store the row.
Sounded like your challenge was for the date piece, so I sketched that out and left the MonthlyAmount piece for you to complete.
Public Sub LoadMonthStartDates(ByVal pFirstDate As Date, _
        ByVal pMonths As Long)
    Const cstrTable = "YourTableNameHere"
    Dim db As DAO.database
    Dim rs As DAO.Recordset
    Dim i As Long

    Set db = CurrentDb
    Set rs = db.OpenRecordset(cstrTable, dbOpenTable, dbAppendOnly)
    For i = 1 To pMonths
        rs.AddNew
        rs!fldDate = DateAdd("m", i - 1, pFirstDate)
        'rs!MonthlyAmount = <your calculated amount>
        rs.Update
    Next
    rs.Close
    Set rs = Nothing
    Set db = Nothing
End Sub


text:
Q: Angular2 DecimalPipe with input type="number" On one hand I have in my component:
public test:number = 1000;

On another hand, I have created a piece of view this way:
<input type="number" [ngModel]="test | number:'1.0-1'" />

As soon as the property "test" is less than 1000, the input displays the value. Whenever it reaches 1000 and more, this value is not displayed anymore in the input.
Here is a plunker:
http://plnkr.co/edit/pFThNc1JNxfsnzJK9nCV
Is there something I missed? Or am I doing something wrong?

A: answer from yurzui: "Input with type number doesn't allow to pass text with comma"


text:
Q: Unable to access "VBOXADDITIONS_4.3.10_93012" I installed Ubuntu 13.10 in Virtual Box and everything went well until i upgraded it recently to Ubuntu 14.04. After the upgrade, it is not entering into full screen and if i try to install "Virtual box additions" inside Ubuntu, it is showing Unable to access "VBOXADDITIONS_4.3.10_93012" as in the screenshot attached,

I think VBOXADDITIONS got corrupted somehow. Please guide me experts.

A: Since you upgraded your VM, I'd suggest to update the Guest additions with the VM package manager in order to get their up-to-date versions.
Login first into your VM and open a Terminal to type:
sudo apt-get install virtualbox-guest-dkms virtualbox-guest-utils virtualbox-guest-x11

Finally restart the VM to complete the installation.
Now you can safely detach the old guest additions ISO from your VM.


text:
Q: Why is the running time of radix-sort minimized when the base of the digits is equal to the number of numbers to be sorted? In CSLR page 199 they state:

Lemma 8.4: Given n b-bit numbers and any positive integer r <= b, RADIX-SORT correctly sorts these numbers in O((b/r)(n + 2^r)) time if the stable sort it uses takes O(n + k) time for inputs in the range 0 to k.

As an example to understand this there is the following, where I follow along with what I think is the CSLR reasoning (and ask questions):
We start with n 32-bit numbers (b = 32). We have n numbers that can take values from 0 to 2^32 - 1. If we run radix-sort it would involve one pass through the numbers, in which counting-sort is used with variable k (which represents the range 0 to k in which the n numbers fall) equal to 2^32 - 1. Counting sort is O(n + k), so if k >> n, we get a very bad running time for variable sizes of n.
What we do now is split each of the 32-bit numbers into, say four 8-bit numbers. This means r = 8, and so each of these four numbers now has range 0 to 2^8 - 1 = 255. d = b / r = 32 / 8 = 4 is the number of digits in each of the n numbers.
My first question is: can we view the number 256 as the new base for each of the four 8-bit numbers? Do we now have four base-256 digits?
Now when we use radix-sort, we have to do four passes instead of one (counting-sort is used four times). Each pass is O(n + k) but now k is 2^8 - 1 = 255 not 2^32 - 1. So the total running time is O(4*(n + 255).
So when we split the initial number into smaller r-bit numbers, we increase the number of radix-sort passes, but decrease the range of values in counting-sort. There seems to be an optimal r that minimizes the running time.
**Second question: There is a paragraph on p.199 that seems to argue that there is such a value of r that minimizes the expression O((b/r)(n+2^r)). Can someone provide a better explanation? I cannot get my head around it. **

For given values of n and b, we wish to choose the value of r, with r
  <=  b, that minimizes the expression (b/r)(n + 2^r). If b < lg(n),
  then for any value of r <= b, we have that (n + 2^r) = O(n). Thus,
  choosing r = b yields a running time of (b/b)(n + 2^b), which is
  asymptotically optimal. If b  >= lg(n), then choosing r = lg(n)
  gives the best time to within a constant factor, which we can see as
  follows. Choosing r = lg(n) yields a running time of O(bn/lg(n)). As
  we increase r above lg(n), the 2^r term in the numerator increases
  faster than the r term in the denominator, and so increasing r above
  lg(n) yields a running time of Omega(bn/lg(n)). If instead we were to
  decrease r below lg(n), then the b/r term increases and the n + 2^r
  term remains at O(n).

On MIT opencourseware (Lecture 7 Course Notes), in one of their algorithms courses they show the minimization slightly differently:
counting-sort runs in O(n + b), where b is the base in which the numbers are expressed. So if the n numbers are in range 0 to k, each has d = log base b of k digits, where each digit is a number between 0 and b - 1. So b is now what k was in the previous example from CSLR. Radix-sort does d passes of counting-sort, so the total running time is O(d(n + b)) = O((n + b)*(log base b of k)). This is minimized when b is chosen to be n. How is this related to the CSLR discussion above on the same topic.

A: Partial answer here. First question - 256 would be the base number, and there would be four 8 bit digits in a 32 bit integer. Missing from the article is that it takes one read pass of the data to create a matrix of counts which is then converted into a matrix of indices (or pointers). In this case the matrix is [4][256]. After creating the matrix, then it takes 4 read / write radix sort passes to sort the dataset.
Second question - For a math based explanation, the derivative of (b/r)(n+2^r) = (b (2^r (r log(2) - 1) - n))/r^2. A minimum (or maximum) occurs when the derivative == 0, which occurs when 2^r (r log(2) - 1) - n = 0. For n == 2^20 (about 1 million), r ~= 16.606232 results in O() ~= 2212837. Some example values and O():
 r   O
18   2330169
17   2220514
16   2228224
15   2306867
12   2807125
 8   4195328

However, due to cache issues, the optimal value for r versus n becomes smaller. On my system (Intel 2600K, 3.4ghz), for n = 2^20, r = 8 is fastest. At around n = 2^24, r = 10.67, using 3 fields 10, 11, 11 is fastest. At around n = 2^26, r = 16 is fastest. Again, due to cache issues, there's not a lot of difference in performance, less than 10% for r = 8 versus r = 16.