text:
Q: Sorting an array: Firstly by 1 element in a defined order, Then by the total of 2 other elements I've looked at numerous examples on SO, but I'm unable to find a solution to this problem. I have a large array and I need to sort this by 2 elements.

*

*Firstly, by a priority field in a custom order: S1,S2,S3,S4,S5,D,NS

*Secondly, by 2 fields in the array added together. (This bit is working.)

I've made a sorting function which will sort by both of the above, however, it sorts D and NS before S1-S5 since D comes first alphabetically.
- I therefore need to define an array which contains the custom order I want to sort by. Please can anyone help?
The function I'm using is:
function compdaily($a, $b) {
    if ($a['Priority'] == $b['Priority'])
    {
        return ($a['Value1'] + $a['Value2']) < ($b['Value1'] + $b['Value2']);
    }
    return strcmp($a['Priority'], $b['Priority']);
}

I then call above function in this manner:
usort($Array, 'compdaily');

Which brings the items out in this order:
Array
(
    [0] => Array
        (
            [SomeID] => 1234
            [Priority] => D
            [Value1] => 250
            [Value2] => 100
        )
    [1] => Array
        (
            [SomeID] => 456
            [Priority] => NS
            [Value1] => 250
            [Value2] => 100
        )
    [2] => Array
        (
            [SomeID] => 124
            [Priority] => S1
            [Value1] => 200
            [Value2] => 200
        )
    [3] => Array
        (
            [SomeID] => 1235
            [Priority] => S1
            [Value1] => 100
            [Value2] => 100
        )
    [4] => Array
        (
            [SomeID] => 1230
            [Priority] => S2
            [Value1] => 250
            [Value2] => 100
        )
    [5] => Array
        (
            [SomeID] => 123495
            [Priority] => S3
            [Value1] => 250
            [Value2] => 100
        )
    [6] => Array
        (
            [SomeID] => 123498
            [Priority] => S3
            [Value1] => 100
            [Value2] => 100
        )
    [7] => Array
        (
            [SomeID] => 12345
            [Priority] => S4
            [Value1] => 250
            [Value2] => 100
        )
)

However, I need them in this order:
Array
(
    [0] => Array
        (
            [SomeID] => 124
            [Priority] => S1
            [Value1] => 200
            [Value2] => 200
        )
    [1] => Array
        (
            [SomeID] => 1235
            [Priority] => S1
            [Value1] => 100
            [Value2] => 100
        )
    [2] => Array
        (
            [SomeID] => 1230
            [Priority] => S2
            [Value1] => 250
            [Value2] => 100
        )
    [3] => Array
        (
            [SomeID] => 123495
            [Priority] => S3
            [Value1] => 250
            [Value2] => 100
        )
    [4] => Array
        (
            [SomeID] => 123498
            [Priority] => S3
            [Value1] => 100
            [Value2] => 100
        )
    [5] => Array
        (
            [SomeID] => 12345
            [Priority] => S4
            [Value1] => 250
            [Value2] => 100
        )
    [6] => Array
        (
            [SomeID] => 1234
            [Priority] => D
            [Value1] => 250
            [Value2] => 100
        )
    [7] => Array
        (
            [SomeID] => 456
            [Priority] => NS
            [Value1] => 250
            [Value2] => 100
        )
)

I've tried utilising the example at: Sort an array by multiple keys in a certain order
But I was unable to get this to work alongside the above.

A: Rather than using $a['Priority'] directly in sorting, could use a lookup table to get the actual order
something like...
$mapp = array('S1'=>1, 'S2'=>2, 'S3'=>3, 'S4'=>4, 'S5'=>5, 'D'=>6, 'NS'=>7);

function compdaily($a, $b) {
    global $mapp;
    ...
    return ($mapp[$a['Priority']] < $mapp[$b['Priority']]);
}

(the if statement doesn't need changing as can directly compare the strings for equality)


text:
Q: Rollup via Lookup Issue I put together a trigger that will perform a rollup summary (SUM) on a record that is associated via lookup. The trigger works perfectly if I want to include all the lookup records in the calculation.
I want to alter the code to only include certain records in the rollup summary. In particular, I only want to sum the "Value_for_MA__c" field if that record also has "Include_in_Settlement__c" set to True.
My code:
    public class LookupCalculation{

    public enum Method {COUNT, SUM, MIN, MAX, AVG}

    private string sobjectParent,
                   relationName,
                   formulaParent,
                   sobjectChild,
                   parentfield,
                   fieldChild,
                   fieldChild2;

    public LookupCalculation(string mysobjectParent, string myrelationName, string myformulaParent,
                             string mysobjectChild, string myparentfield, string myfieldChild, string myfieldChild2){
        sobjectParent = mysobjectParent;
        relationName = myrelationName;
        formulaParent = myformulaParent;
        sobjectChild = mysobjectChild;
        parentfield = myparentfield;
        fieldChild = myfieldChild;
        fieldChild2 = myfieldChild2;
    }

    public void Calculate(Method calculation, List<sobject> childList){
        set<Id> parentIdSet = new set<Id>();
        for(sobject sobj : childList)
            parentIdSet.add((Id) sobj.get(parentfield));
        string soqlParent = 'select id, (select ' + fieldChild + ' from ' + relationName + ') from ' + sobjectParent + ' , (select ' + fieldChild2 + ' from ' + relationName + ') from ' + sobjectParent + ' where fieldChild2 = True';
        List<sobject> parentList = Database.query(soqlParent);
        for(sobject parent : parentList){
            List<sobject> children = parent.getSObjects(relationName);
            if(children == null)
                children = new List<sobject>();
            Decimal counter = (mustSum(calculation))? 0 : null;
            if(calculation == Method.COUNT)
                counter = children.size();
            for(sobject child : children){
                Decimal value = (Decimal) child.get(fieldChild);
                if(mustSum(calculation) && value != null)
                    counter += value;
                else if(calculation == Method.MIN && (counter == null || value < counter))
                    counter = value;
                else if(calculation == Method.MAX && (counter == null || value > counter))
                    counter = value;
            }
            if(calculation == Method.AVG && children.size() > 0)
                counter = counter / children.size();
            parent.put(formulaParent, counter);
        }
        update parentList;
    }

    private boolean mustSum(Method calculation){
        return (calculation == Method.SUM || calculation == Method.AVG);
    }

}

Trigger
trigger RecRollup on Receiving__c (after insert,after update,after delete,after undelete) {

    /*******************TO BE CUSTOMIZED*********************/
    string mysobjectParent = 'Field__c',      // Parent sobject API Name
           myrelationName = 'RecRpts__r', // Api name of the relation between parent and child (ends with __r)
           myformulaParent = 'Rollup_RecRpts__c',        // Api name of the number field that will contain the calculation
           mysobjectChild = 'Receiving__c',  // Child sobject API Name
           myparentfield = 'Field__c', // Api name of the lookup field on chield object
           myfieldChild = 'Value_for_MA__c',  // Api name of the child field to roll up
           myfieldChild2 = 'Include_in_Settlement__c'; // Api name of the child field to use as a qualifier for rollup

    LookupCalculation.Method method = LookupCalculation.Method.SUM; //Selected method: could be COUNT, SUM, MIN, MAX, AVG
    /*******************************************************/

    LookupCalculation calculation = new LookupCalculation(mysobjectParent, myrelationName, myformulaParent,
                                                          mysobjectChild, myparentfield, myfieldChild, myfieldChild2);
    List<sobject> objList = new List<sobject>((List<sobject>) Trigger.new);
    if(Trigger.isDelete)
        objList = Trigger.old;
    if(Trigger.isUpdate)
        objList.addAll((List<sobject>) Trigger.old);
    calculation.calculate(method, objList);
}

Any help would be greatly appreciated.

A: From the code it looks like you already did an attempt..
This line currently does the query for child records:
    string soqlParent = 'select id, (select ' + fieldChild + ' from ' + relationName + ') from ' + sobjectParent + ' , (select ' + fieldChild2 + ' from ' + relationName + ') from ' + sobjectParent + ' where fieldChild2 = True';

But the filter on fieldChild2 is currently on the parent record instead of on the child record.
Also there are 2 subqueries on the child record, which is usually not a good idea. I suggest changing this to:
    string soqlParent = 'select id, (select ' + fieldChild + ',' + fieldChild2 + ' from ' + relationName + ' where fieldChild2 = True'+ ') from ' + sobjectParent ;

redpajama_set_name: RedPajamaStackExchange


text:
Q: RoundCube Send but dont receive I just finished installing my Mail server following this tutorial : here
And installed Roundcube following this tutorial : here
So For now, I m able to send email but can't receive, so I need some help please.
I m using Centos 7, for further information just let me know.

A: Yes it's pointing, and I found the probléme.
I don't know how I overwritten the SSL files, so I generated it back and it work.


text:
Q: Smb file share not showing correct free space I've been having issues with my samba share. After connecting to it from windows I have all my files but when trying to move files to the share, windows tells me there is not enough space. After running sudo fdisk -l on the server it returns:

Disk /dev/md0: 465.13 GiB, 499434651648 bytes, 975458304 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: gpt
Disk identifier: AC7D137A-4D89-400A-A623-7E46877F1769
Device     Start       End   Sectors   Size Type
/dev/md0p1  2048 975458270 975456223 465.1G Microsoft basic data"

I've only got about 134 GB used.
The df command returns this about the drive:

/dev/md0p1     487608960 141973696 345635264  30% /mnt

Here's my samba.conf file.
    #
    # Sample configuration file for the Samba suite for     Debian GNU/Linux.
#
#
# This is the main Samba configuration file. You should read the
# smb.conf(5) manual page in order to understand the options listed
# here. Samba has a huge number of configurable options most of which
# are not shown in this example
#
# Some options that are often worth tuning have been included as
# commented-out examples in this file.
#  - When such options are commented with ";", the proposed setting
#    differs from the default Samba behaviour
#  - When commented with "#", the proposed setting is the default
#    behaviour of Samba but the option is considered important
#    enough to be mentioned here
#
# NOTE: Whenever you modify this file you should run the command
# "testparm" to check that you have not made any basic syntactic
# errors.

#======================= Global Settings =======================

[global]

## Browsing/Identification ###

# Change this to the workgroup/NT-domain name your Samba server will part of
   workgroup = WORKGROUP

# server string is the equivalent of the NT Description field
   server string = %h server (Samba, Ubuntu)

#### Networking ####

# The specific set of interfaces / networks to bind to
# This can be either the interface name or an IP address/netmask;
# interface names are normally preferred
;   interfaces = 127.0.0.0/8 eth0

# Only bind to the named interfaces and/or networks; you must use the
# 'interfaces' option above to use this.
# It is recommended that you enable this feature if your Samba machine is
# not protected by a firewall or is a firewall itself.  However, this
# option cannot handle dynamic or non-broadcast interfaces correctly.
;   bind interfaces only = yes

#### Debugging/Accounting ####

# This tells Samba to use a separate log file for each machine
# that connects
   log file = /var/log/samba/log.%m

# Cap the size of the individual log files (in KiB).
   max log size = 1000

# We want Samba to only log to /var/log/samba/log.{smbd,nmbd}.
# Append syslog@1 if you want important messages to be sent to syslog too.
   logging = file

# Do something sensible when Samba crashes: mail the admin a backtrace
   panic action = /usr/share/samba/panic-action %d

####### Authentication #######

# Server role. Defines in which mode Samba will operate. Possible
# values are "standalone server", "member server", "classic primary
# domain controller", "classic backup domain controller", "active
# directory domain controller".
#
# Most people will want "standalone server" or "member server".
# Running as "active directory domain controller" will require first
# running "samba-tool domain provision" to wipe databases and create a
# new domain.
   server role = standalone server

   obey pam restrictions = yes

# This boolean parameter controls whether Samba attempts to sync the Unix
# password with the SMB password when the encrypted SMB password in the
# passdb is changed.
   unix password sync = yes

# For Unix password sync to work on a Debian GNU/Linux system, the following
# parameters must be set (thanks to Ian Kahan <<kahan@informatik.tu-muenchen.de> for
# sending the correct chat script for the passwd program in Debian Sarge).
   passwd program = /usr/bin/passwd %u
   passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .

# This boolean controls whether PAM will be used for password changes
# when requested by an SMB client instead of the program listed in
# 'passwd program'. The default is 'no'.
   pam password change = yes

# This option controls how unsuccessful authentication attempts are mapped
# to anonymous connections
   map to guest = bad user

########## Domains ###########

#
# The following settings only takes effect if 'server role = classic
# primary domain controller', 'server role = classic backup domain controller'
# or 'domain logons' is set
#

# It specifies the location of the user's
# profile directory from the client point of view) The following
# required a [profiles] share to be setup on the samba server (see
# below)
;   logon path = \\%N\profiles\%U
# Another common choice is storing the profile in the user's home directory
# (this is Samba's default)
#   logon path = \\%N\%U\profile

# The following setting only takes effect if 'domain logons' is set
# It specifies the location of a user's home directory (from the client
# point of view)
;   logon drive = H:
#   logon home = \\%N\%U

# The following setting only takes effect if 'domain logons' is set
# It specifies the script to run during logon. The script must be stored
# in the [netlogon] share
# NOTE: Must be store in 'DOS' file format convention
;   logon script = logon.cmd

# This allows Unix users to be created on the domain controller via the SAMR
# RPC pipe.  The example command creates a user account with a disabled Unix
# password; please adapt to your needs
; add user script = /usr/sbin/adduser --quiet --disabled-password --gecos "" %u

# This allows machine accounts to be created on the domain controller via the
# SAMR RPC pipe.
# The following assumes a "machines" group exists on the system
; add machine script  = /usr/sbin/useradd -g machines -c "%u machine account" -d /var/lib/samba -s /bin/false %u

# This allows Unix groups to be created on the domain controller via the SAMR
# RPC pipe.
; add group script = /usr/sbin/addgroup --force-badname %g

############ Misc ############

# Using the following line enables you to customise your configuration
# on a per machine basis. The %m gets replaced with the netbios name
# of the machine that is connecting
;   include = /home/samba/etc/smb.conf.%m

# Some defaults for winbind (make sure you're not using the ranges
# for something else.)
;   idmap config * :              backend = tdb
;   idmap config * :              range   = 3000-7999
;   idmap config YOURDOMAINHERE : backend = tdb
;   idmap config YOURDOMAINHERE : range   = 100000-999999
;   template shell = /bin/bash

# Setup usershare options to enable non-root users to share folders
# with the net usershare command.

# Maximum number of usershare. 0 means that usershare is disabled.
#   usershare max shares = 100

# Allow users who've been granted usershare privileges to create
# public shares, not just authenticated ones
   usershare allow guests = yes

#======================= Share Definitions =======================

# Un-comment the following (and tweak the other settings below to suit)
# to enable the default home directory shares. This will share each
# user's home directory as \\server\username
;[homes]
;   comment = Home Directories
;   browseable = no

# By default, the home directories are exported read-only. Change the
# next parameter to 'no' if you want to be able to write to them.
;   read only = yes

# File creation mask is set to 0700 for security reasons. If you want to
# create files with group=rw permissions, set next parameter to 0775.
;   create mask = 0700

# Directory creation mask is set to 0700 for security reasons. If you want to
# create dirs. with group=rw permissions, set next parameter to 0775.
;   directory mask = 0700

# By default, \\server\username shares can be connected to by anyone
# with access to the samba server.
# Un-comment the following parameter to make sure that only "username"
# can connect to \\server\username
# This might need tweaking when using external authentication schemes
;   valid users = %S

# Un-comment the following and create the netlogon directory for Domain Logons
# (you need to configure Samba to act as a domain controller too.)
;[netlogon]
;   comment = Network Logon Service
;   path = /home/samba/netlogon
;   guest ok = yes
;   read only = yes

# Un-comment the following and create the profiles directory to store
# users profiles (see the "logon path" option above)
# (you need to configure Samba to act as a domain controller too.)
# The path below should be writable by all users so that their
# profile directory may be created the first time they log on
;[profiles]
;   comment = Users profiles
;   path = /home/samba/profiles
;   guest ok = no
;   browseable = no
;   create mask = 0600
;   directory mask = 0700

[printers]
   comment = All Printers
   browseable = no
   path = /var/spool/samba
   printable = yes
   guest ok = no
   read only = yes
   create mask = 0700

# Windows clients look for this share name as a source of downloadable
# printer drivers
[print$]
   comment = Printer Drivers
   path = /var/lib/samba/printers
   browseable = yes
   read only = yes
   guest ok = no
# Uncomment to allow remote administration of Windows print drivers.
# You may need to replace 'lpadmin' with the name of the group your
# admin users are members of.
# Please note that you also need to set appropriate Unix permissions
# to the drivers directory for these users to have write rights in it
;   write list = root, @lpadmin

[raid]
  path = /mnt
  read only = no
  browsabe = yes
  writable = yes
  public = yes
  write list = usr
  create mask = 0777
  directory mask = 0777
  force user = root

The drive is a raid 1 created with madam at /dev/md0p1 mounted at /mnt. Any help is appreciated!


text:
Q: undefined method `popups_path' for # I create model, view and controller but when I added form code on new.html.haml file. it started showing error. Routes are defined as follows
model  popups.rb
class Popups < ActiveRecord::Base
  attr_accessible :title, :body, :slug, :pipelinetype
end

controller popups_controller.rb
class PopupsController < ApplicationController
  def new
    @popups = Popups.new
  end

  def create
    @popups = Popups.new(params[:url])
    if @popups.save
      flash[:popups] = @popups.id
      redirect_to new_popups_url
    else
      render :action => "new"
    end
  end

  def show
    @popups = Popups.find(params[:id])
    redirect_to @popups.url
  end

end

Views popups - new.html.haml
= simple_form_for @popups do |f|
  = f.input :title
  = f.input :body
  = f.input :pipelinetype
  = f.input :slug
  = f.submit

routes.rb resources :popups, :only => [:show, :new, :create]
migrate file
create_table :popups do |t|
      t.string :title
      t.text :body
      t.string :slug
      t.string :pipelinetype

      t.timestamps
    end

I am getting following errors on given urls
:3000/popups/new  -  undefined method `popups_index_path' for #

**:3000/popups   -**
Unknown action
The action 'show' could not be found for MainController

Initially I created model and controller with popup name but change it later to popups as suggested
Is there something wrong with code or routes or I am missing someting.
I used http://www.sitepoint.com/building-your-first-rails-application-views-and-controllers/ as reference

A: Always remember when you use resources, you should be giving a plural name(i.e, popups in your case). If you want a singular name(i.e, popup) then use resource instead of resources.
For more Info, see Singular Resources

A: You have to  plurialize your routes.
resources :popup, :only => [:show, :new, :create]
Should be
resources :popups, only: [:show, :new, :create]
Actually your routes look like that:
popup_index POST  /popup(.:format)       popup#create
new_popup GET     /popup/new(.:format)   popup#new
popup GET         /popup/:id(.:format)   popup#show


text:
Q: How to call a function with onclick in jQuery? I used this code to show tabbed content with navigate in URL:

jQuery(function ($) {

  // Define Plugin
  $.organicTabs = function(el, options) {

    // JavaScript native version of this
    var base = this;

    // jQuery version of this
    base.$el = $(el);

    // Navigation for current selector passed to plugin
    base.$nav = base.$el.find(".tab");

    // Runs once when plugin called
    base.init = function() {

      // Pull in arguments
      base.options = $.extend({}, $.organicTabs.defaultOptions, options);

      // Accessible hiding fix (hmmm, re-look at this, screen readers still run JS)
      $(".hide").css({
        "position": "relative",
        "top": 0,
        "left": 0,
        "display": "none"
      });

      // When navigation tab is clicked...
      base.$nav.on("click", "a", function(e) {

        // no hash links
        e.preventDefault();

        // Figure out current list via CSS class
        var curList = base.$el.find("a.current").attr("href").substring(1),

          // List moving to
          $newList = $(this),

          // Figure out ID of new list
          listID = $newList.attr("href").substring(1),

          // Set outer wrapper height to (static) height of current inner list
          $allListWrap = base.$el.find(".list-wrap"),
          curListHeight = $allListWrap.height();
        $allListWrap.height(curListHeight);

        if ((listID != curList) && (base.$el.find(":animated").length == 0)) {

          // Fade out current list
          base.$el.find("#" + curList).fadeOut(base.options.speed, function() {

            // Fade in new list on callback
            base.$el.find("#" + listID).fadeIn(base.options.speed);

            // Adjust outer wrapper to fit new list snuggly
            var newHeight = base.$el.find("#" + listID).height();
            $allListWrap.animate({
              height: newHeight
            }, base.options.speed);

            // Remove highlighting - Add to just-clicked tab
            base.$el.find(".tab li a").removeClass("current");
            $newList.addClass("current");

            // Change window location to add URL params
            if (window.history && history.pushState) {
              // NOTE: doesn't take into account existing params
              history.replaceState("", "", "?" + base.options.param + "=" + listID);
            }
          });

        }

      });

      var queryString = {};
      window.location.href.replace(
        new RegExp("([^?=&]+)(=([^&]*))?", "g"),
        function($0, $1, $2, $3) {
          queryString[$1] = $3;
        }
      );

      if (queryString[base.options.param]) {

        var tab = $("a[href='#" + queryString[base.options.param] + "']");

        tab
          .closest(".tab")
          .find("a")
          .removeClass("current")
          .end()
          .next(".list-wrap")
          .find("ul.me")
          .hide();
        tab.addClass("current");
        $("#" + queryString[base.options.param]).show();

      };

    };
    base.init();
  };

  $.organicTabs.defaultOptions = {
    "speed": 300,
    "param": "tab"
  };

  $.fn.organicTabs = function(options) {
    return this.each(function() {
      (new $.organicTabs(this, options));
    });
  };

});

jQuery(function($) {

  // Calling the plugin
  $("#tabbed-content").organicTabs();

});
/* Generic Utility */
.hide { position: absolute; top: -9999px; left: -9999px; }

/* Specific to example one */

#tabbed-content { background: #eee; padding: 10px; margin: 0 0 20px 0; -moz-box-shadow: 0 0 5px #666; -webkit-box-shadow: 0 0 5px #666; }

#tabbed-content .tab { overflow: hidden; margin: 0 0 10px 0; list-style: none;}
#tabbed-content .tab li { width: 97px; float: left; margin: 0 10px 0 0; }
#tabbed-content .tab li.last { margin-right: 0; }
#tabbed-content .tab li a { display: block; padding: 5px; background: #959290; color: white; font-size: 10px; text-align: center; border: 0; }
#tabbed-content .tab li a:hover { background-color: #111; }

#etabbed-content ul { list-style: none; }
#tabbed-content ul li a { display: block; border-bottom: 1px solid #666; padding: 4px; color: #666; }
#tabbed-content ul li a:hover { background: #fe4902; color: white; }
#tabbed-content ul li:last-child a { border: none; }

#tabbed-content ul li.nav-one a.current, #tabbed-content ul#featured li a:hover { background-color: #0575f4; color: white; }
#tabbed-content ul li.nav-two a.current, #tabbed-content ul#core li a:hover { background-color: #d30000; color: white; }
#tabbed-content ul li.nav-three a.current, #tabbed-content ul#jquerytuts li a:hover { background-color: #8d01b0; color: white; }
#tabbed-content ul li.nav-four a.current, #tabbed-content ul#classics li a:hover { background-color: #FE4902; color: white; }

.page-id-642 footer, .page-id-642 header {
    display: none;
}

Level1

Level2

Level3

content Level 1

content Level 2

content Level 3

Go To Level 2 :)

This code works well, but when I add a new link with class ('.newlink') in the bottom, the link does not work.
I want to navigate to step2 when I click on the link. Like when i click on "Level2" tab link.
Do I need to call function to navigate the link?

A: So, this was actually a very complicated thing!  This may not be a perfect, 100% what you want answer -- but it should basically explain what's going on and lead you in the right direction.
First, you bind $.organicTabs() to just #tabbed-content.  Well, the  element you have added is outside the context of the bound element.  I put the new link in a
 and gave it the id of links, and then made the following update to the jQuery...
$("#tabbed-content, #links").organicTabs();

Next, your definition in $.organicTabs of curList needed updating to have wider document-scope...
var curList = document.getElementsByClassName('current')[0].getAttribute('href').substring(1),

Finally, to have your link connect to your tabbed-body, you'll need to move its scope upwards into the tabbed-body scope...

Go To Level 2 :)

It works!  The styling is certainly off, but this is clearly a massive project and not every little quirk can be perfectly readjusted so easily.  It may be that $.organicTabs() isn't so organic and fresh anymore and could go for some re-engineering!

jQuery(function ($) {

  // Define Plugin
  $.organicTabs = function(el, options) {

    // JavaScript native version of this
    var base = this;

    // jQuery version of this
    base.$el = $(el);

    // Navigation for current selector passed to plugin
    base.$nav = base.$el.find(".tab");

    // Runs once when plugin called
    base.init = function() {

      // Pull in arguments
      base.options = $.extend({}, $.organicTabs.defaultOptions, options);

      // Accessible hiding fix (hmmm, re-look at this, screen readers still run JS)
      $(".hide").css({
        "position": "relative",
        "top": 0,
        "left": 0,
        "display": "none"
      });

      // When navigation tab is clicked...
      base.$nav.on("click", "a", function(e) {
        // no hash links
        e.preventDefault();

        // Figure out current list via CSS class

        var curList = document.getElementsByClassName('current')[0].getAttribute('href').substring(1),

          // List moving to
          $newList = $(this),

          // Figure out ID of new list
          listID = $newList.attr("href").substring(1),

          // Set outer wrapper height to (static) height of current inner list
          $allListWrap = base.$el.find(".list-wrap"),
          curListHeight = $allListWrap.height();
        $allListWrap.height(curListHeight);

        if ((listID != curList) && (base.$el.find(":animated").length == 0)) {

          // Fade out current list
          base.$el.find("#" + curList).fadeOut(base.options.speed, function() {

            // Fade in new list on callback
            base.$el.find("#" + listID).fadeIn(base.options.speed);

            // Adjust outer wrapper to fit new list snuggly
            var newHeight = base.$el.find("#" + listID).height();
            $allListWrap.animate({
              height: newHeight
            }, base.options.speed);

            // Remove highlighting - Add to just-clicked tab
            base.$el.find(".tab li a").removeClass("current");
            $newList.addClass("current");

            // Change window location to add URL params
            if (window.history && history.pushState) {
              // NOTE: doesn't take into account existing params
              history.replaceState("", "", "?" + base.options.param + "=" + listID);
            }
          });

        }

      });

      var queryString = {};
      window.location.href.replace(
        new RegExp("([^?=&]+)(=([^&]*))?", "g"),
        function($0, $1, $2, $3) {
          queryString[$1] = $3;
        }
      );

      if (queryString[base.options.param]) {

        var tab = $("a[href='#" + queryString[base.options.param] + "']");

        tab
          .closest(".tab")
          .find("a")
          .removeClass("current")
          .end()
          .next(".list-wrap")
          .find("ul.me")
          .hide();
        tab.addClass("current");
        $("#" + queryString[base.options.param]).show();

      };

    };
    base.init();
  };

  $.organicTabs.defaultOptions = {
    "speed": 300,
    "param": "tab"
  };

  $.fn.organicTabs = function(options) {
    return this.each(function() {
      (new $.organicTabs(this, options));
    });
  };

});

jQuery(function($) {

  // Calling the plugin
  $("#tabbed-content, #links").organicTabs();

});
/* Generic Utility */
.hide { position: absolute; top: -9999px; left: -9999px; }

/* Specific to example one */

#tabbed-content { background: #eee; padding: 10px; margin: 0 0 20px 0; -moz-box-shadow: 0 0 5px #666; -webkit-box-shadow: 0 0 5px #666; }

#tabbed-content .tab { overflow: hidden; margin: 0 0 10px 0; list-style: none;}
#tabbed-content .tab li { width: 97px; float: left; margin: 0 10px 0 0; }
#tabbed-content .tab li.last { margin-right: 0; }
#tabbed-content .tab li a { display: block; padding: 5px; background: #959290; color: white; font-size: 10px; text-align: center; border: 0; }
#tabbed-content .tab li a:hover { background-color: #111; }

#etabbed-content ul { list-style: none; }
#tabbed-content ul li a { display: block; border-bottom: 1px solid #666; padding: 4px; color: #666; }
#tabbed-content ul li a:hover { background: #fe4902; color: white; }
#tabbed-content ul li:last-child a { border: none; }

#tabbed-content ul li.nav-one a.current, #tabbed-content ul#featured li a:hover { background-color: #0575f4; color: white; }
#tabbed-content ul li.nav-two a.current, #tabbed-content ul#core li a:hover { background-color: #d30000; color: white; }
#tabbed-content ul li.nav-three a.current, #tabbed-content ul#jquerytuts li a:hover { background-color: #8d01b0; color: white; }
#tabbed-content ul li.nav-four a.current, #tabbed-content ul#classics li a:hover { background-color: #FE4902; color: white; }

.page-id-642 footer, .page-id-642 header {
 display: none;
}

Level1

Level2

Level3

content Level 1

content Level 2

content Level 3

Level2

A: Use something like this:
$('.newlink').on('click', function (e){
  e.preventDefault();
  $('#tabbed-content ul li a[href="#step2"]').click();
})

A: You can also try to change this line:
Go To Level 2 :)

Replace $step2 with ?tab=step2
Note: it will reload the page but this is based on you are trying to write the code. If you don't wants to reload then page then need to write javascript for the same.


text:
Q: запуск метода элемента listview, который на экране нужно загружать картинку в элементы listview, но так как элементов может быть много, загружать их все сразу не очень разумно, как сделать так, чтобы метод запускался только у тех жлементов, что на экране, пробовал так:
list.setOnScrollListener(new AbsListView.OnScrollListener() {
        public void onScrollStateChanged(AbsListView view, int scrollState) {
           // Log.d(LOG_TAG, "scrollState = " + scrollState);
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            for(int i = firstVisibleItem; i <= visibleItemCount; i++){
                element.get(i).loadCover();
            }
            list.invalidate();
        }
    });

но загружаются только первые 6 картинок, а дальше все

A: загрузку картинок организовать стоит организовать в методе getView, так же стоит использовать паттерн ViewHolder для кэширования элементов списка. Вот небольшой пример как это можно организовать
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
    ViewHolder viewHolder;
    //если convertView == null,
    // значит этот вью элемент еще ни разу не загружался, инфлэйтим его
    //и сохраняем во view holder
    if (convertView == null){
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    //list_item - это ваш лэйаут для элемента списка
        convertView = inflater.inflate(R.layout.list_item, viewGroup, false);
        viewHolder = new ViewHolder();
    //находим imageView и записываем во viewHolder
        viewHolder.imageView = (ImageView) convertView.findViewById(R.id.my_image);
    //сохраняем ссылку на viewholder в convertView
        convertView.setTag(viewHolder);
    } else {
    //convertView!=null - значит этот вью элемент уже загружался, можно его переиспользовать, достаем из него ссылку на viewHolder
        viewHolder = (ViewHolder) convertView.getTag();
    }
    //загрузку картинки делаем с помощью библиотеки http://square.github.io/picasso/ , она же отвечает за кэширование
    Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(viewHolder.imageView);

        return convertView;
    }

class ViewHolder{ ImageView imageView;}

A: Если загрузка картинки у вас запускается в методе getView адаптера, то будут загружаться только картинки элементов, отображающихся на экране. При скроле новые элементы отображаются и их картинки начинают загружаться. Никаких слушателей скрола тут не надо.

A: Для подобной(Относительно. Ленивая асинхронная загрузка изображений) есть маленькая библиотека https://github.com/thest1/LazyList
Проблема вашего кода - вы считаете что visibleItemCount - общее кол-во элементов в адаптере, но это кол-во видимых элементов. Т.е. после шестого элемента вы запускаете цикл с параметром i=7;i<6.
Можно сделать так. Хотя метод onScroll и плохо работает при быстрой прокрутке.
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
     if(((firstVisibleItem + visibleItemCount) == totalItemCount) && totalItemCount > 0)){
        loadNewData();
     }
     list.invalidate();
 }

или слегка поправить ваш код
for(int i = firstVisibleItem; i <= (firstVisibleItem+visibleItemCount)&&i<=totalItemCount; i++){
            element.get(i).loadCover();
        }


text:
Q: Counting Distinct Items In Apache Pig I have a table user table with Schema
|Column 1 | USER ID |int|

|Column 2 |EMAIL|chararray|

|Column 3 |LANGUAGE |chararray|

|Column 4 |LOCATION |chararray|

and a transactional table with schema
|Column 1 | ID |int|

|Column 2 |PRODUCT|int|

|Column 3 |USER ID |int|

|Column 4 |PURCHASE AMOUNT |double|

|Coulmn 5 |DESCRIPTION |chararray|

Ques...Find out the count of each product in distinctive Locations.
I have written a pig script as following :-
user = LOAD '/tmp/users.txt' USING PigStorage ('    ')
AS (USER_ID:int, EMAIL:chararray, LANGUAGE:chararray, LOCATION:chararray);

transaction = LOAD '/tmp/transaction.txt' USING PigStorage ('   ')
AS (ID:int, PRODUCT:int,USER_ID:int, PURCHASE_AMOUNT:double,DESCRIPTION:chararray);

u1 = JOIN user by USER_ID, transaction by USER_ID;

u2 = GROUP u1 by LOCATION;

Result = FOREACH u2 GENERATE COUNT(u2.PRODUCT);

DUMP Result;

Error---ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1200: Pig script failed to parse:
 Invalid scalar projection: u2
This is what i am getting.

A: In your script Result = FOREACH u2 GENERATE COUNT(u2.PRODUCT); is wrong. After the group by operation, data structure changes. You can find that with describe u2. Please try with following (I'm assuming the fields are comma separated in the txt file):
user = LOAD 'user.txt' USING PigStorage (',') AS (USER_ID:int, EMAIL:chararray, LANGUAGE:chararray, LOCATION:chararray);

transaction = LOAD 'transaction.txt' USING PigStorage (',') AS (ID:int, PRODUCT:int,USER_ID:int, PURCHASE_AMOUNT:double,DESCRIPTION:chararray);

u1 = JOIN user by USER_ID, transaction by USER_ID;

u2 = GROUP u1 by (LOCATION,PRODUCT);

Result = FOREACH u2 GENERATE FLATTEN(group) as (LOCATION,PRODUCT), COUNT($1);

DUMP Result;


text:
Q: Celery raise error while passing my queryset obj as parameter I trying to execute a periodic task, so I used celery with Django 1.8 and Django Rest Framework and Postgres as Database. When I try to send my obj to the task I get TypeError: foreign_model_obj is not JSON serializable. How can I pass my queryset object to my Task.
views.py :
class MyModelCreateApiView(generics.CreateAPIView):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer
    authentication_classes = (TokenAuthentication,)

    def create(self, request, *args, **kwargs):
        data = dict()
        data['foreign_model_id'] = kwargs['pk']
        foreign_model_obj = MyForeignModel.objects.get(id=data['foreign_model_id'])

        obj = MyModel.objects.create(**data)
        result = serialize_query(MyModel, {"id": obj.id})
        local_time = foreign_model_obj.time
        my_celery_task.apply_async([foreign_model_obj], eta=local_time)
        return Response(result)

tasks.py :
@celery_app.task(name="my_celery_task")
def my_first_celery_task(mymodel_obj):
    # ... updating obj attributes
    mymodel_obj.save()

A: You have just to send the id of your instance and retrieve the object within the task.
It's a bad practice to pass the instance, since it can be altered in meantime, specially that you are excuting your task with a deplay as it seems to be.
views.py :
class MyModelCreateApiView(generics.CreateAPIView):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer
    authentication_classes = (TokenAuthentication,)

    def create(self, request, *args, **kwargs):
        data = dict()
        data['foreign_model_id'] = kwargs['pk']
        foreign_model_obj = MyForeignModel.objects.get(id=data['foreign_model_id'])

        obj = MyModel.objects.create(**data)
        result = serialize_query(MyModel, {"id": obj.id})
        local_time = foreign_model_obj.time
        my_celery_task.apply_async([foreign_model_obj.id], eta=local_time) # send only the obj id
        return Response(result)

tasks.py :
@celery_app.task(name="my_celery_task")
def my_celery_task(mymodel_obj_id):
    my_model_obj = MyModel.objects.get(id=mymodel_obj_id) # retrieve your object here
    # ... updating obj attributes
    mymodel_obj.save()

A: Actually, IMHO the best way to go is to get a picklable component of the queryset, then regenerate the queryset in the task (https://docs.djangoproject.com/en/1.9/ref/models/querysets/):
import pickle
query = pickle.loads(s)     # Assuming 's' is the pickled string.
qs = MyModel.objects.filter(a__in=[1,2,3]) # whatever you want here...
querystr = pickle.dumps(qs.query)      # pickle the queryset
my_celery_task.apply_async(querystr, eta=local_time) # send only the string...

The task:
@celery_app.task(name="my_celery_task")
def my_celery_task(querystr):
    my_model_objs = MyModel.objects.all()
    my_model_objs.query = pickle.loads(querystr) # Restore the queryset
    # ... updating obj attributes
    item=my_model_objs[0]

This is the best approach, I think, because the query will get executed (perhaps the first time) in the task, preventing various timing issues, it need not be executed in the caller (so no doubling up on the query).

A: You could change method of serialization to pickle, but it is not recommended to pass queryset as a parameter. Quote from Celery documentation:
Another gotcha is Django model objects. They shouldn't be passed on as arguments to tasks. It's almost always better to re-fetch the object from the database when the task is running instead, as using old data may lead to race conditions.
http://docs.celeryproject.org/en/latest/userguide/tasks.html


text:
Q: NativeScript. Display barcode and qr I'm using nativescript-barcodescanner for scanning codes, but cannot find any solution for displaying this barcode on screen.

A: Correct, that plugin is for scanning, not for displaying.
There are many services that can transform text into a barcode. The Google Chart API for instance. Just try adding an image to your view with this as src: http://chart.apis.google.com/chart?cht=qr&chs=300x300&chl=1234567890


text:
Q: Decimal to binary without for, while, or if loops How can I write a program that reads an integer and displays a binary number without using loops, just with binary operators? (Only with basic functions)
 #include<stdio.h>
 #include<stdint.h>
 #include<math.h>
 int main()
 {uint8_t a;
 scanf("%hhd", &a);
 //i have read the integer, but I don't know how to go on
 return 0;
 }

A: Displays a binary number without using loops, just with binary operators:
#include<stdio.h>
#include<stdint.h>
#include<math.h>
int main()
{
  int a;
  scanf("%u", &a);

  printf("Number: 0x%X\n", a);

  printf("%d", ((a & 0x80) >> 7));
  printf("%d", ((a & 0x40) >> 6));
  printf("%d", ((a & 0x20) >> 5));
  printf("%d", ((a & 0x10) >> 4));
  printf("%d", ((a & 0x08) >> 3));
  printf("%d", ((a & 0x04) >> 2));
  printf("%d", ((a & 0x02) >> 1));
  printf("%d", ((a & 0x01) >> 0));

  printf("\n");

  return 0;
}

Be careful, as the input is integer, I added a printf
131
Number: 0x83
10000011

Of course, it would be easier with loops :
int main()
{
  int     a;
  uint8_t Mask;
  uint8_t Shift;
  scanf("%u", &a);

  printf("Number: %X\n", a);

  Mask  = 0x80;
  Shift = 7;

  while (Mask > 0)
  {
    printf("%d", ((a & Mask) >> Shift));
    Mask = Mask >> 1;
    Shift--;
  }

  printf("\n");

  return 0;
}


text:
Q: Android Adapter formats layout before onDataSetChanged has had time to process the data I'm implementing an instance of RemoteViewsService.RemoteViewsFactory which controls the layout for my widget. The problem is the data to format the layouts gets pulled from the database and formatted asynchronously via RxJava2.
@Override
public void onDataSetChanged() {
    Observable.doSomeLongAsyncRequestAndProcess()
        .subscribe(data -> {
            // Data is ready at this point
            // Unfortunately it's too late
        })
}

@Override
public RemoteViews getViewAt(int position) { // layout with non-existant data }

Since I don't control (not that I know of) when the layout starts initiating the layout in, how can I stop #getViewAt from trying to process the layout before the data's ready?

A: Short answer: Just fetch your data from database in onDataSetChanged() without async. Something like:
Observable.doSomeLongAsyncRequestAndProcess()
    .subscribe(data -> {
        // Data is ready at this point
        // And after that, chain to getViewAt() will be triggered,
        // so you will have all your data for views in time
    }).blockingFirst()

Long answer: onDataSetChanged() is working on binder thread, so it will be safe to fetch data here. In RemoteViewFactory callbacks, only onCreate() is on main thread. You can easily check it by logging current thread in all callbacks of RemoteViewFactory. So there will be no problem anymore, after executing onDataSetChanged(), it will trigger chain to getViewAt(), and you will have already all data for your remoteviews list at this moment.


text:
Q: Would past simple be a better choice? Look at this sentence extract from Emir Kusturica's Wikipedia article:

Despite the aforementioned conflict of religion, Kusturica refused to see himself as either a Bosniak or Serb. Instead, he had continued to insist that he was simply a Yugoslav.[39]

Does had continued indicate that this feeling of being Yugoslav began before the refusal but did it continue after it?
Don't you think the use of had continued past perfect is not very judicious because if you say continue it is because it began before. So we can understand that he always felt Yugoslavian and it began a long time before the refusal and maybe after the refusal even if Yugoslavia did not exist at the refusal time. So would not be past simple a better choice?

A: I suppose the text talks of a particular moment in history.  Imagine yourself transported to the time exactly at that moment.  Imagine that it is now.  Can you now say that Kusturica now has (for some time, unknown from what day exactly) continued (meaning repeatedly done so) calling himself "Yugoslav"?  Saying "Kusturica continues ..." gives it a different meaning, doesn't it?
Let's come back to our time, and if you agree that the choice of Present Perfect ("has continued") was OK for the day we magically visited, the use of Past Perfect is justified over Past Indefinite.


text:
Q: Serre's Local Fields Proposition 2 Chapter 3 Let $V/K$ be a vector space where $K = Frac(A)$ for some Dedekind domain $A$, $X$ a lattice (and hence an $A$- submodule) of $V$, and $u$ a $K$-automorphism of $V$. The claim is that $\chi_A (X, uX) = (det(u))$.
Here for lattices $X_1$ and $X_2$ of $V$, we define $\chi_A(X_1, X_2) = \chi_A(X_1/X_3) \chi_A(X_2/X_3)^{-1}$ for some lattice $X_3$ inside of $X_1$ and $X_2$.
For a finite length $A$- module $M$ we define $\chi_A(M) = \prod \mathfrak{p}_i$ where each $\mathfrak{p}_i$ corresponds to a maximal ideal of $A$ such that $A/(\mathfrak{p}_i) \cong  M_i/M_{i+1}$ for $M_i$ in the composition series of $M$.
For the proof Serre claims that "we are reduced the case where $X$ is free by localizing and multiplying $u$ by a constant." I can see that essentially what he is saying is that we can reduce to the case where $A$ is a DVR via localization and then get that $X$ is free since we have a torsion free module over a PID, but I don't see why we can localize here to reduce to this case and any help in understanding this would be greatly appreciated.


text:
Q: How to connect to MySql using JDBC? Worded fine with java SE, but have problem with java packages in android Android version of DriverManager import section looks like this
//  Android\SDK\sources\android-27\java\sql\DriverManager.java
package java.sql;

import java.util.Iterator;
import java.util.ServiceLoader;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.CopyOnWriteArrayList;

import sun.reflect.CallerSensitive;
import sun.reflect.Reflection;

An exception is raised when I call getConnection(), and hence I could not access the database.
It says - (Cannot resolve symbol CallerSensitive) and (Cannot resolve symbol Reflection).
Java SE version Drivermanager import looks like this
package java.sql;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Stream;

import jdk.internal.reflect.CallerSensitive;
import jdk.internal.reflect.Reflection;

This worked fine when I wanted to connect to mysql using jdbc.
api-27,28,29,30 all have same imports. Can anyone help me how to connect to mysql using JDBC?


text:
Q: Efficient text classification with large number (tens of thousands or more) of classes. I'm working on a text classification problem in which the number of classes/labels is large (tens of thousands or more). What approaches/methods would you use? Can you point me towards any relevant papers?

A: How long your text entities are? If they are document, then Refined Experts is a very good work to look at given that you have large number of document classes. This work did experiment on more than 100 thousand classes but one important fact is the classes are hierarchically organized. They have used hierarchical SVM to build their classifier. SVM is good with large of classes if they are hierarchically organized. You can find lot of relevant works through Google scholar.
If your classes are not hierarchically organized, then you model your problem as n-binary classification problem. You may get some idea if you go through this presentation.


text:
Q: Cross-browser textPath horizontal centre alignment for multi-line text I would like to horizontally centre align more than one line of text.
The following approach works in Firefox 68.0.2

path { stroke: #000; }
text { fill: #000; }
<svg width="400" height="120">
  <path id="p1" d="M10,40l250,0" />
  <text text-anchor="middle">
    <textPath href="#p1" startOffset="50%">
      <tspan x="0" dy="1.4em">this is the first line</tspan>
      <tspan x="0" dy="1.4em">and this is the second</tspan>
    </textPath>
  </text>
</svg>

However, in Chrome Version 77.0.3865.90, both lines are rendered to the left. It looks as though the combined length of the two <tspan> is used to calculate the centre point.

I can make it work in both browsers by using two separate <text> elements:

path { stroke: #000; }
text { fill: #000; }
<svg width="400" height="120">
  <path id="p1" d="M10,40l250,0" />
  <text text-anchor="middle">
    <textPath href="#p1" startOffset="50%">
      <tspan x="0" dy="1.4em">this is the first line</tspan>
    </textPath>
  </text>
  <text text-anchor="middle">
    <textPath href="#p1" startOffset="50%">
      <tspan x="0" dy="2.8em">and this is the second</tspan>
    </textPath>
  </text>
</svg>

(I also tried using two <textPath> within the same <text> parent, but the behaviour of dy is also different between the two browsers)
My questions are:

*

*Which browser is behaving correctly (is this a bug in the other one)?

*Is there a cross-browser way to achieve the same result without rendering two separate <text> elements?

A: I believe Chrome is doing the correct thing here - other than the missing "a". :-/
In SVG 1.1, the interaction of the startOffset and x attributes wasn't well defined, and browsers did all different things.
However, in SVG 2, an attempt to fully describe the text layout algorithm for <textPath> elements has been made.  You can find it here:
https://svgwg.org/svg2-draft/single-page.html#text-TextpathLayoutRules
In there it says:

For text-anchor:middle, startpoint-on-the-path is the point on the path which represents the point on the path which is [ 'startOffset' minus half of the total advance values for all of the glyphs in the 'textPath' element ] distance along the path from the start of the path

Then later, it says:

When the inline-base direction is horizontal, then any 'x' attributes on 'text' or 'tspan' elements represent new absolute offsets along the path, thus providing explicit new values for startpoint-on-the-path.

In other words, your x="0" attributes are overriding the startOffset and text-anchor settings.
So being more simple and explicit, as you are in your second SVG, is the way to go.


text:
Q: How to convert a wave from Amplitude time to Amplitude Frequency domain? Regarding Gravitational waves strain data I have read that on applying FFT on gravitational wave strain we can bring Amplitude time domain to Amplitude-frequency domain. But when I apply this conversion on the data I had I get this curve

I'm looking at gravitational wave strain data provided by LIGO. I am trying to estimate the mass of the black holes using the waveforms. The equation is present in an amplitude frequency domain. So I'm trying to convert it into that domain from Amplitude time.
How were the solar masses and distance of the GW150914 merger event calculated from the signal?
I am referring to this equation
Is this the expected figure or should I have used something other that FFT, if so what would that be?


text:
Q: Is there a way to adjust only the bottom padding of a chart's title in Chart.js? Based on the documentation, the padding property of the title in Chart.js adjusts both the top and bottom paddings. However, I'd like to adjust only the bottom padding.
I've tried using a padding object:
title:{
    display: true,
    text:'Population of cities in California',
    padding:{
        left:0,
        right:0,
        bottom:30,
        top:0
    }
}

But this is probably not supported, because it just messed everything up and made the chart not even visible.
I've searched the documentation and googled a bit to see if this has been asked somewhere already, but I couldn't find any solutions.
Is there a built-in way to do this within Chart.js? If not, what would be the simplest workaround?

A: title.padding takes the number of pixels to add above and below the title text.
There exists a workaround to add padding at the bottom of the chart title only. The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw hook to draw the title yourself directly on the canvas using CanvasRenderingContext2D.fillText().
plugins: [{
  afterDraw: chart => {
    var ctx = chart.chart.ctx;
    ctx.save();
    ctx.textAlign = 'center';
    ctx.font = "18px Arial";
    ctx.fillStyle = "gray";
    ctx.fillText('My Title', chart.chart.width / 2, 20);
    ctx.restore();
  }
}],

Together with this, you'll have to define top padding for your chart. This determines the space between your title and the chart (the title bottom padding basicaly).
layout: {
  padding: {
    top: 80
  }
},

Please have a look at below code that shows how it could look like.

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      ctx.save();
      ctx.textAlign = 'center';
      ctx.font = "18px Arial";
      ctx.fillStyle = "gray";
      ctx.fillText('My Title', chart.chart.width / 2, 20);
      ctx.restore();
    }
  }],
  data: {
    labels: ['A', 'B', 'C', 'D'],
    datasets: [{
      data: [10, 12, 8, 6],
      backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 205, 86, 0.2)', 'rgba(75, 192, 192, 0.2)'],
      borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)'],
      borderWidth: 1
    }]
  },
  options: {
    layout: {
      padding: {
        top: 80
      }
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>


text:
Q: Send $_POST and $_FILES together using AJAX data field so that PHP can grab the value? I have the following form which has

*

*a text field

*date field

*a file browser.

I am using AJAX to send the $_POST data values to another PHP file to insert into a MySQL database. But I want to move the $_FILES too.
In the $.ajax field, there is data: whereby I can assign those data to be transferred to another PHP file.
I am able to do it with the text field and date fields. How to do it for the $_FILES? My codes are as below
AJAX

HTML
<!DOCTYPE html>

        <link rel="icon" type="image/png" href="images/version-control.png">
        <meta charset="utf-8">
        <link href='https://fonts.googleapis.com/css?family=Raleway:400,300,700,900' rel='stylesheet' type='text/css'>
        <link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <link rel="stylesheet" type="text/css" href="style.css">

            <form method="post" enctype="multipart/form-data">

                    Project ID

<?php if(isset($_POST['prjId'])){echo '
                        <input type="text" class="form-control" placeholder="Project ID" name="prjId" id="prjId" value="'.$_POST['prjId'].'">';}else{echo'
                        <input type="text" class="form-control" placeholder="Project ID" name="prjId" id="prjId">';}?>

                    Updated Date

<?php if(isset($_POST['udatedDate'])){echo '
                        <input type="date" class="form-control" name = "updatedDate" id="updatedDate" value="'.$_POST['udatedDate'].'">';}else{echo '
                        <input type="date" class="form-control" name = "updatedDate" id="updatedDate">';}?>

                <fieldset class="form-group ">

                        <input class="tempPerm" style="" type="file" name="file" id="techInputBoxValue" />

                </fieldset>
            </form>

                <input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">

PHP
<?php include ("../db.php");?>
<?php
    $prjId = $_POST['prjId'];
    $updatedDate = $_POST['updatedDate'];
    if(isset($prjId)){
        $sql="INSERT INTO tbl_uploads(prjId, date) VALUES('$prjId','$updatedDate')";
        mysqli_query($conn, $sql);
    }
?>

A: The code below automatically includes all fields from the form without manually adding them using the append function.
Also added $(document).ready(function() for fail safe. So the javascript code only takes effect when the whole document is ready.
You can try tinker with these working template.

process.php
<?php include ("../db.php");?>
<?php
    $prjId = $_POST['prjId'];
    $updatedDate = $_POST['updatedDate'];

    if(isset($_POST['prjId'])){
        $target_dir = "uploads/";
        $target_file = $target_dir.basename($_FILES["file"]["name"]);
        $save_file = basename($target_file); // this holds the filename to save.
        $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
        $is_uploaded = move_uploaded_file($_FILES["file"]["tmp_name"], $target_file));

        // Modify this query string to add the file uploaded as well.
        // Change the query string to use prepared statements for failure safe and for security reasons.
        $sql="INSERT INTO tbl_uploads(prjId, date) VALUES('$prjId','$updatedDate')";
        mysqli_query($conn, $sql);
    }
?>

^ Added a simple file upload handler.

A: You can use formdata to send your files along with your request like this:

A: If you submit form using ajax it will not pass $_FILES
you have to create object for that using FormData
note : please add enctype="multipart/form-data in form tag
 <form id="upload" enctype="multipart/form-data">

please refer : jQuery AJAX file upload PHP
Thanks


text:
Q: Can I change the battery connector on this model aircraft safely? I am working on a project, and am required to build an autonomous glider (no propulsion).
Weight is limited to 9oz, and we are using the Pixhawk 4 mini for flight controls. The power management board (PMB) that came with the package only has XT60 plug, so it does not fit with the small batteries that I have.
Any recommendations on what I can do? I am considering de-soldering the XT60 plug on the PMB and solder a red JST plug. Is this safe to do?

A: The XT60 connector is rated for 65A continuous (per Sparkfun). JST is a manufacturer that makes lots of different connectors. In model aircraft and RC hobbies, I believe the JST SFH connector is quite common. This connector is only rated for 4A.
It sounds as though you have a small battery (assuming a single cell LiPo?) and a power management board that could potentially be used for much larger projects. In that case you should be OK replacing the XT60 with a smaller connector, as long as the project is never going to draw more than the connector's rated current.
If you later re-purpose the PMB for a different project, and it needs more current, don't use the under-rated connector!


text:
Q: Receiving notification when device registry property changes I need to receive current power state of a device. I was able to retrieve it using the code below:
ULONG ulRegDataType;
CM_POWER_DATA powerData;
ULONG ulLength;
auto ret = CM_Get_DevNode_Registry_PropertyW(devInst, CM_DRP_DEVICE_POWER_DATA, &ulRegDataType, &powerData, &ulLength, 0);

I wasn't able, however, to install notification callback with CM_Register_Notification that would notify me about the property change. I tried both CM_NOTIFY_FILTER_FLAG_ALL_INTERFACE_CLASSES and CM_NOTIFY_FILTER_FLAG_ALL_DEVICE_INSTANCES but the callback is never called when device enters D3 state.


text:
Q: Is there a way to know and reference an Identity during INSERT? Consider the following:
CREATE TABLE A
(
    Id int IDENTITY(1,1) NOT NULL,
    Id2 int NULL,
    Name varchar(50)
)

CREATE TABLE B
(
    Id int NULL,
    Name varchar(50)

)

INSERT INTO B (Id, Name)
VALUES
(100, 'val1'),
(200, 'val2'),
(NULL, 'val3'),
(NULL, 'val4')

INSERT INTO A
    (Id2, Name)
SELECT Id, Name FROM B

UPDATE A SET Id2 = Id + 100000 WHERE Id2 IS NULL

Is there a way to avoid the UPDATE after the INSERT? That is, is there a way to know what the identity value will be and reference it during the insert?

A: You can do something like this by using instead of insert trigger
create trigger trg_test on A instead of insert
as begin
  INSERT INTO A (name,id2)
  SELECT INSERTED.name,
  case when INSERTED.id2 is null then 10000 else INSERTED.id2 end
  as super_id from INSERTED;
end

You can as well use an AFTER INSERT trigger and UPDATE the record like
create trigger trg_test on A after insert
as begin
    UPDATE a
    SET id2 = i.Id + 100000
    FROM A a
    INNER JOIN INSERTED i
    ON (i.Id = a.Id)
    WHERE a.id2 is null;
end

So every record insert the trigger will fire and update the record. So after your Insert query completes the result will be as below. See more about Triggers
1   100     val1
2   200     val2
3   100003  val3
4   100004  val4

Another Approach without any trigger in place, using a temporary table as below.
CREATE TABLE #temp1
(
    Id int IDENTITY(1,1) NOT NULL,
    Id2 int NULL,
    Name varchar(50)

);

insert into #temp1(id2,name)
select id,name from B

UPDATE a
SET id2 = i.Id + 100000
FROM A a
INNER JOIN #temp1 i
ON (i.Id = a.Id)
WHERE a.id2 is null;

A: You can use the OUTPUT clause to find the identity values that have been added to the table:
DECLARE @newkeys TABLE (PrimaryKeyValue int)
INSERT INTO A
(
Name, Id2
)
OUTPUT INSERTED.IDENTITYCOL INTO @newkeys
SELECT Name, Id FROM B

But you would still need to update the table as a second step - the identity values aren't available until the INSERT batch has completed.


text:
Q: Is Weaviate compatible with fielded search? I'm working with a dataset that contains multiple fields. I need to conduct searches on several fields simultaneously. Is Weaviate compatible with fielded search? If that is the case, I'd appreciate it if you could instruct me on how to combine many search queries.
This is a scheme:
  schema = {
        "classes": [{
                "class": "Post",
                "vectorizer": "none", # explicitly tell Weaviate not to vectorize anything, we are providing the vectors ourselves through our BERT model
                "properties": [{
                    "name":"pmid",
                    "dataType": ["int"],
                },
                {
                    "name":"title",
                    "dataType": ["text"],
                },
                {
                     "name": "body",
                    "dataType": ["text"],
                },
                {
                    "name":"summary",
                    "dataType": ["text"],
                }]
        }]
    }

I'd want to do a simultaneous search on the body and summary. For instance, it identifies publications that have the term "HIV" in their body and summary.

A: This is certainly possible. Check out the where-filter in the Weaviate docs :-)
Example based on your example schema.
{
  Get {
    Post(
      nearVector: {
        vector: [0, 0, 0] # <== your custom vector
      }
      where: { # <== searching for a pmid > 12
        operator: GreaterThan
        valueInt: 12
        path: ["pmid"]
      }
    ) {
      pmid
      title
    }
  }
}


text:
Q: String to Leet (1337) Speak in PHP Does anyone know where I can find a good starting point to code a function that would take a string and convert it to leet speak?
function stringToLeetSpeak($string) {
  // Logic

  return $leetString;
}

A: You can use strtr to translate certain characters:
$output = strtr($str, 'let', '137');

Or use str_replace with arrays:
$output = str_replace(array('l','e','t'), array('1','3','7'), $str);

With this you can also replace strings and not just single characters:
$output = str_replace(array('hacker'), array('hax0r'), $str);

A: This would be my go:
class Leetify
{
    private $english = array("a", "e", "s", "S", "A", "o", "O", "t", "l", "ph", "y", "H", "W", "M", "D", "V", "x");
    private $leet = array("4", "3", "z", "Z", "4", "0", "0", "+", "1", "f", "j", "|-|", "\\/\\/", "|\\/|", "|)", "\\/", "><");
    function encode($string)
    {
        $result = '';
        for ($i = 0; $i < strlen($string); $i++)
        {
            $char = $string[$i];

            if (false !== ($pos = array_search($char, $this->english)))
            {
                $char = $this->leet[$pos]; //Change the char to l33t.
            }
            $result .= $char;
        }
        return $result;
    }

    function decode($string)
    {
        // Just reverse the above.
    }
}

Small usage example:
$Leet = new Leetify();
$new_leet_text = $Leet->encode("i want this text here to bee leetified xD");

Hope this helps.
Notes:

*

*This is for individual chars only, "Cannot convert whole words"

*This is for demonstration and code may not be perfect.

*My advice is to research string functions and arrays in PHP, also creating a range index so you can combine word + char replacing by using a 3rd array to store string values and there offsets.

A: Make a 256 string array as an latin character to L33t table. Walk over the string using the character ASCII value as an index into your array. Replace where necessary.
EDIT: Using string to capture BoltClock's insight that some translations require multiple characters.

A: I just improved Leetify (performance, etc)
https://gist.github.com/romanitalian/04541ec4b621c0b6ca76
Leetify
/**
 * Class Leetify
 * Leetify::encode('leet'); // "133+"
 * Leetify::decode('133+'); // "leet"
 */
class Leetify
{
    private $string = '';
    private $english = array("a", "e", "s", "S", "A", "o", "O", "t", "l", "ph", "y", "H", "W", "M", "D", "V", "x");
    private $leet = array("4", "3", "z", "Z", "4", "0", "0", "+", "1", "f", "j", "|-|", "\\/\\/", "|\\/|", "|)", "\\/", "><");
    private static $inst = null;
    private static function getInstance() {
        if(is_null(self::$inst)) {
            self::$inst = new self();
        }
        return self::$inst;
    }
    private function run($isEncode = false) {
        $out = '';
        if($this->string) {
            $dict = $isEncode ? $this->english : $this->leet;
            $dict_ = $isEncode ? $this->leet : $this->english;
            $flippedDict = array_flip($dict); // for good performance
            for($i = 0; $i < strlen($this->string); $i++) {
                $char = $this->string[$i];
                $out .= isset($flippedDict[$char]) ? $dict_[$flippedDict[$char]] : $char;
            }
        }
        return $out;
    }
    public function setString($string) {
        $t = self::getInstance();
        $t->string = $string;
        return $t;
    }
    public static function encode($string) {
        return self::getInstance()->setString($string)->run(true);
    }
    public static function decode($string) {
        return self::getInstance()->setString($string)->run();
    }
}


text:
Q: How do I install linux on a laptop without AHCI support? I bought a new laptop (DELL p115g) that only has RST/Raid as options for the disk controller, no AHCI, and when I attempt to install either Solus or Ubuntu the disk is not detected, presumably due to a lack of support for RST, so I am unable to progress with installation. The disk is not listed in /dev/*, gparted or anywhere else.
Is there a way to install and then boot linux on this machine, perhaps by injecting the required driver into the installation medium like we used to have to for earlier versions of Windows and the AHCI drivers, or did I buy an expensive paperweight?


text:
Q: How to merge DataTables but combine rows if ID matches? Input:
Say I have two DataTables. The first one:
ID  Date    ValueA  ValueB
1   Nov.21  72.4    23.4
1   Nov.22  71.4    24.4
2   Nov.21  74.4    21.4

The second one:
ID  Date    ValueC  ValueD
1   Nov.21  42.4    53.4
1   Nov.22  41.4    54.4
2   Nov.21  44.4    51.4

What I tried:
I tried to do DataTable1.Merge(DataTable2);, but I get this:
ID  Date    ValueA  ValueB  ValueC  ValueD
1   Nov.21  72.4    23.4
1   Nov.22  71.4    24.4
2   Nov.21  74.4    21.4
1   Nov.21                  42.4    53.4
1   Nov.22                  41.4    54.4
2   Nov.21                  44.4    51.4

Desired result:
I'd like to combine rows, if their ID and Date match.
I want this:
ID  Date    ValueA  ValueB  ValueC  ValueD
1   Nov.21  72.4    23.4    42.4    53.4
1   Nov.22  71.4    24.4    41.4    54.4
2   Nov.21  74.4    21.4    44.4    51.4

A: You can use LINQ to join the two DataTables based on ID and Date and then project/Load the results into a resultant DataTable using LoadDataRow method like:
DataTable dtResult = new DataTable();

var query = from row1 in dt1.AsEnumerable()
            join row2 in dt2.AsEnumerable() on
                new { ID = row1.Field<int>("ID"), Date = row1.Field<DateTime>("Date") }
                equals
                new { ID = row2.Field<int>("ID"), Date = row2.Field<DateTime>("Date") }
            select dtResult.LoadDataRow(new object[]
    {
        row1.Field<int>("ID"),
        row1.Field<DateTime>("Date"),
        row1.Field<double>("ValueA"),
        row1.Field<double>("ValueB"),
        row2.Field<double>("ValueC"),
        row2.Field<double>("ValueD")
    }, false);

Make sure that the types specified with Field extension method matches with that of your columns in DataTable.

A: You can use LINQ to group by, then put the values back into a DataTable if you need it that way:
var rows = dt.AsEnumerable()
                    .Select(s =>
                        new
                        {
                            ID = s.Field<int>("ID"),
                            Date = s.Field<DateTime>("Date"),
                            ValueA = s.Field<int>("ValueA")
                        })
                    .GroupBy(
                        key => new { key.ID, key.Date },
                        (key, agg) =>
                        new
                        {
                            key.ID,
                            key.Date,
                            ValueA = agg.Max(a => a.ValueA) // etc.
                        });

        var grouped = new DataTable("grouped");

        foreach (var r in rows)
        {
            var row = grouped.NewRow();

            // Put the rows that are now as you want them back into a datatable

            grouped.Rows.Add(row);
        }

A: The above solution is missing a method to fill the datatable. it should be
DataTable dtResult = new DataTable();

var query = (from row1 in dt1.AsEnumerable()
            join row2 in dt2.AsEnumerable() on
                new { ID = row1.Field<int>("ID"), Date = row1.Field<DateTime>("Date") }
                equals
                new { ID = row2.Field<int>("ID"), Date = row2.Field<DateTime>("Date") }
            select dtResult.LoadDataRow(new object[]
    {
        row1.Field<int>("ID"),
        row1.Field<DateTime>("Date"),
        row1.Field<double>("ValueA"),
        row1.Field<double>("ValueB"),
        row2.Field<double>("ValueC"),
        row2.Field<double>("ValueD")
    }, false))
.CopyToDataTable();

the .CopyToDataTable(); is the magic keyword


text:
Q: mysqli Google Store Locator error on echoing $dom ->saveXML I am following a tutorial on how to make use of the Google Maps as a store locator here, however, my webpage is outputting an XML error:

What does the error mean? how will I resolve it?
I declared GLOBALS in a .php file which has the following information. This file is automatically called in my require()
$GLOBALS['SRVR'] ='myServer';
$GLOBALS['USER'] ='myUID';
$GLOBALS['PASS'] ='myPASSWORD';

and then I placed the code as demonstrated in the tutorial in a function, and I call the function. I also converted mysql into mysqli.
I also created the table named markers just like in the tutorial.
require("indexhead.php");

function MaptheStore() //I plan to add an argument later to populate stores
{
    // Get parameters from URL
    $center_lat = $_GET["lat"];
    $center_lng = $_GET["lng"];
    $radius = $_GET["radius"];

    // Start XML file, create parent node
    $dom = new DOMDocument("1.0");
    $node = $dom->createElement("markers");
    $parnode = $dom->appendChild($node);

        // Set the active mySQL database

        $db_selected = mysqli_select_db($GLOBALS['con'], 'myDB');
        if (!$db_selected) {
          die (mysqli_error($db_selected));
        }

    // Search the rows in the markers table
    $query = sprintf("SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') )
    * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') )
    * sin( radians( lat ) ) ) ) AS distance
    FROM myDB.markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
      mysqli_real_escape_string($GLOBALS['con'],$center_lat),
      mysqli_real_escape_string($GLOBALS['con'],$center_lng),
      mysqli_real_escape_string($GLOBALS['con'],$center_lat),
      mysqli_real_escape_string($GLOBALS['con'],$radius));

    $result = mysqli_query($GLOBALS['con'],$query);
    if (!$result) {
      die("Invalid query: " . mysqli_error($result));
    }

    header("Content-type: text/xml");

    // Iterate through the rows, adding XML nodes for each
    while ($row = @mysqli_fetch_assoc($result)){
      $node = $dom->createElement("marker");
      $newnode = $parnode->appendChild($node);
      $newnode->setAttribute("name", $row['name']);
      $newnode->setAttribute("address", $row['address']);
      $newnode->setAttribute("lat", $row['lat']);
      $newnode->setAttribute("lng", $row['lng']);
      $newnode->setAttribute("distance", $row['distance']);
    }

return $dom->saveXML();
}

echo MapTheStore();

Finally, I pasted this to simulate the $_GET[] (?lat=37&lng=-122&radius=25), to test the page like in the tutorial.
Is the error caused by me converting the code to mysqli? how will I resolve it? what exactly causes the error?
EDIT: here is my table structure for markers

and here are it's contents...

EDIT: the pagesource of the webpage has this output, basically only my headers:

A: It must be something you have done in the database.
http://viper-7.com/Nv5tDB
That link above is the rest of the XML created, and it seems all fine, so the database is the likely cause.


text:
Q: Приподнять блок слова на 10px Необходимо приподнять слово на 10px как на фото:

Сам блок out-6

Граф Дра́кула (англ. Count Dracula) — вампир, заглавный персонаж и главный
антагонист
романа Брэма Стокера «Дракула» (1897). В качестве архетипического вампира
Дракула появлялся во множестве произведений массовой культуры, даже не имеющих
непосредственного отношения к роману Брэма Стокера.

A: Элементы с position: relative остаются там где были, но теперь к ним можно применять абсолютное позиционирование, в нашем случае top.

span {
  top: -10px;
  position: relative;
}

Граф Дра́кула (англ. Count Dracula) — вампир, заглавный персонаж и главный антагонист романа Брэма Стокера «Дракула» (1897). В качестве архетипического вампира Дракула появлялся во множестве произведений массовой культуры, даже не имеющих непосредственного отношения к роману Брэма Стокера.

A: Можно использовать transform: translateY(-10px), но перед этим нужно, чтобы к блоку можно было применять блочные свойства. Для этого можно ему задать display: inline-block

.sup {
  display: inline-block;
  transform: translateY(-10px);
}

Граф Дра́кула (англ. Count Dracula) — вампир, заглавный персонаж и главный антагонист романа Брэма Стокера «Дракула» (1897). В качестве архетипического вампира Дракула появлялся во множестве произведений массовой культуры, даже не имеющих непосредственного отношения к роману Брэма Стокера.

A: Почему бы вам не использовать для этого vertical-align?

.s-6 {
  vertical-align: super;
}

Граф Дра́кула (англ. Count Dracula) — вампир, заглавный персонаж и главный
антагонист
романа Брэма Стокера «Дракула» (1897). В качестве архетипического вампира
Дракула появлялся во множестве произведений массовой культуры, даже не имеющих
непосредственного отношения к роману Брэма Стокера.


text:
Q: Create column based on distinctive sets of multiple row values I want to identify unique sets of row values in a column based on row values in another column to ultimately create a new column in the dataframe. The following picture illustrates my problem and the expected result (i.e., the expected_outcome column).
For example:

*

*The first 3 rows have values T1 in the column trial, and values D1, D2, D3 in the column group.

*The next 3  rows have values T3 in the column trial, and values D3, D2, D1 in the column group.
Because the set D1, D2, D3 has the same contain as D3, D2, D1, I want all the 6 rows to have the same value in column expected_outcome.
My data is way more complex than that. I may have to make this grouping over more than 2 columns. So, I prefer a generic solution to this problem. Below is the data in the picture.
test_data <- data.frame(
  trial            = c("T1", "T1", "T1", "T3", "T3", "T3", "T5", "T5", "T6", "T6", "T6"),
  group            = c("D1", "D2", "D3", "D3", "D2", "D1", "D1", "D3", "D1", "D3", "D2")
)

A: I think the last trial in your column should be T7?
library(dplyr)

test_data %>%
  arrange(across(everything())) %>%
  group_by(trial) %>%
  mutate(expected_outcome = toString(group)) %>%
  group_by(expected_outcome) %>%
  mutate(expected_outcome = cur_group_id())

    trial group expected_outcome
   <chr> <chr>            <int>
 1 T1    D1                   1
 2 T1    D2                   1
 3 T1    D3                   1
 4 T3    D1                   1
 5 T3    D2                   1
 6 T3    D3                   1
 7 T5    D1                   2
 8 T5    D3                   2
 9 T6    D1                   2
10 T6    D3                   2
11 T7    D2                   3

data:
test_data <- structure(list(trial = c("T1", "T1", "T1", "T3", "T3", "T3",
"T5", "T5", "T6", "T6", "T7"), group = c("D1", "D2", "D3", "D3",
"D2", "D1", "D1", "D3", "D1", "D3", "D2")), class = "data.frame", row.names = c(NA,
-11L))

A: You could do something like this via tidyverse.
library(tidyverse)

test_data %>%
  group_by(trial) %>%
  summarize(type = paste(sort(unique(group)), collapse = ", "), group) %>%
  group_by(type) %>%
  mutate(expected_outcome = cur_group_id()) %>%
  ungroup() %>%
  dplyr::select(-"type")

Output
# A tibble: 11 × 3
   trial group expected_outcome
   <chr> <chr>            <int>
 1 T1    D1                   1
 2 T1    D2                   1
 3 T1    D3                   1
 4 T3    D3                   1
 5 T3    D2                   1
 6 T3    D1                   1
 7 T5    D1                   2
 8 T5    D3                   2
 9 T6    D1                   1
10 T6    D3                   1
11 T6    D2                   1

Data
test_data <-
  structure(list(
    trial = c("T1", "T1", "T1", "T3", "T3", "T3",
              "T5", "T5", "T6", "T6", "T6"),
    group = c("D1", "D2", "D3", "D3",
              "D2", "D1", "D1", "D3", "D1", "D3", "D2")
  ),
  class = "data.frame",
  row.names = c(NA,-11L))

A: Note: This answer is based on the original problem before OP was edited, where groups had to be identified by themselves without an erroneous 'trial' column.
factorize group column and, using ave calculate cumsum of duplicateds in each group. Then, where even numbers appear, cumsum the differences that equal 1.
(test_data <- within(test_data, {
                    group_int <- as.integer(as.factor(group))
                    group_2 <- ave(group_int, group_int, FUN=\(x)
                                   cumsum(duplicated(x)))
                    expected_outcome <- cumsum(c(1, diff(group_2 %% 2 == 0)) == 1)
                    rm(group_int, group_2)
}))
#    trial group expected_outcome
# 1     T1    D1                1
# 2     T1    D2                1
# 3     T1    D3                1
# 4     T3    D3                1
# 5     T3    D2                1
# 6     T3    D1                1
# 7     T5    D1                2
# 8     T5    D3                2
# 9     T6    D1                2
# 10    T6    D3                2
# 11    T6    D2                3

Note: R >= 4.1

Data:
test_data <- structure(list(trial = c("T1", "T1", "T1", "T3", "T3", "T3",
"T5", "T5", "T6", "T6", "T6"), group = c("D1", "D2", "D3", "D3",
"D2", "D1", "D1", "D3", "D1", "D3", "D2"), expected_outcome = c(1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L)), row.names = c(NA, -11L
), class = "data.frame")


text:
Q: Advice on webserver / database server setup I have a home server (HP ProLiant N36L link with 8Gb of RAM), running Windows Server 2012 that I want to use as a home web server.
Is it worth settings up VM's in Hyper-V for virtual DB servers and web servers? The server will likely never see much traffic, just a couple of hobby sites and a few basic web services.
The setup I had in mind was:

*

*(Physical) Main_Computer_Name (8Gb RAM)

*(Virtual)  Web_Server (2Gb RAM)

*(Virtual)  DB_Server (2Gb RAM)

A: Having separate web & database servers will be helpful in keeping your data secure and isolating any bottlenecks.
With 2GB of RAM, your database server will be starved. If the host has 8GB and you're allocating 2GB to each VM, what are you using the remaining 4GB for? If you're using Hyper-V Server, the following formula may help you back into the amount of RAM you can allocate to each VM:
host RAM (your physical 8GB)  = (VMRamRequirementMB x #ofVMs) + (#ofVMs x 32MBVMOverhead ) + (512MBHost)

So you'd be looking at
8GB = (X*2) + (X*.032) + 0.512 = 2.544X
X = ~3.14GB RAM per VM

Of course, if IIS only needs 2GB RAM, you could bump the database up to a more comfortable 4GB.


text:
Q: How to plot monthly sales data correctly? I'm trying to plot the monthly sales data with RStudio, but the dates on the x-axis are not showing correctly.
My code :-
uc_ts_plot <- ggplot(monthly_sales, aes(DATE,DAUTONSA)) + geom_line(na.rm=TRUE) +
  xlab("Month") + ylab("Auto Sales in Thousands") +
  scale_x_date(labels = date_format(format= "%b-%Y"),
               breaks = date_breaks("1 year")) +
  stat_smooth(colour = "green")

uc_ts_plot

I expect the dates on the x-axis to be displayed as Jan-2011, Jan-2012, as shown here.
All I'm getting is a 0001-01 at the left end and a 0002-01 at the right end of the x-axis.

A: The plot which is shown is filtered between year 2011 and 2018 whereas the data you have is from 1967.
The below code produces the exact plot
library(tidyverse)
library(scales)
library(lubridate)

monthly_sales %>%
  mutate(DATE = as.Date(DATE)) %>%
  filter(year(DATE) >= 2011 & year(DATE) < 2018) %>%
  ggplot() + aes(DATE,DAUTONSA) +
  geom_line(na.rm=TRUE) +
  xlab("Month") + ylab("Auto Sales in Thousands") +
  scale_x_date(labels = date_format(format= "%b-%Y"),
               breaks = date_breaks("1 year")) +
  stat_smooth(colour = "green")

You can remove the filter step to plot data for all the years but then it clutters the x-axis with lot of labels.


text:
Q: Migrate EF6 database-first from SQL Server to PostgreSQL I am looking for easy way to reuse edmx file created with EF6 over SQL Server to PostgreSQL
I have used database-first with EF6 on SQL Server and everything worked fine.
We are going to use PostgreSQL.
I have already migrated the database to PostgreSQL, and installed EntityFramework6.Npgsql, and I wanted use database-first approach again.
I tried to update from database but it looks that I have to fix all the edmx file. The original entity model is quite complex, with abstract class, complex types and enum types.
The new edmx file lost inheritance and complex types.
Do you know an easy way to do it?

A: I don't know if you can get the EDMX file to work with PostgreSQL, but you might be able to use scaffolding and get a db first approach. Something like:
dotnet ef dbcontext scaffold
This would allow you to make changes in the database and have them reflected in code. I'm no PostgreSql expert but this article sure makes it look like it's possible.
If you want a more graphical approach then you may want to consider switching to code first and using the class designer in visual studio.


text:
Q: WordPress Help? If I add wordpress to my site do I have to use there templates for my site because I really don't want to I would like to keep my layout that I hand coded myself. And is it possible to just install a plugin from wordpress to my site without installing wordpress?
One last question is there a PHP and MySQL plugin that will create a database and index all my web pages from my site in order to create an RSS feed.

A: You don't have to use wordpress templates!  You can use the design you created, with a few modifications with wordpress.
It is not possible to install a plugin from wordpress w/o wordpress...that's why they're called wordpress plugins...
I think wordpress sets up RSS automatically, you just have to fish around in the preferences...
Try this and this for theme development reference.
See this site for RSS plugin info.
For more information, try using google to find out how to convert your design to a wordpress theme.

A: I suspect there's two separate questions being asked in this thread which may not be related to each other.
Anyway, for the first question: You could reuse your existing template for your old website and adapt it into your custom Wordpress theme. Though I would say that theme development from scratch could be quite involved. If you don't like the learning curve of doing a Wordpress theme, you could opt to use an existing Wordpress theme and create a custom CSS to make it look like your existing webpage. I personally recommend that you could get a plain vanilla Wordpress theme like Sandbox and work the CSS from there.
As for the second question, if you are asking in the context of migrating your existing site to Wordpress: Wordpress automatically will generate the RSS feeds so long you port your pages into their "Posts" and "Pages" mechanism.
Do let us know and provide more information on what you want to achieve if you are asking the last question on a different context as in you have a set of webpages which you are not migrating to Wordpress but needing a means of needing an automatic means to translate those existing pages into a dynamic RSS feed.


text:
Q: How to pass global variables to JSON object for validation in Javascript Hello I am now to javascript and writing script for API testing in Postman to automate my usecases.
Need help for below query.
Lets say i have my API request as below.
API request: https://reqres.in/api/users/2

Response:
{
   "data":{
      "id":2,
      "email":"janet.weaver@reqres.in",
      "first_name":"Janet",
      "last_name":"Weaver",
      "avatar":"https://reqres.in/img/faces/2-image.jpg"
   },
   "support":{
      "url":"https://reqres.in/#support-heading",
      "text":"To keep ReqRes free, contributions towards server costs are appreciated!"
   }
}

Query is from the response if the data.id == 2 then i have to read the 'email' & 'avatar' keys from global variables of postman and start the validation.
Code:
const response = JSON.parse(responseBody);
if (response.data.id === 2) {
//Here i have to read the 'email' & 'avatar' keys from global variables of postman.
tried response.data.pm.globals.get('email') & response.data.pm.globals.get('avatar') but its failing as the calling itself is not proper i belive.
}

Please help and thanks in advance.

A: Use this code in Tests section
const response = JSON.parse(responseBody);

if (response.data.id === 2) {
    pm.globals.set("email", response.data.email);
    pm.globals.set("avatar", response.data.avatar);
    console.log(pm.globals.get("email"))
    console.log(pm.globals.get("avatar"))
}

You can see it's result at console.


text:
Q: C++: Error C2064 with STL I'm trying to use STL, but the following doesn't compile. main.cpp:
#include <set>
#include <algorithm>

using namespace std;

class Odp
{
public:

    set<int> nums;

    bool IsOdd(int i)
    {
        return i % 2 != 0;
    }

    bool fAnyOddNums()
    {
        set<int>::iterator iter = find_if(nums.begin(), nums.end(), &Odp::IsOdd);
        return iter != nums.end();
    }
};

int main()
{
    Odp o;
    o.nums.insert(0);
    o.nums.insert(1);
    o.nums.insert(2);
}

The error is:
error C2064: term does not evaluate to a function taking 1 arguments
1>          c:\program files\microsoft visual studio 10.0\vc\include\algorithm(95) : see reference to function template instantiation '_InIt std::_Find_if<std::_Tree_unchecked_const_iterator<_Mytree>,_Pr>(_InIt,_InIt,_Pr)' being compiled
1>          with
1>          [
1>              _InIt=std::_Tree_unchecked_const_iterator<std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>>,
1>              _Mytree=std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>,
1>              _Pr=bool (__thiscall Odp::* )(int)
1>          ]
1>          main.cpp(20) : see reference to function template instantiation '_InIt std::find_if<std::_Tree_const_iterator<_Mytree>,bool(__thiscall Odp::* )(int)>(_InIt,_InIt,_Pr)' being compiled
1>          with
1>          [
1>              _InIt=std::_Tree_const_iterator<std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>>,
1>              _Mytree=std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>,
1>              _Pr=bool (__thiscall Odp::* )(int)
1>          ]

What am I doing wrong?

A: It needs to be declared static:
static bool IsOdd(int i)

Otherwise, you'd be asking find_if to call an instance method without an instance.

A: The problem is you are passing a pointer to member function. To call that function you would also need a pointer to this but the find_if doesn't let you to pass it. A solution is to wrap it using a function object, see Boost Bind (http://www.boost.org/doc/libs/1_43_0/libs/bind/bind.html) and Boost Function (http://www.boost.org/doc/libs/1_37_0/doc/html/function.html).

A: IsOdd does not use the class's internals in any way, so don't make it a member function. Instead, pull it out as a standalone function. Then you can call find_if with &IsOdd.
However, there is a benefit to taking things a step further and defining it as a function object:
#include <functional>

struct IsOdd : public unary_function<int, bool>
{
    bool operator()(int i) const { return i % 2 != 0; }
};

Then calling find_if with IsOdd() will inline the code within the find_if loop instead of dereferencing a function pointer and making a function call.


text:
Q: How do I construct a Python time struct from the day of year? I have the day of the year, or as its called in Python, the tm_yday.
I want to get out the month and day of month.
How can I create a Python time struct from just the day of year?

A: You can use datetime.strptime to parse the day of the year:
>>> from datetime import datetime
>>> tm_yday = 59
>>> tm_year = datetime.now().year # current year
>>> datetime.strptime('{} {}'.format(tm_year, tm_yday), '%Y %j')
datetime.datetime(2014, 2, 28, 0, 0)

A: import datetime
>>> datetime.datetime.strptime('10', '%j')
datetime.datetime(1900, 1, 10, 0, 0)
>>> datetime.datetime.strptime('359', '%j')
datetime.datetime(1900, 12, 25, 0, 0)
>>> datetime.datetime.strptime('359', '%j').month
12
>>> datetime.datetime.strptime('359', '%j').day
25

A: import datetime
foo=datetime.datetime(1990, 1, 1) + datetime.timedelta(tm_yday - 1)
month = foo.month
dayOfMonth = foo.day

Year 1990 is an example, try other in the case of leap year.

A: Datetime date types are the way to go here:
import datetime

Here's today:
>>> datetime.date.today()
datetime.date(2014, 2, 27)

And here's Jan 1st of 2014:
>>> datetime.date(2014, 1, 1)
datetime.date(2014, 1, 1)

To combine into a datetime object:
datetime.datetime.combine(datetime.date(2014, 1, 1),
                          datetime.datetime.min.time())


text:
Q: Problem with classification machine learning: prediction is always wrong I am working on a current project where I need to classify and detect data that doesn't follow the standards and parameters required. I have past data which is the data that I will train my model with. I know what data is wrong and why, so I have labeled is as isWrong and assigned it an either 0 or 1.
I know this is a supervised machine learning project, more specifically, a binary classification problem.
I decided to first work with dummy data before going into the real data to correctly understand the functionality of these algorithms.
I have the following data set:
Name    Age    Office#   SSN   isWrong

Name: String
Age: int
Office: int
SSN: int
isWrong: int
A record is wrong if the person has an Age over 60 years old or under 18 years old. A record is also wrong if the Office# is negative or greater than 2.
Either one of those condition makes the record to be labeled as wrong.
I've tried both Logistic Regression and Naïve Bayes. I trained my model with this data set and then decided to test it with another data set that follows the same schema (without the isWrong column) and same pattern. However, when I print the prediction column, I only get at most three out of ten bad data. In other words, I don't get the prediction I wanted because it failed to classify some wrong data as wrong, meaning that my model gave a label of 0 to an obviously wrong data.
Why is this? Is there something I need to specify before going into my training and testing part?
For training I've done something as simple as this:
LogisticRegression lr = new LogisticRegression().setLabelCol("isWrong");
lr.fit(dataset);

EDIT: Here is a sample of the dummy, example data (top 25)
Name    Office  Age    SSN     isAnomaly
  F1        1   32  42376794    0
  F2        2   61  72353599    1
  F3        1   35  49001025    0
  F4        0   25  25613860    0
  F5        1   36  85720367    0
  F6        2   52  85725161    0
  F7        2   48  78016430    0
  F8        2   53  89762357    0
  F9        2   51  84866475    0
 F10        0   24  24062706    0
 F11        4   34  46233821    1
 F12        0   21  17686431    0
 F13        2   51  85547952    0
 F14        0   27  32159403    0
 F15        1   37  52685792    0
 F16        1   35  47836229    0
 F17        1   67  52770341    1
 F18        0   21  17104127    0
 F19        1   41  63042591    0
 F20        1   36  50374422    0
 F21        0   25  26303816    0
 F22        0   22  19645563    0
 F23        2   16  69963996    1
 F24        0   62  19884506    1
 F25        0   26  28498270    0

A: For (standard) logistic regression, there is an assumption being made that the true decision boundary is linear. This isn't the case with your data, because the chance of being "wrong" does not strictly increase with Age or with Office# since you have upper and lower limits.
Using logistic regression after adding squared terms should improve your classifier (approximate a square decision boundary with an ellipse), though a better model would be something like nearest neighbors or decision trees/random forest; the latter would also quickly rule out the other predictors making a difference. (Incidentally, the predictors are not independent for naive Bayes, since SSN should be highly correlated with Age).


text:
Q: Binning categorial variables in SPSS I have two different variables which are both categorical. One of them is the seriousness of the sickness in terms of degrees. The other one is the type of surgery.And my dependent variable is  their recovery day after the surgery. Because the days of surgery is not normally distributed I have to use a non-parametric method.
So I need to combine the independent variables into a new variable: 1:sickness1Surgery1 2:sickness1Surgery2, 3:sickness2Surgery1, sickness2Surgery1. By this way I will be able to test it.
I have checked the Youtube but, they are all about how to bin scales into categories.

A: If you provide more details about the structure of your data (preferably with some sample data) we could provide better suited code. Still, the basic idea should be the same:
if sickness=1 and surgery=1 combinedVar=1.
if sickness=2 and surgery=1 combinedVar=2.
if sickness=1 and surgery=2 combinedVar=3.
if sickness=2 and surgery=2 combinedVar=4.

value labels combinedVar
  1  "sickness=1, surgery=1"
  2  "sickness=2, surgery=1"
  3  "sickness=1, surgery=2"
  4  "sickness=2, surgery=2".