Q: Vb.net 2 decimals double I want to place all my doubles to 2 decimals after the comma.
At this moment when the value is 0.30, my Datagridview shows 0.3..any idea?
This is my code:
    eenheidsprijs = Math.Round(eenheidsprijs, 2)
    basisbedrag = Math.Round(basisbedrag, 2)
    kortingbedrag = Math.Round(kortingbedrag, 2)
    netto = Math.Round(netto, 2)
    btwbedrag = Math.Round(btwbedrag, 2)
    totaal = Math.Round(totaal, 2)

    Dim streenheidsprijs, strbasisbedrag, strkortingbedrag, strnetto, strbtwbedrag, strtotaal As String

    streenheidsprijs = Format(eenheidsprijs, "0.00")
    strbasisbedrag = Format(basisbedrag, "0.00")
    strkortingbedrag = Format(kortingbedrag, "0.00")
    strnetto = Format(netto, "0.00")
    strbtwbedrag = btwbedrag.ToString("N", CultureInfo.InvariantCulture)
    strtotaal = Format(totaal, "0.00")

    eenheidsprijs = Double.Parse(streenheidsprijs)
    basisbedrag = Double.Parse(strbasisbedrag)
    kortingbedrag = Double.Parse(strkortingbedrag)
    netto = Double.Parse(strnetto)
    btwbedrag = Double.Parse(strbtwbedrag)
    totaal = Double.Parse(strtotaal)

A: Which value is bound to your datagrid? streenheidsprijs or eenheidsprijs? The string value is formatted to 2 decimal places, but the double variable doesn't inherit the number of decimal places to show. In actual fact, there is no value in the lines to re-parse the string values that have been formatted:
eenheidsprijs = Double.Parse(streenheidsprijs)

The data grid columns should either be bound to the string values that have been formatted to 2 dp, or you should configure the display properties of the columns in the data grid so that they only show two decimal places.

A: You can provide a format string to the default cell style of the column. In your case, the format F2 would be preferable.
At run-time:
myDataGridView.Columns("myColumnName").DefaultCellStyle.Format = "F2"

At design-time:

Sample form
Public Class Form1

    Public Sub New()
        Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US")
        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US")
        Me.InitializeComponent()
        Me.ClientSize = New Size(350, 400)
        Me.column1 = New DataGridViewTextBoxColumn With {.Name = "Column1", .HeaderText = "Double (F2)", .ValueType = GetType(Double), .Width = 100}
        Me.column1.DefaultCellStyle.Format = "F2"
        Me.column2 = New DataGridViewTextBoxColumn With {.Name = "Column2", .HeaderText = "Double (F8)", .ValueType = GetType(Double), .AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill, .MinimumWidth = 100}
        Me.column2.DefaultCellStyle.Format = "F8"
        Me.grid = New DataGridView With {.Dock = DockStyle.Fill}
        Me.grid.Columns.AddRange(Me.column1, Me.column2)
        For i As Double = 0.0R To 9.0R : Me.grid.Rows.Add(i, i) : Next
        Me.Controls.Add(Me.grid)
    End Sub

    Private WithEvents grid As DataGridView
    Private WithEvents column1 As DataGridViewTextBoxColumn
    Private WithEvents column2 As DataGridViewTextBoxColumn

End Class


Q: Unity Google Play Services: Authentication Failed always: I have a problem with authenticate. The authenticate always fail and I can't understand the cause (not only fail in the editor, in my device too). Here is the code:
 using UnityEngine;
 using UnityEngine.SceneManagement;
 using UnityEngine.UI;
 using UnityEngine.Advertisements;
 using System.Collections;
 using System.Collections.Generic;
 using GooglePlayGames;
 using UnityEngine.SocialPlatforms;
 using GooglePlayGames.BasicApi;
 using UnityEngine.Analytics;

 public class Menu : MonoBehaviour {

 public Text record;

 /**
     Menu when the player isn´t authenticate
  */
 public GameObject signIn;

 public GameObject test;

 void Awake()
 {
     PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder ().Build ();
     PlayGamesPlatform.InitializeInstance(config);
     GooglePlayGames.PlayGamesPlatform.DebugLogEnabled = false;
     GooglePlayGames.PlayGamesPlatform.Activate ();
 }

 void Start()
 {
     Advertisement.Initialize ("CORRECT_NUMBER", true);

     if (PlayerPrefs.HasKey("record"))
     {
         record.text = "Record actual: " + PlayerPrefs.GetInt("record");
         Analytics.CustomEvent ("Start Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} });
         if (Social.localUser.authenticated)
         {
             Social.ReportScore (PlayerPrefs.GetInt ("record"), "CORRECT_CODE", (bool success) => { });
         }
     } else {
             record.text = "Consigue un record!!";
     }

     if (Social.localUser.authenticated)
     {
         signIn.SetActive (false);
     }
     test.SetActive (false);
 }

 public void OnPlay()
 {
     ShowAd ();
     SceneManager.LoadScene("Play");
     Time.timeScale = 0;
 }

 public void OnArchievements()
 {
     if (Social.localUser.authenticated) {
         Social.ShowAchievementsUI ();
     } else {
         Social.localUser.Authenticate ((bool success) => {
             if (success) {
                 Social.ShowAchievementsUI ();
             }
         });
     }

 }

 public void OnMatching()
 {
     if (Social.localUser.authenticated) {
         Social.ShowLeaderboardUI ();
     } else {
         Social.localUser.Authenticate ((bool success) => {
             if (success) {
                 Social.ShowLeaderboardUI ();
             }
         });
     }
 }

 public void OnExit()
 {
     Analytics.CustomEvent ("Stop Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} });
     Application.Quit();
 }

 public void SignIn()
 {
     Social.localUser.Authenticate((bool success) => {
         if (success)
         {
             Debug.Log ("Sign in");
             signIn.SetActive (false);
         }
         else
         {
             Debug.Log ("Fail for some reason...");
             test.SetActive (true);
         }

     });

 }

 public void Later()
 {
     signIn.SetActive (false);
 }

 public void ShowAd()
 {
     if (Advertisement.IsReady())
     {
         Advertisement.Show();
     }
 }
 }

The object "test" is only a white box that appears to know the authentication fail. The console don't show me any type of error, so I don't know where find the problem... Any idea what's the problem? PD: I use version 0.9.34 and Unity 5.3.5f1
Thanks in advance!

A: Not a problem.
I am going to write the response here because it may be quite long.
Unity has the default ISocialPlatform set to Apple. Doing the "PlayGamesClientConfiguration" you change the default ISocialPlatform to Google+.
My comment was talking about your Awake() function. I recommended you to put it in Start() as follows:
    void Start()
         {
    //added code
     PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder ().Build ();
         PlayGamesPlatform.InitializeInstance(config);
         GooglePlayGames.PlayGamesPlatform.DebugLogEnabled = false;

         //GooglePlayGames.PlayGamesPlatform.Activate (); //this is wrong

      //WHAT YOU ARE MISSING
      PlayGamesPlatform.Activate();
      //END OF WHAT YOU ARE MISSING

             Advertisement.Initialize ("CORRECT_NUMBER", true);

             if (PlayerPrefs.HasKey("record"))
             {
                 record.text = "Record actual: " + PlayerPrefs.GetInt("record");
                 Analytics.CustomEvent ("Start Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} });

      //you should do this once the user is authenticated and logged in
                 if (Social.localUser.authenticated)
                 {
                     Social.ReportScore (PlayerPrefs.GetInt ("record"), "CORRECT_CODE", (bool success) => { });
                 }
             } else {
                     record.text = "Consigue un record!!";
             }

             if (Social.localUser.authenticated)
             {
                 signIn.SetActive (false);
             }
             test.SetActive (false);
         }

Then, you can create a button in the inspector inside your scene and call this:
 public void SignIn()
 {
     Social.localUser.Authenticate( ProcessAuthentication)
 }

The CallBackFunction is a void function that takes in a bool. (You were doing this correctly) I like making my code readable and easy to understand.
    void ProcessAuthentication (bool success)
        {
            if (true == success)
            {
                Debug.Log ("AUTHENTICATED!");
                if (Social.localUser.authenticated)
                 {
                     Social.ReportScore (PlayerPrefs.GetInt ("record"), "CORRECT_CODE", (bool success) => { });
                 }
             } else {
                     record.text = "Consigue un record!!";
             }

             if (Social.localUser.authenticated)
             {
                 signIn.SetActive (false);

                 //EDIT: you need to load the achievements to use them
                 Social.LoadAchievements (ProcessLoadedAchievements);

                Social.LoadScores(leaderboardID, CALLBACK) // Callback has to be a Action<IScore[]> callback
            }
             test.SetActive (false);
            }
            else
            {
                Debug.Log("Failed to authenticate");
                signIn.SetActive (true);
            }
        }

void ProcessLoadedAchievements (IAchievement[] achievements) {
        if (achievements.Length == 0)
        {
            Debug.Log ("Error: no achievements found");
        }
        else
        {
            Debug.Log ("Got " + achievements.Length + " achievements");
        }
    }

Let me know.
(I can explain it to you in Spanish too if you want)
Saludos!

A: I follow this tutorial: google tutorial in GitHub (README) and the tutorial don't say I must implement that method, in fact, when I read it, I understand these method are part of the engine.
Here is my new code:
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Advertisements;
using System.Collections;
using System.Collections.Generic;
using GooglePlayGames;
using UnityEngine.SocialPlatforms;
using GooglePlayGames.BasicApi;
using UnityEngine.Analytics;

public class Menu : MonoBehaviour {

public Text record;

public GameObject test;

/**
    Indicador del jugador de que no ha iniciado sesión, y no podrá acceder al  ranking ni a los logros.
 */
public GameObject signIn;

void Start()
{
    PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder ().Build ();
    PlayGamesPlatform.InitializeInstance(config);
    GooglePlayGames.PlayGamesPlatform.DebugLogEnabled = true;
    PlayGamesPlatform.Activate();

    Advertisement.Initialize ("NUMBER", true);
    test.SetActive (false);

    //EDIT:
    SignIn ();

    if (PlayerPrefs.HasKey("record"))
    {
        record.text = "Record actual: " + PlayerPrefs.GetInt("record");
        Analytics.CustomEvent ("Start Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} });

    } else {
            record.text = "Consigue un record!!";
    }

}

public void OnPlay()
{
    ShowAd ();
    SceneManager.LoadScene("Jugar");
    Time.timeScale = 0;
}

public void OnArchievements()
{
    if (Social.Active.localUser.authenticated) {
        Social.Active.ShowAchievementsUI ();
    } else {
        Social.Active.localUser.Authenticate ((bool success) => {
            if (success) {
                Social.Active.ShowAchievementsUI ();
            }
        });
    }

}

public void OnMatching()
{
    if (Social.Active.localUser.authenticated) {
        Social.Active.ShowLeaderboardUI ();
    } else {
        Social.Active.localUser.Authenticate ((bool success) => {
            if (success) {
                Social.Active.ShowLeaderboardUI ();
            }
        });
    }
}

public void OnExit()
{
    Analytics.CustomEvent ("Stop Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} });
    Application.Quit();
}

public void SignIn()
{
    Social.Active.localUser.Authenticate (ProcessAuthentication);
}

public void Later()
{
    signIn.SetActive (false);
}

public void ShowAd()
{
    if (Advertisement.IsReady())
    {
        Advertisement.Show();
    }
}
//EDIT:
void ProcessAuthentication (bool success)
{
    if (true == success)
    {
        Debug.Log ("AUTHENTICATED!");
        if (Social.Active.localUser.authenticated)
        {
            Social.Active.LoadAchievements (ProcessLoadedAchievements);
            Social.Active.LoadScores (Fireball.GPGSIds.leaderboard_ranking, ProcessLoadedScores );
            if (PlayerPrefs.HasKey ("record"))
            {
                Social.Active.ReportScore (PlayerPrefs.GetInt ("record"),Fireball.GPGSIds.leaderboard_ranking, (bool report) => { });
            }
            signIn.SetActive (false);
            test.SetActive (true);
        }
    } else {
        Debug.Log("Failed to authenticate");
        signIn.SetActive (true);
    }
 }

  void ProcessLoadedAchievements (IAchievement[] achievements)
{
    if (achievements.Length == 0)
    {
        Debug.Log ("Error: no achievements found");
    }
    else
    {
        Debug.Log ("Got " + achievements.Length + " achievements");
    }
}

void ProcessLoadedScores (IScore[] scores)
{
    if (scores.Length == 0)
    {
        Debug.Log ("Error: no scores found");
    }
    else
    {
        Debug.Log ("Got " + scores.Length + " scores");
    }
}
}

EDIT:
Again in the editor I can't authenticate (in my device it fail too), I really don't understand the cause... Here the debug log (I active it, may can help):
DEBUG: Activating PlayGamesPlatform.
DEBUG: PlayGamesPlatform activated: GooglePlayGames.PlayGamesPlatform.
DEBUG: Creating platform-specific Play Games client.
DEBUG: Creating IPlayGamesClient in editor, using DummyClient.
DEBUG: Received method call on DummyClient - using stub implementation.
The last message, is when I try to authenticate, maybe you know the problem with the debug log.
PD: I read de documentation you send me, but is oriented to GameCenter (iOS), but I understand now more thing about that, really thanks.
Again thanks a lot for your time.


Q: Import Excel sheet into database using MVC .net Web Application Im new to programming and i am trying to import excel sheet into my database using mvc. I am able to import into my database but i need to find out how do i add validation for example email and duplicates. It seems like if i upload the same excel sheet twice, the data will be imported twice into my database. Also i would like to display the number of rows on the web page updated after importing . How do i do it ? This is my controller code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.OleDb;
using System.IO;

namespace excelimport.Controllers
{
    public class HomeController : Controller
    {
    // GET: /Home/
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
    OleDbConnection Econ;

    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        string filename = Guid.NewGuid() + Path.GetExtension(file.FileName);
        string filepath = "/excelfolder/" + filename;
        file.SaveAs(Path.Combine(Server.MapPath("/excelfolder"), filename));
        InsertExceldata(filepath, filename);
        return View();
    }

    private void ExcelConn(string filepath)
    {
        string constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", filepath);
        Econ = new OleDbConnection(constr);
    }

    private void InsertExceldata(string fileepath, string filename)
    {
        string fullpath = Server.MapPath("/excelfolder/") + filename;
        ExcelConn(fullpath);
        String query = string.Format("Select * from [{0}]", "Sheet1$");
        OleDbCommand Ecom = new OleDbCommand(query, Econ);
        Econ.Open();

        DataSet ds = new DataSet();
        OleDbDataAdapter oda = new OleDbDataAdapter(query, Econ);
        Econ.Close();
        oda.Fill(ds);

        DataTable dt =ds.Tables[0];

        SqlBulkCopy objbulk = new SqlBulkCopy(con)
        {
            DestinationTableName = "UserInformation"
        };
        objbulk.ColumnMappings.Add("Email", "Email");
        objbulk.ColumnMappings.Add("Name", "Name");
        objbulk.ColumnMappings.Add("PhoneNo", "PhoneNo");
        objbulk.ColumnMappings.Add("Address", "Address");
        objbulk.ColumnMappings.Add("ZipCode", "ZipCode");
        objbulk.ColumnMappings.Add("Country", "Country");
        objbulk.ColumnMappings.Add("State", "State");
        objbulk.ColumnMappings.Add("City", "City");
        con.Open();
        objbulk.WriteToServer(dt);
        con.Close();       }
}

}


Q: remove  from a draggable when being dragged - jquery I have this site which is a grid of draggable links. When dragged a drop down  appears where the user can drag to trash the draggable.
Problem is that when they drop it on the droppble, the link opens up! Which is not supposed to be happening. I've tried adding
ui.draggable.find('a').removeAttr('href')

to my handleDropEvent function, but it didn't help.
Any javascript geniuses care to take a look?
EDIT I tried also adding :
ui.draggable.find('a').click(function(e) { e.preventDefault();

to the following like so:
$('.draggable').draggable({ start: function( event, ui ) {$('#dropdownAddTile').slideDown();ui.draggable.find('a').click(function(e) { e.preventDefault(); });},  stop: function() {$('#dropdownAddTile').slideUp();}, containment: '#container', snap:'.droppable', snapMode:'inner', revert:'invalid',snapTolerance: 32});

ANOTHER EDIT
I should point out (just figured out) that I have the draggable class applied to an href like this :

So solutions so far have caused the problem where we remove the link and it stops the draggable from being draggable! Is there another way?

A: When they are dragged set a click handler to prevent the default action, like so:
ui.draggable.find('a').click(function(e) { e.preventDefault(); });

As I said, do it when they are dragged in case it's too late when doing it in the dropped event.
UPDATE:
$('.draggable').draggable({
  start: function( event, ui ) {
    $('#dropdownAddTile').slideDown();
    ui.draggable.find('a').click(function(e) {
      e.preventDefault();
    });
  },
  stop: function() {
    $('#dropdownAddTile').slideUp();
  },
  containment: '#container',
  snap:'.droppable',
  snapMode:'inner',
  revert:'invalid',
  snapTolerance: 32
});

so you can call ui.draggable.find('a').click(function(e) { e.preventDefault();

A: The issue didn't arise in Chrome, Firefox, or IE10 but it did happen in IE9 and lower.
My advice would be to run preventDefault on the event. Using your code,
function handleDropEvent( event, ui ) {
    event.preventDefault();
    var draggable = ui.draggable;
    var droppable = $(this);
    var droppableId = $(this).attr("id");
    var draggableId = ui.draggable.attr("id");
    $('.draggable').draggable({containment: '#container', snap:'.droppable', snapMode:'inner', revert:'invalid',snapTolerance: 32});
    $('.droppable').droppable({drop: handleDropEvent, accept: function(e){if(e.hasClass('draggable')) { if (!$(this).hasClass('occupied')) {return true; }}}});
    var initPosit = ui.draggable.parent().attr('id');

    $.post("tiles/updateTilePosition", { draggableId:draggableId, droppableId: droppableId }).done(function(data) {

    })
    $(this).addClass('occupied');
    ui.draggable.parent().removeClass('occupied');
    if($(ui.draggable).parent() !==$(this)){
        $(ui.draggable).appendTo($( this ));
    }
}

Also, if you view your source code, everything is encoded (apostrophes, quotes, etc.) Not sure how that happened but I'd fix that.

A: If I understood correctly you just want the a link not to be drag able right?
Do this:
Test

This is basically how you disable the drag function idk why everyone writes such a long code for this....

A: Try setting the onclick to
    return false;


Q: How do I remove extra whitespaces created by iniparser? Recently I'm taking iniparser as primary choice. However, with its API creating too many whitespaces resulting in waste of memory.
For example, iniparser_set() will create
/*test.ini*/
[section]
key                               = value

instead
/*test.ini*/
[section]
key = value

From the point of embedded system's view, removing those extra whitespaces is a great thing for saving memory space. So, how to fix it?

A: As per the source code of iniparser (https://github.com/ndevilla/iniparser/blob/deb85ad4936d4ca32cc2260ce43323d47936410d/src/iniparser.c#L312):
in iniparser_dumpsection_ini function, there is this line:
fprintf(f,
    "%-30s = %s\n",
    d->key[j]+seclen+1,
    d->val[j] ? d->val[j] : "");

As you can see, key is printed with format specifier %-30s which is probably causing this issue.
So, you can clone the repo source code and make the changes. Example, replace format specifier with %s, like:
fprintf(f,
    "%s = %s\n",        // CHANGE HERE
    d->key[j]+seclen+1,
    d->val[j] ? d->val[j] : "");


Q: How to use replace regex in Komodo? I am trying to create a regex to find and replace (keep empty) different names in an txt file. I use Komodo, as it is part of the examen.
Here the text sample:
*Cassidy: What's your name again?
Chrissie Watkins: Chrissie!
Cassidy: Where are we going?
Chrissie: Swimming!
Cassidy: Slow up, slow down! I'm not drunk! Slow down! Wait I'm coming! I'm
coming! I'm definitely
coming! Wait, slow up! I can swim -- just can't walk or dress myself.
Chrissie: Come on in the water!
Cassidy: Take it easy. Take it easy.
Chrissie: Oh! God help me! God! Argh! God help!
Cassidy: I'm coming... I'm coming.
Chrissie: It hurts! It hurts! Oh my god! God help me! God please help!
Martin Brody: How come the sun didn't use to shine in here.
Ellen Brody: We bought the house in the fall, this is summer.
Ellen: Somebody feed the dogs, huh?
Martin: Right.
Ellen: See the kids?
Martin: They must be in the backyard.
Ellen: In Amity, you say: yahd.

The text must be cleaned up, meaning all names at the beginning of each line must be deleted (replaced by nothing).
If I use this: \w.¨:
Also names in texts (not the person speaking) are gone / deleted.
Is it possible to use just one regular expression for cleaning up?

A: You may use
(?m)^\*?[A-Z][\w' -]*:\s*

See the regex demo
Details

*

*(?m) - re.M flag, it makes ^ match start of a line

*^ - start of a line

*\*? - an optional * char

*[A-Z] - an uppercase letter

*[\w' -]* - 0 or more word chars, spaces, - or apostrophes

*: - a colon

*\s* - 0+ whitespaces.


Q: Ruby on Rails tutorial Chapter 11: Rspec tests fail on follower/following section I'm working on Chapter 11 of Hartl's tutorial, trying to get the non-logged-in users in the Users controller visiting the followers and following page to pass. I'm running into an error where Rails would complain about an undefined admin? method despite it being only used in a User partial.
Rails local server
Rendered users/_user.html.erb (9.4ms)
Rendered users/show_follow.html.erb within layouts/application (33.0ms)
Completed 500 Internal Server Error in 43ms

ActionView::Template::Error (undefined method `admin?' for nil:NilClass):
    1:

    2:   <%= gravatar_for user, size: 52 %>
    3:   <%= link_to user.name, user %>
    4:   <% if current_user.admin? && !current_user?(user) %>
    5:     | <%= link_to 'delete', user, method: :delete,
    6:                                   data: { confirm: 'Are you sure?' } %>
    7:   <% end %>
  app/views/users/_user.html.erb:4:in `_app_views_users__user_html_erb___4000670281664801561_70099451578240'
  app/views/users/show_follow.html.erb:25:in `_app_views_users_show_follow_html_erb__2024448610717183111_70099484108000'
  app/controllers/users_controller.rb:68:in `followers'

RSpec failures
 1) Authentication authorization for non-logged-in users in the Users controller visiting the following page
     Failure/Error: it { should have_selector('title', text: 'Login') }
       expected css "title" with text "Login" to return something
     # ./spec/requests/authentication_pages_spec.rb:122:in `block (6 levels) in <top (required)>'

  2) Authentication authorization for non-logged-in users in the Users controller visiting the followers page
     Failure/Error: it { should have_selector('title', text: 'Login') }
       expected css "title" with text "Login" to return something
     # ./spec/requests/authentication_pages_spec.rb:127:in `block (6 levels) in <top (required)>'

authorization_pages_spec.rb
  describe "authorization" do
    .
    .
    .
    describe "for non-logged-in users" do
      let(:user) { FactoryGirl.create(:user) }
      .
      .
      .
      describe "in the Users controller" do
        .
        .
        .
        describe "visiting the following page" do
          before { visit following_user_path(user) }
          it { should have_selector('title', text: 'Login') }
        end

        describe "visiting the followers page" do
          before { visit followers_user_path(user) }
          it { should have_selector('title', text: 'Login') }
        end
      end

show_follow.html.erb
<% provide(:title, @title) %>

      <%= gravatar_for @user %>

<%= @user.name %>

      <%= link_to "view my profile", @user %>
      Posts: <%= @user.posts.count %>

      <%= render 'shared/stats' %>
      <% if @users.any? %>

          <% @users.each do |user| %>
            <%= link_to gravatar_for(user, size: 30), user %>
          <% end %>

      <% end %>

<%= @title %>

    <% if @users.any? %>

        <%= render @users %>

      <%= will_paginate %>
    <% end %>

_user.html.erb

  <%= gravatar_for user, size: 52 %>
  <%= link_to user.name, user %>
  <% if current_user.admin? && !current_user?(user) %>
    | <%= link_to 'delete', user, method: :delete,
                                  data: { confirm: 'Are you sure?' } %>
  <% end %>

I tried copy and pasting all the problematic files from the tutorial itself to no avail. It's mentioned that by assigning the :admin attribute to the User class, a method admin? is made available to use. I'm guessing it's somehow I'm passing a nil object into the partials, but I'm having trouble debugging where exactly that's happening.

A: Okay, I finally figured it out.
I forgot to put the :following and :followers actions in the before_filter for :logged_in_user in the User controller.
class UsersController < ApplicationController
  before_filter :logged_in_user,
                only: [:index, :edit, :update, :destroy, :following, :followers]

That took a while.

A: Your code is checking current_user.admin? and changing what is displayed based on that. However from the title of your specs it appears that you are testing the behaviour when a non logged in user visits the page: current_user will be nil
Sounds like the if statement in the _user partial needs an extra condition to check that there is a logged in user before checking that that user is an admin

A: Try looking in the users_controller, your code in the partials looks okay to me which means it's possibly something behind the scenes that is missing. The local server trace seems to point to line 68 and the followers method. Mine looks like this, fyi:
def followers
   @title = "Followers"
   @user = User.find(params[:id])
   @users = @user.followers.paginate(page: params[:page])
   render 'show_follow'
end

Hope that helps.

A: I also forgot to put the :following and :followers actions in the before_filter for :logged_in_user in the User controller, but I was curious about this error.
Like Frederick Cheung points in is response there is bug in the code of the parcial: _user.html.erb.  We should check if current_user is nil before calling the admin? method on it.
So instead of:
 <% if current_user.admin? && !current_user?(user) %>

you should have:
 <% if current_user && current_user.admin? && !current_user?(user) %>

This removes the "undefined method admin?" error and gives us the correct test error:
 Expected response to be a <redirect>, but was <200>

This last one we remove by putting the :following and :followers actions in the before_filter for :logged_in_user.


Q: How to create/add multiple tittles and border lines to one text table in Tableau Desktop I have a text table in Tableau Desktop that looks like this.

I want to partition it to add multiple tittles with border lines to separate into three parts within one tableau sheet, expecting result to look like this.

Any ideas on how to achieve that? or if it's even possible in Tableau Desktop? Version 2022.1.10


Q: Unable to call F# Extension in VB.Net Solved: IntelliSense just doesn't show the Extension!
Lets say we got the following extension method in F#:
[<Extension>]
module Extension =
    [<Extension>]
    let Increment(value : System.Int32) = value + 1

In C# I can call it like this way:
x.Increment(); //Result x=1

But the equivalent VB code to this returns an error, it doesn't find the extension method for the type integer:
x.Increment() 'No method called "Increment()" for type Int32

While it's possible to call the method by the standard way:
Increment(x) 'Works

So where is the difference between handling VB and C# on calling F# code, why isn't the VB environment able to resolve the extension methods?

A: If you build a regular F# library project
namespace A
open System.Runtime.CompilerServices
[<Extension>]
module Extension =
    [<Extension>]
    let Increment(value : System.Int32) = value + 1

and then refer to this library from VB project
Imports A.Extension
Module Module1
    Sub Main()
        Console.WriteLine((1).Increment())
    End Sub
End Module

then VB treats F# extension method as expected <Extension>Public Function Increment() As Integer and works correctly, giving 2 as output.
A clean experiment does not indicate any VB-specific idiosyncrasy to F#-defined extension methods.


Q: Generic ListView Adapter I am trying to create a Custom Adapter which can handle any kind of layout to be inflated. By generic I mean any kind of data to be set in an adapter and any kind of a layout could be used with Event Listeners to be set for an item.
For example:
I have a contact list and a country list. The Contact list has four items in its layout i.e person image, name, number and a checkBox. The Country List contains a CountryName(TextView) and a checkbox.
Is it possible for both to use the same adapter and that adapter handle all kind of items?
I wish the tick images would reset after clicking on any item.

A: If you have an List with different object that can be of different kinds and need different views to display. Do it that way:
Let the object define the view by themselves. Implement an interface ViewProvider on every object. This interface should provide the method getView() which then can be called in the adapter.
The adapter has now only to get the element out of the list full of ViewProviders and call the method getView to get the view.
You will not have to worry about the recycling off the views as the views are stored in every ViewProvider and will be created only once. The update of the fields (if any) can then also be made on the Object side and not in the adapter. But you have to notify the adapter about the data change by calling notifyDataSetChanged()


Q: Why the return type of getchar() is int? I searched for the answer on Internet but I could not understand what is this 'EOF'?
Please let me know from basic about what is getchar() and what are it's uses?
Note that I am just a beginner of C language.

A: In C there's really no difference between a char and an int. Even character literals, like e.g. 'A', are almost universally promoted to int.
But the most important thing is that EOF is an int value. If char is unsigned (it's implementation-specific if char is signed or unsigned) then when the char value -1 is promoted to int it becomes 0x000000ff, which is very different from the int value -1 which is 0xffffffff (assuming normal two's complement systems).


Q: row layout not set on on Main Activity Recycler View I am just parse some data and display on my ListProperty Class. I am using RecyclerView and CardView as a row layout. Somehow all is working fine i don't see any error in verbose. But the Data and row layout dosent display in my main activity. Activity is showing blank. I am trying from hours but kind find the error. Please someone help
My MainActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/cardList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

This is row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:id="@+id/imageViewFront" />
            </LinearLayout>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textStyle="bold"
            android:text="New Text"
            android:textColor="#0055CC"
            android:id="@+id/textViewPropertyname" />

        <TextView
            android:layout_marginTop="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:textColor="#0055CC"
            android:layout_columnWeight="1"
            android:id="@+id/textViewPropertyDescription"/>
    </LinearLayout>

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

</LinearLayout>

This is myAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
List<Bean> DataList;
public MyAdapter(List<Bean> List){
    super();
    DataList = List;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
    // each data item is just a string in this case
    public TextView propertyName;
    public TextView propertyDesc;
    public ImageView ImageFront;
    public MyViewHolder(View v) {
        super(v);
        propertyName = (TextView) v.findViewById(R.id.textViewPropertyname);
        propertyDesc = (TextView) v.findViewById(R.id.textViewPropertyDescription);
        ImageFront  = (ImageView) v.findViewById(R.id.imageViewFront);
    }
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View itemView = LayoutInflater.from(parent.getContext()).
            inflate(R.layout.list_card_view,parent,false);
    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyAdapter.MyViewHolder holder, int position) {
    Bean bean = DataList.get(position);
    holder.propertyName.setText(bean.getPropertyName());
    holder.propertyDesc.setText(bean.getPropertyDescription());
    holder.ImageFront.setImageResource(R.drawable.agriculture);

}

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

}

And this is my MainActivity.java
    public class ListProperty extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private MyAdapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    Bean bean;
    AQuery aQuery;
    JSONObject jsonObject;
    List<Bean> list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_property);
        aQuery= new AQuery(getApplicationContext());
        String URL = "http://192.168.0.107/propertyapp/service/simpleservice.php";
        list = new ArrayList<Bean>();
        mRecyclerView = (RecyclerView) findViewById(R.id.cardList);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new MyAdapter(list);
        mRecyclerView.setAdapter(mAdapter);
        aQuery.ajax(URL, JSONObject.class,new AjaxCallback<JSONObject>(){
            @Override
            public void callback(String url, JSONObject object, AjaxStatus status) {

                try {
                    bean = new Bean();
                    list = new ArrayList<Bean>();
                    String string = object.getString("data");
                    JSONArray jsonArray = new JSONArray(string);
                    for (int i=0;i<jsonArray.length();i++) {
                        jsonObject = jsonArray.getJSONObject(i);
                        bean.setPropertyName("property_name");
                        bean.setPropertyDescription("property_desc");
                        list.add(bean);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
}

A: Try to remove parent LinearLayout. Because you have CardView which is acting as list item.
Try this row.xml -
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="wrap_content">

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <ImageView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:id="@+id/imageViewFront" />
                </LinearLayout>
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_marginLeft="100dp"
            android:layout_height="wrap_content">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:text="New Text"
                android:textColor="#0055CC"
                android:id="@+id/textViewPropertyname" />

            <TextView
                android:layout_marginTop="10dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New Text"
                android:textColor="#0055CC"
                android:layout_columnWeight="1"
                android:id="@+id/textViewPropertyDescription"/>
        </LinearLayout>

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

Hope it will help :)

A: Just add notifyDataSetChanged() to your Activity as below:
    aQuery.ajax(URL, JSONObject.class,new AjaxCallback<JSONObject>(){
        @Override
        public void callback(String url, JSONObject object, AjaxStatus status) {

            try {
                bean = new Bean();
                list = new ArrayList<Bean>();
                String string = object.getString("data");
                JSONArray jsonArray = new JSONArray(string);
                for (int i=0;i<jsonArray.length();i++) {
                    jsonObject = jsonArray.getJSONObject(i);
                    bean.setPropertyName("property_name");
                    bean.setPropertyDescription("property_desc");
                    list.add(bean);
                }
                //here notify your adapter
                //is to Notify any registered observers that the data set has changed.
                mAdapter.notifyDataSetChanged();

               } catch (JSONException e) {
                  e.printStackTrace();
               }

           }
       });

A: Because on your callback you have created new instance of list
list = new ArrayList<Bean>();

then in fact, the new created list and DataList in your adapter are pointing to 2 difference objects => calling notifyDataSetChanged here won't work. Try writing method updateData on MyAdapter and call it from your callback method
public void updateData(List<Bean> List){
   DataList = List;
   notifyDataSetChanged();
   }

On your callback:
aQuery.ajax(URL, JSONObject.class,new AjaxCallback<JSONObject>(){
    @Override
    public void callback(String url, JSONObject object, AjaxStatus status) {

        try {
            bean = new Bean();
            list = new ArrayList<Bean>();
            String string = object.getString("data");
            JSONArray jsonArray = new JSONArray(string);
            for (int i=0;i<jsonArray.length();i++) {
                jsonObject = jsonArray.getJSONObject(i);
                bean.setPropertyName("property_name");
                bean.setPropertyDescription("property_desc");
                list.add(bean);
            }
            // update data
            mAdapter.updateData(list);

           } catch (JSONException e) {
              e.printStackTrace();
           }

       }
   });


Q: How to change the text of textview more than one Hi and sorry for my English! :)
I want to change the text of Text View after 3 second by random number but it's just show last number and I didn't see last numbers in Text View
What should I do?
Thanks... :)
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

public class TestActivity extends Activity {

    int rand;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final TextView txtShow = (TextView) findViewById(R.id.txtShow);
        Handler handler = new Handler();
        for (int i = 0; i < 5; i++)
        {
            rand = (int) (Math.random() * 9);

            handler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    txtShow.setText("" + rand);

                }
            }, 3000);

        }

    }
}

A: you don't need a loop. In this case you can use postDealyed to repost a runnable in the ui thread queue:
public class TestActivity extends Activity {
int rand;
int counter;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final TextView txtShow = (TextView) findViewById(R.id.txtShow);
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                if (counter > 4) {
                    handler.removeCallbacks(this);
                    return;
                }
                ++counter;
                rand = (int) (Math.random() * 9);
                txtShow.setText("" + rand);
                handler.postDelayed(this, 3000);
            }
        }, 3000);
    }
}

When counter reaches 5, removeCallbacks cancel all the runnables still present in the handler queue and returns. Otherwise counter is increased and handler.postDelayed add the runnable to the handler queue,

A: I think this should work.
private Handler handler;
private TextView txt;

/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    handler = new Handler();
    txt = (TextView) findViewById(R.id.txt);
    new Thread(new Task()).start();
}

class Task implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i <= 5; i++) {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    int rand = (int) (Math.random() * 9);
                    txt.setText("" + rand);
                }
            });
        }
    }
}

A: The problem is that all of the Runnables that are changing the TextView are executing right after one another; the change is so fast that you cannot see the intermediate values and instead only see the final value.
To fix your problem change the delay in postDelayed() from 3000 to 3000 * i. This will ensure that the updates are spaced with 3 seconds between each one instead of just all executing 3 seconds after onCreate() finishes (as it is now).
For things like this you may also want to look into Timer (http://developer.android.com/reference/java/util/Timer.html)


Q: 'Access attribute not allowed in generic body with external package I'm having some issues with generics in Ada. Given the below example, gnatmake results in:
g_package.adb:13:33: 'Access attribute not allowed in generic body
g_package.adb:13:33: because access type "t_callback_p" is declared outside generic unit (RM 3.10.2(32))
g_package.adb:13:33: move 'Access to private part, or (Ada 2005) use anonymous access type instead of "t_callback_p"
gnatmake: "g_package.adb" compilation error

With the assumption that the external package cannot be changed, is there a way to solve this? I get the reason for the error message in the first place (compiler doesn't know the proper type of the generic package, but it's a bit annoying when the passed function in question doesn't touch any part of the generic..)
g_package.adb
with Ada.Text_IO; use Ada.Text_IO;
with external;

package body g_package is
   procedure quix (f : String) is
   begin
      Put_Line ("Does a thing");
   end quix;

   procedure foo (bar : String) is
   begin
      Put_Line ("baz" & bar & Boolean'Image(flag));
      external.procedure_f (quix'Access);
   end foo;
end g_package;

g_package.ads
generic
   flag : Boolean;
package g_package is
   procedure foo (bar : String);
end g_package;

external.ads
package external is
   type t_callback_p is access procedure (s : String);
   procedure procedure_f (proc : t_callback_p);
end external;

A: You can (as mentioned in the error message) move the 'Access to the private part of the package spec:
private with external;

generic
   flag : Boolean;
package g_package is
   procedure foo (bar : String);

private
   procedure quix (f : String);
   quix_access : constant external.t_callback_p := quix'Access;

end g_package;

and the use the constant in the body:
external.procedure_f (quix_access);

A: There's no way to do this in Ada. If you wish to be non-portable and are using (as it appears) GNAT, you can use the GNAT-specific attribute 'Unrestricted_Access.


Q: Why does insert invalidate the std::set reverse iterator My understanding is the iterators of associative containers are not invalidated during insert or erase (unless the node pointed by iterator is erased). But in the below program
the insert seems to invalidate the iterator. Is my understanding wrong?
typedef std::set<unsigned int> myset_t;

int main(int argc, char **argv)
{
    myset_t rs;
    myset_t::reverse_iterator rit;
    myset_t::reverse_iterator srit;
    int ii = 500;

    rs.insert(10);
    rs.insert(11);
    rs.insert(12);
    rs.insert(13);
    rs.insert(14);
    rs.insert(100000);
    rs.insert(102000);
    rs.insert(103000);

    rit = rs.rbegin();

    while(rit != rs.rend()) {
        srit = rit;
        if (*rit < 100000) {
            cout << "bailing here " << *rit << endl;
            return 0;
        }
        rit++;
        cout << "Before erase " << *rit << endl;
        rs.erase(*srit);
        cout << "Before insert " << *rit << endl;
        rs.insert(ii);
        cout << "After insert " << *rit << endl;
        ii++;
    }
    cout << "Out of loop" << endl;
}
===

The output is
Before erase 102000
Before insert 102000
After insert 14
bailing here 14

=====

A: The promised behavior for iterators of a standard container does not hold for reverse iterators of that container.
A reverse iterator actually stores, as a member, the normal (forward moving) iterator which comes after the element to which the reverse iterator refers when dereferenced.  Then when you dereference the reverse iterator, essentially it decrements a copy of this stored normal iterator and dereferences that.  So this is a problem:
rit = rs.rbegin();     // rit stores rs.end()
srit = rit;            // srit also stores rs.end()
rit++;                 // rit stores a normal iterator pointing to the last element

rs.erase(*srit);       // this deletes the last element, invalidating the normal
                       // iterator which is stored in rit. Funnily enough, the
                       // one stored in srit remains valid, but now *srit is a
                       // different value

Reverse iterators behave this way because there is no "before begin" iterator.  If they stored the iterator to the element to which they actually refer, what would rs.rend() store?  I'm sure there are ways around this, but I guess they required compromises which the standards committee was not willing to make.  Or perhaps they never considered this problem, or didn't consider it significant enough.


Q: Text transition on hover image I'am trying to set css transition on the text on hover image like this -> https://victorthemes.com/themes/glazov/portfolio-grid/
I tried to do this with cubic-bezier() function, but without result.
Here's my code.

* {
  margin: 0;
  padding: 0;
  border: 0;
}

.img__wrap {
  position: relative;
  height: 200px;
  width: 257px;
}

.img__description {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(29, 106, 154, 0.72);
  color: #fff;
  visibility: hidden;
  opacity: 0;
  transition: opacity .2s, visibility .2s;
}

.img__wrap:hover .img__description {
  visibility: visible;
  opacity: 1;
}

Teext.

Please give me some hints how to do this.

A: I used transform: translate(); to move object. Play with cubic-bezier here to achieve perfect animation. But I used the same which was on the website you posted in example.
Also I removed opacity, visibility

* {
  margin: 0;
  padding: 0;
  border: 0;
}

.img__wrap {
  position: relative;
  height: 200px;
  width: 257px;
}

.img__description {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(29, 106, 154, 0.72);
  color: #fff;
  transform: translateX(-100%);
  transition: all 600ms cubic-bezier(0.645, 0.045, 0.095, 1.08);
}

.img__wrap:hover .img__description {
  transform: translate(0);
}

Teext.

A: Ok, first, I would suggest using "all" for the transition element instead of defining the same values for all of the proprieties you want to transition.
transition: all .2s;

Second, let's get the bezier right. I think this is close enough:
cubic-bezier(1.000, 0.215, 0.355, 0.990)

So the transition propriety should look like this:
transition: all .2s cubic-bezier(1.000, 0.215, 0.355, 0.990);

For the text animation I suggest using animate.css and use fadeInLeft.

A: To darken the image, you need to change the opacity of it. To zoom the image, use a scale transform and to move the caption text, you need a translateX transform. Apply those css styles and their respective transitions (you need a transition in the image as well as in the text) and you're left with the following:

* {
  margin: 0;
  padding: 0;
  border: 0;
}

.img__wrap {
  position: relative;
  background: black;
  height: 200px;
  width: 257px;
  overflow: hidden;

}
.img__img {
    opacity: 1;
    transition: all 0.2s;
}
.img__description {
    position: absolute;
    color: #fff;
    transition: all .2s;
    left: 15px;
    right: 0;
    bottom: 15px;
    transform: translateX(-100%);
}

.img__wrap:hover .img__img {
    opacity: 0.5;
    transform: scale(1.2);
}

.img__wrap:hover .img__description {
    transform: translateX(0);
}

Teext.


Q: Delphi DLL Modal Form causes AV on Second Call I am trying to show a modal (FMX) form from a DLL. Eventually this will be ported to OSX so I'm trying to keep the 'Windows' code to a minimum. Based on what's in the forum I have tried to keep the code as simple possible.
I know that the first time showmodal is called, the code works as expected, but if I subsequently call the DLL function, I get an AV trying to create the form. I then tried to (without exiting the function) create and free the form several times, this works without issue. And it works if I call the function, create and free the form and DO NOT showmodal. In all my tests, if I showmodal I get the AV trying to create the form the second time and the application hangs.
Of course, if I just show the form I do not get the issue, ie. I can create the form, show it and free it in a loop and it works fine. The issue is of course that the code just continues through destroying the form and I need the form to be modal.
THE DLL EMPSECURE_UI.DLL
function dAbout_UI:boolean; {$IFDEF MSWINDOWS}stdcall{$ELSE}cdecl{$ENDIF} export;
var
  dAbout: TfAbout;

begin
  try
    try
      Result := True;

      dAbout := TfAbout.Create(nil);
      dAbout.Showmodal;
    except
        Result := False;
    end;
  finally
    FreeandNil(dAbout);
  end;

The UNIT in the ABOUT Form
procedure TfAbout.bOKClick(Sender: TObject);
begin
  ModalResult := mrOK;
  Close;
end;

procedure TfAbout.FormClose(Sender: TObject; var Action: TCloseAction);
begin

  Action := System.UITypes.TCloseAction.caFree;
end;

The Test program that calls the function in the DLL  uTESTEMPSECURE_UI.pas, ie. the main program, the simple call to the function that displays the modal form:
const
  {$IFDEF MSWINDOWS}
  EMPSecureUI = 'empsecure_ui.dll';
  {$ENDIF MSWINDOWS}
  {$IFDEF MACOS}
  EMPSecureUI = 'libempsecure_ui.dylib';
  {$ENDIF MACOS}

// EMPSecure_UI Functions
function dAbout_UI: boolean; {$IFDEF MSWINDOWS}stdcall{$ELSE}cdecl{$ENDIF}; external EMPSecureUI;

procedure TForm1.Button1Click(Sender: TObject);
begin
  dAbout_UI;
end;

So the first time I run this code and call the function which shows the modal form it works as expected, a modal form is shown. When I click OK on the form, the form is freed and control is returned to the main test program. This is exactly as expected.
If I then execute a second call to the DLL function an AV occurs when trying to create the form the second time. IF, OTOH, the form is simply shown (not modal), no AV occurs when I try to create the form a second or subsequent time.


Q: How to configure locations of installed applications on Ubuntu 18.04 I've just started using Ubuntu 18.04 on an Asus ROG with two hard disks, SSD+HDD. I am a beginner at using Ubuntu.
The SSD has only 100GB space and I heard from somewhere that it's not polite to such device to overwrite it often. That's why I want to install all programs such as Chrome, VirtualBox, etc. on the HDD (I mounted it at /media/user). How can I configure it?
Results of df -h :
user@muzalevsky:~$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            5.8G     0  5.8G   0% /dev
tmpfs           1.2G  3.5M  1.2G   1% /run
/dev/sdb4       106G   61G   39G  61% /
tmpfs           5.9G   21M  5.8G   1% /dev/shm
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           5.9G     0  5.9G   0% /sys/fs/cgroup
/dev/sdb2       477M  4.7M  472M   1% /boot/efi
/dev/sda2       820G   29G  750G   4% /media/user
tmpfs           1.2G   20K  1.2G   1% /run/user/120
tmpfs           1.2G   52K  1.2G   1% /run/user/1000

A: I recommend installing all applications on the SSD. SSDs have no moving parts and are more reliable and have a longer life expectancy than HDDs. If disk space on the SSD is at a premium, you can save valuable disk space on the SSD by configuring the default locations of the guest OSs in VirtualBox to be on the HDD. In addition you don't need to store much data in your /home directory on the SSD. In order to free up space on the SSD, files that take up a lot of space such as your music library can be stored on the HDD instead. Another way of saving space on the SSD is to move your entire /home directory from the SSD to the HDD by following the instructions in the answers to: Move home folder to second drive.
You can use custom folders for folders in /home/. Example:
 xdg-user-dirs-update --set DOWNLOAD /media/user/Downloads/

would switch from /home/$USER/Downloads/ to /media/user/Downloads/ and documents downloaded would then download to the HDD and not the SSD. Same applies for all the other directories. See ~./config/user-dirs.dirs on manually editing these settings.


Q: DateTime::__construct(): Failed to parse time string (//) at position 0 (/): Unexpected character Could not pass date to MySQL using php POST method. Got the error as given in the title.
Here is my code.

date_default_timezone_set("Asia/Kolkata");
$dd = substr($dob,0,2)."/";
$mm = substr($dob,3,2)."/";
$yyyy = substr($dob,6,4);
$fd = $yyyy.$mm.$dd;
$date = new DateTime($fd);
$formDateConverted = $date->format('Y-m-d');

A: Are you sure you are getting data ? Your substr() must be returning empty strings.
You are adding a slash to your day and month and putting them back together in the wrong order. Just run your code with a fixed string:
$dob = 'dd/mm/yyyy';
$dd = substr($dob,0,2)."/";
$mm = substr($dob,3,2)."/";
$yyyy = substr($dob,6,4);
$fd = $yyyy.$mm.$dd;

var_dump($fd);

Result:
string(10) "yyyymm/dd/"

To me, $dob is clearly empty, as all three variables resulting from the substr() are as well, except for the slashes you add back, which is what you get on the error. Run the code again with an empty variable and you'll get: string(2) "//".
Once you fix your $dob issue, you can use the DateTime class directly as suggested by Chayan:
$date = DateTime::createFromFormat('d/m/Y', $dob);
echo $date->format('Y-m-d');

A: By default PHP can't parse date having '/' in it. Use DateTime::createFromFormat function.
 $date = DateTime::createFromFormat('Y/m/d', $fd);
 echo $date->format('Y-m-d');


Q: Compare one col with another containing multiple entries We need to compare one col with another in a df and identify if the entry from col"a" matches any of the entries in col"b". The result would be a new col with T = match or F = no match.
# task df
df <- data.frame(
  a = c("ABC", 'ABB', 'ACC', 'AAG'),
  b = c("XXC TTZ", "XCT ABB", "TTG WHO ACC", 'AAG')
)

# expected result
df <- data.frame(
  a = c("ABC", 'ABB', 'ACC', 'AAG'),
  b = c("XXC", "XCT ABB", "TTG WHO ACC", 'AAG'),
  match = c("F", "T", "T", "T")
)

I just come out of one year clinical rotation so my coding got a bit rusty. Could not find an answer here, excuse the hustle if this has been asked before. I guess the solution is rather straight forward but I can't wrap my head around it. Thanks a lot for helping (dplyr solutions much appreciated).

A: Use str_detect from stringr which is vectorized for both string and pattern
library(stringr)
library(dplyr)
df %>%
   mutate(match = str_detect(b, a))
    a           b match
1 ABC         XXC FALSE
2 ABB     XCT ABB  TRUE
3 ACC TTG WHO ACC  TRUE
4 AAG         AAG  TRUE

A: A base R option
transform(
  df,
  match = mapply(grepl, a, b, USE.NAMES = FALSE)
)

gives
    a           b match
1 ABC     XXC TTZ FALSE
2 ABB     XCT ABB  TRUE
3 ACC TTG WHO ACC  TRUE
4 AAG         AAG  TRUE


Q: im getting a error message parse error: syntax error, unexpected " I get this error can someone help please

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\Users\packardbell\Desktop\hdd\htdocs\qr\index.php on line 217

this is line 217
$username = $_REQUEST['username'];

$password = $_REQUEST['pass'];

$good=0;

if(isset($username) && isset($password))

A: If what you are using being your actual code that you posted in a comment, you're missing a closing brace } and one too many after mysqlerror()); <= Consult "footnotes" about this.
Your code from a comment:
$db_selected = mysql_select_db('qrcodes');
if(!$db_selected) {
die ('cant\'t connect :' . mysqlerror());
} }
else { this is line 217 $username = $_REQUEST['username']; $password = $_REQUEST['pass'];

Sidenote: You have mysqlerror which should read as mysql_error as per the manual
New code:
$db_selected = mysql_select_db('qrcodes');
if(!$db_selected) {
die ('cant\'t connect :' . mysql_error());
}
else
{
$username = $_REQUEST['username'];
$password = $_REQUEST['pass'];
}

Footnotes:
I agree with Andy Lester's comment in regards to actual errors coming from a line or lines further above. Error messages pointing to a certain line number, doesn't necessarily mean it's on "that" line.
Showing full code will take the guesswork out of things, however from what you did post in your comment, it's a bracing mismatch issue, and using mysqlerror instead of mysql_error (you forgot the underscore between mysql and error) would have provided more information which failed in doing so because of it.

mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.


Q: Discord.js how to delete a message if they have too many capital letters I want to block my user from using too many capital letters in the same message (i.e typing in full CAPS LOCK). I tried this, but it doesn't seem to work if they put spaces between capital letters; here is my current code:
client.on("message", async (msg) => {
  let sChannel = msg.guild.channels.find((c) => c.name === "guard-log");
  if (msg.channel.type === "dm") return;
  if (msg.author.bot) return;
  if (msg.content.length > 15) {
    if (db.fetch(`capslock_${msg.guild.id}`)) {
      let caps = msg.content.replace(" ", "").toUpperCase();
      if (msg.content == caps) {
        if (!msg.member.hasPermission("ADMINISTRATOR")) {
          if (!msg.mentions.users.first()) {
            msg.delete();
            let embed = new Discord.RichEmbed()
              .setColor(0xffa300)
              .setFooter("Retro Guard", client.user.avatarURL)
              .setTitle("Caps-lock Engel")
              .setDescription("Fazla caps lock kullanımı yakalandı!")
              .addField("Kanal Adı", msg.channel.name, true)
              .addField(
                "Kişi",
                "Kullanıcı: " + msg.author.tag + "\nID: " + msg.author.id,
                true
              )
              .addField("Engellenen mesaj", "```" + msg.content + "```", true)
              .setTimestamp();
            sChannel.send(embed);
            return msg.channel
              .send(`${msg.author} fazla caps kullanıyorsun.`)
              .then((m) => m.delete(5000));
          }
        }
      }
    }
  }
});

A: Use .toUpperCase() on each letter and compare it to the letter capitalized, if it is the same, then it's in capital. Otherwise it's not, you don't actualy need any databases. Try following this code:
client.on("message", async msg => {
  let sChannel = msg.guild.channels.find(c => c.name === "guard-log");

  if (msg.channel.type === "dm" || msg.author.bot || msg.content.length < 15) return;
  // Use `||` (OR) to make it cleaner.

  let non_caps, caps;
  // Create the variables.

  for (x=0;x<msg.content.length;x++) {
    if (msg.content[x].toUpperCase() === msg.content[x]) caps++;
    else non_caps++;
  }
  // `caps` is the amount of capital letters, while `non_caps` is the amount of non-capital letters. This checks for each letter of the message and gets the amount of `caps` and `non_caps`.

  const textCaps = (caps / message.content.length) * 100;
  // Gets a percentage of the capital letters.

  if (textCaps >= 60 && !msg.member.permissions.has('ADMINISTRATOR')) {
  // If the capital letters is over or equals to 60% of the message,
  // and if the user isn't an ADMINISTRATOR, then...

    let embed = new Discord.RichEmbed()
      .setColor(0xffa300)
      .setFooter('Retro Guard', client.user.avatarURL)
      .setTitle("Caps-lock Engel")
      .setDescription("Fazla caps lock kullanımı yakalandı!")
      .addField("Kanal Adı", msg.channel.name, true)
      .addField('Kişi', 'Kullanıcı: '+ msg.author.tag +'\nID: '+ msg.author.id, true)
      .addField('Engellenen mesaj', "```" + msg.content + "```", true)
      .setTimestamp()
    sChannel.send(embed);
    msg.delete(); // Deletes the capped message.
    return msg.reply(`fazla caps kullanıyorsun.`)
    // `message.reply()` mentions the user that sent the message and is cleaner.
      .then(m => m.delete(5000))
  }
})

Do be careful, since this will delete the message if they put too much caps, including them quoting someone, whether they mean it or not.
If you still don't understand, here are some reference:

*

*How can I test if a letter in a string is uppercase or lowercase using JavaScript?


Q: Android Kotlin - Unit test a delayed coroutine that invokes a lambda action when delay is finished Ive been struggling with this for quite some time now, perhaps someone could help...
I have this function in my class under test:
fun launchForegroundTimer(context: Context) {
        helper.log("AppRate", "[$TAG] Launching foreground count down [10 seconds]")
        timerJob = helper.launchActionInMillisWithBundle(Dispatchers.Main, TimeUnit.SECOND.toMillis(10), context, this::showGoodPopupIfAllowed)
}

So in that function, I first write to some log and then I call a coroutine function that expects a Dispatcher param, how long to wait before running the action, Any object that I would like to pass on to the action and the actual action function that is invoked when time has passed.
So in this case, the this::showGoodPopupIfAllowed which is a private method in the class, gets called when the 10,000 ms have passed.
Here is that function:
private fun showGoodPopupIfAllowed(context: Context?) {
        if (isAllowedToShowAppRate()) {
            showGoodPopup(context)
        }
}

In that first if, there are a bunch of checks that occur before I can call showGoodPopup(context)
Now, here is the helper.launchActionInMillisWithBundle function:
fun <T> launchActionInMillisWithBundle(dispatcher: CoroutineContext, inMillis: Long, bundle: T, action: (T) -> Unit): Job = CoroutineScope(dispatcher).launchInMillisWithBundle(inMillis, bundle, action)

And here is the actual CoroutineScope extension function:
fun <T> CoroutineScope.launchInMillisWithBundle(inMillisFromNow: Long, bundle: T, action: (T) -> Unit) = this.launch {
    delay(inMillisFromNow)
    action(bundle)
}

What I am trying to achieve is a UnitTest that calls the launchForegroundTimer function, calls the helper function with the appropriate arguments and also continue through and call that lambda showGoodPopupIfAllowed function where I can also provide mocked behaviour to all the IF statments that occur in isAllowedToShowAppRate.
Currently my test stops right after the launchActionInMillisWithBundle is called and the test just ends. I assume there is no real call to any coroutine because I am mocking the helper class... not sure how to continue here.
I read a few interesting articles but none seems to resolve such state.
My current test function looks like this:
    private val appRaterManagerHelperMock = mockkClass(AppRaterManagerHelper::class)
    private val timerJobMock = mockkClass(Job::class)
    private val contextMock = mockkClass(Context::class)

    @Test
    fun `launch foreground timer`() {
        every { appRaterManagerHelperMock.launchActionInMillisWithBundle(Dispatchers.Main, TimeUnit.SECOND.toMillis(10), contextMock, any()) } returns timerJobMock
        val appRaterManager = AppRaterManager(appRaterManagerHelperMock)
        appRaterManager.launchForegroundTimer(contextMock)

        verify(exactly = 1) { appRaterManagerHelperMock.log("AppRate", "[AppRaterManager] Launching foreground count down [10 seconds]") }
    }

I'm using mockk as my Mocking lib.
AppRaterManager is the class under test
I'd like to also mention that, in theory I could have moved the coroutine invocation outside the class under test. So an external class like activity.onResume() could launch some sort of countdown and then call directly a function that checks showGoodPopupIfAllowed(). But currently, please assume that I do not have any way to change the calling code so the timer and coroutine should remain in the class under test domain.
Thank you!

A: Alright, I read a bit deeper into capturing/answers over at https://mockk.io/#capturing and saw there is a capture function.
So I captured the lambda function in a slot which enables me invoke the lambda and then the actual code continues in the class under test. I can mock the rest of the behavior from there.
Here is my test function for this case (for anyone who gets stuck):
    @Test
    fun `launch foreground timer, not participating, not showing good popup`() {
        val slot = slot<(Context) -> Unit>()
        every { appRaterManagerHelperMock.launchActionInMillisWithBundle(Dispatchers.Main, TimeUnit.SECOND.toMillis(10), contextMock, capture(slot)) } answers {
            slot.captured.invoke(contextMock)
            timerJobMock
        }

        every { appRaterManagerHelperMock.isParticipating() } returns false

        val appRaterManager = AppRaterManager(appRaterManagerHelperMock)
        appRaterManager.launchForegroundTimer(contextMock)

        verify(exactly = 1) { appRaterManagerHelperMock.log("AppRate", "[AppRaterManager] Launching foreground count down [10 seconds]") }
        verify(exactly = 1) { appRaterManagerHelperMock.isParticipating() }
        verify(exactly = 0) { appRaterManagerHelperMock.showGoodPopup(contextMock, appRaterManager) }
    }

So what's left now is how to test the coroutine actually invokes the lambda after the provided delay time is up.


Q: Changing the working directory for a process remotely I've got an application that has a bug right now, but we're unable to update the end-user to get the fix out. What a possible workaround would be is to change the working directory to the application's install directory, but from what I can tell, there's no way to do that outside of the program itself. Is there some sort of Windows API call that can change other processes' working directories, or is that not available due to security issues? I figure it's not possible.

A: You can change the directory that it initially starts in with a shortcut. If that is not enough, I don't believe what you want is possible without injecting a custom dll into the process after the fact.

A: Why do you want to change the working directory? Maybe you could modify the PATH environment variable in some way to change the order of directories your app searches for files.


Q: Content in scrollview as a list item disappears when scrolling (swiftui), why? Solution by @Asperi, ScrollView().id(UUID().uuidString).
There is a scrollview in the list item, when I scroll the list, the content in scrollview disappears.
I think the issue is about scrollview & list reusable item conflict.
If I remove scrollview(just hstack{}), nothing disappears. So I think it's scrollview's issue. Any ideal?
struct ContentView: View {
    var body: some View {
        List {
            ForEach(0...100, id: \.self) { _ in
                ItemView().padding()
            }
        }
    }
}

struct ItemView: View {
    var body: some View {
        VStack(alignment: .leading) {
            Text("Tag list:")
            ScrollView(.horizontal, showsIndicators: false) {
                HStack {
                    ForEach(0...8, id: \.self) { _ in
                        TagView1()
                    }
                }
            }.id(UUID().uuidString) /// <- fix
        }
    }
}

struct TagView1: View {
    var body: some View {
        Text("Tag\(String(UUID().uuidString.prefix(5)))")
            .foregroundColor(.secondary)
            .padding(.horizontal, 2)
            .background(RoundedRectangle(cornerRadius: 4).stroke(Color.secondary.opacity(0.5)))
            .padding(1)
    }
}

A: If I correctly understood what disappears (I assume you meant list rows on vertical scrolling), then yes it is due to List reuse/cache optimisation issue.
The following approach should work (tested with Xcode 11.2 / iOS 13.2)
struct ItemView: View {
    var body: some View {
        VStack {
            Text("Tag list:")
            ScrollView(.horizontal, showsIndicators: false) {
                HStack {
                    ForEach(0...8, id: \.self) { _ in
                        TagView().padding()
                    }
                }
            }.id(UUID().uuidString) // << here is a fix !
        }
    }
}


Q: Swift - How to correctly set up a Weak Variable I have an app with a lot of Astronomical calculations in them.
For sanity they are separated into individual methods/functions.
Run individually there are no memory runaways.
HOWEVER when I need to calculate something complex like the angle of incidence of the sun's rays to any place on the Earth I have to call 19 methods in a row and the memory usage goes through the roof. Clearly variables are still live so the ARC can't evaporate them.
So I presumed the solution was to create a weak link. If I change my call from
var angleIncidence = Celestial().calculateAngleIncidence(....)

to
weak var angleIncidence = Celestial().calculateAngleIncidence(....)

I get a "Weak cannot be applied to a non class type Double".
I am clearly being too naive.

A: Doubles are not objects, so referring to them as strong and weak does not make sense because they do not have reference counts.
In practice, they obey the typical rules of variable scope. However, they should really not be a cause for significant memory usage, unless you are using very large arrays of them. My feeling is that something else is probably going on - probably to do with other data types present and how data is being passed between the functions.


Q: ibm-cloud-private dashboard first record does not look like a TLS handshake I'm trying to use ibm-private-cloud dashboard to install ibm-chart.
And after selecting any chart, and proceed to configure, I'm pressing "install".
Then i got the following error in the bottom of the page:

Internal service error : rpc error: code = Internal desc = connection
  error: desc = "transport: authentication handshake failed: tls: first
  record does not look like a TLS handshake"

Does anybody have a solution?

A: May be try to use http_s_:// when making api requests or opening the web-interface


Q: Python 3 taking multiple data types in input, separated by space So i need to find a way to take multiple data types as an input and store them in variables. Lets say i have 3 variables, each of them should store a fixed data type
a - float
b - str
c - int
and if the user enters a wrong, he will be asked to type again.
The user will enter all of them, separated by space but i can't think of a way to store them in the variables, while keeping the data type. I've tried with .split(), but it just transforms them into strings. It's probably something quite obvious, but can't figure it out right now. Thanks in advance!

A: Maybe:
def myfucn(vars):
    vars = vars.split()
    try:
        float(vars[0])
        if not "." in vars[0]:
            raise Exception("First var should be INT not Float")
    except ValueError:
        print("Error not Float found")

    try:
        int(vars[2])
    except ValueError:
        print("Error Int no found")

    #answer
    a_float, b_str, c_int = vars
    print(" Yes ")

greetings

A: You are on the right track if the split() function. The problem is that when you say that user will give three values separated by ' ', you are taking in a string.
The following is a string:
'34.44 35.45 5'
Maybe what you can do is after using split, you can cast each returned item to a variable. If you still need to check the type of variable, you can use the type() function.
Hope this helps!


Q: Generating every outcome possible when parsing a list : element(N, L,X) I am trying to implement a simple element(N,L,X) predicate, where L is a list, X an element of the list, and N the position of this element in the list.
I want to be able to do that :
element(3, [a,b,c,d,e], X).
yes : X=c.

element(N, [a,b,c,d,e], X).
yes : { N=1, X=a}; { N=2, X=b}; ... { N=5, X=e};

I am sure I have seen this somewhere, but I can't find it.
Thanks.

A: Since you're trying to describe a relation between a list, a potential element of that list and its position, why not give the predicate a more descriptive name, e.g. list_element_position/3. Then consider what the relation should describe. Basically there are two cases:
1) The head of the list matches the element. In that case you already know a position for that element. But there might be other occurrences as well, so:
2) Regardless whether the head matches the element or not, we should take a look at the tail of the list as well, since there might be further occurrences.
An accumlator can be used to count the positions. I take it from your first example that you'd like to start counting at 1. Putting all that together you could write something like:
list_element_position(L,E,P) :-
   list_element_position_(L,E,P,1).         % start counting at 1

list_element_position_([X|Xs],X,P,P).       % case 1)
list_element_position_([X|Xs],Y,R,P0) :-    % case 2)
   P1 is P0+1,
   list_element_position_(Xs,Y,R,P1).

Your example queries:
   ?- list_element_position([a,b,c,d,e],E,3).
E = c ? ;
no
   ?- list_element_position([a,b,c,d,e],E,X).
E = a,
X = 1 ? ;
E = b,
X = 2 ? ;
E = c,
X = 3 ? ;
E = d,
X = 4 ? ;
E = e,
X = 5 ? ;
no

Multiple occurrences of an element:
   ?- list_element_position([a,b,c,d,e,a],a,X).
X = 1 ? ;
X = 6 ? ;
no

If you only intend to use the predicate with the first argument being ground, this already works fine. However, if you want to ask questions like: What lists are there with a certain element, say a, at a certain position, say 1?:
   ?- list_element_position(L,a,1).
L = [a|_A] ? ;

You get one answer and then the predicate loops. You can avoid that by adding a goal with length/2 to list_element_position/3:
list_element_position(L,E,P) :-
   length(L,_),                       % <- here
   list_element_position_(L,E,P,1).

The above query now produces additional solutions:
   ?- list_element_position(L,a,1).
L = [a] ? ;
L = [a,_A] ? ;
L = [a,_A,_B] ? ;
L = [a,_A,_B,_C] ? ;
...

Or even better, you can avoid the loop by using clpfd and adding a goal in list_element_position_/4 to ensure that the accumlator does not become larger than the actual position:
:- use_module(library(clpfd)).

list_element_position(L,E,P) :-
   list_element_position_(L,E,P,1).

list_element_position_([X|Xs],X,P,P).
list_element_position_([X|Xs],Y,R,P0) :-
   R #> P0,                                  % <- here
   P1 #= P0+1,
   list_element_position_(Xs,Y,R,P1).

This way the query yields a single solution and terminates subsequently:
   ?- list_element_position(L,a,1).
L = [a|_A] ? ;
no


Q: rails postgres some of the sequence not start from 1 I am using ruby on rails with postgresql database. A weird thing happened that some of the tables_id_seq are not starting from 1, but 980190963. But some of the seq are correctly starting from 1.
The problem is when I tried to insert data into those table which seq not start from 1, unique primary key violation raised occasionally.
--EDIT--
I found that when I do
rake db:migrate test

The problem happens.
If I do
rake db:migrate RAILS_ENV=test

The problem has gone.

A: If you don't need to keep the data in those tables, you can run the following which will reset the table (THIS WILL REMOVE ANY DATA THERE) and restart the tables id to start at 1.  THIS IS ONLY VIABLE IF YOU DON"T NEED THE DATA IN THAT TABLE!
ActiveRecord::Base.connection.execute("TRUNCATE TABLE table_name_here RESTART IDENTITY")

As far as why your tables are starting at that id value I would start by checking your migrations.  Maybe somewhere in the code there is an "Alter Sequence" sql statement but again not sure.


Q: Why is my Apollo Client optimistic reply failing? I'm recording this to document the answer to a problem that took me several hours to solve. Scenario:
I'm using two mutation queries on a single component in React Apollo-Client. This is a component wrapped into a larger component to form a page. Something like this (this is not the actual code, but it should give the idea):
import { compose } from 'react-apollo';

// submitNewUser contains
//  postedBy
//  createdAt
//  content

// submitRepository contains
//  otherProp

const thisProps1 = {
  name: 'mutation1',
  props: ({ ownProps, mutation1 }) => ({
    submit: ({ repoFullName, commentContent }) => mutation1({
      variables: { repoFullName, commentContent },
      optimisticResponse: {
        __typename: 'Mutation',
        submitNewUser: {
          __typename: 'Comment',
          postedBy: ownProps.currentUser,
          content: commentContent,
        },
      },
    }),
  }),
};
const thisProps2 = {
  name: 'mutation2',
  props: ({ ownProps, mutation2 }) => ({
    submit: ({ repoFullName, commentContent }) => mutation2({
      variables: { repoFullName, commentContent },
      optimisticResponse: {
        __typename: 'Mutation',
        submitRepository: {
          __typename: 'Comment',
          otherProp: 'foobar',
        },
      },
    }),
  }),
};
const ComponentWithMutations = compose(
  graphql(submitNewUser, thisProps1),
  graphql(submitRepository, thisProps2)
)(Component);

Whenever the optimistic response fires, only the second result is fed back to into the query-response in the outer component. In other words, the first query gives an 'undefined' response (but no error), while the second returns an object as expect.
Why??

A: The property "createdAt" is not included in the optimistic reply.
__typename: 'Comment',
postedBy: ownProps.currentUser,
content: commentContent,

Should be:
__typename: 'Comment',
postedBy: ownProps.currentUser,
createdAt: Date(),
content: commentContent,

A missing field in an optimistic reply will silently fail to return anything to any queries that call that data.


Q: Error in model.frame.default(formula = meansharelocal ~ meanshareglobal) : invalid type (list) for variable 'meansharelocal' Trying to conduct a t.test of two sets of data. The code I am writing for this is:
t.test(meansharelocal ~ meanshareglobal)

Each data set has 4 pieces of data, in a column like this in a table:

mean(Share_1)
mean(Share_2)
mean(Share_3)
mean(Share_4)

1.396552
1.034483
1.189655
1.396552

When I run t.test(meansharelocal ~ meanshareglobal) I receive this error.

Error in model.frame.default(formula = meansharelocal ~
meanshareglobal) :    invalid type (list) for variable
'meansharelocal'

Can someone tell me what is going wrong? I am trying to see if the two piece of data are statistically different enough.
This is what I got from Reprex, again, I am new to this so don't know if I accessed this wrong as it is coming up with more errors? But the only error I actually have is the last line!
globalshare <- global %>% mutate_at(c("Share_1", "Share_2", "Share_3", "Share_4"), funs(recode(.,"Extremely likely" = 4, "Somewhat likely" = 3, "Neither likely nor unlikely" = 2, "Somewhat unlikely" = 1, "Extremely unlikely" = 0)))
#> Error in tbl_vars_dispatch(x): object 'global' not found

localshare <- local %>% mutate_at(c("Share_1", "Share_2", "Share_3", "Share_4"), funs(recode(.,"Extremely likely" = 4, "Somewhat likely" = 3, "Neither likely nor unlikely" = 2, "Somewhat unlikely" = 1, "Extremely unlikely" = 0)))
#> Error in UseMethod("tbl_vars"): no applicable method for 'tbl_vars' applied to an object of class "function"

boxplot(globalshare$Share_1, globalshare$Share_2, globalshare$Share_3, globalshare$Share_4,
        localshare$Share_1, localshare$Share_2, localshare$Share_3, localshare$Share_4, names=c
        ("Global1", "Global2", "Global3", "Global4", "Local1", "Local2","Local3", "Local4"))
#> Error in boxplot(globalshare$Share_1, globalshare$Share_2, globalshare$Share_3, : object 'globalshare' not found

meanshareglobal <- globalshare %>% summarise(mean(Share_1), mean(Share_2), mean(Share_3), mean(Share_4))
#> Error in summarise(., mean(Share_1), mean(Share_2), mean(Share_3), mean(Share_4)): object 'globalshare' not found

meansharelocal <- localshare %>% summarise(mean(Share_1), mean(Share_2), mean(Share_3), mean(Share_4))
#> Error in summarise(., mean(Share_1), mean(Share_2), mean(Share_3), mean(Share_4)): object 'localshare' not found

t.test(meanshareglobal ~ meansharelocal)
#> Error in eval(predvars, data, env): object 'meanshareglobal' not found

A: If I am understanding from your comments correctly you have wide dataframes of 1 row. Assuming they are the same dimensions you can just transpose and bind them then do your t test.
t.globalshare  = t(globalshare)
t.localshare  = t(localshare)

combined = cbind(t.globalshare, t.localshare)

t.test(combined, t.globalshare ~ t.localshare)


Q: Laravel show maintenance mode during composer update I'm have a question extremely similar to this unanswered one: laravel 5 maintenance page broken during composer update
I am new to Laravel (using version 5.2) and am trying to work out the deployment process. From what I've gathered, the workflow that I want to use (once I've made and thoroughly tested changes on a development server, of course) is to put the production site into maintenance mode, deploy changes via git, run composer/artisan tasks (composer update, php artisan migrate, etc.) and then take the production site out of maintenance mode.
The problem I'm running into is that if I have new providers in config/app.php, the live site displays an error message (until I run composer update) even while in maintenance mode.
Is there a way to have the maintenance mode view override the error view so that I can perform my updates in peace without the site telling the world that there are errors? I turned off error reporting so it at least doesn't show the specifics, but I'd love it if it kept any mention of errors on the DL while maintenance mode was enabled.
Alternatively, is there a better deployment workflow that I can use to eliminate this problem all together?

A: Why not use symlinks for releases? Below is an example of a deployment process that I've used on Laravel applications with Envoy. Aside from the PHP variable notation, it would be straightforward to substitute a purely bash/shell script if you are not using Envoy. Essentially, having a script automates the deployment, and using symlinks can make the update nearly instantaneous. Additional benefits include previous releases existing for the unfortunate time when a rollback is necessary.
Note: The below script makes some basic assumptions:

*

*Your .env file is in the $root_dir (ex: /var/www/my-website/.env).

*Your vhost points to the site/public directory within the $root_dir (ex: /var/www/my-website/site/public). However, if you can not update the vhost, you can simply add the following to number 4 below in the empty line:
ln -nfs {{ $app_dir }}/public {{ $root_dir }}/public ;
sudo chgrp -h www-data {{ $root_dir }}/public;

*You have added SSH keys to pull from Git repo

*(optional) nodejs is installed

Here are the relevant example variables for the script:
$repo        = 'git@bitbucket.org:myusername/my-repo.git';
$root_dir    = '/var/www/my-website';
$release_dir = '/var/www/my-website/releases';
$app_dir     = '/var/www/my-website/site';
$release     = 'release_' . date('YmdHis');
$branch      = 'master';

Here is the gist of the deployment process with code:

*

*Fetch the updated code into a new release directory:
@task('fetch_repo')
[ -d {{ $release_dir }} ] || mkdir {{ $release_dir }};
cd {{ $release_dir }};
git clone {{ $repo }} -b {{ $branch }} {{ $release }};
@endtask

*Install the dependencies by running composer:
@task('run_composer')
cd {{ $release_dir }}/{{ $release }};
composer install;
@endtask

*(optional) If we are using asset precompiler like Elixir, we will want to fetch npm dependencies, reset permissions, and run gulp:
@task('npm_install')
cd {{ $release_dir }}/{{ $release }};
sudo npm install;
@endtask

@task('update_permissions')
cd {{ $release_dir }};
sudo chgrp -R www-data {{ $release }};
sudo chmod -R ug+rwx {{ $release }};
@endtask

@task('compile_assets')
cd {{ $release_dir }}/{{ $release }};
gulp --production;
@endtask

*Update symlinks
@task('update_symlinks')
ln -nfs {{ $root_dir  }}/.env {{ $release_dir }}/{{ $release }}/.env;
ln -nfs {{ $release_dir }}/{{ $release }} {{ $app_dir }};

sudo chgrp -h www-data {{ $app_dir }};
sudo service php5-fpm restart;
@endtask

*(Optional) Prune old release folders (30+ days old) so we don't fill up the server.
@task('prune_old')
sudo find {{ $release_dir }} -maxdepth 1 -type d -mtime +30 -exec rm -rf {} \;
@endtask

Note: Restarting the php5-fpm service clears the cache that ensures the new symlink is followed.
I found it somewhat difficult to find deployment script examples (like the aforementioned) when I initially began developing with Laravel, so hopefully this will help alleviate some searching.